diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 000000000..9a1c54393 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,10 @@ +preset: psr2 + +finder: + name: + - "*.php" + not-name: + - "*Stub.php" + path: + - "src" + - "tests" \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..c09c89bdf --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2005-2017 TorrentPier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/admin/admin_attach_cp.php b/admin/admin_attach_cp.php index 274b673bb..fc701b4a3 100644 --- a/admin/admin_attach_cp.php +++ b/admin/admin_attach_cp.php @@ -1,30 +1,48 @@ '; -for($i = 0; $i < count($view_types_text); $i++) -{ - $selected = ($view == $view_types[$i]) ? ' selected="selected"' : ''; - $select_view .= ''; +for ($i = 0; $i < count($view_types_text); $i++) { + $selected = ($view == $view_types[$i]) ? ' selected="selected"' : ''; + $select_view .= ''; } $select_view .= ''; -if (count($mode_types_text) > 0) -{ - $select_sort_mode = ''; - for($i = 0; $i < count($mode_types_text); $i++) - { - $selected = ($mode == $mode_types[$i]) ? ' selected="selected"' : ''; - $select_sort_mode .= ''; - } - $select_sort_mode .= ''; + for ($i = 0; $i < count($mode_types_text); $i++) { + $selected = ($mode == $mode_types[$i]) ? ' selected="selected"' : ''; + $select_sort_mode .= ''; + } + $select_sort_mode .= ''; } $select_sort_order = ''; -$submit_change = ( isset($_POST['submit_change']) ) ? TRUE : FALSE; -$delete = ( isset($_POST['delete']) ) ? TRUE : FALSE; +$submit_change = (isset($_POST['submit_change'])) ? true : false; +$delete = (isset($_POST['delete'])) ? true : false; $delete_id_list = get_var('delete_id_list', array(0)); $confirm = isset($_POST['confirm']); -if ($confirm && sizeof($delete_id_list) > 0) -{ - $attachments = array(); +if ($confirm && sizeof($delete_id_list) > 0) { + $attachments = array(); - delete_attachment(0, $delete_id_list); -} -else if ($delete && sizeof($delete_id_list) > 0) -{ - // Not confirmed, show confirmation message - $hidden_fields = ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - $hidden_fields .= ''; + delete_attachment(0, $delete_id_list); +} elseif ($delete && sizeof($delete_id_list) > 0) { + // Not confirmed, show confirmation message + $hidden_fields = ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + $hidden_fields .= ''; - for ($i = 0; $i < sizeof($delete_id_list); $i++) - { - $hidden_fields .= ''; - } + for ($i = 0; $i < sizeof($delete_id_list); $i++) { + $hidden_fields .= ''; + } - print_confirmation(array( - 'FORM_ACTION' => "admin_attach_cp.php", - 'HIDDEN_FIELDS' => $hidden_fields, - )); + print_confirmation(array( + 'FORM_ACTION' => "admin_attach_cp.php", + 'HIDDEN_FIELDS' => $hidden_fields, + )); } // Assign Default Template Vars $template->assign_vars(array( - 'S_VIEW_SELECT' => $select_view, - 'S_MODE_ACTION' => 'admin_attach_cp.php', + 'S_VIEW_SELECT' => $select_view, + 'S_MODE_ACTION' => 'admin_attach_cp.php', )); -if ($submit_change && $view == 'attachments') -{ - $attach_change_list = get_var('attach_id_list', array(0)); - $attach_comment_list = get_var('attach_comment_list', array('')); - $attach_download_count_list = get_var('attach_count_list', array(0)); +if ($submit_change && $view == 'attachments') { + $attach_change_list = get_var('attach_id_list', array(0)); + $attach_comment_list = get_var('attach_comment_list', array('')); + $attach_download_count_list = get_var('attach_count_list', array(0)); - // Generate correct Change List - $attachments = array(); + // Generate correct Change List + $attachments = array(); - for ($i = 0; $i < count($attach_change_list); $i++) - { - $attachments['_' . $attach_change_list[$i]]['comment'] = $attach_comment_list[$i]; - $attachments['_' . $attach_change_list[$i]]['download_count'] = $attach_download_count_list[$i]; - } + for ($i = 0; $i < count($attach_change_list); $i++) { + $attachments['_' . $attach_change_list[$i]]['comment'] = $attach_comment_list[$i]; + $attachments['_' . $attach_change_list[$i]]['download_count'] = $attach_download_count_list[$i]; + } - $sql = 'SELECT * + $sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' ORDER BY attach_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment informations'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment informations'); + } - while ( $attachrow = DB()->sql_fetchrow($result) ) - { - if ( isset($attachments['_' . $attachrow['attach_id']]) ) - { - if ($attachrow['comment'] != $attachments['_' . $attachrow['attach_id']]['comment'] || $attachrow['download_count'] != $attachments['_' . $attachrow['attach_id']]['download_count']) - { - $sql = "UPDATE " . BB_ATTACHMENTS_DESC . " - SET comment = '" . attach_mod_sql_escape($attachments['_' . $attachrow['attach_id']]['comment']) . "', download_count = " . (int) $attachments['_' . $attachrow['attach_id']]['download_count'] . " - WHERE attach_id = " . (int) $attachrow['attach_id']; + while ($attachrow = DB()->sql_fetchrow($result)) { + if (isset($attachments['_' . $attachrow['attach_id']])) { + if ($attachrow['comment'] != $attachments['_' . $attachrow['attach_id']]['comment'] || $attachrow['download_count'] != $attachments['_' . $attachrow['attach_id']]['download_count']) { + $sql = "UPDATE " . BB_ATTACHMENTS_DESC . " + SET comment = '" . attach_mod_sql_escape($attachments['_' . $attachrow['attach_id']]['comment']) . "', download_count = " . (int)$attachments['_' . $attachrow['attach_id']]['download_count'] . " + WHERE attach_id = " . (int)$attachrow['attach_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update attachments informations'); - } - } - } - } - DB()->sql_freeresult($result); + if (!DB()->sql_query($sql)) { + bb_die('Could not update attachments informations'); + } + } + } + } + DB()->sql_freeresult($result); } // Statistics -if ($view == 'stats') -{ - $upload_dir_size = get_formatted_dirsize(); +if ($view == 'stats') { + $upload_dir_size = get_formatted_dirsize(); - $attachment_quota = humn_size($attach_config['attachment_quota']); + $attachment_quota = humn_size($attach_config['attachment_quota']); - // number_of_attachments - $row = DB()->fetch_row(" - SELECT COUNT(*) AS total FROM ". BB_ATTACHMENTS_DESC ." + // number_of_attachments + $row = DB()->fetch_row(" + SELECT COUNT(*) AS total FROM " . BB_ATTACHMENTS_DESC . " "); - $number_of_attachments = $number_of_posts = $row['total']; + $number_of_attachments = $number_of_posts = $row['total']; - $number_of_pms = 0; + $number_of_pms = 0; - // number_of_topics - $row = DB()->fetch_row(" - SELECT COUNT(*) AS topics FROM ". BB_TOPICS ." WHERE topic_attachment = 1 + // number_of_topics + $row = DB()->fetch_row(" + SELECT COUNT(*) AS topics FROM " . BB_TOPICS . " WHERE topic_attachment = 1 "); - $number_of_topics = $row['topics']; + $number_of_topics = $row['topics']; - // number_of_users - $row = DB()->fetch_row(" - SELECT COUNT(DISTINCT user_id_1) AS users FROM ". BB_ATTACHMENTS ." WHERE post_id != 0 + // number_of_users + $row = DB()->fetch_row(" + SELECT COUNT(DISTINCT user_id_1) AS users FROM " . BB_ATTACHMENTS . " WHERE post_id != 0 "); - $number_of_users = $row['users']; - - $template->assign_vars(array( - 'TPL_ATTACH_STATISTICS' => true, - 'TOTAL_FILESIZE' => $upload_dir_size, - 'ATTACH_QUOTA' => $attachment_quota, - 'NUMBER_OF_ATTACHMENTS' => $number_of_attachments, - 'NUMBER_OF_POSTS' => $number_of_posts, - 'NUMBER_OF_PMS' => $number_of_pms, - 'NUMBER_OF_TOPICS' => $number_of_topics, - 'NUMBER_OF_USERS' => $number_of_users, - )); + $number_of_users = $row['users']; + $template->assign_vars(array( + 'TPL_ATTACH_STATISTICS' => true, + 'TOTAL_FILESIZE' => $upload_dir_size, + 'ATTACH_QUOTA' => $attachment_quota, + 'NUMBER_OF_ATTACHMENTS' => $number_of_attachments, + 'NUMBER_OF_POSTS' => $number_of_posts, + 'NUMBER_OF_PMS' => $number_of_pms, + 'NUMBER_OF_TOPICS' => $number_of_topics, + 'NUMBER_OF_USERS' => $number_of_users, + )); } // Search -if ($view == 'search') -{ - // Get Forums and Categories - //sf - add [, f.forum_parent] - $sql = "SELECT c.cat_title, c.cat_id, f.forum_name, f.forum_id, f.forum_parent +if ($view == 'search') { + // Get Forums and Categories + //sf - add [, f.forum_parent] + $sql = "SELECT c.cat_title, c.cat_id, f.forum_name, f.forum_id, f.forum_parent FROM " . BB_CATEGORIES . " c, " . BB_FORUMS . " f WHERE f.cat_id = c.cat_id ORDER BY c.cat_id, f.forum_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain forum_name / forum_id'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain forum_name / forum_id'); + } - $s_forums = ''; - while ($row = DB()->sql_fetchrow($result)) - { //sf - $s_forums .= ''; + $s_forums = ''; + while ($row = DB()->sql_fetchrow($result)) { //sf + $s_forums .= ''; - if( empty($list_cat[$row['cat_id']]) ) - { - $list_cat[$row['cat_id']] = $row['cat_title']; - } - } + if (empty($list_cat[$row['cat_id']])) { + $list_cat[$row['cat_id']] = $row['cat_title']; + } + } - if( $s_forums != '' ) - { - $s_forums = '' . $s_forums; + if ($s_forums != '') { + $s_forums = '' . $s_forums; - // Category to search - $s_categories = ''; + // Category to search + $s_categories = ''; - foreach ($list_cat as $cat_id => $cat_title) - { - $s_categories .= ''; - } - } - else - { - bb_die($lang['NO_SEARCHABLE_FORUMS']); - } + foreach ($list_cat as $cat_id => $cat_title) { + $s_categories .= ''; + } + } else { + bb_die($lang['NO_SEARCHABLE_FORUMS']); + } - $template->assign_vars(array( - 'TPL_ATTACH_SEARCH' => true, - 'S_FORUM_OPTIONS' => $s_forums, - 'S_CATEGORY_OPTIONS' => $s_categories, - 'S_SORT_OPTIONS' => $select_sort_mode, - 'S_SORT_ORDER' => $select_sort_order, - )); + $template->assign_vars(array( + 'TPL_ATTACH_SEARCH' => true, + 'S_FORUM_OPTIONS' => $s_forums, + 'S_CATEGORY_OPTIONS' => $s_categories, + 'S_SORT_OPTIONS' => $select_sort_mode, + 'S_SORT_ORDER' => $select_sort_order, + )); } // Username -if ($view == 'username') -{ - $template->assign_vars(array( - 'TPL_ATTACH_USER' => true, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, - )); - $total_rows = 0; - bb_die('removed'); +if ($view == 'username') { + $template->assign_vars(array( + 'TPL_ATTACH_USER' => true, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, + )); + $total_rows = 0; + bb_die('removed'); } // Attachments -if ($view == 'attachments') -{ - $user_based = ($uid) ? TRUE : FALSE; - $search_based = (isset($_POST['search']) && $_POST['search']) ? TRUE : FALSE; +if ($view == 'attachments') { + $user_based = ($uid) ? true : false; + $search_based = (isset($_POST['search']) && $_POST['search']) ? true : false; - $hidden_fields = ''; + $hidden_fields = ''; - $template->assign_vars(array( - 'TPL_ATTACH_ATTACHMENTS' => true, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, - )); + $template->assign_vars(array( + 'TPL_ATTACH_ATTACHMENTS' => true, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, + )); - $total_rows = 0; + $total_rows = 0; - // Are we called from Username ? - if ($user_based) - { - $sql = "SELECT username FROM " . BB_USERS . " WHERE user_id = " . intval($uid); + // Are we called from Username ? + if ($user_based) { + $sql = "SELECT username FROM " . BB_USERS . " WHERE user_id = " . intval($uid); - if (!($result = DB()->sql_query($sql))) - { - bb_die('Error getting username'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Error getting username'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $username = $row['username']; + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); + $username = $row['username']; - $s_hidden = ''; + $s_hidden = ''; - $template->assign_block_vars('switch_user_based', array()); + $template->assign_block_vars('switch_user_based', array()); - $template->assign_vars(array( - 'S_USER_HIDDEN' => $s_hidden, - 'L_STATISTICS_FOR_USER' => sprintf($lang['STATISTICS_FOR_USER'], $username), - )); + $template->assign_vars(array( + 'S_USER_HIDDEN' => $s_hidden, + 'L_STATISTICS_FOR_USER' => sprintf($lang['STATISTICS_FOR_USER'], $username), + )); - $sql = "SELECT attach_id + $sql = "SELECT attach_id FROM " . BB_ATTACHMENTS . " WHERE user_id_1 = " . intval($uid) . " GROUP BY attach_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #1'); + } - $attach_ids = DB()->sql_fetchrowset($result); - $num_attach_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); + $attach_ids = DB()->sql_fetchrowset($result); + $num_attach_ids = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_attach_ids == 0) - { - bb_die('For some reason no attachments are assigned to the user ' . $username); - } + if ($num_attach_ids == 0) { + bb_die('For some reason no attachments are assigned to the user ' . $username); + } - $total_rows = $num_attach_ids; + $total_rows = $num_attach_ids; - $attach_id = array(); + $attach_id = array(); - for ($j = 0; $j < $num_attach_ids; $j++) - { - $attach_id[] = intval($attach_ids[$j]['attach_id']); - } + for ($j = 0; $j < $num_attach_ids; $j++) { + $attach_id[] = intval($attach_ids[$j]['attach_id']); + } - $sql = "SELECT a.* + $sql = "SELECT a.* FROM " . BB_ATTACHMENTS_DESC . " a WHERE a.attach_id IN (" . implode(', ', $attach_id) . ") " . - $order_by; + $order_by; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #2'); + } - $attachments = DB()->sql_fetchrowset($result); - $num_attach = DB()->num_rows($result); - DB()->sql_freeresult($result); - } - else - { - // we are called from search - $attachments = search_attachments($order_by, $total_rows); - } + $attachments = DB()->sql_fetchrowset($result); + $num_attach = DB()->num_rows($result); + DB()->sql_freeresult($result); + } else { + // we are called from search + $attachments = search_attachments($order_by, $total_rows); + } - if (sizeof($attachments) > 0) - { - for ($i = 0; $i < sizeof($attachments); $i++) - { - $delete_box = ''; + if (sizeof($attachments) > 0) { + for ($i = 0; $i < sizeof($attachments); $i++) { + $delete_box = ''; - for ($j = 0; $j < count($delete_id_list); $j++) - { - if ($delete_id_list[$j] == $attachments[$i]['attach_id']) - { - $delete_box = ''; - break; - } - } + for ($j = 0; $j < count($delete_id_list); $j++) { + if ($delete_id_list[$j] == $attachments[$i]['attach_id']) { + $delete_box = ''; + break; + } + } - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - // Is the Attachment assigned to more than one post ? - // If it's not assigned to any post, it's an private message thingy. ;) - $post_titles = array(); + // Is the Attachment assigned to more than one post ? + // If it's not assigned to any post, it's an private message thingy. ;) + $post_titles = array(); - $sql = "SELECT * + $sql = "SELECT * FROM " . BB_ATTACHMENTS . " WHERE attach_id = " . intval($attachments[$i]['attach_id']); - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #3'); + } - $ids = DB()->sql_fetchrowset($result); - $num_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); + $ids = DB()->sql_fetchrowset($result); + $num_ids = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($j = 0; $j < $num_ids; $j++) - { - if ($ids[$j]['post_id'] != 0) - { - $sql = "SELECT t.topic_title + for ($j = 0; $j < $num_ids; $j++) { + if ($ids[$j]['post_id'] != 0) { + $sql = "SELECT t.topic_title FROM " . BB_TOPICS . " t, " . BB_POSTS . " p WHERE p.post_id = " . intval($ids[$j]['post_id']) . " AND p.topic_id = t.topic_id GROUP BY t.topic_id, t.topic_title"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query topic'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query topic'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $post_title = $row['topic_title']; + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); + $post_title = $row['topic_title']; - if (strlen($post_title) > 32) - { - $post_title = str_short($post_title, 30); - } + if (strlen($post_title) > 32) { + $post_title = str_short($post_title, 30); + } - $view_topic = BB_ROOT . 'viewtopic.php?' . POST_POST_URL . '=' . $ids[$j]['post_id'] . '#' . $ids[$j]['post_id']; + $view_topic = BB_ROOT . 'viewtopic.php?' . POST_POST_URL . '=' . $ids[$j]['post_id'] . '#' . $ids[$j]['post_id']; - $post_titles[] = '' . $post_title . ''; - } - else - { - $post_titles[] = $lang['PRIVATE_MESSAGE']; - } - } + $post_titles[] = '' . $post_title . ''; + } else { + $post_titles[] = $lang['PRIVATE_MESSAGE']; + } + } - $post_titles = implode('
', $post_titles); + $post_titles = implode('
', $post_titles); - $hidden_field = ''; + $hidden_field = ''; - $template->assign_block_vars('attachrow', array( - 'ROW_NUMBER' => $i + ( @$_GET['start'] + 1 ), - 'ROW_CLASS' => $row_class, + $template->assign_block_vars('attachrow', array( + 'ROW_NUMBER' => $i + (@$_GET['start'] + 1), + 'ROW_CLASS' => $row_class, - 'FILENAME' => htmlspecialchars($attachments[$i]['real_filename']), - 'COMMENT' => htmlspecialchars($attachments[$i]['comment']), - 'EXTENSION' => $attachments[$i]['extension'], - 'SIZE' => round(($attachments[$i]['filesize'] / 1024), 2), - 'DOWNLOAD_COUNT' => $attachments[$i]['download_count'], - 'POST_TIME' => bb_date($attachments[$i]['filetime']), - 'POST_TITLE' => $post_titles, + 'FILENAME' => htmlspecialchars($attachments[$i]['real_filename']), + 'COMMENT' => htmlspecialchars($attachments[$i]['comment']), + 'EXTENSION' => $attachments[$i]['extension'], + 'SIZE' => round(($attachments[$i]['filesize'] / 1024), 2), + 'DOWNLOAD_COUNT' => $attachments[$i]['download_count'], + 'POST_TIME' => bb_date($attachments[$i]['filetime']), + 'POST_TITLE' => $post_titles, - 'S_DELETE_BOX' => $delete_box, - 'S_HIDDEN' => $hidden_field, - 'U_VIEW_ATTACHMENT' => BB_ROOT . DOWNLOAD_URL . $attachments[$i]['attach_id'], - )); + 'S_DELETE_BOX' => $delete_box, + 'S_HIDDEN' => $hidden_field, + 'U_VIEW_ATTACHMENT' => BB_ROOT . DOWNLOAD_URL . $attachments[$i]['attach_id'], + )); + } + } - } - } + if (!$search_based && !$user_based) { + if ($total_attachments == 0) { + $sql = "SELECT attach_id FROM " . BB_ATTACHMENTS_DESC; - if (!$search_based && !$user_based) - { - if ($total_attachments == 0) - { - $sql = "SELECT attach_id FROM " . BB_ATTACHMENTS_DESC; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment description table'); + } - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachment description table'); - } - - $total_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); - } - } + $total_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); + } + } } // Generate Pagination -if ($do_pagination && $total_rows > $bb_cfg['topics_per_page']) -{ - generate_pagination('admin_attach_cp.php?view=' . $view . '&mode=' . $mode . '&order=' . $sort_order . '&uid=' . $uid, $total_rows, $bb_cfg['topics_per_page'], $start).' '; +if ($do_pagination && $total_rows > $bb_cfg['topics_per_page']) { + generate_pagination('admin_attach_cp.php?view=' . $view . '&mode=' . $mode . '&order=' . $sort_order . '&uid=' . $uid, $total_rows, $bb_cfg['topics_per_page'], $start) . ' '; } -print_page('admin_attach_cp.tpl', 'admin'); \ No newline at end of file +print_page('admin_attach_cp.tpl', 'admin'); diff --git a/admin/admin_attachments.php b/admin/admin_attachments.php index 3d0d93356..5ae88e5db 100644 --- a/admin/admin_attachments.php +++ b/admin/admin_attachments.php @@ -1,149 +1,146 @@ sql_query($sql)) -{ - bb_die('Could not find attachment config table #1'); +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not find attachment config table #1'); } -while ($row = DB()->sql_fetchrow($result)) -{ - $config_name = $row['config_name']; - $config_value = $row['config_value']; +while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; - $new_attach[$config_name] = get_var($config_name, trim($attach_config[$config_name])); + $new_attach[$config_name] = get_var($config_name, trim($attach_config[$config_name])); - if (!$size && !$submit && $config_name == 'max_filesize') - { - $size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$size && !$submit && $config_name == 'max_filesize') { + $size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$quota_size && !$submit && $config_name == 'attachment_quota') - { - $quota_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$quota_size && !$submit && $config_name == 'attachment_quota') { + $quota_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$pm_size && !$submit && $config_name == 'max_filesize_pm') - { - $pm_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); - } + if (!$pm_size && !$submit && $config_name == 'max_filesize_pm') { + $pm_size = ($attach_config[$config_name] >= 1048576) ? 'mb' : (($attach_config[$config_name] >= 1024) ? 'kb' : 'b'); + } - if (!$submit && ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm')) - { - if ($new_attach[$config_name] >= 1048576) - { - $new_attach[$config_name] = round($new_attach[$config_name] / 1048576 * 100) / 100; - } - else if ($new_attach[$config_name] >= 1024) - { - $new_attach[$config_name] = round($new_attach[$config_name] / 1024 * 100) / 100; - } - } + if (!$submit && ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm')) { + if ($new_attach[$config_name] >= 1048576) { + $new_attach[$config_name] = round($new_attach[$config_name] / 1048576 * 100) / 100; + } elseif ($new_attach[$config_name] >= 1024) { + $new_attach[$config_name] = round($new_attach[$config_name] / 1024 * 100) / 100; + } + } - if ( $submit && ( $mode == 'manage' || $mode == 'cats') ) - { - if ($config_name == 'max_filesize') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($submit && ($mode == 'manage' || $mode == 'cats')) { + if ($config_name == 'max_filesize') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($size == 'kb') ? round($new_attach[$config_name] * 1024) : (($size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'attachment_quota') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $quota_size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($quota_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($config_name == 'attachment_quota') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($quota_size == 'kb') ? round($new_attach[$config_name] * 1024) : (($quota_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'max_filesize_pm') - { - $old = $new_attach[$config_name]; - $new_attach[$config_name] = ( $pm_size == 'kb' ) ? round($new_attach[$config_name] * 1024) : ( ($pm_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name] ); - } + if ($config_name == 'max_filesize_pm') { + $old = $new_attach[$config_name]; + $new_attach[$config_name] = ($pm_size == 'kb') ? round($new_attach[$config_name] * 1024) : (($pm_size == 'mb') ? round($new_attach[$config_name] * 1048576) : $new_attach[$config_name]); + } - if ($config_name == 'max_filesize') - { - $old_size = $attach_config[$config_name]; - $new_size = $new_attach[$config_name]; + if ($config_name == 'max_filesize') { + $old_size = $attach_config[$config_name]; + $new_size = $new_attach[$config_name]; - if ($old_size != $new_size) - { - // See, if we have a similar value of old_size in Mime Groups. If so, update these values. - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' - SET max_filesize = ' . (int) $new_size . ' - WHERE max_filesize = ' . (int) $old_size; + if ($old_size != $new_size) { + // See, if we have a similar value of old_size in Mime Groups. If so, update these values. + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' + SET max_filesize = ' . (int)$new_size . ' + WHERE max_filesize = ' . (int)$old_size; - if (!($result_2 = DB()->sql_query($sql))) - { - bb_die('Could not update extension group information'); - } + if (!($result_2 = DB()->sql_query($sql))) { + bb_die('Could not update extension group information'); + } + } - } - - $sql = "UPDATE " . BB_ATTACH_CONFIG . " + $sql = "UPDATE " . BB_ATTACH_CONFIG . " SET config_value = '" . attach_mod_sql_escape($new_attach[$config_name]) . "' WHERE config_name = '" . attach_mod_sql_escape($config_name) . "'"; - } - else - { - $sql = "UPDATE " . BB_ATTACH_CONFIG . " + } else { + $sql = "UPDATE " . BB_ATTACH_CONFIG . " SET config_value = '" . attach_mod_sql_escape($new_attach[$config_name]) . "' WHERE config_name = '" . attach_mod_sql_escape($config_name) . "'"; - } + } - if (!DB()->sql_query($sql)) - { - bb_die('Failed to update attachment configuration for ' . $config_name); - } + if (!DB()->sql_query($sql)) { + bb_die('Failed to update attachment configuration for ' . $config_name); + } - if ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm') - { - $new_attach[$config_name] = $old; - } - } + if ($config_name == 'max_filesize' || $config_name == 'attachment_quota' || $config_name == 'max_filesize_pm') { + $new_attach[$config_name] = $old; + } + } } DB()->sql_freeresult($result); @@ -155,565 +152,471 @@ $select_quota_size_mode = size_select('quota_size', $quota_size); $select_pm_size_mode = size_select('pm_size', $pm_size); // Search Imagick -if ($search_imagick) -{ - $imagick = ''; +if ($search_imagick) { + $imagick = ''; - if (preg_match('/convert/i', $imagick)) - { - return true; - } - else if ($imagick != 'none') - { - if (!preg_match('/WIN/i', PHP_OS)) - { - $retval = @exec('whereis convert'); - $paths = explode(' ', $retval); + if (preg_match('/convert/i', $imagick)) { + return true; + } elseif ($imagick != 'none') { + if (!preg_match('/WIN/i', PHP_OS)) { + $retval = @exec('whereis convert'); + $paths = explode(' ', $retval); - if (is_array($paths)) - { - for ( $i=0; $i < sizeof($paths); $i++) - { - $path = basename($paths[$i]); + if (is_array($paths)) { + for ($i = 0; $i < sizeof($paths); $i++) { + $path = basename($paths[$i]); - if ($path == 'convert') - { - $imagick = $paths[$i]; - } - } - } - } - else if (preg_match('/WIN/i', PHP_OS)) - { - $path = 'c:/imagemagick/convert.exe'; + if ($path == 'convert') { + $imagick = $paths[$i]; + } + } + } + } elseif (preg_match('/WIN/i', PHP_OS)) { + $path = 'c:/imagemagick/convert.exe'; - if ( !@file_exists(@amod_realpath($path))) - { - $imagick = $path; - } - } - } + if (!@file_exists(@amod_realpath($path))) { + $imagick = $path; + } + } + } - if ( !@file_exists(@amod_realpath(trim($imagick)))) - { - $new_attach['img_imagick'] = trim($imagick); - } - else - { - $new_attach['img_imagick'] = ''; - } + if (!@file_exists(@amod_realpath(trim($imagick)))) { + $new_attach['img_imagick'] = trim($imagick); + } else { + $new_attach['img_imagick'] = ''; + } } // Check Settings -if ($check_upload) -{ - // Some tests... - $attach_config = array(); +if ($check_upload) { + // Some tests... + $attach_config = array(); - $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not find attachment config table #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not find attachment config table #2'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); - } + for ($i = 0; $i < $num_rows; $i++) { + $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); + } - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $upload_dir = $attach_config['upload_dir']; + } else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; + } - $error = false; + $error = false; - // Does the target directory exist, is it a directory and writeable - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - $error = true; - $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $attach_config['upload_dir']) . '
'; - } + // Does the target directory exist, is it a directory and writeable + if (!@file_exists(@amod_realpath($upload_dir))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $attach_config['upload_dir']) . '
'; + } - if (!$error && !is_dir($upload_dir)) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $attach_config['upload_dir']) . '
'; - } + if (!$error && !is_dir($upload_dir)) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $attach_config['upload_dir']) . '
'; + } - if (!$error) - { - if ( !($fp = @fopen($upload_dir . '/0_000000.000', 'w')) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $attach_config['upload_dir']) . '
'; - } - else - { - @fclose($fp); - unlink_attach($upload_dir . '/0_000000.000'); - } - } + if (!$error) { + if (!($fp = @fopen($upload_dir . '/0_000000.000', 'w'))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $attach_config['upload_dir']) . '
'; + } else { + @fclose($fp); + unlink_attach($upload_dir . '/0_000000.000'); + } + } - if (!$error) - { - bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } // Management -if ($submit && $mode == 'manage') -{ - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } +if ($submit && $mode == 'manage') { + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'manage') -{ - $yes_no_switches = array('disable_mod', 'allow_pm_attach', 'display_order'); +if ($mode == 'manage') { + $yes_no_switches = array('disable_mod', 'allow_pm_attach', 'display_order'); - for ($i = 0; $i < sizeof($yes_no_switches); $i++) - { - eval("\$" . $yes_no_switches[$i] . "_yes = ( \$new_attach['" . $yes_no_switches[$i] . "'] != '0' ) ? 'checked=\"checked\"' : '';"); - eval("\$" . $yes_no_switches[$i] . "_no = ( \$new_attach['" . $yes_no_switches[$i] . "'] == '0' ) ? 'checked=\"checked\"' : '';"); - } + for ($i = 0; $i < sizeof($yes_no_switches); $i++) { + eval("\$" . $yes_no_switches[$i] . "_yes = ( \$new_attach['" . $yes_no_switches[$i] . "'] != '0' ) ? 'checked=\"checked\"' : '';"); + eval("\$" . $yes_no_switches[$i] . "_no = ( \$new_attach['" . $yes_no_switches[$i] . "'] == '0' ) ? 'checked=\"checked\"' : '';"); + } - $template->assign_vars(array( - 'TPL_ATTACH_MANAGE' => true, - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=manage', - 'S_FILESIZE' => $select_size_mode, - 'S_FILESIZE_QUOTA' => $select_quota_size_mode, - 'S_FILESIZE_PM' => $select_pm_size_mode, - 'S_DEFAULT_UPLOAD_LIMIT' => default_quota_limit_select('default_upload_quota', intval(trim($new_attach['default_upload_quota']))), - 'S_DEFAULT_PM_LIMIT' => default_quota_limit_select('default_pm_quota', intval(trim($new_attach['default_pm_quota']))), + $template->assign_vars(array( + 'TPL_ATTACH_MANAGE' => true, + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=manage', + 'S_FILESIZE' => $select_size_mode, + 'S_FILESIZE_QUOTA' => $select_quota_size_mode, + 'S_FILESIZE_PM' => $select_pm_size_mode, + 'S_DEFAULT_UPLOAD_LIMIT' => default_quota_limit_select('default_upload_quota', intval(trim($new_attach['default_upload_quota']))), + 'S_DEFAULT_PM_LIMIT' => default_quota_limit_select('default_pm_quota', intval(trim($new_attach['default_pm_quota']))), - 'UPLOAD_DIR' => $new_attach['upload_dir'], - 'ATTACHMENT_IMG_PATH' => $new_attach['upload_img'], - 'TOPIC_ICON' => $new_attach['topic_icon'], - 'MAX_FILESIZE' => $new_attach['max_filesize'], - 'ATTACHMENT_QUOTA' => $new_attach['attachment_quota'], - 'MAX_FILESIZE_PM' => $new_attach['max_filesize_pm'], - 'MAX_ATTACHMENTS' => $new_attach['max_attachments'], - 'MAX_ATTACHMENTS_PM' => $new_attach['max_attachments_pm'], - 'DISABLE_MOD_YES' => $disable_mod_yes, - 'DISABLE_MOD_NO' => $disable_mod_no, - 'PM_ATTACH_YES' => $allow_pm_attach_yes, - 'PM_ATTACH_NO' => $allow_pm_attach_no, - 'DISPLAY_ORDER_ASC' => $display_order_yes, - 'DISPLAY_ORDER_DESC' => $display_order_no, - )); + 'UPLOAD_DIR' => $new_attach['upload_dir'], + 'ATTACHMENT_IMG_PATH' => $new_attach['upload_img'], + 'TOPIC_ICON' => $new_attach['topic_icon'], + 'MAX_FILESIZE' => $new_attach['max_filesize'], + 'ATTACHMENT_QUOTA' => $new_attach['attachment_quota'], + 'MAX_FILESIZE_PM' => $new_attach['max_filesize_pm'], + 'MAX_ATTACHMENTS' => $new_attach['max_attachments'], + 'MAX_ATTACHMENTS_PM' => $new_attach['max_attachments_pm'], + 'DISABLE_MOD_YES' => $disable_mod_yes, + 'DISABLE_MOD_NO' => $disable_mod_no, + 'PM_ATTACH_YES' => $allow_pm_attach_yes, + 'PM_ATTACH_NO' => $allow_pm_attach_no, + 'DISPLAY_ORDER_ASC' => $display_order_yes, + 'DISPLAY_ORDER_DESC' => $display_order_no, + )); } -if ($submit && $mode == 'cats') -{ - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } +if ($submit && $mode == 'cats') { + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'cats') -{ - $s_assigned_group_images = $lang['NONE']; +if ($mode == 'cats') { + $s_assigned_group_images = $lang['NONE']; - $sql = 'SELECT group_name, cat_id FROM ' . BB_EXTENSION_GROUPS . ' WHERE cat_id > 0 ORDER BY cat_id'; + $sql = 'SELECT group_name, cat_id FROM ' . BB_EXTENSION_GROUPS . ' WHERE cat_id > 0 ORDER BY cat_id'; - $s_assigned_group_images = array(); + $s_assigned_group_images = array(); - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group names from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group names from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($row); $i++) - { - if ($row[$i]['cat_id'] == IMAGE_CAT) - { - $s_assigned_group_images[] = $row[$i]['group_name']; - } - } + for ($i = 0; $i < sizeof($row); $i++) { + if ($row[$i]['cat_id'] == IMAGE_CAT) { + $s_assigned_group_images[] = $row[$i]['group_name']; + } + } - $display_inlined_yes = ( $new_attach['img_display_inlined'] != '0' ) ? 'checked="checked"' : ''; - $display_inlined_no = ( $new_attach['img_display_inlined'] == '0' ) ? 'checked="checked"' : ''; + $display_inlined_yes = ($new_attach['img_display_inlined'] != '0') ? 'checked="checked"' : ''; + $display_inlined_no = ($new_attach['img_display_inlined'] == '0') ? 'checked="checked"' : ''; - $create_thumbnail_yes = ( $new_attach['img_create_thumbnail'] != '0' ) ? 'checked="checked"' : ''; - $create_thumbnail_no = ( $new_attach['img_create_thumbnail'] == '0' ) ? 'checked="checked"' : ''; + $create_thumbnail_yes = ($new_attach['img_create_thumbnail'] != '0') ? 'checked="checked"' : ''; + $create_thumbnail_no = ($new_attach['img_create_thumbnail'] == '0') ? 'checked="checked"' : ''; - $use_gd2_yes = ( $new_attach['use_gd2'] != '0' ) ? 'checked="checked"' : ''; - $use_gd2_no = ( $new_attach['use_gd2'] == '0' ) ? 'checked="checked"' : ''; + $use_gd2_yes = ($new_attach['use_gd2'] != '0') ? 'checked="checked"' : ''; + $use_gd2_no = ($new_attach['use_gd2'] == '0') ? 'checked="checked"' : ''; - // Check Thumbnail Support - if (!is_imagick() && !@extension_loaded('gd')) - { - $new_attach['img_create_thumbnail'] = '0'; - } - else - { - $template->assign_block_vars('switch_thumbnail_support', array()); - } + // Check Thumbnail Support + if (!is_imagick() && !@extension_loaded('gd')) { + $new_attach['img_create_thumbnail'] = '0'; + } else { + $template->assign_block_vars('switch_thumbnail_support', array()); + } - $template->assign_vars(array( - 'TPL_ATTACH_SPECIAL_CATEGORIES' => true, - 'IMAGE_MAX_HEIGHT' => $new_attach['img_max_height'], - 'IMAGE_MAX_WIDTH' => $new_attach['img_max_width'], - 'IMAGE_LINK_HEIGHT' => $new_attach['img_link_height'], - 'IMAGE_LINK_WIDTH' => $new_attach['img_link_width'], - 'IMAGE_MIN_THUMB_FILESIZE' => $new_attach['img_min_thumb_filesize'], - 'IMAGE_IMAGICK_PATH' => $new_attach['img_imagick'], - 'DISPLAY_INLINED_YES' => $display_inlined_yes, - 'DISPLAY_INLINED_NO' => $display_inlined_no, - 'CREATE_THUMBNAIL_YES' => $create_thumbnail_yes, - 'CREATE_THUMBNAIL_NO' => $create_thumbnail_no, - 'USE_GD2_YES' => $use_gd2_yes, - 'USE_GD2_NO' => $use_gd2_no, - 'S_ASSIGNED_GROUP_IMAGES' => implode(', ', $s_assigned_group_images), - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=cats', - )); + $template->assign_vars(array( + 'TPL_ATTACH_SPECIAL_CATEGORIES' => true, + 'IMAGE_MAX_HEIGHT' => $new_attach['img_max_height'], + 'IMAGE_MAX_WIDTH' => $new_attach['img_max_width'], + 'IMAGE_LINK_HEIGHT' => $new_attach['img_link_height'], + 'IMAGE_LINK_WIDTH' => $new_attach['img_link_width'], + 'IMAGE_MIN_THUMB_FILESIZE' => $new_attach['img_min_thumb_filesize'], + 'IMAGE_IMAGICK_PATH' => $new_attach['img_imagick'], + 'DISPLAY_INLINED_YES' => $display_inlined_yes, + 'DISPLAY_INLINED_NO' => $display_inlined_no, + 'CREATE_THUMBNAIL_YES' => $create_thumbnail_yes, + 'CREATE_THUMBNAIL_NO' => $create_thumbnail_no, + 'USE_GD2_YES' => $use_gd2_yes, + 'USE_GD2_NO' => $use_gd2_no, + 'S_ASSIGNED_GROUP_IMAGES' => implode(', ', $s_assigned_group_images), + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=cats', + )); } // Check Cat Settings -if ($check_image_cat) -{ - // Some tests... - $attach_config = array(); +if ($check_image_cat) { + // Some tests... + $attach_config = array(); - $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; + $sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not find attachment config table #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not find attachment config table #3'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); - } + for ($i = 0; $i < $num_rows; $i++) { + $attach_config[$row[$i]['config_name']] = trim($row[$i]['config_value']); + } - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $upload_dir = $attach_config['upload_dir']; + } else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; + } - $upload_dir = $upload_dir . '/' . THUMB_DIR; + $upload_dir = $upload_dir . '/' . THUMB_DIR; - $error = false; + $error = false; - // Does the target directory exist, is it a directory and writeable - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - @mkdir($upload_dir, 0755); - @chmod($upload_dir, 0777); + // Does the target directory exist, is it a directory and writeable + if (!@file_exists(@amod_realpath($upload_dir))) { + @mkdir($upload_dir, 0755); + @chmod($upload_dir, 0777); - if ( !@file_exists(@amod_realpath($upload_dir)) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $upload_dir) . '
'; - } - } + if (!@file_exists(@amod_realpath($upload_dir))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_DOES_NOT_EXIST'], $upload_dir) . '
'; + } + } - if (!$error && !is_dir($upload_dir)) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $upload_dir) . '
'; - } + if (!$error && !is_dir($upload_dir)) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_IS_NOT_A_DIR'], $upload_dir) . '
'; + } - if (!$error) - { - if ( !($fp = @fopen($upload_dir . '/0_000000.000', 'w')) ) - { - $error = TRUE; - $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $upload_dir) . '
'; - } - else - { - @fclose($fp); - @unlink($upload_dir . '/0_000000.000'); - } - } + if (!$error) { + if (!($fp = @fopen($upload_dir . '/0_000000.000', 'w'))) { + $error = true; + $error_msg = sprintf($lang['DIRECTORY_NOT_WRITEABLE'], $upload_dir) . '
'; + } else { + @fclose($fp); + @unlink($upload_dir . '/0_000000.000'); + } + } - if (!$error) - { - bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!$error) { + bb_die($lang['TEST_SETTINGS_SUCCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } // Quota Limit Settings -if ($submit && $mode == 'quota') -{ - // Change Quota Limit - $quota_change_list = get_var('quota_change_list', array(0)); - $quota_desc_list = get_var('quota_desc_list', array('')); - $filesize_list = get_var('max_filesize_list', array(0)); - $size_select_list = get_var('size_select_list', array('')); +if ($submit && $mode == 'quota') { + // Change Quota Limit + $quota_change_list = get_var('quota_change_list', array(0)); + $quota_desc_list = get_var('quota_desc_list', array('')); + $filesize_list = get_var('max_filesize_list', array(0)); + $size_select_list = get_var('size_select_list', array('')); - $allowed_list = array(); + $allowed_list = array(); - for ($i = 0; $i < sizeof($quota_change_list); $i++) - { - $filesize_list[$i] = ( $size_select_list[$i] == 'kb' ) ? round($filesize_list[$i] * 1024) : ( ($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i] ); + for ($i = 0; $i < sizeof($quota_change_list); $i++) { + $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : (($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i]); - $sql = 'UPDATE ' . BB_QUOTA_LIMITS . " - SET quota_desc = '" . attach_mod_sql_escape($quota_desc_list[$i]) . "', quota_limit = " . (int) $filesize_list[$i] . " - WHERE quota_limit_id = " . (int) $quota_change_list[$i]; + $sql = 'UPDATE ' . BB_QUOTA_LIMITS . " + SET quota_desc = '" . attach_mod_sql_escape($quota_desc_list[$i]) . "', quota_limit = " . (int)$filesize_list[$i] . " + WHERE quota_limit_id = " . (int)$quota_change_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update quota limits'); - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not update quota limits'); + } + } - // Delete Quota Limits - $quota_id_list = get_var('quota_id_list', array(0)); + // Delete Quota Limits + $quota_id_list = get_var('quota_id_list', array(0)); - $quota_id_sql = implode(', ', $quota_id_list); + $quota_id_sql = implode(', ', $quota_id_list); - if ($quota_id_sql != '') - { - $sql = 'DELETE FROM ' . BB_QUOTA_LIMITS . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; + if ($quota_id_sql != '') { + $sql = 'DELETE FROM ' . BB_QUOTA_LIMITS . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete quota limits'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete quota limits'); + } - // Delete Quotas linked to this setting - $sql = 'DELETE FROM ' . BB_QUOTA . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; + // Delete Quotas linked to this setting + $sql = 'DELETE FROM ' . BB_QUOTA . ' WHERE quota_limit_id IN (' . $quota_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete quotas'); - } - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete quotas'); + } + } - // Add Quota Limit ? - $quota_desc = get_var('quota_description', ''); - $filesize = get_var('add_max_filesize', 0); - $size_select = get_var('add_size_select', ''); - $add = ( isset($_POST['add_quota_check']) ) ? TRUE : FALSE; + // Add Quota Limit ? + $quota_desc = get_var('quota_description', ''); + $filesize = get_var('add_max_filesize', 0); + $size_select = get_var('add_size_select', ''); + $add = (isset($_POST['add_quota_check'])) ? true : false; - if ($quota_desc != '' && $add) - { - // check Quota Description - $sql = 'SELECT quota_desc FROM ' . BB_QUOTA_LIMITS; + if ($quota_desc != '' && $add) { + // check Quota Description + $sql = 'SELECT quota_desc FROM ' . BB_QUOTA_LIMITS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ( $num_rows > 0 ) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($row[$i]['quota_desc'] == $quota_desc) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['QUOTA_LIMIT_EXIST'], $extension_group); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($row[$i]['quota_desc'] == $quota_desc) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['QUOTA_LIMIT_EXIST'], $extension_group); + } + } + } - if (!$error) - { - $filesize = ( $size_select == 'kb' ) ? round($filesize * 1024) : ( ($size_select == 'mb') ? round($filesize * 1048576) : $filesize ); + if (!$error) { + $filesize = ($size_select == 'kb') ? round($filesize * 1024) : (($size_select == 'mb') ? round($filesize * 1048576) : $filesize); - $sql = "INSERT INTO " . BB_QUOTA_LIMITS . " (quota_desc, quota_limit) - VALUES ('" . attach_mod_sql_escape($quota_desc) . "', " . (int) $filesize . ")"; + $sql = "INSERT INTO " . BB_QUOTA_LIMITS . " (quota_desc, quota_limit) + VALUES ('" . attach_mod_sql_escape($quota_desc) . "', " . (int)$filesize . ")"; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not add quota limit'); - } - } - - } - - if (!$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not add quota limit'); + } + } + } + if (!$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'quota') -{ - $max_add_filesize = $attach_config['max_filesize']; - $size = ($max_add_filesize >= 1048576) ? 'mb' : ( ($max_add_filesize >= 1024) ? 'kb' : 'b' ); +if ($mode == 'quota') { + $max_add_filesize = $attach_config['max_filesize']; + $size = ($max_add_filesize >= 1048576) ? 'mb' : (($max_add_filesize >= 1024) ? 'kb' : 'b'); - if ($max_add_filesize >= 1048576) - { - $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; - } - else if ( $max_add_filesize >= 1024) - { - $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; - } + if ($max_add_filesize >= 1048576) { + $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; + } elseif ($max_add_filesize >= 1024) { + $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; + } - $template->assign_vars(array( - 'TPL_ATTACH_QUOTA' => true, - 'MAX_FILESIZE' => $max_add_filesize, - 'S_FILESIZE' => size_select('add_size_select', $size), - 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=quota', - )); + $template->assign_vars(array( + 'TPL_ATTACH_QUOTA' => true, + 'MAX_FILESIZE' => $max_add_filesize, + 'S_FILESIZE' => size_select('add_size_select', $size), + 'S_ATTACH_ACTION' => 'admin_attachments.php?mode=quota', + )); - $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " ORDER BY quota_limit DESC"; + $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " ORDER BY quota_limit DESC"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #1'); + } - $rows = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($rows); $i++) - { - $size_format = ($rows[$i]['quota_limit'] >= 1048576) ? 'mb' : ( ($rows[$i]['quota_limit'] >= 1024) ? 'kb' : 'b' ); + for ($i = 0; $i < sizeof($rows); $i++) { + $size_format = ($rows[$i]['quota_limit'] >= 1048576) ? 'mb' : (($rows[$i]['quota_limit'] >= 1024) ? 'kb' : 'b'); - if ( $rows[$i]['quota_limit'] >= 1048576) - { - $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1048576 * 100) / 100; - } - else if($rows[$i]['quota_limit'] >= 1024) - { - $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1024 * 100) / 100; - } + if ($rows[$i]['quota_limit'] >= 1048576) { + $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1048576 * 100) / 100; + } elseif ($rows[$i]['quota_limit'] >= 1024) { + $rows[$i]['quota_limit'] = round($rows[$i]['quota_limit'] / 1024 * 100) / 100; + } - $template->assign_block_vars('limit_row', array( - 'QUOTA_NAME' => $rows[$i]['quota_desc'], - 'QUOTA_ID' => $rows[$i]['quota_limit_id'], - 'S_FILESIZE' => size_select('size_select_list[]', $size_format), - 'U_VIEW' => "admin_attachments.php?mode=$mode&e_mode=view_quota&quota_id=" . $rows[$i]['quota_limit_id'], - 'MAX_FILESIZE' => $rows[$i]['quota_limit'], - )); - } + $template->assign_block_vars('limit_row', array( + 'QUOTA_NAME' => $rows[$i]['quota_desc'], + 'QUOTA_ID' => $rows[$i]['quota_limit_id'], + 'S_FILESIZE' => size_select('size_select_list[]', $size_format), + 'U_VIEW' => "admin_attachments.php?mode=$mode&e_mode=view_quota&quota_id=" . $rows[$i]['quota_limit_id'], + 'MAX_FILESIZE' => $rows[$i]['quota_limit'], + )); + } } -if ($mode == 'quota' && $e_mode == 'view_quota') -{ - $quota_id = get_var('quota_id', 0); +if ($mode == 'quota' && $e_mode == 'view_quota') { + $quota_id = get_var('quota_id', 0); - if (!$quota_id) - { - bb_die('Invalid call'); - } + if (!$quota_id) { + bb_die('Invalid call'); + } - $template->assign_block_vars('switch_quota_limit_desc', array()); + $template->assign_block_vars('switch_quota_limit_desc', array()); - $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " WHERE quota_limit_id = " . (int) $quota_id . " LIMIT 1"; + $sql = "SELECT * FROM " . BB_QUOTA_LIMITS . " WHERE quota_limit_id = " . (int)$quota_id . " LIMIT 1"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #2'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $template->assign_vars(array( - 'L_QUOTA_LIMIT_DESC' => $row['quota_desc'], - )); + $template->assign_vars(array( + 'L_QUOTA_LIMIT_DESC' => $row['quota_desc'], + )); - $sql = 'SELECT q.user_id, u.username, q.quota_type + $sql = 'SELECT q.user_id, u.username, q.quota_type FROM ' . BB_QUOTA . ' q, ' . BB_USERS . ' u - WHERE q.quota_limit_id = ' . (int) $quota_id . ' + WHERE q.quota_limit_id = ' . (int)$quota_id . ' AND q.user_id <> 0 AND q.user_id = u.user_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #3'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $template->assign_block_vars('users_upload_row', array( - 'USER_ID' => $rows[$i]['user_id'], - 'USERNAME' => $rows[$i]['username'], - )); - } - else if ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) - { - $template->assign_block_vars('users_pm_row', array( - 'USER_ID' => $rows[$i]['user_id'], - 'USERNAME' => $rows[$i]['username'], - )); - } - } + for ($i = 0; $i < $num_rows; $i++) { + if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $template->assign_block_vars('users_upload_row', array( + 'USER_ID' => $rows[$i]['user_id'], + 'USERNAME' => $rows[$i]['username'], + )); + } elseif ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) { + $template->assign_block_vars('users_pm_row', array( + 'USER_ID' => $rows[$i]['user_id'], + 'USERNAME' => $rows[$i]['username'], + )); + } + } - $sql = 'SELECT q.group_id, g.group_name, q.quota_type + $sql = 'SELECT q.group_id, g.group_name, q.quota_type FROM ' . BB_QUOTA . ' q, ' . BB_GROUPS . ' g - WHERE q.quota_limit_id = ' . (int) $quota_id . ' + WHERE q.quota_limit_id = ' . (int)$quota_id . ' AND q.group_id <> 0 AND q.group_id = g.group_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get quota limits #4'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get quota limits #4'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_rows; $i++) - { - if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $template->assign_block_vars('groups_upload_row', array( - 'GROUP_ID' => $rows[$i]['group_id'], - 'GROUPNAME' => $rows[$i]['group_name'], - )); - } - else if ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) - { - $template->assign_block_vars('groups_pm_row', array( - 'GROUP_ID' => $rows[$i]['group_id'], - 'GROUPNAME' => $rows[$i]['group_name'], - )); - } - } + for ($i = 0; $i < $num_rows; $i++) { + if ($rows[$i]['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $template->assign_block_vars('groups_upload_row', array( + 'GROUP_ID' => $rows[$i]['group_id'], + 'GROUPNAME' => $rows[$i]['group_name'], + )); + } elseif ($rows[$i]['quota_type'] == QUOTA_PM_LIMIT) { + $template->assign_block_vars('groups_pm_row', array( + 'GROUP_ID' => $rows[$i]['group_id'], + 'GROUPNAME' => $rows[$i]['group_name'], + )); + } + } } -if ($error) -{ - $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); +if ($error) { + $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); } -print_page('admin_attachments.tpl', 'admin'); \ No newline at end of file +print_page('admin_attachments.tpl', 'admin'); diff --git a/admin/admin_board.php b/admin/admin_board.php index a709f7a34..93785a036 100644 --- a/admin/admin_board.php +++ b/admin/admin_board.php @@ -1,149 +1,166 @@ '

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''), - 'config' => '

'. sprintf($lang['CLICK_RETURN_CONFIG'], '', ''), - 'config_mods' => '

'. sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '', '') + 'index' => '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''), + 'config' => '

' . sprintf($lang['CLICK_RETURN_CONFIG'], '', ''), + 'config_mods' => '

' . sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '', '') ); // // Pull all config data // $sql = "SELECT * FROM " . BB_CONFIG; -if (!$result = DB()->sql_query($sql)) -{ - bb_die('Could not query config information in admin_board'); -} -else -{ - while ($row = DB()->sql_fetchrow($result)) - { - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query config information in admin_board'); +} else { + while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; + $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - if ($config_name == 'seed_bonus_points' || $config_name == 'seed_bonus_release' || $config_name == 'bonus_upload' || $config_name == 'bonus_upload_price') $new[$config_name] = serialize(str_replace(',', '.', $new[$config_name])); - bb_update_config(array($config_name => $new[$config_name])); - } - } + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + if ($config_name == 'seed_bonus_points' || $config_name == 'seed_bonus_release' || $config_name == 'bonus_upload' || $config_name == 'bonus_upload_price') { + $new[$config_name] = serialize(str_replace(',', '.', $new[$config_name])); + } + bb_update_config(array($config_name => $new[$config_name])); + } + } - if (isset($_POST['submit'])) - { - bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']); - } + if (isset($_POST['submit'])) { + bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']); + } } -switch ($mode) -{ - case 'config_mods': - $template->assign_vars(array( - 'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods', - 'CONFIG_MODS' => true, +switch ($mode) { + case 'config_mods': + $template->assign_vars(array( + 'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods', + 'CONFIG_MODS' => true, - 'MAGNET_LINKS_ENABLED' => $new['magnet_links_enabled'], - 'GENDER' => $new['gender'], - 'CALLSEED' => $new['callseed'], - 'TOR_STATS' => $new['tor_stats'], - 'SHOW_LATEST_NEWS' => $new['show_latest_news'], - 'MAX_NEWS_TITLE' => $new['max_news_title'], - 'LATEST_NEWS_COUNT' => $new['latest_news_count'], - 'LATEST_NEWS_FORUM_ID' => $new['latest_news_forum_id'], - 'SHOW_NETWORK_NEWS' => $new['show_network_news'], - 'MAX_NET_TITLE' => $new['max_net_title'], - 'NETWORK_NEWS_COUNT' => $new['network_news_count'], - 'NETWORK_NEWS_FORUM_ID' => $new['network_news_forum_id'], - 'WHOIS_INFO' => $new['whois_info'], - 'SHOW_MOD_INDEX' => $new['show_mod_index'], - 'BIRTHDAY_ENABLED' => $new['birthday_enabled'], - 'BIRTHDAY_MAX_AGE' => $new['birthday_max_age'], - 'BIRTHDAY_MIN_AGE' => $new['birthday_min_age'], - 'BIRTHDAY_CHECK_DAY' => $new['birthday_check_day'], - 'PREMOD' => $new['premod'], - 'TOR_COMMENT' => $new['tor_comment'], - 'NEW_TPLS' => $new['new_tpls'], - 'SEED_BONUS_ENABLED' => $new['seed_bonus_enabled'], - 'SEED_BONUS_TOR_SIZE' => $new['seed_bonus_tor_size'], - 'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'], - )); + 'MAGNET_LINKS_ENABLED' => $new['magnet_links_enabled'], + 'GENDER' => $new['gender'], + 'CALLSEED' => $new['callseed'], + 'TOR_STATS' => $new['tor_stats'], + 'SHOW_LATEST_NEWS' => $new['show_latest_news'], + 'MAX_NEWS_TITLE' => $new['max_news_title'], + 'LATEST_NEWS_COUNT' => $new['latest_news_count'], + 'LATEST_NEWS_FORUM_ID' => $new['latest_news_forum_id'], + 'SHOW_NETWORK_NEWS' => $new['show_network_news'], + 'MAX_NET_TITLE' => $new['max_net_title'], + 'NETWORK_NEWS_COUNT' => $new['network_news_count'], + 'NETWORK_NEWS_FORUM_ID' => $new['network_news_forum_id'], + 'WHOIS_INFO' => $new['whois_info'], + 'SHOW_MOD_INDEX' => $new['show_mod_index'], + 'BIRTHDAY_ENABLED' => $new['birthday_enabled'], + 'BIRTHDAY_MAX_AGE' => $new['birthday_max_age'], + 'BIRTHDAY_MIN_AGE' => $new['birthday_min_age'], + 'BIRTHDAY_CHECK_DAY' => $new['birthday_check_day'], + 'PREMOD' => $new['premod'], + 'TOR_COMMENT' => $new['tor_comment'], + 'NEW_TPLS' => $new['new_tpls'], + 'SEED_BONUS_ENABLED' => $new['seed_bonus_enabled'], + 'SEED_BONUS_TOR_SIZE' => $new['seed_bonus_tor_size'], + 'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'], + )); - if ($new['seed_bonus_points'] && $new['seed_bonus_release']) - { - $seed_bonus = unserialize($new['seed_bonus_points']); - $seed_release = unserialize($new['seed_bonus_release']); + if ($new['seed_bonus_points'] && $new['seed_bonus_release']) { + $seed_bonus = unserialize($new['seed_bonus_points']); + $seed_release = unserialize($new['seed_bonus_release']); - foreach ($seed_bonus as $i => $row) - { - if (!$row || !$seed_release[$i]) continue; + foreach ($seed_bonus as $i => $row) { + if (!$row || !$seed_release[$i]) { + continue; + } - $template->assign_block_vars('seed_bonus', array( - 'RELEASE' => $seed_release[$i], - 'POINTS' => $row, - )); - } - } + $template->assign_block_vars('seed_bonus', array( + 'RELEASE' => $seed_release[$i], + 'POINTS' => $row, + )); + } + } - if ($new['bonus_upload'] && $new['bonus_upload_price']) - { - $upload_row = unserialize($new['bonus_upload']); - $price_row = unserialize($new['bonus_upload_price']); + if ($new['bonus_upload'] && $new['bonus_upload_price']) { + $upload_row = unserialize($new['bonus_upload']); + $price_row = unserialize($new['bonus_upload_price']); - foreach ($upload_row as $i => $row) - { - if (!$row || !$price_row[$i]) continue; + foreach ($upload_row as $i => $row) { + if (!$row || !$price_row[$i]) { + continue; + } - $template->assign_block_vars('bonus_upload', array( - 'UP' => $row, - 'PRICE' => $price_row[$i], - )); - } - } - break; + $template->assign_block_vars('bonus_upload', array( + 'UP' => $row, + 'PRICE' => $price_row[$i], + )); + } + } + break; - default: - $template->assign_vars(array( - 'S_CONFIG_ACTION' => 'admin_board.php?mode=config', - 'CONFIG' => true, + default: + $template->assign_vars(array( + 'S_CONFIG_ACTION' => 'admin_board.php?mode=config', + 'CONFIG' => true, - 'SITENAME' => htmlCHR($new['sitename']), - 'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']), - 'DISABLE_BOARD' => ($new['board_disable']) ? true : false, - 'ALLOW_AUTOLOGIN' => ($new['allow_autologin']) ? true : false, - 'AUTOLOGIN_TIME' => (int) $new['max_autologin_time'], - 'MAX_POLL_OPTIONS' => $new['max_poll_options'], - 'FLOOD_INTERVAL' => $new['flood_interval'], - 'TOPICS_PER_PAGE' => $new['topics_per_page'], - 'POSTS_PER_PAGE' => $new['posts_per_page'], - 'HOT_TOPIC' => $new['hot_threshold'], - 'DEFAULT_DATEFORMAT' => $new['default_dateformat'], - 'LANG_SELECT' => language_select($new['default_lang'], 'default_lang'), - 'TIMEZONE_SELECT' => tz_select($new['board_timezone'], 'board_timezone'), - 'MAX_LOGIN_ATTEMPTS' => $new['max_login_attempts'], - 'LOGIN_RESET_TIME' => $new['login_reset_time'], - 'PRUNE_ENABLE' => ($new['prune_enable']) ? true : false, - 'ALLOW_BBCODE' => ($new['allow_bbcode']) ? true : false, - 'ALLOW_SMILIES' => ($new['allow_smilies']) ? true : false, - 'ALLOW_SIG' => ($new['allow_sig']) ? true : false, - 'SIG_SIZE' => $new['max_sig_chars'], - 'ALLOW_NAMECHANGE' => ($new['allow_namechange']) ? true : false, - 'SMILIES_PATH' => $new['smilies_path'], - )); - break; + 'SITENAME' => htmlCHR($new['sitename']), + 'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']), + 'DISABLE_BOARD' => ($new['board_disable']) ? true : false, + 'ALLOW_AUTOLOGIN' => ($new['allow_autologin']) ? true : false, + 'AUTOLOGIN_TIME' => (int)$new['max_autologin_time'], + 'MAX_POLL_OPTIONS' => $new['max_poll_options'], + 'FLOOD_INTERVAL' => $new['flood_interval'], + 'TOPICS_PER_PAGE' => $new['topics_per_page'], + 'POSTS_PER_PAGE' => $new['posts_per_page'], + 'HOT_TOPIC' => $new['hot_threshold'], + 'DEFAULT_DATEFORMAT' => $new['default_dateformat'], + 'LANG_SELECT' => language_select($new['default_lang'], 'default_lang'), + 'TIMEZONE_SELECT' => tz_select($new['board_timezone'], 'board_timezone'), + 'MAX_LOGIN_ATTEMPTS' => $new['max_login_attempts'], + 'LOGIN_RESET_TIME' => $new['login_reset_time'], + 'PRUNE_ENABLE' => ($new['prune_enable']) ? true : false, + 'ALLOW_BBCODE' => ($new['allow_bbcode']) ? true : false, + 'ALLOW_SMILIES' => ($new['allow_smilies']) ? true : false, + 'ALLOW_SIG' => ($new['allow_sig']) ? true : false, + 'SIG_SIZE' => $new['max_sig_chars'], + 'ALLOW_NAMECHANGE' => ($new['allow_namechange']) ? true : false, + 'SMILIES_PATH' => $new['smilies_path'], + )); + break; } -print_page('admin_board.tpl', 'admin'); \ No newline at end of file +print_page('admin_board.tpl', 'admin'); diff --git a/admin/admin_bt_forum_cfg.php b/admin/admin_bt_forum_cfg.php index ba06b1382..aa34d4b9b 100644 --- a/admin/admin_bt_forum_cfg.php +++ b/admin/admin_bt_forum_cfg.php @@ -1,150 +1,165 @@ 'http://demo.torrentpier.me/bt/', + 'bt_announce_url' => 'http://demo.torrentpier.me/bt/', ); $default_cfg_bool = array( - 'bt_disable_dht' => 1, - 'bt_show_peers' => 1, - 'bt_add_auth_key' => 1, - 'bt_show_dl_list' => 0, - 'bt_dl_list_only_1st_page' => 1, - 'bt_dl_list_only_count' => 1, - 'bt_replace_ann_url' => 1, - 'bt_show_ip_only_moder' => 1, - 'bt_show_port_only_moder' => 1, - 'bt_check_announce_url' => 0, - 'bt_show_dl_list_buttons' => 1, - 'bt_show_dl_but_will' => 1, - 'bt_show_dl_but_down' => 0, - 'bt_show_dl_but_compl' => 1, - 'bt_show_dl_but_cancel' => 1, - 'bt_show_dl_stat_on_index' => 1, - 'bt_newtopic_auto_reg' => 1, - 'bt_tor_browse_only_reg' => 1, - 'bt_search_bool_mode' => 1, - 'bt_allow_spmode_change' => 1, - 'bt_del_addit_ann_urls' => 1, - 'bt_set_dltype_on_tor_reg' => 1, - 'bt_unset_dltype_on_tor_unreg' => 1, + 'bt_disable_dht' => 1, + 'bt_show_peers' => 1, + 'bt_add_auth_key' => 1, + 'bt_show_dl_list' => 0, + 'bt_dl_list_only_1st_page' => 1, + 'bt_dl_list_only_count' => 1, + 'bt_replace_ann_url' => 1, + 'bt_show_ip_only_moder' => 1, + 'bt_show_port_only_moder' => 1, + 'bt_check_announce_url' => 0, + 'bt_show_dl_list_buttons' => 1, + 'bt_show_dl_but_will' => 1, + 'bt_show_dl_but_down' => 0, + 'bt_show_dl_but_compl' => 1, + 'bt_show_dl_but_cancel' => 1, + 'bt_show_dl_stat_on_index' => 1, + 'bt_newtopic_auto_reg' => 1, + 'bt_tor_browse_only_reg' => 1, + 'bt_search_bool_mode' => 1, + 'bt_allow_spmode_change' => 1, + 'bt_del_addit_ann_urls' => 1, + 'bt_set_dltype_on_tor_reg' => 1, + 'bt_unset_dltype_on_tor_unreg' => 1, ); $default_cfg_num = array( - 'bt_show_peers_mode' => SHOW_PEERS_COUNT, + 'bt_show_peers_mode' => SHOW_PEERS_COUNT, ); $default_cfg = array_merge($default_cfg_str, $default_cfg_bool, $default_cfg_num); $db_fields_bool = array( - 'allow_reg_tracker' => 0, // Allowed forums for registering torrents on tracker - 'allow_porno_topic' => 0, // Allowed forums for porno topics - 'self_moderated' => 0, // Users can move theirs topic to another forum + 'allow_reg_tracker' => 0, // Allowed forums for registering torrents on tracker + 'allow_porno_topic' => 0, // Allowed forums for porno topics + 'self_moderated' => 0, // Users can move theirs topic to another forum ); // Get config $cfg = bb_get_config(BB_CONFIG, true, false); // Submit new config -if ($submit && $confirm) -{ - foreach ($db_fields_bool as $field_name => $field_def_val) - { - update_table_bool(BB_FORUMS, 'forum_id', $field_name, $field_def_val); - } +if ($submit && $confirm) { + foreach ($db_fields_bool as $field_name => $field_def_val) { + update_table_bool(BB_FORUMS, 'forum_id', $field_name, $field_def_val); + } - update_config_table(BB_CONFIG, $default_cfg_str, $cfg, 'str'); - update_config_table(BB_CONFIG, $default_cfg_bool, $cfg, 'bool'); - update_config_table(BB_CONFIG, $default_cfg_num, $cfg, 'num'); + update_config_table(BB_CONFIG, $default_cfg_str, $cfg, 'str'); + update_config_table(BB_CONFIG, $default_cfg_bool, $cfg, 'bool'); + update_config_table(BB_CONFIG, $default_cfg_num, $cfg, 'num'); - $datastore->update('cat_forums'); + $datastore->update('cat_forums'); - bb_die($lang['CONFIG_UPD'] .'

'. sprintf($lang['RETURN_CONFIG'], '', '') .'

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['CONFIG_UPD'] . '

' . sprintf($lang['RETURN_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); } // Set template vars -set_tpl_vars ($default_cfg_str, $cfg); -set_tpl_vars_lang ($default_cfg_str); +set_tpl_vars($default_cfg_str, $cfg); +set_tpl_vars_lang($default_cfg_str); -set_tpl_vars_bool ($default_cfg_bool, $cfg); -set_tpl_vars_lang ($default_cfg_bool); +set_tpl_vars_bool($default_cfg_bool, $cfg); +set_tpl_vars_lang($default_cfg_bool); -set_tpl_vars ($default_cfg_num, $cfg); -set_tpl_vars_lang ($default_cfg_num); +set_tpl_vars($default_cfg_num, $cfg); +set_tpl_vars_lang($default_cfg_num); -set_tpl_vars_lang ($db_fields_bool); +set_tpl_vars_lang($db_fields_bool); // Get Forums list $sql = "SELECT f.* - FROM ". BB_CATEGORIES ." c, ". BB_FORUMS ." f + FROM " . BB_CATEGORIES . " c, " . BB_FORUMS . " f WHERE f.cat_id = c.cat_id ORDER BY c.cat_order, f.forum_order"; -if (!$result = DB()->sql_query($sql)) -{ - bb_die('Could not obtain forum names'); +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain forum names'); } $rowset = DB()->sql_fetchrowset($result); $forum_rows = min($max_forum_rows, count($rowset)); -foreach ($db_fields_bool as $field_name => $field_def_val) -{ - $$field_name = ''; +foreach ($db_fields_bool as $field_name => $field_def_val) { + $$field_name = ''; } -foreach ($rowset as $rid => $forum) -{ - foreach ($db_fields_bool as $field_name => $field_def_val) - { - $forum_name = $forum['forum_name']; - $selected = ($forum[$field_name]) ? ' selected="selected"' : ''; +foreach ($rowset as $rid => $forum) { + foreach ($db_fields_bool as $field_name => $field_def_val) { + $forum_name = $forum['forum_name']; + $selected = ($forum[$field_name]) ? ' selected="selected"' : ''; - $forum_name = str_short($forum_name, $max_forum_name_len); + $forum_name = str_short($forum_name, $max_forum_name_len); - $$field_name .= '\n"; - } + $$field_name .= '\n"; + } } -foreach ($db_fields_bool as $field_name => $field_def_val) -{ - $$field_name = ''; - $template->assign_vars(array('S_'. strtoupper($field_name) => $$field_name)); +foreach ($db_fields_bool as $field_name => $field_def_val) { + $$field_name = ''; + $template->assign_vars(array('S_' . strtoupper($field_name) => $$field_name)); } $template->assign_vars(array( - 'L_BT_SHOW_PEERS_MODE_COUNT' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? ''. $lang['BT_SHOW_PEERS_MODE_COUNT'] .'' : $lang['BT_SHOW_PEERS_MODE_COUNT'], - 'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? ''. $lang['BT_SHOW_PEERS_MODE_NAMES'] .'' : $lang['BT_SHOW_PEERS_MODE_NAMES'], - 'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? ''. $lang['BT_SHOW_PEERS_MODE_FULL'] .'' : $lang['BT_SHOW_PEERS_MODE_FULL'], + 'L_BT_SHOW_PEERS_MODE_COUNT' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? '' . $lang['BT_SHOW_PEERS_MODE_COUNT'] . '' : $lang['BT_SHOW_PEERS_MODE_COUNT'], + 'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? '' . $lang['BT_SHOW_PEERS_MODE_NAMES'] . '' : $lang['BT_SHOW_PEERS_MODE_NAMES'], + 'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? '' . $lang['BT_SHOW_PEERS_MODE_FULL'] . '' : $lang['BT_SHOW_PEERS_MODE_FULL'], - 'BT_SHOW_PEERS_MODE_COUNT_VAL' => SHOW_PEERS_COUNT, - 'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES, - 'BT_SHOW_PEERS_MODE_FULL_VAL' => SHOW_PEERS_FULL, + 'BT_SHOW_PEERS_MODE_COUNT_VAL' => SHOW_PEERS_COUNT, + 'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES, + 'BT_SHOW_PEERS_MODE_FULL_VAL' => SHOW_PEERS_FULL, - 'BT_SHOW_PEERS_MODE_COUNT_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? HTML_CHECKED : '', - 'BT_SHOW_PEERS_MODE_NAMES_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? HTML_CHECKED : '', - 'BT_SHOW_PEERS_MODE_FULL_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_COUNT_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_NAMES_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? HTML_CHECKED : '', + 'BT_SHOW_PEERS_MODE_FULL_SEL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? HTML_CHECKED : '', - 'S_HIDDEN_FIELDS' => '', - 'S_CONFIG_ACTION' => 'admin_bt_forum_cfg.php', + 'S_HIDDEN_FIELDS' => '', + 'S_CONFIG_ACTION' => 'admin_bt_forum_cfg.php', )); -print_page('admin_bt_forum_cfg.tpl', 'admin'); \ No newline at end of file +print_page('admin_bt_forum_cfg.tpl', 'admin'); diff --git a/admin/admin_bt_tracker_cfg.php b/admin/admin_bt_tracker_cfg.php index 9406a5b89..d0f7c56af 100644 --- a/admin/admin_bt_tracker_cfg.php +++ b/admin/admin_bt_tracker_cfg.php @@ -1,64 +1,90 @@ 'Tracker is disabled', - 'browser_redirect_url' => 'http://demo.torrentpier.me/', + 'off_reason' => 'Tracker is disabled', + 'browser_redirect_url' => 'http://demo.torrentpier.me/', ); $default_cfg_bool = array( - 'autoclean' => 1, - 'off' => 0, - 'compact_mode' => 1, - 'update_dlstat' => 1, - 'limit_active_tor' => 0, - 'limit_concurrent_ips' => 0, - 'retracker' => 1, + 'autoclean' => 1, + 'off' => 0, + 'compact_mode' => 1, + 'update_dlstat' => 1, + 'limit_active_tor' => 0, + 'limit_concurrent_ips' => 0, + 'retracker' => 1, ); $default_cfg_num = array( - 'numwant' => 50, - 'expire_factor' => 4, - 'limit_seed_count' => 20, - 'limit_leech_count' => 4, - 'leech_expire_factor' => 60, - 'limit_seed_ips' => 0, - 'limit_leech_ips' => 0, + 'numwant' => 50, + 'expire_factor' => 4, + 'limit_seed_count' => 20, + 'limit_leech_count' => 4, + 'leech_expire_factor' => 60, + 'limit_seed_ips' => 0, + 'limit_leech_ips' => 0, ); // Set template vars -set_tpl_vars ($default_cfg_str, $tr_cfg); -set_tpl_vars_lang ($default_cfg_str); +set_tpl_vars($default_cfg_str, $tr_cfg); +set_tpl_vars_lang($default_cfg_str); -set_tpl_vars_bool ($default_cfg_bool, $tr_cfg); -set_tpl_vars_lang ($default_cfg_bool); +set_tpl_vars_bool($default_cfg_bool, $tr_cfg); +set_tpl_vars_lang($default_cfg_bool); -set_tpl_vars ($default_cfg_num, $tr_cfg); -set_tpl_vars_lang ($default_cfg_num); +set_tpl_vars($default_cfg_num, $tr_cfg); +set_tpl_vars_lang($default_cfg_num); $template->assign_vars(array( - 'IGNORE_REPORTED_IP' => $bb_cfg['ignore_reported_ip'], - 'ANNOUNCE_INTERVAL' => $bb_cfg['announce_interval'], - 'PASSKEY_KEY' => $bb_cfg['passkey_key'], - 'GOLD_SILVER_ENABLED' => $tr_cfg['gold_silver_enabled'], - 'DISABLE_SUBMIT' => true, + 'IGNORE_REPORTED_IP' => $bb_cfg['ignore_reported_ip'], + 'ANNOUNCE_INTERVAL' => $bb_cfg['announce_interval'], + 'PASSKEY_KEY' => $bb_cfg['passkey_key'], + 'GOLD_SILVER_ENABLED' => $tr_cfg['gold_silver_enabled'], + 'DISABLE_SUBMIT' => true, - 'S_HIDDEN_FIELDS' => '', - 'S_CONFIG_ACTION' => 'admin_bt_tracker_cfg.php', + 'S_HIDDEN_FIELDS' => '', + 'S_CONFIG_ACTION' => 'admin_bt_tracker_cfg.php', )); -print_page('admin_bt_tracker_cfg.tpl', 'admin'); \ No newline at end of file +print_page('admin_bt_tracker_cfg.tpl', 'admin'); diff --git a/admin/admin_cron.php b/admin/admin_cron.php index 7999137c4..205f4a933 100644 --- a/admin/admin_cron.php +++ b/admin/admin_cron.php @@ -1,228 +1,230 @@ session_start(); - redirect('admin/'.basename(__FILE__) . '?mode=list'); +if ($mode == 'run' && !$job_id) { + define('BB_ROOT', './../'); + require(BB_ROOT . 'common.php'); + $user->session_start(); + redirect('admin/' . basename(__FILE__) . '?mode=list'); +} else { + require('./pagestart.php'); } -else require('./pagestart.php'); -if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['NOT_ADMIN']); +} -require(INC_DIR .'functions_admin_torrent.php'); -require(INC_DIR .'functions_admin_cron.php'); +require(INC_DIR . 'functions_admin_torrent.php'); +require(INC_DIR . 'functions_admin_cron.php'); -$sql = DB()->fetch_rowset("SELECT * FROM ". BB_CONFIG ." WHERE config_name = 'cron_enabled' OR config_name = 'cron_check_interval'"); +$sql = DB()->fetch_rowset("SELECT * FROM " . BB_CONFIG . " WHERE config_name = 'cron_enabled' OR config_name = 'cron_check_interval'"); -foreach ($sql as $row) -{ - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; +foreach ($sql as $row) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; + $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - bb_update_config(array($config_name => $new[$config_name])); - } + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + bb_update_config(array($config_name => $new[$config_name])); + } } $template->assign_vars(array( - 'CRON_ENABLED' => ($new['cron_enabled']) ? true : false, - 'CRON_CHECK_INTERVAL' => $new['cron_check_interval'], + 'CRON_ENABLED' => ($new['cron_enabled']) ? true : false, + 'CRON_CHECK_INTERVAL' => $new['cron_check_interval'], )); -switch ($mode) -{ - case 'list': - $sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." ORDER BY cron_id"); +switch ($mode) { + case 'list': + $sql = DB()->fetch_rowset("SELECT * FROM " . BB_CRON . " ORDER BY cron_id"); - foreach ($sql as $i => $row) - { - $template->assign_block_vars('list', array( - 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', - 'JOB_ID' => $i + 1, - 'CRON_ID' => $row['cron_id'], - 'CRON_ACTIVE' => $row['cron_active'] ? ''. $lang['YES'] .'' : ''. $lang['NO'] .'', - 'CRON_TITLE' => $row['cron_title'], - 'CRON_SCRIPT' => $row['cron_script'], - 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : ''. $lang['NOSELECT'] .'', - 'RUN_DAY' => $row['run_day'], - 'LAST_RUN' => $row['last_run'], - 'NEXT_RUN' => $row['next_run'], - 'RUN_COUNT' => $row['run_counter'], - )); - } + foreach ($sql as $i => $row) { + $template->assign_block_vars('list', array( + 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', + 'JOB_ID' => $i + 1, + 'CRON_ID' => $row['cron_id'], + 'CRON_ACTIVE' => $row['cron_active'] ? '' . $lang['YES'] . '' : '' . $lang['NO'] . '', + 'CRON_TITLE' => $row['cron_title'], + 'CRON_SCRIPT' => $row['cron_script'], + 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '' . $lang['NOSELECT'] . '', + 'RUN_DAY' => $row['run_day'], + 'LAST_RUN' => $row['last_run'], + 'NEXT_RUN' => $row['next_run'], + 'RUN_COUNT' => $row['run_counter'], + )); + } - $template->assign_vars(array( - 'TPL_CRON_LIST' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'list', - )); + $template->assign_vars(array( + 'TPL_CRON_LIST' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'list', + )); - //detect cron status - if (@file_exists('../triggers/cron_running')) - { - $template->assign_vars(array( - 'CRON_RUNNING' => true, - )); - } - break; + //detect cron status + if (@file_exists('../triggers/cron_running')) { + $template->assign_vars(array( + 'CRON_RUNNING' => true, + )); + } + break; - case 'repair': - if (@file_exists('../triggers/cron_running')) - { - rename("../triggers/cron_running", "../triggers/cron_allowed"); - } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - break; + case 'repair': + if (@file_exists('../triggers/cron_running')) { + rename("../triggers/cron_running", "../triggers/cron_allowed"); + } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + break; - case 'run': - run_jobs($job_id); - redirect('admin/'.basename(__FILE__) . '?mode=list'); - break; + case 'run': + run_jobs($job_id); + redirect('admin/' . basename(__FILE__) . '?mode=list'); + break; - case 'edit': - $sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." WHERE cron_id = $job_id"); + case 'edit': + $sql = DB()->fetch_rowset("SELECT * FROM " . BB_CRON . " WHERE cron_id = $job_id"); - foreach ($sql as $row) - { - $template->assign_vars(array( - 'CRON_ID' => $row['cron_id'], - 'CRON_ACTIVE' => $row['cron_active'], - 'CRON_TITLE' => $row['cron_title'], - 'CRON_SCRIPT' => $row['cron_script'], - 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '', - 'RUN_DAY' => $row['run_day'], - 'RUN_TIME' => $row['run_time'], - 'RUN_ORDER' => $row['run_order'], - 'LAST_RUN' => $row['last_run'], - 'NEXT_RUN' => $row['next_run'], - 'RUN_INTERVAL' => $row['run_interval'], - 'LOG_ENABLED' => $row['log_enabled'], - 'LOG_FILE' => $row['log_file'], - 'LOG_SQL_QUERIES' => $row['log_sql_queries'], - 'DISABLE_BOARD' => $row['disable_board'], - 'RUN_COUNTER' => $row['run_counter'], - )); - } + foreach ($sql as $row) { + $template->assign_vars(array( + 'CRON_ID' => $row['cron_id'], + 'CRON_ACTIVE' => $row['cron_active'], + 'CRON_TITLE' => $row['cron_title'], + 'CRON_SCRIPT' => $row['cron_script'], + 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '', + 'RUN_DAY' => $row['run_day'], + 'RUN_TIME' => $row['run_time'], + 'RUN_ORDER' => $row['run_order'], + 'LAST_RUN' => $row['last_run'], + 'NEXT_RUN' => $row['next_run'], + 'RUN_INTERVAL' => $row['run_interval'], + 'LOG_ENABLED' => $row['log_enabled'], + 'LOG_FILE' => $row['log_file'], + 'LOG_SQL_QUERIES' => $row['log_sql_queries'], + 'DISABLE_BOARD' => $row['disable_board'], + 'RUN_COUNTER' => $row['run_counter'], + )); + } - $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); - for ($i = 1; $i <= 28; $i++) - { - $run_day[$i] = $i; - } + $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); + for ($i = 1; $i <= 28; $i++) { + $run_day[$i] = $i; + } - $schedule = array($lang['SCHEDULE']['select'] => 0); - foreach ($lang['SCHEDULE'] as $type => $key) - { - $schedule[$key] = $type; - } + $schedule = array($lang['SCHEDULE']['select'] => 0); + foreach ($lang['SCHEDULE'] as $type => $key) { + $schedule[$key] = $type; + } - $template->assign_vars(array( - 'TPL_CRON_EDIT' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'edit', - 'SCHEDULE' => build_select('schedule', $schedule, $row['schedule']), - 'RUN_DAY' => build_select('run_day', $run_day, $row['run_day']), - 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_EDIT'], - )); - break; + $template->assign_vars(array( + 'TPL_CRON_EDIT' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'edit', + 'SCHEDULE' => build_select('schedule', $schedule, $row['schedule']), + 'RUN_DAY' => build_select('run_day', $run_day, $row['run_day']), + 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_EDIT'], + )); + break; - case 'add': - $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); - for ($i = 1; $i <= 28; $i++) - { - $run_day[$i] = $i; - } + case 'add': + $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); + for ($i = 1; $i <= 28; $i++) { + $run_day[$i] = $i; + } - $schedule = array(); - foreach ($lang['SCHEDULE'] as $type => $key) - { - $schedule[$key] = $type; - } + $schedule = array(); + foreach ($lang['SCHEDULE'] as $type => $key) { + $schedule[$key] = $type; + } - $template->assign_vars(array( - 'TPL_CRON_EDIT' => true, - 'S_CRON_ACTION' => 'admin_cron.php', - 'S_MODE' => 'add', - 'SCHEDULE' => build_select('schedule', $schedule, 'select', null, null), - 'RUN_DAY' => build_select('run_day', $run_day, 0, null, null), - 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_ADD'], - 'CRON_ID' => 'none', - 'CRON_ACTIVE' => 1, - 'CRON_TITLE' => '', - 'CRON_SCRIPT' => '', - 'RUN_TIME' => '', - 'RUN_ORDER' => 255, - 'LAST_RUN' => '0000-00-00 00:00:00', - 'NEXT_RUN' => '0000-00-00 00:00:00', - 'RUN_INTERVAL' => '', - 'LOG_ENABLED' => 0, - 'LOG_FILE' => '', - 'LOG_SQL_QUERIES' => 0, - 'DISABLE_BOARD' => 0, - 'RUN_COUNTER' => 0, - )); - break; + $template->assign_vars(array( + 'TPL_CRON_EDIT' => true, + 'S_CRON_ACTION' => 'admin_cron.php', + 'S_MODE' => 'add', + 'SCHEDULE' => build_select('schedule', $schedule, 'select', null, null), + 'RUN_DAY' => build_select('run_day', $run_day, 0, null, null), + 'L_CRON_EDIT_HEAD' => $lang['CRON_EDIT_HEAD_ADD'], + 'CRON_ID' => 'none', + 'CRON_ACTIVE' => 1, + 'CRON_TITLE' => '', + 'CRON_SCRIPT' => '', + 'RUN_TIME' => '', + 'RUN_ORDER' => 255, + 'LAST_RUN' => '0000-00-00 00:00:00', + 'NEXT_RUN' => '0000-00-00 00:00:00', + 'RUN_INTERVAL' => '', + 'LOG_ENABLED' => 0, + 'LOG_FILE' => '', + 'LOG_SQL_QUERIES' => 0, + 'DISABLE_BOARD' => 0, + 'RUN_COUNTER' => 0, + )); + break; - case 'delete': - delete_jobs($job_id); - bb_die($lang['JOB_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_JOBS'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + case 'delete': + delete_jobs($job_id); + bb_die($lang['JOB_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_JOBS'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; } -if ($submit) -{ - if ($_POST['mode'] == 'list') - { - if ($cron_action == 'run' && $jobs) - { - run_jobs($jobs); - } - else if ($cron_action == 'delete' && $jobs) - { - delete_jobs($jobs); - } - else if (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) - { - toggle_active($jobs, $cron_action); - } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - } - else if (validate_cron_post($_POST) == 1) - { - if ($_POST['mode'] == 'edit') - { - update_cron_job($_POST); - } - else if ($_POST['mode'] == 'add') - { - insert_cron_job($_POST); - } - else bb_die('Mode error'); +if ($submit) { + if ($_POST['mode'] == 'list') { + if ($cron_action == 'run' && $jobs) { + run_jobs($jobs); + } elseif ($cron_action == 'delete' && $jobs) { + delete_jobs($jobs); + } elseif (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) { + toggle_active($jobs, $cron_action); + } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + } elseif (validate_cron_post($_POST) == 1) { + if ($_POST['mode'] == 'edit') { + update_cron_job($_POST); + } elseif ($_POST['mode'] == 'add') { + insert_cron_job($_POST); + } else { + bb_die('Mode error'); + } - redirect('admin/'.basename(__FILE__) . '?mode=list'); - } - else - { - bb_die(validate_cron_post($_POST)); - } + redirect('admin/' . basename(__FILE__) . '?mode=list'); + } else { + bb_die(validate_cron_post($_POST)); + } } -print_page('admin_cron.tpl', 'admin'); \ No newline at end of file +print_page('admin_cron.tpl', 'admin'); diff --git a/admin/admin_disallow.php b/admin/admin_disallow.php index 6fe2ef3b9..7657a4f5b 100644 --- a/admin/admin_disallow.php +++ b/admin/admin_disallow.php @@ -1,58 +1,70 @@ escape($disallowed_user) . "')"; - $result = DB()->sql_query( $sql ); - if (!$result) - { - bb_die('Could not add disallowed user'); - } - $message = $lang['DISALLOW_SUCCESSFUL']; - } + if ($disallowed_user == '') { + bb_die($lang['FIELDS_EMPTY']); + } + if (!validate_username($disallowed_user)) { + $message = $lang['DISALLOWED_ALREADY']; + } else { + $sql = "INSERT INTO " . BB_DISALLOW . " (disallow_username) VALUES('" . DB()->escape($disallowed_user) . "')"; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not add disallowed user'); + } + $message = $lang['DISALLOW_SUCCESSFUL']; + } - $message .= '

'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message .= '

' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); -} -elseif (isset($_POST['delete_name'])) -{ - $disallowed_id = (isset($_POST['disallowed_id']) ) ? intval( $_POST['disallowed_id'] ) : intval( $_GET['disallowed_id']); + bb_die($message); +} elseif (isset($_POST['delete_name'])) { + $disallowed_id = (isset($_POST['disallowed_id'])) ? intval($_POST['disallowed_id']) : intval($_GET['disallowed_id']); - $sql = "DELETE FROM " . BB_DISALLOW . " WHERE disallow_id = $disallowed_id"; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not removed disallowed user'); - } + $sql = "DELETE FROM " . BB_DISALLOW . " WHERE disallow_id = $disallowed_id"; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not removed disallowed user'); + } - $message .= $lang['DISALLOWED_DELETED'] .'

'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') .'

'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - - bb_die($message); + $message .= $lang['DISALLOWED_DELETED'] . '

' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); } // @@ -60,9 +72,8 @@ elseif (isset($_POST['delete_name'])) // $sql = "SELECT * FROM " . BB_DISALLOW; $result = DB()->sql_query($sql); -if (!$result) -{ - bb_die('Could not get disallowed users'); +if (!$result) { + bb_die('Could not get disallowed users'); } $disallowed = DB()->sql_fetchrowset($result); @@ -73,23 +84,19 @@ $disallowed = DB()->sql_fetchrowset($result); // $disallow_select = ''; $template->assign_vars(array( - 'S_DISALLOW_SELECT' => $disallow_select, - 'S_FORM_ACTION' => 'admin_disallow.php', + 'S_DISALLOW_SELECT' => $disallow_select, + 'S_FORM_ACTION' => 'admin_disallow.php', )); -print_page('admin_disallow.tpl', 'admin'); \ No newline at end of file +print_page('admin_disallow.tpl', 'admin'); diff --git a/admin/admin_extensions.php b/admin/admin_extensions.php index d36b997c7..00b4c49a2 100644 --- a/admin/admin_extensions.php +++ b/admin/admin_extensions.php @@ -1,35 +1,55 @@ update('attach_extensions'); +function update_attach_extensions() +{ + $GLOBALS['datastore']->update('attach_extensions'); } + register_shutdown_function('update_attach_extensions'); -if (($attach_config['upload_dir'][0] == '/') || (($attach_config['upload_dir'][0] != '/') && ($attach_config['upload_dir'][1] == ':'))) -{ - $upload_dir = $attach_config['upload_dir']; -} -else -{ - $upload_dir = BB_ROOT . $attach_config['upload_dir']; +if (($attach_config['upload_dir'][0] == '/') || (($attach_config['upload_dir'][0] != '/') && ($attach_config['upload_dir'][1] == ':'))) { + $upload_dir = $attach_config['upload_dir']; +} else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; } -include(ATTACH_DIR .'includes/functions_selects.php'); +include(ATTACH_DIR . 'includes/functions_selects.php'); // Check if the language got included -if (!isset($lang['TEST_SETTINGS_SUCCESSFUL'])) -{ - // include_once is used within the function - include_attach_lang(); +if (!isset($lang['TEST_SETTINGS_SUCCESSFUL'])) { + // include_once is used within the function + include_attach_lang(); } // Init Vars @@ -43,738 +63,631 @@ $size = get_var('size', ''); $mode = get_var('mode', ''); $e_mode = get_var('e_mode', ''); -$submit = (isset($_POST['submit'])) ? TRUE : FALSE; +$submit = (isset($_POST['submit'])) ? true : false; // Get Attachment Config $attach_config = array(); -$sql = 'SELECT * FROM '. BB_ATTACH_CONFIG; +$sql = 'SELECT * FROM ' . BB_ATTACH_CONFIG; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information'); } -while ($row = DB()->sql_fetchrow($result)) -{ - $attach_config[$row['config_name']] = trim($row['config_value']); +while ($row = DB()->sql_fetchrow($result)) { + $attach_config[$row['config_name']] = trim($row['config_value']); } DB()->sql_freeresult($result); // Extension Management -if ($submit && $mode == 'extensions') -{ - // Change Extensions ? - $extension_change_list = get_var('extension_change_list', array(0)); - $extension_explain_list = get_var('extension_explain_list', array('')); - $group_select_list = get_var('group_select', array(0)); +if ($submit && $mode == 'extensions') { + // Change Extensions ? + $extension_change_list = get_var('extension_change_list', array(0)); + $extension_explain_list = get_var('extension_explain_list', array('')); + $group_select_list = get_var('group_select', array(0)); - // Generate correct Change List - $extensions = array(); + // Generate correct Change List + $extensions = array(); - for ($i = 0; $i < sizeof($extension_change_list); $i++) - { - $extensions['_' . $extension_change_list[$i]]['comment'] = $extension_explain_list[$i]; - $extensions['_' . $extension_change_list[$i]]['group_id'] = intval($group_select_list[$i]); - } + for ($i = 0; $i < sizeof($extension_change_list); $i++) { + $extensions['_' . $extension_change_list[$i]]['comment'] = $extension_explain_list[$i]; + $extensions['_' . $extension_change_list[$i]]['group_id'] = intval($group_select_list[$i]); + } - $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY ext_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension informations #1'); - } + $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY ext_id'; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension informations #1'); + } - $num_rows = DB()->num_rows($result); - $extension_row = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + $extension_row = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < sizeof($extension_row); $i++) - { - if ($extension_row[$i]['comment'] != $extensions['_' . $extension_row[$i]['ext_id']]['comment'] || intval($extension_row[$i]['group_id']) != intval($extensions['_' . $extension_row[$i]['ext_id']]['group_id'])) - { - $sql_ary = array( - 'comment' => (string) $extensions['_' . $extension_row[$i]['ext_id']]['comment'], - 'group_id' => (int) $extensions['_' . $extension_row[$i]['ext_id']]['group_id'] - ); + if ($num_rows > 0) { + for ($i = 0; $i < sizeof($extension_row); $i++) { + if ($extension_row[$i]['comment'] != $extensions['_' . $extension_row[$i]['ext_id']]['comment'] || intval($extension_row[$i]['group_id']) != intval($extensions['_' . $extension_row[$i]['ext_id']]['group_id'])) { + $sql_ary = array( + 'comment' => (string)$extensions['_' . $extension_row[$i]['ext_id']]['comment'], + 'group_id' => (int)$extensions['_' . $extension_row[$i]['ext_id']]['group_id'] + ); - $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE ext_id = ' . (int) $extension_row[$i]['ext_id']; + $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' + WHERE ext_id = ' . (int)$extension_row[$i]['ext_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update extension informations'); - } - } - } - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update extension informations'); + } + } + } + } - // Delete Extension? - $extension_id_list = get_var('extension_id_list', array(0)); + // Delete Extension? + $extension_id_list = get_var('extension_id_list', array(0)); - $extension_id_sql = implode(', ', $extension_id_list); + $extension_id_sql = implode(', ', $extension_id_list); - if ($extension_id_sql != '') - { - $sql = 'DELETE FROM ' . BB_EXTENSIONS . ' WHERE ext_id IN (' . $extension_id_sql . ')'; + if ($extension_id_sql != '') { + $sql = 'DELETE FROM ' . BB_EXTENSIONS . ' WHERE ext_id IN (' . $extension_id_sql . ')'; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not delete extensions'); - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete extensions'); + } + } - // Add Extension ? - $extension = get_var('add_extension', ''); - $extension_explain = get_var('add_extension_explain', ''); - $extension_group = get_var('add_group_select', 0); - $add = ( isset($_POST['add_extension_check']) ) ? TRUE : FALSE; + // Add Extension ? + $extension = get_var('add_extension', ''); + $extension_explain = get_var('add_extension_explain', ''); + $extension_group = get_var('add_group_select', 0); + $add = (isset($_POST['add_extension_check'])) ? true : false; - if ($extension != '' && $add) - { - $template->assign_vars(array( - 'ADD_EXTENSION' => $extension, - 'ADD_EXTENSION_EXPLAIN' => $extension_explain, - )); + if ($extension != '' && $add) { + $template->assign_vars(array( + 'ADD_EXTENSION' => $extension, + 'ADD_EXTENSION_EXPLAIN' => $extension_explain, + )); - if (!@$error) - { - // check extension - $sql = 'SELECT extension FROM ' . BB_EXTENSIONS; + if (!@$error) { + // check extension + $sql = 'SELECT extension FROM ' . BB_EXTENSIONS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extensions'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extensions'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if (strtolower(trim($row[$i]['extension'])) == strtolower(trim($extension))) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['EXTENSION_EXIST'], strtolower(trim($extension))); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if (strtolower(trim($row[$i]['extension'])) == strtolower(trim($extension))) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['EXTENSION_EXIST'], strtolower(trim($extension))); + } + } + } - if (!@$error) - { - $sql_ary = array( - 'group_id' => (int) $extension_group, - 'extension' => (string) strtolower($extension), - 'comment' => (string) $extension_explain - ); + if (!@$error) { + $sql_ary = array( + 'group_id' => (int)$extension_group, + 'extension' => (string)strtolower($extension), + 'comment' => (string)$extension_explain + ); - $sql = 'INSERT INTO ' . BB_EXTENSIONS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_EXTENSIONS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - if (!DB()->sql_query($sql)) - { - bb_die('Could not add extension'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not add extension'); + } + } + } + } - } - } - } - - if (!@$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!@$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'extensions') -{ - // Extensions - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSIONS' => true, - 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=extensions', - 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=extensions', - )); +if ($mode == 'extensions') { + // Extensions + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSIONS' => true, + 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=extensions', + 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=extensions', + )); - if ($submit) - { - $template->assign_vars(array( - 'S_ADD_GROUP_SELECT' => group_select('add_group_select', $extension_group)) - ); - } - else - { - $template->assign_vars(array( - 'S_ADD_GROUP_SELECT' => group_select('add_group_select')) - ); - } + if ($submit) { + $template->assign_vars(array( + 'S_ADD_GROUP_SELECT' => group_select('add_group_select', $extension_group)) + ); + } else { + $template->assign_vars(array( + 'S_ADD_GROUP_SELECT' => group_select('add_group_select')) + ); + } - $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY group_id'; + $sql = 'SELECT * FROM ' . BB_EXTENSIONS . ' ORDER BY group_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension informations #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension informations #2'); + } - $extension_row = DB()->sql_fetchrowset($result); - $num_extension_row = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension_row = DB()->sql_fetchrowset($result); + $num_extension_row = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_extension_row > 0) - { - $extension_row = sort_multi_array($extension_row, 'group_name', 'ASC'); - - for ($i = 0; $i < $num_extension_row; $i++) - { - if ($submit) - { - $template->assign_block_vars('extension_row', array( - 'EXT_ID' => $extension_row[$i]['ext_id'], - 'EXTENSION' => $extension_row[$i]['extension'], - 'EXTENSION_EXPLAIN' => $extension_explain_list[$i], - 'S_GROUP_SELECT' => group_select('group_select[]', $group_select_list[$i])) - ); - } - else - { - $template->assign_block_vars('extension_row', array( - 'EXT_ID' => $extension_row[$i]['ext_id'], - 'EXTENSION' => $extension_row[$i]['extension'], - 'EXTENSION_EXPLAIN' => $extension_row[$i]['comment'], - 'S_GROUP_SELECT' => group_select('group_select[]', $extension_row[$i]['group_id'])) - ); - } - } - } + if ($num_extension_row > 0) { + $extension_row = sort_multi_array($extension_row, 'group_name', 'ASC'); + for ($i = 0; $i < $num_extension_row; $i++) { + if ($submit) { + $template->assign_block_vars('extension_row', array( + 'EXT_ID' => $extension_row[$i]['ext_id'], + 'EXTENSION' => $extension_row[$i]['extension'], + 'EXTENSION_EXPLAIN' => $extension_explain_list[$i], + 'S_GROUP_SELECT' => group_select('group_select[]', $group_select_list[$i])) + ); + } else { + $template->assign_block_vars('extension_row', array( + 'EXT_ID' => $extension_row[$i]['ext_id'], + 'EXTENSION' => $extension_row[$i]['extension'], + 'EXTENSION_EXPLAIN' => $extension_row[$i]['comment'], + 'S_GROUP_SELECT' => group_select('group_select[]', $extension_row[$i]['group_id'])) + ); + } + } + } } // Extension Groups -if ($submit && $mode == 'groups') -{ - // Change Extension Groups ? - $group_change_list = get_var('group_change_list', array(0)); - $extension_group_list = get_var('extension_group_list', array('')); - $group_allowed_list = get_var('allowed_list', array(0)); - $download_mode_list = get_var('download_mode_list', array(0)); - $category_list = get_var('category_list', array(0)); - $upload_icon_list = get_var('upload_icon_list', array('')); - $filesize_list = get_var('max_filesize_list', array(0)); - $size_select_list = get_var('size_select_list', array('')); +if ($submit && $mode == 'groups') { + // Change Extension Groups ? + $group_change_list = get_var('group_change_list', array(0)); + $extension_group_list = get_var('extension_group_list', array('')); + $group_allowed_list = get_var('allowed_list', array(0)); + $download_mode_list = get_var('download_mode_list', array(0)); + $category_list = get_var('category_list', array(0)); + $upload_icon_list = get_var('upload_icon_list', array('')); + $filesize_list = get_var('max_filesize_list', array(0)); + $size_select_list = get_var('size_select_list', array('')); - $allowed_list = array(); + $allowed_list = array(); - for ($i = 0; $i < sizeof($group_allowed_list); $i++) - { - for ($j = 0; $j < sizeof($group_change_list); $j++) - { - if ($group_allowed_list[$i] == $group_change_list[$j]) - { - $allowed_list[$j] = 1; - } - } - } + for ($i = 0; $i < sizeof($group_allowed_list); $i++) { + for ($j = 0; $j < sizeof($group_change_list); $j++) { + if ($group_allowed_list[$i] == $group_change_list[$j]) { + $allowed_list[$j] = 1; + } + } + } - for ($i = 0; $i < sizeof($group_change_list); $i++) - { - $allowed = (isset($allowed_list[$i])) ? 1 : 0; + for ($i = 0; $i < sizeof($group_change_list); $i++) { + $allowed = (isset($allowed_list[$i])) ? 1 : 0; - $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : ( ($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i] ); + $filesize_list[$i] = ($size_select_list[$i] == 'kb') ? round($filesize_list[$i] * 1024) : (($size_select_list[$i] == 'mb') ? round($filesize_list[$i] * 1048576) : $filesize_list[$i]); - $sql_ary = array( - 'group_name' => (string) $extension_group_list[$i], - 'cat_id' => (int) $category_list[$i], - 'allow_group' => (int) $allowed, - 'download_mode' => (int) $download_mode_list[$i], - 'upload_icon' => (string) $upload_icon_list[$i], - 'max_filesize' => (int) $filesize_list[$i] - ); + $sql_ary = array( + 'group_name' => (string)$extension_group_list[$i], + 'cat_id' => (int)$category_list[$i], + 'allow_group' => (int)$allowed, + 'download_mode' => (int)$download_mode_list[$i], + 'upload_icon' => (string)$upload_icon_list[$i], + 'max_filesize' => (int)$filesize_list[$i] + ); - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE group_id = ' . (int) $group_change_list[$i]; + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' + WHERE group_id = ' . (int)$group_change_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update extension groups informations'); - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not update extension groups informations'); + } + } - // Delete Extension Groups - $group_id_list = get_var('group_id_list', array(0)); + // Delete Extension Groups + $group_id_list = get_var('group_id_list', array(0)); - $group_id_sql = implode(', ', $group_id_list); + $group_id_sql = implode(', ', $group_id_list); - if ($group_id_sql != '') - { - $sql = 'DELETE + if ($group_id_sql != '') { + $sql = 'DELETE FROM ' . BB_EXTENSION_GROUPS . ' WHERE group_id IN (' . $group_id_sql . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not delete extension groups'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete extension groups'); + } - // Set corresponding Extensions to a pending Group - $sql = 'UPDATE ' . BB_EXTENSIONS . ' + // Set corresponding Extensions to a pending Group + $sql = 'UPDATE ' . BB_EXTENSIONS . ' SET group_id = 0 WHERE group_id IN (' . $group_id_sql . ')'; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not assign extensions to pending group'); - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not assign extensions to pending group'); + } + } - // Add Extensions? - $extension_group = get_var('add_extension_group', ''); - $download_mode = get_var('add_download_mode', 0); - $cat_id = get_var('add_category', 0); - $upload_icon = get_var('add_upload_icon', ''); - $filesize = get_var('add_max_filesize', 0); - $size_select = get_var('add_size_select', ''); + // Add Extensions? + $extension_group = get_var('add_extension_group', ''); + $download_mode = get_var('add_download_mode', 0); + $cat_id = get_var('add_category', 0); + $upload_icon = get_var('add_upload_icon', ''); + $filesize = get_var('add_max_filesize', 0); + $size_select = get_var('add_size_select', ''); - $is_allowed = (isset($_POST['add_allowed'])) ? 1 : 0; - $add = ( isset($_POST['add_extension_group_check']) ) ? TRUE : FALSE; + $is_allowed = (isset($_POST['add_allowed'])) ? 1 : 0; + $add = (isset($_POST['add_extension_group_check'])) ? true : false; - if ($extension_group != '' && $add) - { - // check Extension Group - $sql = 'SELECT group_name FROM ' . BB_EXTENSION_GROUPS; + if ($extension_group != '' && $add) { + // check Extension Group + $sql = 'SELECT group_name FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table'); + } - $row = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($row[$i]['group_name'] == $extension_group) - { - $error = TRUE; - if( isset($error_msg) ) - { - $error_msg .= '
'; - } - $error_msg .= sprintf($lang['EXTENSION_GROUP_EXIST'], $extension_group); - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($row[$i]['group_name'] == $extension_group) { + $error = true; + if (isset($error_msg)) { + $error_msg .= '
'; + } + $error_msg .= sprintf($lang['EXTENSION_GROUP_EXIST'], $extension_group); + } + } + } - if (!@$error) - { - $filesize = ($size_select == 'kb') ? round($filesize * 1024) : ( ($size_select == 'mb') ? round($filesize * 1048576) : $filesize ); + if (!@$error) { + $filesize = ($size_select == 'kb') ? round($filesize * 1024) : (($size_select == 'mb') ? round($filesize * 1048576) : $filesize); - $sql_ary = array( - 'group_name' => (string) $extension_group, - 'cat_id' => (int) $cat_id, - 'allow_group' => (int) $is_allowed, - 'download_mode' => (int) $download_mode, - 'upload_icon' => (string) $upload_icon, - 'max_filesize' => (int) $filesize, - 'forum_permissions' => '' - ); + $sql_ary = array( + 'group_name' => (string)$extension_group, + 'cat_id' => (int)$cat_id, + 'allow_group' => (int)$is_allowed, + 'download_mode' => (int)$download_mode, + 'upload_icon' => (string)$upload_icon, + 'max_filesize' => (int)$filesize, + 'forum_permissions' => '' + ); - $sql = 'INSERT INTO ' . BB_EXTENSION_GROUPS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_EXTENSION_GROUPS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - if (!(DB()->sql_query($sql))) - { - bb_die('Could not add extension group'); - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not add extension group'); + } + } + } - } - - if (!@$error) - { - bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } + if (!@$error) { + bb_die($lang['ATTACH_CONFIG_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_ATTACH_CONFIG'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } } -if ($mode == 'groups') -{ - // Extension Groups - if (!$size && !$submit) - { - $max_add_filesize = $attach_config['max_filesize']; +if ($mode == 'groups') { + // Extension Groups + if (!$size && !$submit) { + $max_add_filesize = $attach_config['max_filesize']; - $size = ($max_add_filesize >= 1048576) ? 'mb' : ( ($max_add_filesize >= 1024) ? 'kb' : 'b' ); - } + $size = ($max_add_filesize >= 1048576) ? 'mb' : (($max_add_filesize >= 1024) ? 'kb' : 'b'); + } - if ($max_add_filesize >= 1048576) - { - $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; - } - else if ( $max_add_filesize >= 1024) - { - $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; - } + if ($max_add_filesize >= 1048576) { + $max_add_filesize = round($max_add_filesize / 1048576 * 100) / 100; + } elseif ($max_add_filesize >= 1024) { + $max_add_filesize = round($max_add_filesize / 1024 * 100) / 100; + } - $viewgroup = get_var(POST_GROUPS_URL, 0); + $viewgroup = get_var(POST_GROUPS_URL, 0); - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSION_GROUPS' => true, - 'ADD_GROUP_NAME' => ( isset($submit) ) ? @$extension_group : '', - 'MAX_FILESIZE' => $max_add_filesize, - 'S_FILESIZE' => size_select('add_size_select', $size), - 'S_ADD_DOWNLOAD_MODE' => download_select('add_download_mode'), - 'S_SELECT_CAT' => category_select('add_category'), - 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=groups', - 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=groups', - )); + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSION_GROUPS' => true, + 'ADD_GROUP_NAME' => (isset($submit)) ? @$extension_group : '', + 'MAX_FILESIZE' => $max_add_filesize, + 'S_FILESIZE' => size_select('add_size_select', $size), + 'S_ADD_DOWNLOAD_MODE' => download_select('add_download_mode'), + 'S_SELECT_CAT' => category_select('add_category'), + 'S_CANCEL_ACTION' => 'admin_extensions.php?mode=groups', + 'S_ATTACH_ACTION' => 'admin_extensions.php?mode=groups', + )); - $sql = 'SELECT * FROM ' . BB_EXTENSION_GROUPS; + $sql = 'SELECT * FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get extension group informations'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get extension group informations'); + } - $extension_group = DB()->sql_fetchrowset($result); - $num_extension_group = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension_group = DB()->sql_fetchrowset($result); + $num_extension_group = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($i = 0; $i < $num_extension_group; $i++) - { - // Format the filesize - if (!$extension_group[$i]['max_filesize']) - { - $extension_group[$i]['max_filesize'] = $attach_config['max_filesize']; - } + for ($i = 0; $i < $num_extension_group; $i++) { + // Format the filesize + if (!$extension_group[$i]['max_filesize']) { + $extension_group[$i]['max_filesize'] = $attach_config['max_filesize']; + } - $size_format = ($extension_group[$i]['max_filesize'] >= 1048576) ? 'mb' : ( ($extension_group[$i]['max_filesize'] >= 1024) ? 'kb' : 'b' ); + $size_format = ($extension_group[$i]['max_filesize'] >= 1048576) ? 'mb' : (($extension_group[$i]['max_filesize'] >= 1024) ? 'kb' : 'b'); - if ( $extension_group[$i]['max_filesize'] >= 1048576) - { - $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1048576 * 100) / 100; - } - else if($extension_group[$i]['max_filesize'] >= 1024) - { - $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1024 * 100) / 100; - } + if ($extension_group[$i]['max_filesize'] >= 1048576) { + $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1048576 * 100) / 100; + } elseif ($extension_group[$i]['max_filesize'] >= 1024) { + $extension_group[$i]['max_filesize'] = round($extension_group[$i]['max_filesize'] / 1024 * 100) / 100; + } - $s_allowed = ($extension_group[$i]['allow_group'] == 1) ? 'checked="checked"' : ''; + $s_allowed = ($extension_group[$i]['allow_group'] == 1) ? 'checked="checked"' : ''; - $template->assign_block_vars('grouprow', array( - 'GROUP_ID' => $extension_group[$i]['group_id'], - 'EXTENSION_GROUP' => $extension_group[$i]['group_name'], - 'UPLOAD_ICON' => $extension_group[$i]['upload_icon'], + $template->assign_block_vars('grouprow', array( + 'GROUP_ID' => $extension_group[$i]['group_id'], + 'EXTENSION_GROUP' => $extension_group[$i]['group_name'], + 'UPLOAD_ICON' => $extension_group[$i]['upload_icon'], - 'S_ALLOW_SELECTED' => $s_allowed, - 'S_SELECT_CAT' => category_select('category_list[]', $extension_group[$i]['group_id']), - 'S_DOWNLOAD_MODE' => download_select('download_mode_list[]', $extension_group[$i]['group_id']), - 'S_FILESIZE' => size_select('size_select_list[]', $size_format), + 'S_ALLOW_SELECTED' => $s_allowed, + 'S_SELECT_CAT' => category_select('category_list[]', $extension_group[$i]['group_id']), + 'S_DOWNLOAD_MODE' => download_select('download_mode_list[]', $extension_group[$i]['group_id']), + 'S_FILESIZE' => size_select('size_select_list[]', $size_format), - 'MAX_FILESIZE' => $extension_group[$i]['max_filesize'], - 'CAT_BOX' => ( $viewgroup == $extension_group[$i]['group_id'] ) ? '+' : '-', - 'U_VIEWGROUP' => ( $viewgroup == $extension_group[$i]['group_id'] ) ? "admin_extensions.php?mode=groups" : "admin_extensions.php?mode=groups&" . POST_GROUPS_URL . "=" . $extension_group[$i]['group_id'], - 'U_FORUM_PERMISSIONS' => "admin_extensions.php?mode=$mode&e_mode=perm&e_group=" . $extension_group[$i]['group_id'], - )); + 'MAX_FILESIZE' => $extension_group[$i]['max_filesize'], + 'CAT_BOX' => ($viewgroup == $extension_group[$i]['group_id']) ? '+' : '-', + 'U_VIEWGROUP' => ($viewgroup == $extension_group[$i]['group_id']) ? "admin_extensions.php?mode=groups" : "admin_extensions.php?mode=groups&" . POST_GROUPS_URL . "=" . $extension_group[$i]['group_id'], + 'U_FORUM_PERMISSIONS' => "admin_extensions.php?mode=$mode&e_mode=perm&e_group=" . $extension_group[$i]['group_id'], + )); - if ($viewgroup && $viewgroup == $extension_group[$i]['group_id']) - { - $sql = 'SELECT comment, extension FROM ' . BB_EXTENSIONS . ' WHERE group_id = ' . (int) $viewgroup; + if ($viewgroup && $viewgroup == $extension_group[$i]['group_id']) { + $sql = 'SELECT comment, extension FROM ' . BB_EXTENSIONS . ' WHERE group_id = ' . (int)$viewgroup; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get extension informations #3'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get extension informations #3'); + } - $extension = DB()->sql_fetchrowset($result); - $num_extension = DB()->num_rows($result); - DB()->sql_freeresult($result); + $extension = DB()->sql_fetchrowset($result); + $num_extension = DB()->num_rows($result); + DB()->sql_freeresult($result); - for ($j = 0; $j < $num_extension; $j++) - { - $template->assign_block_vars('grouprow.extensionrow', array( - 'EXPLANATION' => $extension[$j]['comment'], - 'EXTENSION' => $extension[$j]['extension']) - ); - } - } - } + for ($j = 0; $j < $num_extension; $j++) { + $template->assign_block_vars('grouprow.extensionrow', array( + 'EXPLANATION' => $extension[$j]['comment'], + 'EXTENSION' => $extension[$j]['extension']) + ); + } + } + } } -if ($e_mode == 'perm') -{ - $group = get_var('e_group', 0); +if ($e_mode == 'perm') { + $group = get_var('e_group', 0); - $add_forum = (isset($_POST['add_forum'])) ? TRUE : FALSE; - $delete_forum = (isset($_POST['del_forum'])) ? TRUE : FALSE; + $add_forum = (isset($_POST['add_forum'])) ? true : false; + $delete_forum = (isset($_POST['del_forum'])) ? true : false; - if (isset($_POST['close_perm'])) - { - $e_mode = ''; - } + if (isset($_POST['close_perm'])) { + $e_mode = ''; + } } // Add Forums -if (@$add_forum && $e_mode == 'perm' && $group) -{ - $add_forums_list = get_var('entries', array(0)); - $add_all_forums = FALSE; +if (@$add_forum && $e_mode == 'perm' && $group) { + $add_forums_list = get_var('entries', array(0)); + $add_all_forums = false; - for ($i = 0; $i < sizeof($add_forums_list); $i++) - { - if ($add_forums_list[$i] == 0) - { - $add_all_forums = TRUE; - } - } + for ($i = 0; $i < sizeof($add_forums_list); $i++) { + if ($add_forums_list[$i] == 0) { + $add_all_forums = true; + } + } - // If we add ALL FORUMS, we are able to overwrite the Permissions - if ($add_all_forums) - { - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '' WHERE group_id = " . (int) $group; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #1'); - } - } + // If we add ALL FORUMS, we are able to overwrite the Permissions + if ($add_all_forums) { + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '' WHERE group_id = " . (int)$group; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #1'); + } + } - // Else we have to add Permissions - if (!$add_all_forums) - { - $sql = 'SELECT forum_permissions + // Else we have to add Permissions + if (!$add_all_forums) { + $sql = 'SELECT forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' WHERE group_id = ' . intval($group) . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - if (trim($row['forum_permissions']) == '') - { - $auth_p = array(); - } - else - { - $auth_p = auth_unpack($row['forum_permissions']); - } + if (trim($row['forum_permissions']) == '') { + $auth_p = array(); + } else { + $auth_p = auth_unpack($row['forum_permissions']); + } - // Generate array for Auth_Pack, do not add doubled forums - for ($i = 0; $i < sizeof($add_forums_list); $i++) - { - if (!in_array($add_forums_list[$i], $auth_p)) - { - $auth_p[] = $add_forums_list[$i]; - } - } + // Generate array for Auth_Pack, do not add doubled forums + for ($i = 0; $i < sizeof($add_forums_list); $i++) { + if (!in_array($add_forums_list[$i], $auth_p)) { + $auth_p[] = $add_forums_list[$i]; + } + } - $auth_bitstream = auth_pack($auth_p); + $auth_bitstream = auth_pack($auth_p); - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int) $group; - - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #2'); - } - } + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int)$group; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #2'); + } + } } // Delete Forums -if (@$delete_forum && $e_mode == 'perm' && $group) -{ - $delete_forums_list = get_var('entries', array(0)); +if (@$delete_forum && $e_mode == 'perm' && $group) { + $delete_forums_list = get_var('entries', array(0)); - // Get the current Forums - $sql = 'SELECT forum_permissions + // Get the current Forums + $sql = 'SELECT forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' WHERE group_id = ' . intval($group) . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group permissions from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $auth_p2 = auth_unpack(trim($row['forum_permissions'])); - $auth_p = array(); + $auth_p2 = auth_unpack(trim($row['forum_permissions'])); + $auth_p = array(); - // Generate array for Auth_Pack, delete the chosen ones - for ($i = 0; $i < sizeof($auth_p2); $i++) - { - if (!in_array($auth_p2[$i], $delete_forums_list)) - { - $auth_p[] = $auth_p2[$i]; - } - } + // Generate array for Auth_Pack, delete the chosen ones + for ($i = 0; $i < sizeof($auth_p2); $i++) { + if (!in_array($auth_p2[$i], $delete_forums_list)) { + $auth_p[] = $auth_p2[$i]; + } + } - $auth_bitstream = (sizeof($auth_p) > 0) ? auth_pack($auth_p) : ''; + $auth_bitstream = (sizeof($auth_p) > 0) ? auth_pack($auth_p) : ''; - $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int) $group; + $sql = 'UPDATE ' . BB_EXTENSION_GROUPS . " SET forum_permissions = '" . attach_mod_sql_escape($auth_bitstream) . "' WHERE group_id = " . (int)$group; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update permissions #3'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update permissions #3'); + } } // Display the Group Permissions Box for configuring it -if ($e_mode == 'perm' && $group) -{ - $sql = 'SELECT group_name, forum_permissions +if ($e_mode == 'perm' && $group) { + $sql = 'SELECT group_name, forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' WHERE group_id = ' . intval($group) . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group name from ' . BB_EXTENSION_GROUPS); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group name from ' . BB_EXTENSION_GROUPS); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $group_name = $row['group_name']; - $allowed_forums = trim($row['forum_permissions']); + $group_name = $row['group_name']; + $allowed_forums = trim($row['forum_permissions']); - $forum_perm = array(); + $forum_perm = array(); - if ($allowed_forums == '') - { - $forum_perm[0]['forum_id'] = 0; - $forum_perm[0]['forum_name'] = $lang['PERM_ALL_FORUMS']; - } - else - { - $forum_p = array(); - $act_id = 0; - $forum_p = auth_unpack($allowed_forums); - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE forum_id IN (" . implode(', ', $forum_p) . ")"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get forum names'); - } + if ($allowed_forums == '') { + $forum_perm[0]['forum_id'] = 0; + $forum_perm[0]['forum_name'] = $lang['PERM_ALL_FORUMS']; + } else { + $forum_p = array(); + $act_id = 0; + $forum_p = auth_unpack($allowed_forums); + $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE forum_id IN (" . implode(', ', $forum_p) . ")"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get forum names'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $forum_perm[$act_id]['forum_id'] = $row['forum_id']; - $forum_perm[$act_id]['forum_name'] = $row['forum_name']; - $act_id++; - } - } + while ($row = DB()->sql_fetchrow($result)) { + $forum_perm[$act_id]['forum_id'] = $row['forum_id']; + $forum_perm[$act_id]['forum_name'] = $row['forum_name']; + $act_id++; + } + } - for ($i = 0; $i < sizeof($forum_perm); $i++) - { - $template->assign_block_vars('allow_option_values', array( - 'VALUE' => $forum_perm[$i]['forum_id'], - 'OPTION' => htmlCHR($forum_perm[$i]['forum_name'])) - ); - } + for ($i = 0; $i < sizeof($forum_perm); $i++) { + $template->assign_block_vars('allow_option_values', array( + 'VALUE' => $forum_perm[$i]['forum_id'], + 'OPTION' => htmlCHR($forum_perm[$i]['forum_name'])) + ); + } - $template->assign_vars(array( - 'TPL_ATTACH_EXTENSION_GROUPS_PERMISSIONS' => true, - 'L_GROUP_PERMISSIONS_TITLE' => sprintf($lang['GROUP_PERMISSIONS_TITLE_ADMIN'], trim($group_name)), - 'A_PERM_ACTION' => "admin_extensions.php?mode=groups&e_mode=perm&e_group=$group", - )); + $template->assign_vars(array( + 'TPL_ATTACH_EXTENSION_GROUPS_PERMISSIONS' => true, + 'L_GROUP_PERMISSIONS_TITLE' => sprintf($lang['GROUP_PERMISSIONS_TITLE_ADMIN'], trim($group_name)), + 'A_PERM_ACTION' => "admin_extensions.php?mode=groups&e_mode=perm&e_group=$group", + )); - $forum_option_values = array(0 => $lang['PERM_ALL_FORUMS']); + $forum_option_values = array(0 => $lang['PERM_ALL_FORUMS']); - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS; + $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get forums #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get forums #1'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $forum_option_values[intval($row['forum_id'])] = $row['forum_name']; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $forum_option_values[intval($row['forum_id'])] = $row['forum_name']; + } + DB()->sql_freeresult($result); - foreach ($forum_option_values as $value => $option) - { - $template->assign_block_vars('forum_option_values', array( - 'VALUE' => $value, - 'OPTION' => htmlCHR($option)) - ); - } + foreach ($forum_option_values as $value => $option) { + $template->assign_block_vars('forum_option_values', array( + 'VALUE' => $value, + 'OPTION' => htmlCHR($option)) + ); + } - $empty_perm_forums = array(); + $empty_perm_forums = array(); - $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE auth_attachments < " . AUTH_ADMIN; + $sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " WHERE auth_attachments < " . AUTH_ADMIN; - if (!($f_result = DB()->sql_query($sql))) - { - bb_die('Could not get forums #2'); - } + if (!($f_result = DB()->sql_query($sql))) { + bb_die('Could not get forums #2'); + } - while ($row = DB()->sql_fetchrow($f_result)) - { - $forum_id = $row['forum_id']; + while ($row = DB()->sql_fetchrow($f_result)) { + $forum_id = $row['forum_id']; - $sql = "SELECT forum_permissions + $sql = "SELECT forum_permissions FROM " . BB_EXTENSION_GROUPS . " WHERE allow_group = 1 ORDER BY group_name ASC"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - $found_forum = FALSE; + $found_forum = false; - for ($i = 0; $i < $num_rows; $i++) - { - $allowed_forums = auth_unpack(trim($rows[$i]['forum_permissions'])); - if (in_array($forum_id, $allowed_forums) || trim($rows[$i]['forum_permissions']) == '') - { - $found_forum = TRUE; - break; - } - } + for ($i = 0; $i < $num_rows; $i++) { + $allowed_forums = auth_unpack(trim($rows[$i]['forum_permissions'])); + if (in_array($forum_id, $allowed_forums) || trim($rows[$i]['forum_permissions']) == '') { + $found_forum = true; + break; + } + } - if (!$found_forum) - { - $empty_perm_forums[$forum_id] = $row['forum_name']; - } - } - DB()->sql_freeresult($f_result); + if (!$found_forum) { + $empty_perm_forums[$forum_id] = $row['forum_name']; + } + } + DB()->sql_freeresult($f_result); - $message = ''; + $message = ''; - foreach ($empty_perm_forums as $forum_id => $forum_name) - { - $message .= ( $message == '' ) ? $forum_name : '
' . $forum_name; - } + foreach ($empty_perm_forums as $forum_id => $forum_name) { + $message .= ($message == '') ? $forum_name : '
' . $forum_name; + } - if (sizeof($empty_perm_forums) > 0) - { - $template->assign_vars(array('ERROR_MESSAGE' => $lang['NOTE_ADMIN_EMPTY_GROUP_PERMISSIONS'] . $message)); - } + if (sizeof($empty_perm_forums) > 0) { + $template->assign_vars(array('ERROR_MESSAGE' => $lang['NOTE_ADMIN_EMPTY_GROUP_PERMISSIONS'] . $message)); + } } -if (@$error) -{ - $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); +if (@$error) { + $template->assign_vars(array('ERROR_MESSAGE' => $error_msg)); } -print_page('admin_extensions.tpl', 'admin'); \ No newline at end of file +print_page('admin_extensions.tpl', 'admin'); diff --git a/admin/admin_forum_prune.php b/admin/admin_forum_prune.php index 86e8968e3..90d3dee82 100644 --- a/admin/admin_forum_prune.php +++ b/admin/admin_forum_prune.php @@ -1,9 +1,31 @@ fetch_rowset($sql) as $i => $row) - { - $pruned_topics = topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types'])); - $pruned_total += $pruned_topics; - $prune_performed = true; + foreach (DB()->fetch_rowset($sql) as $i => $row) { + $pruned_topics = topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types'])); + $pruned_total += $pruned_topics; + $prune_performed = true; - $template->assign_block_vars('pruned', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'FORUM_NAME' => htmlCHR($row['forum_name']), - 'PRUNED_TOPICS' => $pruned_topics, - )); - } - if (!$prune_performed) - { - bb_die($lang['NONE_SELECTED']); - } - if (!$pruned_total) - { - bb_die($lang['NO_SEARCH_MATCH']); - } + $template->assign_block_vars('pruned', array( + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'FORUM_NAME' => htmlCHR($row['forum_name']), + 'PRUNED_TOPICS' => $pruned_topics, + )); + } + if (!$prune_performed) { + bb_die($lang['NONE_SELECTED']); + } + if (!$pruned_total) { + bb_die($lang['NO_SEARCH_MATCH']); + } } $template->assign_vars(array( - 'PRUNED_TOTAL' => $pruned_total, - 'S_PRUNE_ACTION' => basename(__FILE__), - 'SEL_FORUM' => get_forum_select('admin', 'f[]', null, 65, 16, '', $all_forums), + 'PRUNED_TOTAL' => $pruned_total, + 'S_PRUNE_ACTION' => basename(__FILE__), + 'SEL_FORUM' => get_forum_select('admin', 'f[]', null, 65, 16, '', $all_forums), )); -print_page('admin_forum_prune.tpl', 'admin'); \ No newline at end of file +print_page('admin_forum_prune.tpl', 'admin'); diff --git a/admin/admin_forumauth.php b/admin/admin_forumauth.php index f4798d3dc..34a3f2c9e 100644 --- a/admin/admin_forumauth.php +++ b/admin/admin_forumauth.php @@ -1,135 +1,144 @@ array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL, AUTH_ALL, AUTH_MOD, AUTH_MOD), // Public -/* Reg */ 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered -/* Reg [Hid] */ 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered [Hidden] -/* Priv */ 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private -/* Priv [Hid] */ 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private [Hidden] -/* MOD */ 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators -/* MOD [Hid] */ 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] + /* Public */ + 0 => array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL, AUTH_ALL, AUTH_MOD, AUTH_MOD), // Public + /* Reg */ + 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered + /* Reg [Hid] */ + 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD), // Registered [Hidden] + /* Priv */ + 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private + /* Priv [Hid] */ + 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD), // Private [Hidden] + /* MOD */ + 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators + /* MOD [Hid] */ + 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] ); $simple_auth_types = array( - $lang['PUBLIC'], - $lang['REGISTERED'], - $lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', - $lang['PRIVATE'], - $lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', - $lang['MODERATORS'], - $lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', + $lang['PUBLIC'], + $lang['REGISTERED'], + $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']', + $lang['PRIVATE'], + $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']', + $lang['MODERATORS'], + $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']', ); $field_names = array(); -foreach ($forum_auth_fields as $auth_type) -{ - $field_names[$auth_type] = $lang[strtoupper($auth_type)]; +foreach ($forum_auth_fields as $auth_type) { + $field_names[$auth_type] = $lang[strtoupper($auth_type)]; } -$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); -$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); +$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); +$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); -if (@$_REQUEST[POST_FORUM_URL]) -{ - $forum_id = (int) $_REQUEST[POST_FORUM_URL]; - $forum_sql = "WHERE forum_id = $forum_id"; -} -else -{ - unset($forum_id); - $forum_sql = ''; +if (@$_REQUEST[POST_FORUM_URL]) { + $forum_id = (int)$_REQUEST[POST_FORUM_URL]; + $forum_sql = "WHERE forum_id = $forum_id"; +} else { + unset($forum_id); + $forum_sql = ''; } -if( isset($_GET['adv']) ) -{ - $adv = intval($_GET['adv']); -} -else -{ - unset($adv); +if (isset($_GET['adv'])) { + $adv = intval($_GET['adv']); +} else { + unset($adv); } // // Start program proper // -if( isset($_POST['submit']) ) -{ - $sql = ''; +if (isset($_POST['submit'])) { + $sql = ''; - if(!empty($forum_id)) - { - if(isset($_POST['simpleauth'])) - { - $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; + if (!empty($forum_id)) { + if (isset($_POST['simpleauth'])) { + $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; - for($i = 0; $i < count($simple_ary); $i++) - { - $sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; - } + for ($i = 0; $i < count($simple_ary); $i++) { + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; + } - if (is_array($simple_ary)) - { - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } - } - else - { - for ($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); + if (is_array($simple_ary)) { + $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } + } else { + for ($i = 0; $i < count($forum_auth_fields); $i++) { + $value = intval($_POST[$forum_auth_fields[$i]]); - if ($forum_auth_fields[$i] == 'auth_vote') - { - if ($_POST['auth_vote'] == AUTH_ALL) - { - $value = AUTH_REG; - } - } + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } + $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table'); - } - } + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table'); + } + } - $forum_sql = ''; - $adv = 0; - } - - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); + $forum_sql = ''; + $adv = 0; + } + $datastore->update('cat_forums'); + bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); } // End of submit // @@ -137,116 +146,101 @@ if( isset($_POST['submit']) ) // no id was specified or just the requsted if it // was // -$forum_rows = DB()->fetch_rowset("SELECT * FROM ". BB_FORUMS ." $forum_sql"); +$forum_rows = DB()->fetch_rowset("SELECT * FROM " . BB_FORUMS . " $forum_sql"); -if (empty($forum_id)) -{ - // Output the selection table if no forum id was specified - $template->assign_vars(array( - 'TPL_AUTH_SELECT_FORUM' => true, - 'S_AUTH_ACTION' => 'admin_forumauth.php', - 'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80), - )); +if (empty($forum_id)) { + // Output the selection table if no forum id was specified + $template->assign_vars(array( + 'TPL_AUTH_SELECT_FORUM' => true, + 'S_AUTH_ACTION' => 'admin_forumauth.php', + 'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80), + )); +} else { + // Output the authorisation details if an id was specified + $forum_name = $forum_rows[0]['forum_name']; -} -else -{ - // Output the authorisation details if an id was specified - $forum_name = $forum_rows[0]['forum_name']; + @reset($simple_auth_ary); + while (list($key, $auth_levels) = each($simple_auth_ary)) { + $matched = 1; + for ($k = 0; $k < count($auth_levels); $k++) { + $matched_type = $key; - @reset($simple_auth_ary); - while (list($key, $auth_levels) = each($simple_auth_ary)) - { - $matched = 1; - for ($k = 0; $k < count($auth_levels); $k++) - { - $matched_type = $key; + if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) { + $matched = 0; + } + } - if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) - { - $matched = 0; - } - } + if ($matched) { + break; + } + } - if ( $matched ) - { - break; - } - } + // + // If we didn't get a match above then we + // automatically switch into 'advanced' mode + // + if (!isset($adv) && !$matched) { + $adv = 1; + } - // - // If we didn't get a match above then we - // automatically switch into 'advanced' mode - // - if ( !isset($adv) && !$matched ) - { - $adv = 1; - } + $s_column_span = 0; - $s_column_span = 0; + if (empty($adv)) { + $simple_auth = ''; + for ($j = 0; $j < count($simple_auth_types); $j++) { + $selected = ($matched_type == $j) ? ' selected="selected"' : ''; + $simple_auth .= ''; + } - for($j = 0; $j < count($simple_auth_types); $j++) - { - $selected = ( $matched_type == $j ) ? ' selected="selected"' : ''; - $simple_auth .= ''; - } + $simple_auth .= ''; - $simple_auth .= ''; + $template->assign_block_vars('forum_auth', array( + 'CELL_TITLE' => $lang['SIMPLE_MODE'], + 'S_AUTH_LEVELS_SELECT' => $simple_auth, + )); - $template->assign_block_vars('forum_auth', array( - 'CELL_TITLE' => $lang['SIMPLE_MODE'], - 'S_AUTH_LEVELS_SELECT' => $simple_auth, - )); + $s_column_span++; + } else { + // + // Output values of individual + // fields + // + for ($j = 0; $j < count($forum_auth_fields); $j++) { + $custom_auth[$j] = ' '; + for ($k = 0; $k < count($forum_auth_levels); $k++) { + $selected = ($forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k]) ? ' selected="selected"' : ''; + $custom_auth[$j] .= ''; + } + $custom_auth[$j] .= ' '; - for ($k = 0; $k < count($forum_auth_levels); $k++) - { - $selected = ( $forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k] ) ? ' selected="selected"' : ''; - $custom_auth[$j] .= ''; - } - $custom_auth[$j] .= ' '; + $cell_title = $field_names[$forum_auth_fields[$j]]; - $cell_title = $field_names[$forum_auth_fields[$j]]; + $template->assign_block_vars('forum_auth', array( + 'CELL_TITLE' => $cell_title, + 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j], + )); - $template->assign_block_vars('forum_auth', array( - 'CELL_TITLE' => $cell_title, - 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j], - )); + $s_column_span++; + } + } - $s_column_span++; - } - } + $adv_mode = (empty($adv)) ? '1' : '0'; + $switch_mode = "admin_forumauth.php?f=$forum_id&adv=$adv_mode"; + $switch_mode_text = (empty($adv)) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE']; + $u_switch_mode = '' . $switch_mode_text . ''; - $adv_mode = ( empty($adv) ) ? '1' : '0'; - $switch_mode = "admin_forumauth.php?f=$forum_id&adv=$adv_mode"; - $switch_mode_text = ( empty($adv) ) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE']; - $u_switch_mode = '' . $switch_mode_text . ''; + $s_hidden_fields = ''; - $s_hidden_fields = ''; - - $template->assign_vars(array( - 'TPL_EDIT_FORUM_AUTH' => true, - 'FORUM_NAME' => htmlCHR($forum_name), - 'U_SWITCH_MODE' => $u_switch_mode, - 'S_FORUMAUTH_ACTION' => 'admin_forumauth.php', - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); + $template->assign_vars(array( + 'TPL_EDIT_FORUM_AUTH' => true, + 'FORUM_NAME' => htmlCHR($forum_name), + 'U_SWITCH_MODE' => $u_switch_mode, + 'S_FORUMAUTH_ACTION' => 'admin_forumauth.php', + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); } -print_page('admin_forumauth.tpl', 'admin'); \ No newline at end of file +print_page('admin_forumauth.tpl', 'admin'); diff --git a/admin/admin_forumauth_list.php b/admin/admin_forumauth_list.php index b8c8a7188..613563f78 100644 --- a/admin/admin_forumauth_list.php +++ b/admin/admin_forumauth_list.php @@ -1,175 +1,174 @@ array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL), // Public -/* Reg */ 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered -/* Reg [Hid] */ 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered [Hidden] -/* Priv */ 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private -/* Priv [Hid] */ 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private [Hidden] -/* MOD */ 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators -/* MOD [Hid] */ 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] + /* Public */ + 0 => array(AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_ALL), // Public + /* Reg */ + 1 => array(AUTH_ALL, AUTH_ALL, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered + /* Reg [Hid] */ + 2 => array(AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_REG, AUTH_REG, AUTH_REG, AUTH_REG), // Registered [Hidden] + /* Priv */ + 3 => array(AUTH_REG, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private + /* Priv [Hid] */ + 4 => array(AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_MOD, AUTH_MOD, AUTH_ACL, AUTH_ACL, AUTH_ACL, AUTH_ACL), // Private [Hidden] + /* MOD */ + 5 => array(AUTH_REG, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators + /* MOD [Hid] */ + 6 => array(AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD, AUTH_MOD), // Moderators [Hidden] ); $simple_auth_types = array( - $lang['PUBLIC'], - $lang['REGISTERED'], - $lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', - $lang['PRIVATE'], - $lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', - $lang['MODERATORS'], - $lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', + $lang['PUBLIC'], + $lang['REGISTERED'], + $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']', + $lang['PRIVATE'], + $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']', + $lang['MODERATORS'], + $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']', ); $forum_auth_fields = array( - 'auth_view', - 'auth_read', - 'auth_reply', - 'auth_edit', - 'auth_delete', - 'auth_vote', - 'auth_pollcreate', - 'auth_attachments', - 'auth_download', - 'auth_post', - 'auth_sticky', - 'auth_announce', + 'auth_view', + 'auth_read', + 'auth_reply', + 'auth_edit', + 'auth_delete', + 'auth_vote', + 'auth_pollcreate', + 'auth_attachments', + 'auth_download', + 'auth_post', + 'auth_sticky', + 'auth_announce', ); $field_names = array(); -foreach ($forum_auth_fields as $auth_type) -{ - $field_names[$auth_type] = $lang[strtoupper($auth_type)]; +foreach ($forum_auth_fields as $auth_type) { + $field_names[$auth_type] = $lang[strtoupper($auth_type)]; } -$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); -$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); +$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); +$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); -if(isset($_GET[POST_FORUM_URL]) || isset($_POST[POST_FORUM_URL])) -{ - $forum_id = (isset($_POST[POST_FORUM_URL])) ? intval($_POST[POST_FORUM_URL]) : intval($_GET[POST_FORUM_URL]); - $forum_sql = "AND forum_id = $forum_id"; -} -else -{ - unset($forum_id); - $forum_sql = ''; +if (isset($_GET[POST_FORUM_URL]) || isset($_POST[POST_FORUM_URL])) { + $forum_id = (isset($_POST[POST_FORUM_URL])) ? intval($_POST[POST_FORUM_URL]) : intval($_GET[POST_FORUM_URL]); + $forum_sql = "AND forum_id = $forum_id"; +} else { + unset($forum_id); + $forum_sql = ''; } -if(isset($_GET[POST_CAT_URL]) || isset($_POST[POST_CAT_URL])) -{ - $cat_id = (isset($_POST[POST_CAT_URL])) ? intval($_POST[POST_CAT_URL]) : intval($_GET[POST_CAT_URL]); - $cat_sql = "AND c.cat_id = $cat_id"; -} -else -{ - unset($cat_id); - $cat_sql = ''; +if (isset($_GET[POST_CAT_URL]) || isset($_POST[POST_CAT_URL])) { + $cat_id = (isset($_POST[POST_CAT_URL])) ? intval($_POST[POST_CAT_URL]) : intval($_GET[POST_CAT_URL]); + $cat_sql = "AND c.cat_id = $cat_id"; +} else { + unset($cat_id); + $cat_sql = ''; } -if( isset($_GET['adv']) ) -{ - $adv = intval($_GET['adv']); -} -else -{ - unset($adv); +if (isset($_GET['adv'])) { + $adv = intval($_GET['adv']); +} else { + unset($adv); } // // Start program proper // -if( isset($_POST['submit']) ) -{ - $sql = ''; +if (isset($_POST['submit'])) { + $sql = ''; - if(!empty($forum_id)) - { - if(isset($_POST['simpleauth'])) - { - $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; + if (!empty($forum_id)) { + if (isset($_POST['simpleauth'])) { + $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; - for($i = 0; $i < count($simple_ary); $i++) - { - $sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; - } + for ($i = 0; $i < count($simple_ary); $i++) { + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i]; + } - if (is_array($simple_ary)) - { - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } - } - else - { - for($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); + if (is_array($simple_ary)) { + $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } + } else { + for ($i = 0; $i < count($forum_auth_fields); $i++) { + $value = intval($_POST[$forum_auth_fields[$i]]); - if ( $forum_auth_fields[$i] == 'auth_vote' ) - { - if ( $_POST['auth_vote'] == AUTH_ALL ) - { - $value = AUTH_REG; - } - } + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; - } + $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; + } - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table #1'); - } - } + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table #1'); + } + } - $forum_sql = ''; - $adv = 0; - } - elseif (!empty($cat_id)) - { - for ($i = 0; $i < count($forum_auth_fields); $i++) - { - $value = intval($_POST[$forum_auth_fields[$i]]); + $forum_sql = ''; + $adv = 0; + } elseif (!empty($cat_id)) { + for ($i = 0; $i < count($forum_auth_fields); $i++) { + $value = intval($_POST[$forum_auth_fields[$i]]); - if ($forum_auth_fields[$i] == 'auth_vote') - { - if ( $_POST['auth_vote'] == AUTH_ALL ) - { - $value = AUTH_REG; - } - } + if ($forum_auth_fields[$i] == 'auth_vote') { + if ($_POST['auth_vote'] == AUTH_ALL) { + $value = AUTH_REG; + } + } - $sql .= ( ( $sql != '' ) ? ', ' : '' ) .$forum_auth_fields[$i] . ' = ' . $value; - } + $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $value; + } - $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE cat_id = $cat_id"; + $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE cat_id = $cat_id"; - if ($sql != '') - { - if (!DB()->sql_query($sql)) - { - bb_die('Could not update auth table #2'); - } - } + if ($sql != '') { + if (!DB()->sql_query($sql)) { + bb_die('Could not update auth table #2'); + } + } - $cat_sql = ''; - } - - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); + $cat_sql = ''; + } + $datastore->update('cat_forums'); + bb_die($lang['FORUM_AUTH_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); } // End of submit // @@ -182,182 +181,161 @@ $sql = "SELECT f.* WHERE c.cat_id = f.cat_id $forum_sql $cat_sql ORDER BY c.cat_order ASC, f.forum_order ASC"; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not obtain forum list'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain forum list'); } $forum_rows = DB()->sql_fetchrowset($result); DB()->sql_freeresult($result); -if( empty($forum_id) && empty($cat_id) ) -{ - // - // Output the summary list if no forum id was - // specified - // - $template->assign_vars(array( - 'TPL_AUTH_FORUM_LIST' => true, - 'S_COLUMN_SPAN' => count($forum_auth_fields)+1, - )); +if (empty($forum_id) && empty($cat_id)) { + // + // Output the summary list if no forum id was + // specified + // + $template->assign_vars(array( + 'TPL_AUTH_FORUM_LIST' => true, + 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, + )); - for ($i = 0; $iassign_block_vars('forum_auth_titles', array( - 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], - )); - } + for ($i = 0; $i < count($forum_auth_fields); $i++) { + $template->assign_block_vars('forum_auth_titles', array( + 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], + )); + } - // Obtain the category list - $sql = "SELECT c.cat_id, c.cat_title, c.cat_order + // Obtain the category list + $sql = "SELECT c.cat_id, c.cat_title, c.cat_order FROM " . BB_CATEGORIES . " c ORDER BY c.cat_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query categories list #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query categories list #1'); + } - $category_rows = DB()->sql_fetchrowset($result); - $cat_count = count($category_rows); + $category_rows = DB()->sql_fetchrowset($result); + $cat_count = count($category_rows); - for ($i=0; $i<$cat_count; $i++) - { - $cat_id = $category_rows[$i]['cat_id']; + for ($i = 0; $i < $cat_count; $i++) { + $cat_id = $category_rows[$i]['cat_id']; - $template->assign_block_vars('cat_row', array( - 'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']), - 'CAT_URL' => 'admin_forumauth_list.php'.'?'.POST_CAT_URL.'='.$category_rows[$i]['cat_id']) - ); + $template->assign_block_vars('cat_row', array( + 'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']), + 'CAT_URL' => 'admin_forumauth_list.php' . '?' . POST_CAT_URL . '=' . $category_rows[$i]['cat_id']) + ); - for ($j=0; $jassign_block_vars('cat_row.forum_row', array( - 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', - 'FORUM_NAME' => ''. htmlCHR($forum_rows[$j]['forum_name']) .'', - 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], - )); + for ($j = 0; $j < count($forum_rows); $j++) { + if ($cat_id == $forum_rows[$j]['cat_id']) { + $template->assign_block_vars('cat_row.forum_row', array( + 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', + 'FORUM_NAME' => '' . htmlCHR($forum_rows[$j]['forum_name']) . '', + 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], + )); - for ($k=0; $kassign_block_vars('cat_row.forum_row.forum_auth_data', array( - 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], - 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) - ); - } - } - } - } -} -else -{ - // - // output the authorisation details if an category id was - // specified - // + for ($k = 0; $k < count($forum_auth_fields); $k++) { + $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; + for ($l = 0; $l < count($forum_auth_const); $l++) { + if ($item_auth_value == $forum_auth_const[$l]) { + $item_auth_level = $forum_auth_levels[$l]; + break; + } + } + $template->assign_block_vars('cat_row.forum_row.forum_auth_data', array( + 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], + 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) + ); + } + } + } + } +} else { + // + // output the authorisation details if an category id was + // specified + // - // - // first display the current details for all forums - // in the category - // - for ($i = 0; $iassign_block_vars('forum_auth_titles', array( - 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], - )); - } + // + // first display the current details for all forums + // in the category + // + for ($i = 0; $i < count($forum_auth_fields); $i++) { + $template->assign_block_vars('forum_auth_titles', array( + 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], + )); + } - // obtain the category list - $sql = "SELECT c.cat_id, c.cat_title, c.cat_order + // obtain the category list + $sql = "SELECT c.cat_id, c.cat_title, c.cat_order FROM " . BB_CATEGORIES . " c WHERE c.cat_id = $cat_id ORDER BY c.cat_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query categories list #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query categories list #2'); + } - $category_rows = DB()->sql_fetchrowset($result); + $category_rows = DB()->sql_fetchrowset($result); - $cat_id = $category_rows[0]['cat_id']; - $cat_name = $category_rows[0]['cat_title']; + $cat_id = $category_rows[0]['cat_id']; + $cat_name = $category_rows[0]['cat_title']; - $template->assign_block_vars('cat_row', array( - 'CAT_NAME' => htmlCHR($cat_name), - 'CAT_URL' => 'admin_forumauth_list.php?'. POST_CAT_URL .'='. $cat_id) - ); + $template->assign_block_vars('cat_row', array( + 'CAT_NAME' => htmlCHR($cat_name), + 'CAT_URL' => 'admin_forumauth_list.php?' . POST_CAT_URL . '=' . $cat_id) + ); - for ($j=0; $jassign_block_vars('cat_row.forum_row', array( - 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', - 'FORUM_NAME' => ''. htmlCHR($forum_rows[$j]['forum_name']) .'', - 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], - )); + for ($j = 0; $j < count($forum_rows); $j++) { + if ($cat_id == $forum_rows[$j]['cat_id']) { + $template->assign_block_vars('cat_row.forum_row', array( + 'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', + 'FORUM_NAME' => '' . htmlCHR($forum_rows[$j]['forum_name']) . '', + 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'], + )); - for ($k=0; $kassign_block_vars('cat_row.forum_row.forum_auth_data', array( - 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], - 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) - ); - } - } - } + for ($k = 0; $k < count($forum_auth_fields); $k++) { + $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; + for ($l = 0; $l < count($forum_auth_const); $l++) { + if ($item_auth_value == $forum_auth_const[$l]) { + $item_auth_level = $forum_auth_levels[$l]; + break; + } + } + $template->assign_block_vars('cat_row.forum_row.forum_auth_data', array( + 'CELL_VALUE' => $lang['FORUM_' . $item_auth_level], + 'AUTH_EXPLAIN' => sprintf($lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $forum_auth_fields[$k])], $lang[strtoupper('FORUM_AUTH_LIST_EXPLAIN_' . $item_auth_level)])) + ); + } + } + } - // - // next generate the information to allow the permissions to be changed - // note: we always read from the first forum in the category - // - for($j = 0; $j < count($forum_auth_fields); $j++) - { - $custom_auth[$j] = ''; - for($k = 0; $k < count($forum_auth_levels); $k++) - { - $selected = ( !empty($forum_rows) && $forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k] ) ? ' selected="selected"' : ''; - $custom_auth[$j] .= ''; - } - $custom_auth[$j] .= ''; + for ($k = 0; $k < count($forum_auth_levels); $k++) { + $selected = (!empty($forum_rows) && $forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k]) ? ' selected="selected"' : ''; + $custom_auth[$j] .= ''; + } + $custom_auth[$j] .= ''; - $template->assign_block_vars('forum_auth_data', array( - 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j]) - ); - } + $template->assign_block_vars('forum_auth_data', array( + 'S_AUTH_LEVELS_SELECT' => $custom_auth[$j]) + ); + } - // - // finally pass any remaining items to the template - // - $s_hidden_fields = ''; + // + // finally pass any remaining items to the template + // + $s_hidden_fields = ''; - $template->assign_vars(array( - 'TPL_AUTH_CAT' => true, - 'CAT_NAME' => htmlCHR($cat_name), - 'S_FORUMAUTH_ACTION' => 'admin_forumauth_list.php', - 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); + $template->assign_vars(array( + 'TPL_AUTH_CAT' => true, + 'CAT_NAME' => htmlCHR($cat_name), + 'S_FORUMAUTH_ACTION' => 'admin_forumauth_list.php', + 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); } -print_page('admin_forumauth_list.tpl', 'admin'); \ No newline at end of file +print_page('admin_forumauth_list.tpl', 'admin'); diff --git a/admin/admin_forums.php b/admin/admin_forums.php index eb2c56ae4..f2d2d4fae 100644 --- a/admin/admin_forums.php +++ b/admin/admin_forums.php @@ -1,302 +1,298 @@ AUTH_ALL, - 'auth_read' => AUTH_ALL, - 'auth_post' => AUTH_REG, - 'auth_reply' => AUTH_REG, - 'auth_edit' => AUTH_REG, - 'auth_delete' => AUTH_REG, - 'auth_sticky' => AUTH_MOD, - 'auth_announce' => AUTH_MOD, - 'auth_vote' => AUTH_REG, - 'auth_pollcreate' => AUTH_REG, - 'auth_attachments' => AUTH_REG, - 'auth_download' => AUTH_REG, + 'auth_view' => AUTH_ALL, + 'auth_read' => AUTH_ALL, + 'auth_post' => AUTH_REG, + 'auth_reply' => AUTH_REG, + 'auth_edit' => AUTH_REG, + 'auth_delete' => AUTH_REG, + 'auth_sticky' => AUTH_MOD, + 'auth_announce' => AUTH_MOD, + 'auth_vote' => AUTH_REG, + 'auth_pollcreate' => AUTH_REG, + 'auth_attachments' => AUTH_REG, + 'auth_download' => AUTH_REG, ); -$mode = (@$_REQUEST['mode']) ? (string) $_REQUEST['mode'] : ''; +$mode = (@$_REQUEST['mode']) ? (string)$_REQUEST['mode'] : ''; $cat_forums = get_cat_forums(); -if ($orphan_sf_sql = get_orphan_sf()) -{ - fix_orphan_sf($orphan_sf_sql, TRUE); +if ($orphan_sf_sql = get_orphan_sf()) { + fix_orphan_sf($orphan_sf_sql, true); } $forum_parent = $cat_id = 0; $forumname = ''; -if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) -{ - $mode = (isset($_REQUEST['addforum'])) ? "addforum" : "addcat"; +if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) { + $mode = (isset($_REQUEST['addforum'])) ? "addforum" : "addcat"; - if ($mode == 'addforum' && isset($_POST['addforum']) && isset($_POST['forumname']) && is_array($_POST['addforum'])) - { - $req_cat_id = array_keys($_POST['addforum']); - $cat_id = $req_cat_id[0]; - $forumname = stripslashes($_POST['forumname'][$cat_id]); - } + if ($mode == 'addforum' && isset($_POST['addforum']) && isset($_POST['forumname']) && is_array($_POST['addforum'])) { + $req_cat_id = array_keys($_POST['addforum']); + $cat_id = $req_cat_id[0]; + $forumname = stripslashes($_POST['forumname'][$cat_id]); + } } $show_main_page = false; -if ($mode) -{ - switch ($mode) - { - case 'addforum': - case 'editforum': - // - // Show form to create/modify a forum - // - if ($mode == 'editforum') - { - // $newmode determines if we are going to INSERT or UPDATE after posting? +if ($mode) { + switch ($mode) { + case 'addforum': + case 'editforum': + // + // Show form to create/modify a forum + // + if ($mode == 'editforum') { + // $newmode determines if we are going to INSERT or UPDATE after posting? - $l_title = $lang['EDIT_FORUM']; - $newmode = 'modforum'; - $buttonvalue = $lang['UPDATE']; + $l_title = $lang['EDIT_FORUM']; + $newmode = 'modforum'; + $buttonvalue = $lang['UPDATE']; - $forum_id = intval($_GET[POST_FORUM_URL]); + $forum_id = intval($_GET[POST_FORUM_URL]); - $row = get_info('forum', $forum_id); + $row = get_info('forum', $forum_id); - $cat_id = $row['cat_id']; - $forumname = $row['forum_name']; - $forumdesc = $row['forum_desc']; - $forumstatus = $row['forum_status']; - $forum_display_sort = $row['forum_display_sort']; - $forum_display_order = $row['forum_display_order']; - $forum_parent = $row['forum_parent']; - $show_on_index = $row['show_on_index']; - $prune_days = $row['prune_days']; - $forum_tpl_id = $row['forum_tpl_id']; - $allow_reg_tracker = $row['allow_reg_tracker']; - $allow_porno_topic = $row['allow_porno_topic']; - $self_moderated = $row['self_moderated']; - } - else - { - $l_title = $lang['CREATE_FORUM']; - $newmode = 'createforum'; - $buttonvalue = $lang['CREATE_FORUM']; + $cat_id = $row['cat_id']; + $forumname = $row['forum_name']; + $forumdesc = $row['forum_desc']; + $forumstatus = $row['forum_status']; + $forum_display_sort = $row['forum_display_sort']; + $forum_display_order = $row['forum_display_order']; + $forum_parent = $row['forum_parent']; + $show_on_index = $row['show_on_index']; + $prune_days = $row['prune_days']; + $forum_tpl_id = $row['forum_tpl_id']; + $allow_reg_tracker = $row['allow_reg_tracker']; + $allow_porno_topic = $row['allow_porno_topic']; + $self_moderated = $row['self_moderated']; + } else { + $l_title = $lang['CREATE_FORUM']; + $newmode = 'createforum'; + $buttonvalue = $lang['CREATE_FORUM']; - $forumdesc = ''; - $forumstatus = FORUM_UNLOCKED; - $forum_display_sort = 0; - $forum_display_order = 0; - $forum_id = ''; - $show_on_index = 1; - $prune_days = 0; - $forum_tpl_id = 0; - $allow_reg_tracker = 0; - $allow_porno_topic = 0; - $self_moderated = 0; - } + $forumdesc = ''; + $forumstatus = FORUM_UNLOCKED; + $forum_display_sort = 0; + $forum_display_order = 0; + $forum_id = ''; + $show_on_index = 1; + $prune_days = 0; + $forum_tpl_id = 0; + $allow_reg_tracker = 0; + $allow_porno_topic = 0; + $self_moderated = 0; + } - if (isset($_REQUEST['forum_parent'])) - { - $forum_parent = intval($_REQUEST['forum_parent']); + if (isset($_REQUEST['forum_parent'])) { + $forum_parent = intval($_REQUEST['forum_parent']); - if ($parent = get_forum_data($forum_parent)) - { - $cat_id = $parent['cat_id']; - } - } - else if (isset($_REQUEST['c'])) - { - $cat_id = (int) $_REQUEST['c']; - } + if ($parent = get_forum_data($forum_parent)) { + $cat_id = $parent['cat_id']; + } + } elseif (isset($_REQUEST['c'])) { + $cat_id = (int)$_REQUEST['c']; + } - $catlist = get_list('category', $cat_id, TRUE); - $forumlocked = $forumunlocked = ''; + $catlist = get_list('category', $cat_id, true); + $forumlocked = $forumunlocked = ''; - $forumstatus == ( FORUM_LOCKED ) ? $forumlocked = 'selected="selected"' : $forumunlocked = 'selected="selected"'; + $forumstatus == (FORUM_LOCKED) ? $forumlocked = 'selected="selected"' : $forumunlocked = 'selected="selected"'; - $statuslist = '\n'; - $statuslist .= '\n'; + $statuslist = '\n'; + $statuslist .= '\n'; - $forum_display_sort_list = get_forum_display_sort_option($forum_display_sort, 'list', 'sort'); - $forum_display_order_list = get_forum_display_sort_option($forum_display_order, 'list', 'order'); + $forum_display_sort_list = get_forum_display_sort_option($forum_display_sort, 'list', 'sort'); + $forum_display_order_list = get_forum_display_sort_option($forum_display_order, 'list', 'order'); - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $s_parent = '\n'; - $sel_forum = ($forum_parent && !isset($_REQUEST['forum_parent'])) ? $forum_id : $forum_parent; - $s_parent .= sf_get_list('forum', $forum_id, $sel_forum); + $s_parent = '\n'; + $sel_forum = ($forum_parent && !isset($_REQUEST['forum_parent'])) ? $forum_id : $forum_parent; + $s_parent .= sf_get_list('forum', $forum_id, $sel_forum); - $template->assign_vars(array( - 'TPL_EDIT_FORUM' => true, + $template->assign_vars(array( + 'TPL_EDIT_FORUM' => true, - 'S_FORUM_DISPLAY_SORT_LIST' => $forum_display_sort_list, - 'S_FORUM_DISPLAY_ORDER_LIST' => $forum_display_order_list, - 'S_FORUM_ACTION' => 'admin_forums.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_SUBMIT_VALUE' => $buttonvalue, - 'S_CAT_LIST' => $catlist, - 'S_STATUS_LIST' => $statuslist, + 'S_FORUM_DISPLAY_SORT_LIST' => $forum_display_sort_list, + 'S_FORUM_DISPLAY_ORDER_LIST' => $forum_display_order_list, + 'S_FORUM_ACTION' => 'admin_forums.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_SUBMIT_VALUE' => $buttonvalue, + 'S_CAT_LIST' => $catlist, + 'S_STATUS_LIST' => $statuslist, - 'SHOW_ON_INDEX' => $show_on_index, - 'S_PARENT_FORUM' => $s_parent, - 'CAT_LIST_CLASS' => ($forum_parent) ? 'hidden' : '', - 'SHOW_ON_INDEX_CLASS' => (!$forum_parent) ? 'hidden' : '', - 'TPL_SELECT' => get_select('forum_tpl', $forum_tpl_id, 'html', $lang['TEMPLATE_DISABLE']), - 'ALLOW_REG_TRACKER' => build_select('allow_reg_tracker', array($lang['DISALLOWED'] => 0, $lang['ALLOWED'] => 1), $allow_reg_tracker), - 'ALLOW_PORNO_TOPIC' => build_select('allow_porno_topic', array($lang['NONE'] => 0, $lang['YES'] => 1), $allow_porno_topic), - 'SELF_MODERATED' => build_select('self_moderated', array($lang['NONE'] => 0, $lang['YES'] => 1), $self_moderated), + 'SHOW_ON_INDEX' => $show_on_index, + 'S_PARENT_FORUM' => $s_parent, + 'CAT_LIST_CLASS' => ($forum_parent) ? 'hidden' : '', + 'SHOW_ON_INDEX_CLASS' => (!$forum_parent) ? 'hidden' : '', + 'TPL_SELECT' => get_select('forum_tpl', $forum_tpl_id, 'html', $lang['TEMPLATE_DISABLE']), + 'ALLOW_REG_TRACKER' => build_select('allow_reg_tracker', array($lang['DISALLOWED'] => 0, $lang['ALLOWED'] => 1), $allow_reg_tracker), + 'ALLOW_PORNO_TOPIC' => build_select('allow_porno_topic', array($lang['NONE'] => 0, $lang['YES'] => 1), $allow_porno_topic), + 'SELF_MODERATED' => build_select('self_moderated', array($lang['NONE'] => 0, $lang['YES'] => 1), $self_moderated), - 'L_FORUM_TITLE' => $l_title, + 'L_FORUM_TITLE' => $l_title, - 'PRUNE_DAYS' => $prune_days, - 'FORUM_NAME' => htmlCHR($forumname), - 'DESCRIPTION' => htmlCHR($forumdesc), - )); - break; + 'PRUNE_DAYS' => $prune_days, + 'FORUM_NAME' => htmlCHR($forumname), + 'DESCRIPTION' => htmlCHR($forumdesc), + )); + break; - case 'createforum': - // - // Create a forum in the DB - // - $cat_id = intval($_POST[POST_CAT_URL]); - $forum_name = (string) $_POST['forumname']; - $forum_desc = (string) $_POST['forumdesc']; - $forum_status = intval($_POST['forumstatus']); + case 'createforum': + // + // Create a forum in the DB + // + $cat_id = intval($_POST[POST_CAT_URL]); + $forum_name = (string)$_POST['forumname']; + $forum_desc = (string)$_POST['forumdesc']; + $forum_status = intval($_POST['forumstatus']); - $prune_days = intval($_POST['prune_days']); + $prune_days = intval($_POST['prune_days']); - $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; - $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; + $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; + $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; - $forum_display_sort = intval($_POST['forum_display_sort']); - $forum_display_order = intval($_POST['forum_display_order']); + $forum_display_sort = intval($_POST['forum_display_sort']); + $forum_display_order = intval($_POST['forum_display_order']); - $forum_tpl_id = (int) $_POST['forum_tpl_select']; - $allow_reg_tracker = (int) $_POST['allow_reg_tracker']; - $allow_porno_topic = (int) $_POST['allow_porno_topic']; - $self_moderated = (int) $_POST['self_moderated']; + $forum_tpl_id = (int)$_POST['forum_tpl_select']; + $allow_reg_tracker = (int)$_POST['allow_reg_tracker']; + $allow_porno_topic = (int)$_POST['allow_porno_topic']; + $self_moderated = (int)$_POST['self_moderated']; - if (!$forum_name) - { - bb_die('Can not create a forum without a name'); - } + if (!$forum_name) { + bb_die('Can not create a forum without a name'); + } - if ($forum_parent) - { - if (!$parent = get_forum_data($forum_parent)) - { - bb_die('Parent forum with id '. $forum_parent .' not found'); - } + if ($forum_parent) { + if (!$parent = get_forum_data($forum_parent)) { + bb_die('Parent forum with id ' . $forum_parent . ' not found'); + } - $cat_id = $parent['cat_id']; - $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; - $forum_order = $parent['forum_order'] + 5; - } - else - { - $max_order = get_max_forum_order($cat_id); - $forum_order = $max_order + 5; - } + $cat_id = $parent['cat_id']; + $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; + $forum_order = $parent['forum_order'] + 5; + } else { + $max_order = get_max_forum_order($cat_id); + $forum_order = $max_order + 5; + } - // Default permissions of public forum - $field_sql = $value_sql = ''; + // Default permissions of public forum + $field_sql = $value_sql = ''; - foreach ($default_forum_auth as $field => $value) - { - $field_sql .= ", $field"; - $value_sql .= ", $value"; - } + foreach ($default_forum_auth as $field => $value) { + $field_sql .= ", $field"; + $value_sql .= ", $value"; + } - $forum_name_sql = DB()->escape($forum_name); - $forum_desc_sql = DB()->escape($forum_desc); + $forum_name_sql = DB()->escape($forum_name); + $forum_desc_sql = DB()->escape($forum_desc); - $columns = ' forum_name, cat_id, forum_desc, forum_order, forum_status, prune_days, forum_parent, show_on_index, forum_display_sort, forum_display_order, forum_tpl_id, allow_reg_tracker, allow_porno_topic, self_moderated'. $field_sql; - $values = "'$forum_name_sql', $cat_id, '$forum_desc_sql', $forum_order, $forum_status, $prune_days, $forum_parent, $show_on_index, $forum_display_sort, $forum_display_order, $forum_tpl_id, $allow_reg_tracker, $allow_porno_topic, $self_moderated". $value_sql; + $columns = ' forum_name, cat_id, forum_desc, forum_order, forum_status, prune_days, forum_parent, show_on_index, forum_display_sort, forum_display_order, forum_tpl_id, allow_reg_tracker, allow_porno_topic, self_moderated' . $field_sql; + $values = "'$forum_name_sql', $cat_id, '$forum_desc_sql', $forum_order, $forum_status, $prune_days, $forum_parent, $show_on_index, $forum_display_sort, $forum_display_order, $forum_tpl_id, $allow_reg_tracker, $allow_porno_topic, $self_moderated" . $value_sql; - DB()->query("INSERT INTO ". BB_FORUMS ." ($columns) VALUES ($values)"); + DB()->query("INSERT INTO " . BB_FORUMS . " ($columns) VALUES ($values)"); - renumber_order('forum', $cat_id); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $cat_id); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'modforum': - // - // Modify a forum in the DB - // - $cat_id = intval($_POST[POST_CAT_URL]); - $forum_id = intval($_POST[POST_FORUM_URL]); - $forum_name = (string) $_POST['forumname']; - $forum_desc = (string) $_POST['forumdesc']; - $forum_status = intval($_POST['forumstatus']); - $prune_days = intval($_POST['prune_days']); + case 'modforum': + // + // Modify a forum in the DB + // + $cat_id = intval($_POST[POST_CAT_URL]); + $forum_id = intval($_POST[POST_FORUM_URL]); + $forum_name = (string)$_POST['forumname']; + $forum_desc = (string)$_POST['forumdesc']; + $forum_status = intval($_POST['forumstatus']); + $prune_days = intval($_POST['prune_days']); - $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; - $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; + $forum_parent = ($_POST['forum_parent'] != -1) ? intval($_POST['forum_parent']) : 0; + $show_on_index = ($forum_parent) ? intval($_POST['show_on_index']) : 1; - $forum_display_order = intval($_POST['forum_display_order']); - $forum_display_sort = intval($_POST['forum_display_sort']); - $forum_tpl_id = (int) $_POST['forum_tpl_select']; - $allow_reg_tracker = (int) $_POST['allow_reg_tracker']; - $allow_porno_topic = (int) $_POST['allow_porno_topic']; - $self_moderated = (int) $_POST['self_moderated']; + $forum_display_order = intval($_POST['forum_display_order']); + $forum_display_sort = intval($_POST['forum_display_sort']); + $forum_tpl_id = (int)$_POST['forum_tpl_select']; + $allow_reg_tracker = (int)$_POST['allow_reg_tracker']; + $allow_porno_topic = (int)$_POST['allow_porno_topic']; + $self_moderated = (int)$_POST['self_moderated']; - $forum_data = get_forum_data($forum_id); - $old_cat_id = $forum_data['cat_id']; - $forum_order = $forum_data['forum_order']; + $forum_data = get_forum_data($forum_id); + $old_cat_id = $forum_data['cat_id']; + $forum_order = $forum_data['forum_order']; - if (!$forum_name) - { - bb_die('Can not modify a forum without a name'); - } + if (!$forum_name) { + bb_die('Can not modify a forum without a name'); + } - if ($forum_parent) - { - if (!$parent = get_forum_data($forum_parent)) - { - bb_die('Parent forum with id '. $forum_parent .' not found'); - } + if ($forum_parent) { + if (!$parent = get_forum_data($forum_parent)) { + bb_die('Parent forum with id ' . $forum_parent . ' not found'); + } - $cat_id = $parent['cat_id']; - $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; - $forum_order = $parent['forum_order'] + 5; + $cat_id = $parent['cat_id']; + $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; + $forum_order = $parent['forum_order'] + 5; - if ($forum_id == $forum_parent) - { - bb_die('Ambiguous forum ID. Please select other parent forum'); - } - } - else if ($cat_id != $old_cat_id) - { - $max_order = get_max_forum_order($cat_id); - $forum_order = $max_order + 5; - } - else if ($forum_data['forum_parent']) - { - $old_parent = $forum_data['forum_parent']; - $forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5; - } + if ($forum_id == $forum_parent) { + bb_die('Ambiguous forum ID. Please select other parent forum'); + } + } elseif ($cat_id != $old_cat_id) { + $max_order = get_max_forum_order($cat_id); + $forum_order = $max_order + 5; + } elseif ($forum_data['forum_parent']) { + $old_parent = $forum_data['forum_parent']; + $forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5; + } - $forum_name_sql = DB()->escape($forum_name); - $forum_desc_sql = DB()->escape($forum_desc); + $forum_name_sql = DB()->escape($forum_name); + $forum_desc_sql = DB()->escape($forum_desc); - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(" + UPDATE " . BB_FORUMS . " SET forum_name = '$forum_name_sql', cat_id = $cat_id, forum_desc = '$forum_desc_sql', @@ -314,905 +310,812 @@ if ($mode) WHERE forum_id = $forum_id "); - if ($cat_id != $old_cat_id) - { - change_sf_cat($forum_id, $cat_id, $forum_order); - renumber_order('forum', $cat_id); - } + if ($cat_id != $old_cat_id) { + change_sf_cat($forum_id, $cat_id, $forum_order); + renumber_order('forum', $cat_id); + } - renumber_order('forum', $old_cat_id); + renumber_order('forum', $old_cat_id); - $cat_forums = get_cat_forums(); - $fix = fix_orphan_sf(); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $message = $lang['FORUMS_UPDATED'] . '

'; - $message .= ($fix) ? "$fix

" : ''; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + $message = $lang['FORUMS_UPDATED'] . '

'; + $message .= ($fix) ? "$fix

" : ''; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); - break; + break; - case 'addcat': - // - // Create a category in the DB - // - if (!$new_cat_title = trim($_POST['categoryname'])) - { - bb_die('Category name is empty'); - } + case 'addcat': + // + // Create a category in the DB + // + if (!$new_cat_title = trim($_POST['categoryname'])) { + bb_die('Category name is empty'); + } - check_name_dup('cat', $new_cat_title); + check_name_dup('cat', $new_cat_title); - $order = DB()->fetch_row("SELECT MAX(cat_order) AS max_order FROM ". BB_CATEGORIES); + $order = DB()->fetch_row("SELECT MAX(cat_order) AS max_order FROM " . BB_CATEGORIES); - $args = DB()->build_array('INSERT', array( - 'cat_title' => (string) $new_cat_title, - 'cat_order' => (int) $order['max_order'] + 10, - )); + $args = DB()->build_array('INSERT', array( + 'cat_title' => (string)$new_cat_title, + 'cat_order' => (int)$order['max_order'] + 10, + )); - DB()->query("INSERT INTO ". BB_CATEGORIES . $args); + DB()->query("INSERT INTO " . BB_CATEGORIES . $args); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'editcat': - // - // Show form to edit a category - // - $cat_id = (int) $_GET['c']; - $cat_info = get_info('category', $cat_id); + case 'editcat': + // + // Show form to edit a category + // + $cat_id = (int)$_GET['c']; + $cat_info = get_info('category', $cat_id); - $hidden_fields = array( - 'mode' => 'modcat', - 'c' => $cat_id, - ); + $hidden_fields = array( + 'mode' => 'modcat', + 'c' => $cat_id, + ); - $template->assign_vars(array( - 'TPL_EDIT_CATEGORY' => true, - 'CAT_TITLE' => htmlCHR($cat_info['cat_title']), - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_SUBMIT_VALUE' => $lang['UPDATE'], - 'S_FORUM_ACTION' => "admin_forums.php", - )); + $template->assign_vars(array( + 'TPL_EDIT_CATEGORY' => true, + 'CAT_TITLE' => htmlCHR($cat_info['cat_title']), + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_SUBMIT_VALUE' => $lang['UPDATE'], + 'S_FORUM_ACTION' => "admin_forums.php", + )); - break; + break; - case 'modcat': - // - // Modify a category in the DB - // - if (!$new_cat_title = trim($_POST['cat_title'])) - { - bb_die('Category name is empty'); - } + case 'modcat': + // + // Modify a category in the DB + // + if (!$new_cat_title = trim($_POST['cat_title'])) { + bb_die('Category name is empty'); + } - $cat_id = (int) $_POST['c']; + $cat_id = (int)$_POST['c']; - $row = get_info('category', $cat_id); - $cur_cat_title = $row['cat_title']; + $row = get_info('category', $cat_id); + $cur_cat_title = $row['cat_title']; - if ($cur_cat_title && $cur_cat_title !== $new_cat_title) - { - check_name_dup('cat', $new_cat_title); + if ($cur_cat_title && $cur_cat_title !== $new_cat_title) { + check_name_dup('cat', $new_cat_title); - $new_cat_title_sql = DB()->escape($new_cat_title); + $new_cat_title_sql = DB()->escape($new_cat_title); - DB()->query(" - UPDATE ". BB_CATEGORIES ." SET + DB()->query(" + UPDATE " . BB_CATEGORIES . " SET cat_title = '$new_cat_title_sql' WHERE cat_id = $cat_id "); - } + } - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'deleteforum': - // - // Show form to delete a forum - // - $forum_id = (int) $_GET['f']; + case 'deleteforum': + // + // Show form to delete a forum + // + $forum_id = (int)$_GET['f']; - $move_to_options = ''; - $move_to_options .= sf_get_list('forum', $forum_id, 0); + $move_to_options = ''; + $move_to_options .= sf_get_list('forum', $forum_id, 0); - $foruminfo = get_info('forum', $forum_id); + $foruminfo = get_info('forum', $forum_id); - $hidden_fields = array( - 'mode' => 'movedelforum', - 'from_id' => $forum_id, - ); + $hidden_fields = array( + 'mode' => 'movedelforum', + 'from_id' => $forum_id, + ); - $template->assign_vars(array( - 'TPL_DELETE_FORUM' => true, + $template->assign_vars(array( + 'TPL_DELETE_FORUM' => true, - 'WHAT_TO_DELETE' => htmlCHR($foruminfo['forum_name']), - 'DELETE_TITLE' => $lang['FORUM_DELETE'], - 'CAT_FORUM_NAME' => $lang['FORUM_NAME'], + 'WHAT_TO_DELETE' => htmlCHR($foruminfo['forum_name']), + 'DELETE_TITLE' => $lang['FORUM_DELETE'], + 'CAT_FORUM_NAME' => $lang['FORUM_NAME'], - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_FORUM_ACTION' => "admin_forums.php", - 'MOVE_TO_OPTIONS' => $move_to_options, - 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], - )); + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_FORUM_ACTION' => "admin_forums.php", + 'MOVE_TO_OPTIONS' => $move_to_options, + 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], + )); - break; + break; - case 'movedelforum': - // - // Move or delete a forum in the DB - // - $from_id = (int) $_POST['from_id']; - $to_id = (int) $_POST['to_id']; + case 'movedelforum': + // + // Move or delete a forum in the DB + // + $from_id = (int)$_POST['from_id']; + $to_id = (int)$_POST['to_id']; - if ($to_id == -1) - { - // Delete everything from forum - topic_delete('prune', $from_id, 0, true); - } - else - { - // Move all posts - $sql = "SELECT * FROM ". BB_FORUMS ." WHERE forum_id IN($from_id, $to_id)"; - $result = DB()->query($sql); + if ($to_id == -1) { + // Delete everything from forum + topic_delete('prune', $from_id, 0, true); + } else { + // Move all posts + $sql = "SELECT * FROM " . BB_FORUMS . " WHERE forum_id IN($from_id, $to_id)"; + $result = DB()->query($sql); - if (DB()->num_rows($result) != 2) - { - bb_die('Ambiguous forum ID'); - } + if (DB()->num_rows($result) != 2) { + bb_die('Ambiguous forum ID'); + } - DB()->query("UPDATE ". BB_TOPICS ." SET forum_id = $to_id WHERE forum_id = $from_id"); - DB()->query("UPDATE ". BB_BT_TORRENTS ." SET forum_id = $to_id WHERE forum_id = $from_id"); + DB()->query("UPDATE " . BB_TOPICS . " SET forum_id = $to_id WHERE forum_id = $from_id"); + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET forum_id = $to_id WHERE forum_id = $from_id"); - $row = DB()->fetch_row("SELECT MIN(post_id) AS start_id, MAX(post_id) AS finish_id FROM ". BB_POSTS); - $start_id = (int) $row['start_id']; - $finish_id = (int) $row['finish_id']; - $per_cycle = 10000; - while (true) - { - set_time_limit(600); - $end_id = $start_id + $per_cycle - 1; - DB()->query(" - UPDATE ". BB_POSTS ." SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id + $row = DB()->fetch_row("SELECT MIN(post_id) AS start_id, MAX(post_id) AS finish_id FROM " . BB_POSTS); + $start_id = (int)$row['start_id']; + $finish_id = (int)$row['finish_id']; + $per_cycle = 10000; + while (true) { + set_time_limit(600); + $end_id = $start_id + $per_cycle - 1; + DB()->query(" + UPDATE " . BB_POSTS . " SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id "); - if ($end_id > $finish_id) - { - break; - } - $start_id += $per_cycle; - } + if ($end_id > $finish_id) { + break; + } + $start_id += $per_cycle; + } - sync('forum', $to_id); - } + sync('forum', $to_id); + } - DB()->query("DELETE FROM ". BB_FORUMS ." WHERE forum_id = $from_id"); - DB()->query("DELETE FROM ". BB_AUTH_ACCESS ." WHERE forum_id = $from_id"); - DB()->query("DELETE FROM ". BB_AUTH_ACCESS_SNAP ." WHERE forum_id = $from_id"); + DB()->query("DELETE FROM " . BB_FORUMS . " WHERE forum_id = $from_id"); + DB()->query("DELETE FROM " . BB_AUTH_ACCESS . " WHERE forum_id = $from_id"); + DB()->query("DELETE FROM " . BB_AUTH_ACCESS_SNAP . " WHERE forum_id = $from_id"); - $cat_forums = get_cat_forums(); - fix_orphan_sf(); - update_user_level('all'); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + $cat_forums = get_cat_forums(); + fix_orphan_sf(); + update_user_level('all'); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + bb_die($lang['FORUMS_UPDATED'] . '

' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + break; - case 'deletecat': - // Show form to delete a category - $cat_id = (int) $_GET['c']; - $catinfo = get_info('category', $cat_id); - $categories_count = $catinfo['number']; + case 'deletecat': + // Show form to delete a category + $cat_id = (int)$_GET['c']; + $catinfo = get_info('category', $cat_id); + $categories_count = $catinfo['number']; - if ($categories_count == 1) - { - $row = DB()->fetch_row("SELECT COUNT(*) AS forums_count FROM ". BB_FORUMS); + if ($categories_count == 1) { + $row = DB()->fetch_row("SELECT COUNT(*) AS forums_count FROM " . BB_FORUMS); - if ($row['forums_count'] > 0) - { - bb_die($lang['MUST_DELETE_FORUMS']); - } - else - { - $template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']); - } - } + if ($row['forums_count'] > 0) { + bb_die($lang['MUST_DELETE_FORUMS']); + } else { + $template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']); + } + } - $hidden_fields = array( - 'mode' => 'movedelcat', - 'from_id' => $cat_id, - ); + $hidden_fields = array( + 'mode' => 'movedelcat', + 'from_id' => $cat_id, + ); - $template->assign_vars(array( - 'TPL_DELETE_FORUM' => true, + $template->assign_vars(array( + 'TPL_DELETE_FORUM' => true, - 'WHAT_TO_DELETE' => htmlCHR($catinfo['cat_title']), - 'DELETE_TITLE' => $lang['CATEGORY_DELETE'], - 'CAT_FORUM_NAME' => $lang['CATEGORY'], + 'WHAT_TO_DELETE' => htmlCHR($catinfo['cat_title']), + 'DELETE_TITLE' => $lang['CATEGORY_DELETE'], + 'CAT_FORUM_NAME' => $lang['CATEGORY'], - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - 'S_FORUM_ACTION' => "admin_forums.php", - 'MOVE_TO_OPTIONS' => get_list('category', $cat_id, 0), - 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], - )); + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + 'S_FORUM_ACTION' => "admin_forums.php", + 'MOVE_TO_OPTIONS' => get_list('category', $cat_id, 0), + 'S_SUBMIT_VALUE' => $lang['MOVE_AND_DELETE'], + )); - break; + break; - case 'movedelcat': - // Move or delete a category in the DB - $from_id = (int) $_POST['from_id']; - $to_id = (int) $_POST['to_id']; + case 'movedelcat': + // Move or delete a category in the DB + $from_id = (int)$_POST['from_id']; + $to_id = (int)$_POST['to_id']; - if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) - { - bb_die('Bad input'); - } + if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) { + bb_die('Bad input'); + } - $order_shear = get_max_forum_order($to_id) + 10; + $order_shear = get_max_forum_order($to_id) + 10; - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(" + UPDATE " . BB_FORUMS . " SET cat_id = $to_id, forum_order = forum_order + $order_shear WHERE cat_id = $from_id "); - DB()->query("DELETE FROM ". BB_CATEGORIES ." WHERE cat_id = $from_id"); + DB()->query("DELETE FROM " . BB_CATEGORIES . " WHERE cat_id = $from_id"); - renumber_order('forum', $to_id); - $cat_forums = get_cat_forums(); - $fix = fix_orphan_sf(); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $to_id); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $message = $lang['FORUMS_UPDATED'] . '

'; - $message .= ($fix) ? "$fix

" : ''; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + $message = $lang['FORUMS_UPDATED'] . '

'; + $message .= ($fix) ? "$fix

" : ''; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); - break; + break; - case 'forum_order': - // Change order of forums - $move = intval($_GET['move']); - $forum_id = intval($_GET[POST_FORUM_URL]); + case 'forum_order': + // Change order of forums + $move = intval($_GET['move']); + $forum_id = intval($_GET[POST_FORUM_URL]); - $forum_info = get_info('forum', $forum_id); - renumber_order('forum', $forum_info['cat_id']); + $forum_info = get_info('forum', $forum_id); + renumber_order('forum', $forum_info['cat_id']); - $cat_id = $forum_info['cat_id']; + $cat_id = $forum_info['cat_id']; - $move_down_forum_id = FALSE; - $forums = $cat_forums[$cat_id]['f_ord']; - $forum_order = $forum_info['forum_order']; - $prev_forum = (isset($forums[$forum_order - 10])) ? $forums[$forum_order - 10] : FALSE; - $next_forum = (isset($forums[$forum_order + 10])) ? $forums[$forum_order + 10] : FALSE; + $move_down_forum_id = false; + $forums = $cat_forums[$cat_id]['f_ord']; + $forum_order = $forum_info['forum_order']; + $prev_forum = (isset($forums[$forum_order - 10])) ? $forums[$forum_order - 10] : false; + $next_forum = (isset($forums[$forum_order + 10])) ? $forums[$forum_order + 10] : false; - // move selected forum ($forum_id) UP - if ($move < 0 && $prev_forum) - { - if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent']) - { - $show_main_page = true; - break; - } - else if ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) - { - $move_up_forum_id = $forum_id; - $move_down_ord_val = (get_sf_count($forum_id) + 1) * 10; - $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; - $move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order']; - } - } - // move selected forum ($forum_id) DOWN - else if ($move > 0 && $next_forum) - { - if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent']) - { - $show_main_page = true; - break; - } - else if ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) - { - $move_down_forum_id = $forum_id; - $move_down_forum_order = $forum_order; - $move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10; - $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; - } - } - else - { - $show_main_page = true; - break; - } + // move selected forum ($forum_id) UP + if ($move < 0 && $prev_forum) { + if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent']) { + $show_main_page = true; + break; + } elseif ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) { + $move_up_forum_id = $forum_id; + $move_down_ord_val = (get_sf_count($forum_id) + 1) * 10; + $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; + $move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order']; + } + } // move selected forum ($forum_id) DOWN + elseif ($move > 0 && $next_forum) { + if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent']) { + $show_main_page = true; + break; + } elseif ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) { + $move_down_forum_id = $forum_id; + $move_down_forum_order = $forum_order; + $move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10; + $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; + } + } else { + $show_main_page = true; + break; + } - if ($forum_info['forum_parent']) - { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + if ($forum_info['forum_parent']) { + DB()->query(" + UPDATE " . BB_FORUMS . " SET forum_order = forum_order + $move WHERE forum_id = $forum_id "); - } - else if ($move_down_forum_id) - { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + } elseif ($move_down_forum_id) { + DB()->query(" + UPDATE " . BB_FORUMS . " SET forum_order = forum_order + $move_down_ord_val WHERE cat_id = $cat_id AND forum_order >= $move_down_forum_order "); - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(" + UPDATE " . BB_FORUMS . " SET forum_order = forum_order - $move_up_ord_val WHERE forum_id = $move_up_forum_id OR forum_parent = $move_up_forum_id "); - } + } - renumber_order('forum', $forum_info['cat_id']); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('forum', $forum_info['cat_id']); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - case 'cat_order': - $move = (int) $_GET['move']; - $cat_id = (int) $_GET['c']; + case 'cat_order': + $move = (int)$_GET['move']; + $cat_id = (int)$_GET['c']; - DB()->query(" - UPDATE ". BB_CATEGORIES ." SET + DB()->query(" + UPDATE " . BB_CATEGORIES . " SET cat_order = cat_order + $move WHERE cat_id = $cat_id "); - renumber_order('category'); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + renumber_order('category'); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - case 'forum_sync': - sync('forum', intval($_GET['f'])); - $datastore->update('cat_forums'); - CACHE('bb_cache')->rm(); + case 'forum_sync': + sync('forum', intval($_GET['f'])); + $datastore->update('cat_forums'); + CACHE('bb_cache')->rm(); - $show_main_page = true; - break; + $show_main_page = true; + break; - default: - bb_die($lang['NO_MODE']); + default: + bb_die($lang['NO_MODE']); - break; - } + break; + } } -if (!$mode || $show_main_page) -{ - $template->assign_vars(array( - 'TPL_FORUMS_LIST' => true, +if (!$mode || $show_main_page) { + $template->assign_vars(array( + 'TPL_FORUMS_LIST' => true, - 'S_FORUM_ACTION' => 'admin_forums.php', - 'L_FORUM_TITLE' => $lang['FORUM_ADMIN_MAIN'], - )); + 'S_FORUM_ACTION' => 'admin_forums.php', + 'L_FORUM_TITLE' => $lang['FORUM_ADMIN_MAIN'], + )); - $sql = "SELECT cat_id, cat_title, cat_order FROM " . BB_CATEGORIES . " ORDER BY cat_order"; - if (!$q_categories = DB()->sql_query($sql)) - { - bb_die('Could not query categories list'); - } + $sql = "SELECT cat_id, cat_title, cat_order FROM " . BB_CATEGORIES . " ORDER BY cat_order"; + if (!$q_categories = DB()->sql_query($sql)) { + bb_die('Could not query categories list'); + } - if ($total_categories = DB()->num_rows($q_categories)) - { - $category_rows = DB()->sql_fetchrowset($q_categories); + if ($total_categories = DB()->num_rows($q_categories)) { + $category_rows = DB()->sql_fetchrowset($q_categories); - $where_cat_sql = $req_cat_id = ''; + $where_cat_sql = $req_cat_id = ''; - if ($c =& $_REQUEST['c']) - { - if ($c !== 'all') - { - $req_cat_id = (int) $c; - $where_cat_sql = "WHERE cat_id = $req_cat_id"; - } - else - { - $req_cat_id = 'all'; - } - } - else - { - $where_cat_sql = "WHERE cat_id = '-1'"; - } + if ($c =& $_REQUEST['c']) { + if ($c !== 'all') { + $req_cat_id = (int)$c; + $where_cat_sql = "WHERE cat_id = $req_cat_id"; + } else { + $req_cat_id = 'all'; + } + } else { + $where_cat_sql = "WHERE cat_id = '-1'"; + } - $sql = "SELECT * FROM ". BB_FORUMS ." $where_cat_sql ORDER BY cat_id, forum_order"; - if (!$q_forums = DB()->sql_query($sql)) - { - bb_die('Could not query forums information'); - } + $sql = "SELECT * FROM " . BB_FORUMS . " $where_cat_sql ORDER BY cat_id, forum_order"; + if (!$q_forums = DB()->sql_query($sql)) { + bb_die('Could not query forums information'); + } - if ($total_forums = DB()->num_rows($q_forums)) - { - $forum_rows = DB()->sql_fetchrowset($q_forums); - } + if ($total_forums = DB()->num_rows($q_forums)) { + $forum_rows = DB()->sql_fetchrowset($q_forums); + } - // Okay, let's build the index - $gen_cat = array(); + // Okay, let's build the index + $gen_cat = array(); - $bgr_class_1 = 'prow1'; - $bgr_class_2 = 'prow2'; - $bgr_class_over = 'prow3'; + $bgr_class_1 = 'prow1'; + $bgr_class_2 = 'prow2'; + $bgr_class_over = 'prow3'; - $template->assign_vars(array( - 'U_ALL_FORUMS' => 'admin_forums.php?c=all', - 'FORUMS_COUNT' => $total_forums, - )); + $template->assign_vars(array( + 'U_ALL_FORUMS' => 'admin_forums.php?c=all', + 'FORUMS_COUNT' => $total_forums, + )); - for ($i = 0; $i < $total_categories; $i++) - { - $cat_id = $category_rows[$i]['cat_id']; + for ($i = 0; $i < $total_categories; $i++) { + $cat_id = $category_rows[$i]['cat_id']; - $template->assign_block_vars("c", array( - 'S_ADD_FORUM_SUBMIT' => "addforum[$cat_id]", - 'S_ADD_FORUM_NAME' => "forumname[$cat_id]", + $template->assign_block_vars("c", array( + 'S_ADD_FORUM_SUBMIT' => "addforum[$cat_id]", + 'S_ADD_FORUM_NAME' => "forumname[$cat_id]", - 'CAT_ID' => $cat_id, - 'CAT_DESC' => htmlCHR($category_rows[$i]['cat_title']), + 'CAT_ID' => $cat_id, + 'CAT_DESC' => htmlCHR($category_rows[$i]['cat_title']), - 'U_CAT_EDIT' => "admin_forums.php?mode=editcat&c=$cat_id", - 'U_CAT_DELETE' => "admin_forums.php?mode=deletecat&c=$cat_id", - 'U_CAT_MOVE_UP' => "admin_forums.php?mode=cat_order&move=-15&c=$cat_id", - 'U_CAT_MOVE_DOWN' => "admin_forums.php?mode=cat_order&move=15&c=$cat_id", - 'U_VIEWCAT' => "admin_forums.php?c=$cat_id", - 'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&c=$cat_id", - )); + 'U_CAT_EDIT' => "admin_forums.php?mode=editcat&c=$cat_id", + 'U_CAT_DELETE' => "admin_forums.php?mode=deletecat&c=$cat_id", + 'U_CAT_MOVE_UP' => "admin_forums.php?mode=cat_order&move=-15&c=$cat_id", + 'U_CAT_MOVE_DOWN' => "admin_forums.php?mode=cat_order&move=15&c=$cat_id", + 'U_VIEWCAT' => "admin_forums.php?c=$cat_id", + 'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&c=$cat_id", + )); - for ($j = 0; $j < $total_forums; $j++) - { - $forum_id = $forum_rows[$j]['forum_id']; + for ($j = 0; $j < $total_forums; $j++) { + $forum_id = $forum_rows[$j]['forum_id']; - $bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1; - $row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\""; + $bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1; + $row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\""; - if ($forum_rows[$j]['cat_id'] == $cat_id) - { + if ($forum_rows[$j]['cat_id'] == $cat_id) { + $template->assign_block_vars("c.f", array( + 'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']), + 'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']), + 'NUM_TOPICS' => $forum_rows[$j]['forum_topics'], + 'NUM_POSTS' => $forum_rows[$j]['forum_posts'], + 'PRUNE_DAYS' => ($forum_rows[$j]['prune_days']) ? $forum_rows[$j]['prune_days'] : '-', - $template->assign_block_vars("c.f", array( - 'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']), - 'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']), - 'NUM_TOPICS' => $forum_rows[$j]['forum_topics'], - 'NUM_POSTS' => $forum_rows[$j]['forum_posts'], - 'PRUNE_DAYS' => ($forum_rows[$j]['prune_days']) ? $forum_rows[$j]['prune_days'] : '-', + 'ORDER' => $forum_rows[$j]['forum_order'], + 'FORUM_ID' => $forum_rows[$j]['forum_id'], + 'ROW_BGR' => $row_bgr, - 'ORDER' => $forum_rows[$j]['forum_order'], - 'FORUM_ID' => $forum_rows[$j]['forum_id'], - 'ROW_BGR' => $row_bgr, - - 'SHOW_ON_INDEX' => (bool) $forum_rows[$j]['show_on_index'], - 'FORUM_PARENT' => $forum_rows[$j]['forum_parent'], - 'SF_PAD' => ($forum_rows[$j]['forum_parent']) ? ' style="padding-left: 20px;" ' : '', - 'FORUM_NAME_CLASS' => ($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen', - 'ADD_SUB_HREF' => "admin_forums.php?mode=addforum&forum_parent={$forum_rows[$j]['forum_id']}", - 'U_VIEWFORUM' => BB_ROOT ."viewforum.php?f=$forum_id", - 'U_FORUM_EDIT' => "admin_forums.php?mode=editforum&f=$forum_id", - 'U_FORUM_PERM' => "admin_forumauth.php?f=$forum_id", - 'U_FORUM_DELETE' => "admin_forums.php?mode=deleteforum&f=$forum_id", - 'U_FORUM_MOVE_UP' => "admin_forums.php?mode=forum_order&move=-15&f=$forum_id&c=$req_cat_id", - 'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&move=15&f=$forum_id&c=$req_cat_id", - 'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&f=$forum_id", - )); - - }// if ... forumid == catid - } // for ... forums - } // for ... categories - }// if ... total_categories + 'SHOW_ON_INDEX' => (bool)$forum_rows[$j]['show_on_index'], + 'FORUM_PARENT' => $forum_rows[$j]['forum_parent'], + 'SF_PAD' => ($forum_rows[$j]['forum_parent']) ? ' style="padding-left: 20px;" ' : '', + 'FORUM_NAME_CLASS' => ($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen', + 'ADD_SUB_HREF' => "admin_forums.php?mode=addforum&forum_parent={$forum_rows[$j]['forum_id']}", + 'U_VIEWFORUM' => BB_ROOT . "viewforum.php?f=$forum_id", + 'U_FORUM_EDIT' => "admin_forums.php?mode=editforum&f=$forum_id", + 'U_FORUM_PERM' => "admin_forumauth.php?f=$forum_id", + 'U_FORUM_DELETE' => "admin_forums.php?mode=deleteforum&f=$forum_id", + 'U_FORUM_MOVE_UP' => "admin_forums.php?mode=forum_order&move=-15&f=$forum_id&c=$req_cat_id", + 'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&move=15&f=$forum_id&c=$req_cat_id", + 'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&f=$forum_id", + )); + }// if ... forumid == catid + } // for ... forums + } // for ... categories + }// if ... total_categories } print_page('admin_forums.tpl', 'admin'); // Functions -function get_info ($mode, $id) +function get_info($mode, $id) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - break; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + break; - default: - bb_die('Wrong mode for generating select list #1'); - break; - } - $sql = "SELECT count(*) as total FROM $table"; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not get forum / category information #1'); - } - $count = DB()->sql_fetchrow($result); - $count = $count['total']; + default: + bb_die('Wrong mode for generating select list #1'); + break; + } + $sql = "SELECT count(*) as total FROM $table"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get forum / category information #1'); + } + $count = DB()->sql_fetchrow($result); + $count = $count['total']; - $sql = "SELECT * FROM $table WHERE $idfield = $id"; + $sql = "SELECT * FROM $table WHERE $idfield = $id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get forum / category information #2'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get forum / category information #2'); + } - if (DB()->num_rows($result) != 1) - { - bb_die('Forum / category does not exist or multiple forums / categories with ID '. $id); - } + if (DB()->num_rows($result) != 1) { + bb_die('Forum / category does not exist or multiple forums / categories with ID ' . $id); + } - $return = DB()->sql_fetchrow($result); - $return['number'] = $count; - return $return; + $return = DB()->sql_fetchrow($result); + $return['number'] = $count; + return $return; } -function get_list ($mode, $id, $select) +function get_list($mode, $id, $select) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - $namefield = 'cat_title'; - $order = 'cat_order'; - break; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + $namefield = 'cat_title'; + $order = 'cat_order'; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - $namefield = 'forum_name'; - $order = 'cat_id, forum_order'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + $namefield = 'forum_name'; + $order = 'cat_id, forum_order'; + break; - default: - bb_die('Wrong mode for generating select list #2'); - break; - } + default: + bb_die('Wrong mode for generating select list #2'); + break; + } - $sql = "SELECT * FROM $table"; - if( $select == 0 ) - { - $sql .= " WHERE $idfield <> $id"; - } - $sql .= " ORDER BY $order"; + $sql = "SELECT * FROM $table"; + if ($select == 0) { + $sql .= " WHERE $idfield <> $id"; + } + $sql .= " ORDER BY $order"; - if( !$result = DB()->sql_query($sql) ) - { - bb_die('Could not get list of categories / forums #1'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #1'); + } - $catlist = ''; + $catlist = ''; - while( $row = DB()->sql_fetchrow($result) ) - { - $s = ''; - if ($row[$idfield] == $id) - { - $s = ' selected="selected"'; - } - $catlist .= '\n'; - } + while ($row = DB()->sql_fetchrow($result)) { + $s = ''; + if ($row[$idfield] == $id) { + $s = ' selected="selected"'; + } + $catlist .= '\n'; + } - return($catlist); + return ($catlist); } -function renumber_order ($mode, $cat = 0) +function renumber_order($mode, $cat = 0) { - switch($mode) - { - case 'category': - $table = BB_CATEGORIES; - $idfield = 'cat_id'; - $orderfield = 'cat_order'; - $cat = 0; - break; + switch ($mode) { + case 'category': + $table = BB_CATEGORIES; + $idfield = 'cat_id'; + $orderfield = 'cat_order'; + $cat = 0; + break; - case 'forum': - $table = BB_FORUMS; - $idfield = 'forum_id'; - $orderfield = 'forum_order'; - $catfield = 'cat_id'; - break; + case 'forum': + $table = BB_FORUMS; + $idfield = 'forum_id'; + $orderfield = 'forum_order'; + $catfield = 'cat_id'; + break; - default: - bb_die('Wrong mode for generating select list #3'); - break; - } + default: + bb_die('Wrong mode for generating select list #3'); + break; + } - $sql = "SELECT * FROM $table"; - if( $cat != 0) - { - $sql .= " WHERE $catfield = $cat"; - } - $sql .= " ORDER BY $orderfield ASC"; + $sql = "SELECT * FROM $table"; + if ($cat != 0) { + $sql .= " WHERE $catfield = $cat"; + } + $sql .= " ORDER BY $orderfield ASC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #2'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #2'); + } - $i = 10; + $i = 10; - while ($row = DB()->sql_fetchrow($result)) - { - $sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield]; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update order fields'); - } - $i += 10; - } - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #3'); - } + while ($row = DB()->sql_fetchrow($result)) { + $sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield]; + if (!DB()->sql_query($sql)) { + bb_die('Could not update order fields'); + } + $i += 10; + } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #3'); + } } -function get_cat_forums ($cat_id = FALSE) +function get_cat_forums($cat_id = false) { - $forums = array(); - $where_sql = ''; + $forums = array(); + $where_sql = ''; - if ($cat_id = intval($cat_id)) - { - $where_sql = "AND f.cat_id = $cat_id"; - } + if ($cat_id = intval($cat_id)) { + $where_sql = "AND f.cat_id = $cat_id"; + } - $sql = 'SELECT c.cat_title, f.* - FROM '. BB_FORUMS .' f, '. BB_CATEGORIES ." c + $sql = 'SELECT c.cat_title, f.* + FROM ' . BB_FORUMS . ' f, ' . BB_CATEGORIES . " c WHERE f.cat_id = c.cat_id $where_sql ORDER BY c.cat_order, f.cat_id, f.forum_order"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get list of categories / forums #4'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get list of categories / forums #4'); + } - if ($rowset = DB()->sql_fetchrowset($result)) - { - foreach ($rowset as $rid => $row) - { - $forums[$row['cat_id']]['cat_title'] = $row['cat_title']; - $forums[$row['cat_id']]['f'][$row['forum_id']] = $row; - $forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row; - } - } + if ($rowset = DB()->sql_fetchrowset($result)) { + foreach ($rowset as $rid => $row) { + $forums[$row['cat_id']]['cat_title'] = $row['cat_title']; + $forums[$row['cat_id']]['f'][$row['forum_id']] = $row; + $forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row; + } + } - return $forums; + return $forums; } -function get_sf_count ($forum_id) +function get_sf_count($forum_id) { - global $cat_forums; + global $cat_forums; - $sf_count = 0; + $sf_count = 0; - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($f['forum_parent'] == $forum_id) - { - $sf_count++; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($f['forum_parent'] == $forum_id) { + $sf_count++; + } + } + } - return $sf_count; + return $sf_count; } -function get_prev_root_forum_id ($forums, $curr_forum_order) +function get_prev_root_forum_id($forums, $curr_forum_order) { - $i = $curr_forum_order - 10; + $i = $curr_forum_order - 10; - while ($i > 0) - { - if (isset($forums[$i]) && !$forums[$i]['forum_parent']) - { - return $forums[$i]['forum_id']; - } - $i = $i - 10; - } + while ($i > 0) { + if (isset($forums[$i]) && !$forums[$i]['forum_parent']) { + return $forums[$i]['forum_id']; + } + $i = $i - 10; + } - return FALSE; + return false; } -function get_next_root_forum_id ($forums, $curr_forum_order) +function get_next_root_forum_id($forums, $curr_forum_order) { - $i = $curr_forum_order + 10; - $limit = (count($forums) * 10) + 10; + $i = $curr_forum_order + 10; + $limit = (count($forums) * 10) + 10; - while ($i < $limit) - { - if (isset($forums[$i]) && !$forums[$i]['forum_parent']) - { - return $forums[$i]['forum_id']; - } - $i = $i + 10; - } + while ($i < $limit) { + if (isset($forums[$i]) && !$forums[$i]['forum_parent']) { + return $forums[$i]['forum_id']; + } + $i = $i + 10; + } - return FALSE; + return false; } -function get_orphan_sf () +function get_orphan_sf() { - global $cat_forums; + global $cat_forums; - $last_root = 0; - $bad_sf_ary = array(); + $last_root = 0; + $bad_sf_ary = array(); - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($f['forum_parent']) - { - if ($f['forum_parent'] != $last_root) - { - $bad_sf_ary[] = $f['forum_id']; - } - } - else - { - $last_root = $f['forum_id']; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($f['forum_parent']) { + if ($f['forum_parent'] != $last_root) { + $bad_sf_ary[] = $f['forum_id']; + } + } else { + $last_root = $f['forum_id']; + } + } + } - return implode(',', $bad_sf_ary); + return implode(',', $bad_sf_ary); } -function fix_orphan_sf ($orphan_sf_sql = '', $show_mess = FALSE) +function fix_orphan_sf($orphan_sf_sql = '', $show_mess = false) { - global $lang; + global $lang; - $done_mess = ''; + $done_mess = ''; - if (!$orphan_sf_sql) - { - $orphan_sf_sql = get_orphan_sf(); - } + if (!$orphan_sf_sql) { + $orphan_sf_sql = get_orphan_sf(); + } - if ($orphan_sf_sql) - { - $sql = "UPDATE ". BB_FORUMS ." SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)"; + if ($orphan_sf_sql) { + $sql = "UPDATE " . BB_FORUMS . " SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not change subforums data'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not change subforums data'); + } - if ($affectedrows = DB()->affected_rows()) - { - $done_mess = 'Subforums data corrected. '. $affectedrows .' orphan subforum(s) moved to root level.'; - } + if ($affectedrows = DB()->affected_rows()) { + $done_mess = 'Subforums data corrected. ' . $affectedrows . ' orphan subforum(s) moved to root level.'; + } - if ($show_mess) - { - $message = $done_mess .'

'; - $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - } + if ($show_mess) { + $message = $done_mess . '

'; + $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + bb_die($message); + } + } - return $done_mess; + return $done_mess; } -function sf_get_list ($mode, $exclude = 0, $select = 0) +function sf_get_list($mode, $exclude = 0, $select = 0) { - global $cat_forums, $forum_parent; + global $cat_forums, $forum_parent; - $opt = ''; + $opt = ''; - if ($mode == 'forum') - { - foreach ($cat_forums as $cid => $c) - { - $opt .= ''; + if ($mode == 'forum') { + foreach ($cat_forums as $cid => $c) { + $opt .= ''; - foreach ($c['f'] as $fid => $f) - { - $selected = ($fid == $select) ? HTML_SELECTED : ''; - $disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : ''; - $style = ($disabled) ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : ''); - $opt .= '\n"; - } + foreach ($c['f'] as $fid => $f) { + $selected = ($fid == $select) ? HTML_SELECTED : ''; + $disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : ''; + $style = ($disabled) ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : ''); + $opt .= '\n"; + } - $opt .= ''; - } - } + $opt .= ''; + } + } - return $opt; + return $opt; } -function get_forum_data ($forum_id) +function get_forum_data($forum_id) { - global $cat_forums; + global $cat_forums; - foreach ($cat_forums as $cid => $c) - { - foreach ($c['f'] as $fid => $f) - { - if ($fid == $forum_id) - { - return $f; - } - } - } + foreach ($cat_forums as $cid => $c) { + foreach ($c['f'] as $fid => $f) { + if ($fid == $forum_id) { + return $f; + } + } + } - return FALSE; + return false; } -function get_max_forum_order ($cat_id) +function get_max_forum_order($cat_id) { - $row = DB()->fetch_row(" + $row = DB()->fetch_row(" SELECT MAX(forum_order) AS max_forum_order - FROM ". BB_FORUMS ." + FROM " . BB_FORUMS . " WHERE cat_id = $cat_id "); - return intval($row['max_forum_order']); + return intval($row['max_forum_order']); } -function check_name_dup ($mode, $name, $die_on_error = true) +function check_name_dup($mode, $name, $die_on_error = true) { - $name_sql = DB()->escape($name); + $name_sql = DB()->escape($name); - if ($mode == 'cat') - { - $what_checked = 'category'; - $sql = "SELECT cat_id FROM ". BB_CATEGORIES ." WHERE cat_title = '$name_sql'"; - } - else - { - $what_checked = 'forum'; - $sql = "SELECT forum_id FROM ". BB_FORUMS ." WHERE forum_name = '$name_sql'"; - } + if ($mode == 'cat') { + $what_checked = 'category'; + $sql = "SELECT cat_id FROM " . BB_CATEGORIES . " WHERE cat_title = '$name_sql'"; + } else { + $what_checked = 'forum'; + $sql = "SELECT forum_id FROM " . BB_FORUMS . " WHERE forum_name = '$name_sql'"; + } - $name_is_dup = DB()->fetch_row($sql); + $name_is_dup = DB()->fetch_row($sql); - if ($name_is_dup && $die_on_error) - { - bb_die('This '. $what_checked .' name taken, please choose something else'); - } + if ($name_is_dup && $die_on_error) { + bb_die('This ' . $what_checked . ' name taken, please choose something else'); + } - return $name_is_dup; + return $name_is_dup; } /** * Change subforums cat_id if parent's cat_id was changed */ -function change_sf_cat ($parent_id, $new_cat_id, $order_shear) +function change_sf_cat($parent_id, $new_cat_id, $order_shear) { - DB()->query(" - UPDATE ". BB_FORUMS ." SET + DB()->query(" + UPDATE " . BB_FORUMS . " SET cat_id = $new_cat_id, forum_order = forum_order + $order_shear WHERE forum_parent = $parent_id "); -} \ No newline at end of file +} diff --git a/admin/admin_groups.php b/admin/admin_groups.php index ade36db3a..7fee72bbd 100644 --- a/admin/admin_groups.php +++ b/admin/admin_groups.php @@ -1,188 +1,185 @@ $row['group_name'], - 'group_description' => $row['group_description'], - 'group_moderator' => $row['group_moderator'], - 'group_mod_name' => $row['moderator_name'], - 'group_type' => $row['group_type'], - 'release_group' => $row['release_group'], - ); - $mode = 'editgroup'; - $template->assign_block_vars('group_edit', array()); - } - else if (!empty($_POST['new'])) - { - $group_info = array( - 'group_name' => '', - 'group_description' => '', - 'group_moderator' => '', - 'group_mod_name' => '', - 'group_type' => GROUP_OPEN, - 'release_group' => 0, - ); - $mode = 'newgroup'; - } +if (!empty($_POST['edit']) || !empty($_POST['new'])) { + if (!empty($_POST['edit'])) { + if (!$row = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + $group_info = array( + 'group_name' => $row['group_name'], + 'group_description' => $row['group_description'], + 'group_moderator' => $row['group_moderator'], + 'group_mod_name' => $row['moderator_name'], + 'group_type' => $row['group_type'], + 'release_group' => $row['release_group'], + ); + $mode = 'editgroup'; + $template->assign_block_vars('group_edit', array()); + } elseif (!empty($_POST['new'])) { + $group_info = array( + 'group_name' => '', + 'group_description' => '', + 'group_moderator' => '', + 'group_mod_name' => '', + 'group_type' => GROUP_OPEN, + 'release_group' => 0, + ); + $mode = 'newgroup'; + } - // Ok, now we know everything about them, let's show the page. - $s_hidden_fields = ' - - + // Ok, now we know everything about them, let's show the page. + $s_hidden_fields = ' + + '; - $template->assign_vars(array( - 'TPL_EDIT_GROUP' => true, + $template->assign_vars(array( + 'TPL_EDIT_GROUP' => true, - 'GROUP_NAME' => stripslashes(htmlspecialchars($group_info['group_name'])), - 'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])), - 'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']), - 'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'], - 'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? HTML_CHECKED : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? HTML_CHECKED : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN ) ? HTML_CHECKED : '', - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'S_GROUP_ACTION' => "admin_groups.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else if (!empty($_POST['group_update'])) -{ - if (!empty($_POST['group_delete'])) - { - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } - // Delete Group - delete_group($group_id); + 'GROUP_NAME' => stripslashes(htmlspecialchars($group_info['group_name'])), + 'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])), + 'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']), + 'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'], + 'U_SEARCH_USER' => BB_ROOT . "search.php?mode=searchuser", + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? HTML_CHECKED : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? HTML_CHECKED : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? HTML_CHECKED : '', + 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, + 'S_GROUP_ACTION' => "admin_groups.php", + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); +} elseif (!empty($_POST['group_update'])) { + if (!empty($_POST['group_delete'])) { + if (!$group_info = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + // Delete Group + delete_group($group_id); - $message = $lang['DELETED_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['DELETED_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else - { - $group_type = isset($_POST['group_type']) ? intval($_POST['group_type']) : GROUP_OPEN; - $release_group = isset($_POST['release_group']) ? intval($_POST['release_group']) : 0; - $group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : ''; - $group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : ''; - $group_moderator = isset($_POST['username']) ? $_POST['username'] : ''; + bb_die($message); + } else { + $group_type = isset($_POST['group_type']) ? intval($_POST['group_type']) : GROUP_OPEN; + $release_group = isset($_POST['release_group']) ? intval($_POST['release_group']) : 0; + $group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : ''; + $group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : ''; + $group_moderator = isset($_POST['username']) ? $_POST['username'] : ''; - if ($group_name === '') - { - bb_die($lang['NO_GROUP_NAME']); - } - else if ($group_moderator === '') - { - bb_die($lang['NO_GROUP_MODERATOR']); - } - $this_userdata = get_userdata($group_moderator, true); + if ($group_name === '') { + bb_die($lang['NO_GROUP_NAME']); + } elseif ($group_moderator === '') { + bb_die($lang['NO_GROUP_MODERATOR']); + } + $this_userdata = get_userdata($group_moderator, true); - if (!$group_moderator = $this_userdata['user_id']) - { - bb_die($lang['NO_GROUP_MODERATOR']); - } + if (!$group_moderator = $this_userdata['user_id']) { + bb_die($lang['NO_GROUP_MODERATOR']); + } - $sql_ary = array( - 'group_type' => (int) $group_type, - 'release_group' => (int) $release_group, - 'group_name' => (string) $group_name, - 'group_description' => (string) $group_desc, - 'group_moderator' => (int) $group_moderator, - 'group_single_user' => 0, - ); + $sql_ary = array( + 'group_type' => (int)$group_type, + 'release_group' => (int)$release_group, + 'group_name' => (string)$group_name, + 'group_description' => (string)$group_desc, + 'group_moderator' => (int)$group_moderator, + 'group_single_user' => 0, + ); - if ($mode == "editgroup") - { - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } + if ($mode == "editgroup") { + if (!$group_info = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - if ($group_info['group_moderator'] != $group_moderator) - { - // Create user_group for new group's moderator - add_user_into_group($group_id, $group_moderator); - $sql_ary['mod_time'] = TIMENOW; + if ($group_info['group_moderator'] != $group_moderator) { + // Create user_group for new group's moderator + add_user_into_group($group_id, $group_moderator); + $sql_ary['mod_time'] = TIMENOW; - // Delete old moderator's user_group - if (isset($_POST['delete_old_moderator'])) - { - delete_user_group($group_id, $group_info['group_moderator']); - } - } + // Delete old moderator's user_group + if (isset($_POST['delete_old_moderator'])) { + delete_user_group($group_id, $group_info['group_moderator']); + } + } - $sql_args = DB()->build_array('UPDATE', $sql_ary); + $sql_args = DB()->build_array('UPDATE', $sql_ary); - // Update group's data - DB()->query("UPDATE ". BB_GROUPS ." SET $sql_args WHERE group_id = $group_id"); + // Update group's data + DB()->query("UPDATE " . BB_GROUPS . " SET $sql_args WHERE group_id = $group_id"); - $message = $lang['UPDATED_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['UPDATED_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else if ($mode == 'newgroup') - { - $sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW; - $sql_args = DB()->build_array('INSERT', $sql_ary); + bb_die($message); + } elseif ($mode == 'newgroup') { + $sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW; + $sql_args = DB()->build_array('INSERT', $sql_ary); - // Create new group - DB()->query("INSERT INTO ". BB_GROUPS ." $sql_args"); - $new_group_id = DB()->sql_nextid(); + // Create new group + DB()->query("INSERT INTO " . BB_GROUPS . " $sql_args"); + $new_group_id = DB()->sql_nextid(); - // Create user_group for group's moderator - add_user_into_group($new_group_id, $group_moderator); + // Create user_group for group's moderator + add_user_into_group($new_group_id, $group_moderator); - $message = $lang['ADDED_NEW_GROUP'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['ADDED_NEW_GROUP'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else - { - bb_die($lang['NO_GROUP_ACTION']); - } - } -} -else -{ - $template->assign_vars(array( - 'TPL_GROUP_SELECT' => true, + bb_die($message); + } else { + bb_die($lang['NO_GROUP_ACTION']); + } + } +} else { + $template->assign_vars(array( + 'TPL_GROUP_SELECT' => true, - 'S_GROUP_ACTION' => "admin_groups.php", - 'S_GROUP_SELECT' => stripslashes(get_select('groups')), - )); + 'S_GROUP_ACTION' => "admin_groups.php", + 'S_GROUP_SELECT' => stripslashes(get_select('groups')), + )); } -print_page('admin_groups.tpl', 'admin'); \ No newline at end of file +print_page('admin_groups.tpl', 'admin'); diff --git a/admin/admin_log.php b/admin/admin_log.php index 2e53c4099..fb3ef5004 100644 --- a/admin/admin_log.php +++ b/admin/admin_log.php @@ -1,60 +1,81 @@ enqueue(array( - 'moderators', + 'moderators', )); $log_action->init(); -$per_page = 50; -$row_class_1 = 'row1'; -$row_class_2 = 'row2'; -$def_days = 3; -$def_datetime = TIMENOW; -$max_forum_name_len = 40; +$per_page = 50; +$row_class_1 = 'row1'; +$row_class_2 = 'row2'; +$def_days = 3; +$def_datetime = TIMENOW; +$max_forum_name_len = 40; $title_match_max_len = 60; $poster_name_max_len = 25; -$select_max_height = 16; -$dt_format = 'Y-m-d'; // used in one-day filter +$select_max_height = 16; +$dt_format = 'Y-m-d'; // used in one-day filter $url = basename(__FILE__); // Key names -$type_key = 'type'; -$forum_key = 'f'; -$topic_key = 't'; -$user_key = 'u'; -$datetime_key = 'dt'; // value should be strtotime() time ("2006-06-25" etc.) -$daysback_key = 'db'; -$sort_key = 'sort'; +$type_key = 'type'; +$forum_key = 'f'; +$topic_key = 't'; +$user_key = 'u'; +$datetime_key = 'dt'; // value should be strtotime() time ("2006-06-25" etc.) +$daysback_key = 'db'; +$sort_key = 'sort'; $title_match_key = 'tm'; // Key values -$all_types = 0; // =| -$all_users = 0; // |> only "0" is a valid value +$all_types = 0; // =| +$all_users = 0; // |> only "0" is a valid value $all_forums = 0; // =| -$sort_asc = 'ASC'; -$sort_desc = 'DESC'; +$sort_asc = 'ASC'; +$sort_desc = 'DESC'; // Defaults -$def_types = $all_types; -$def_users = $all_users; +$def_types = $all_types; +$def_users = $all_users; $def_forums = $all_forums; -$def_sort = $sort_desc; +$def_sort = $sort_desc; // Moderators data -if (!$mod = $datastore->get('moderators')) -{ - $datastore->update('moderators'); - $mod = $datastore->get('moderators'); +if (!$mod = $datastore->get('moderators')) { + $datastore->update('moderators'); + $mod = $datastore->get('moderators'); } array_deep($mod['moderators'], 'html_entity_decode'); array_deep($mod['admins'], 'html_entity_decode'); @@ -64,10 +85,9 @@ $users = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_users) + array_flip($mod['m unset($mod); // Forums data -if (!$forums = $datastore->get('cat_forums')) -{ - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); +if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); } $f_data = $forums['f']; @@ -80,59 +100,52 @@ $start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; $type_selected = array($def_types); $type_csv = ''; -if ($var =& $_REQUEST[$type_key]) -{ - $type_selected = get_id_ary($var); +if ($var =& $_REQUEST[$type_key]) { + $type_selected = get_id_ary($var); - if (in_array($all_types, $type_selected)) - { - $type_selected = array($all_types); - } - $type_csv = join(',', $type_selected); - $url = ($type_csv != $def_types) ? url_arg($url, $type_key, $type_csv) : $url; + if (in_array($all_types, $type_selected)) { + $type_selected = array($all_types); + } + $type_csv = join(',', $type_selected); + $url = ($type_csv != $def_types) ? url_arg($url, $type_key, $type_csv) : $url; } // User $user_selected = array($def_users); $user_csv = ''; -if ($var =& $_REQUEST[$user_key]) -{ - $user_selected = get_id_ary($var); +if ($var =& $_REQUEST[$user_key]) { + $user_selected = get_id_ary($var); - if (in_array($all_users, $user_selected)) - { - $user_selected = array($all_users); - } - $user_csv = join(',', $user_selected); - $url = ($user_csv != $def_users) ? url_arg($url, $user_key, $user_csv) : $url; + if (in_array($all_users, $user_selected)) { + $user_selected = array($all_users); + } + $user_csv = join(',', $user_selected); + $url = ($user_csv != $def_users) ? url_arg($url, $user_key, $user_csv) : $url; } // Forum $forum_selected = array($def_forums); $forum_csv = ''; -if ($var =& $_REQUEST[$forum_key]) -{ - $forum_selected = get_id_ary($var); +if ($var =& $_REQUEST[$forum_key]) { + $forum_selected = get_id_ary($var); - if (in_array($all_forums, $forum_selected)) - { - $forum_selected = array($all_forums); - } - $forum_csv = join(',', $forum_selected); - $url = ($forum_csv != $def_forums) ? url_arg($url, $forum_key, $forum_csv) : $url; + if (in_array($all_forums, $forum_selected)) { + $forum_selected = array($all_forums); + } + $forum_csv = join(',', $forum_selected); + $url = ($forum_csv != $def_forums) ? url_arg($url, $forum_key, $forum_csv) : $url; } // Topic $topic_selected = null; $topic_csv = ''; -if ($var =& $_REQUEST[$topic_key]) -{ - $topic_selected = get_id_ary($var); - $topic_csv = join(',', $topic_selected); - $url = ($topic_csv) ? url_arg($url, $topic_key, $topic_csv) : $url; +if ($var =& $_REQUEST[$topic_key]) { + $topic_selected = get_id_ary($var); + $topic_csv = join(',', $topic_selected); + $url = ($topic_csv) ? url_arg($url, $topic_key, $topic_csv) : $url; } // Order @@ -141,48 +154,42 @@ $order_val = 'log_time'; // Sort $sort_val = $def_sort; -if ($var =& $_REQUEST[$sort_key] AND $var != $def_sort) -{ - $sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc; - $url = url_arg($url, $sort_key, $sort_val); +if ($var =& $_REQUEST[$sort_key] and $var != $def_sort) { + $sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc; + $url = url_arg($url, $sort_key, $sort_val); } // Time $datetime_val = $def_datetime; $daysback_val = $def_days; -if ($var =& $_REQUEST[$daysback_key] AND $var != $def_days) -{ - $daysback_val = max(intval($var), 1); - $url = url_arg($url, $daysback_key, $daysback_val); +if ($var =& $_REQUEST[$daysback_key] and $var != $def_days) { + $daysback_val = max(intval($var), 1); + $url = url_arg($url, $daysback_key, $daysback_val); } -if ($var =& $_REQUEST[$datetime_key] AND $var != $def_datetime) -{ - $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); - if (($tmp_timestamp = strtotime($var, $tz)) > 0) - { - $datetime_val = $tmp_timestamp; - $url = url_arg($url, $datetime_key, date($dt_format, $datetime_val)); - } +if ($var =& $_REQUEST[$datetime_key] and $var != $def_datetime) { + $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); + if (($tmp_timestamp = strtotime($var, $tz)) > 0) { + $datetime_val = $tmp_timestamp; + $url = url_arg($url, $datetime_key, date($dt_format, $datetime_val)); + } } $time_end_val = 86400 + mktime(0, 0, 0, date('m', $datetime_val), date('d', $datetime_val), date('Y', $datetime_val)); -$time_start_val = $time_end_val - 86400*$daysback_val; +$time_start_val = $time_end_val - 86400 * $daysback_val; // First log time -$row = DB()->fetch_row("SELECT MIN(log_time) AS first_log_time FROM ". BB_LOG); -$first_log_time = (int) $row['first_log_time']; +$row = DB()->fetch_row("SELECT MIN(log_time) AS first_log_time FROM " . BB_LOG); +$first_log_time = (int)$row['first_log_time']; // Title match $title_match_val = $title_match_sql = ''; -if ($var =& $_REQUEST[$title_match_key]) -{ - if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len)) - { - $title_match_sql = DB()->escape($tmp_title_match); - $url = url_arg($url, $title_match_key, urlencode($tmp_title_match)); - } +if ($var =& $_REQUEST[$title_match_key]) { + if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len)) { + $title_match_sql = DB()->escape($tmp_title_match); + $url = url_arg($url, $title_match_key, urlencode($tmp_title_match)); + } } // @@ -190,32 +197,32 @@ if ($var =& $_REQUEST[$title_match_key]) // $select = "SELECT *"; -$from = "FROM ". BB_LOG; +$from = "FROM " . BB_LOG; $where = " WHERE log_time BETWEEN $time_start_val AND $time_end_val "; $where .= ($type_csv) ? " AND log_type_id IN($type_csv) -" : ''; +" : ''; $where .= ($user_csv) ? " AND log_user_id IN($user_csv) -" : ''; +" : ''; $where .= ($forum_csv) ? " AND log_forum_id IN($forum_csv) -" : ''; +" : ''; $where .= ($topic_csv) ? " AND log_topic_id IN($topic_csv) -" : ''; +" : ''; $where .= ($title_match_sql) ? " AND MATCH (log_topic_title) AGAINST ('$title_match_sql' IN BOOLEAN MODE) -" : ''; +" : ''; $order = "ORDER BY $order_val"; $sort = $sort_val; -$limit = "LIMIT $start, ". ($per_page + 1); +$limit = "LIMIT $start, " . ($per_page + 1); $sql = " $select @@ -229,147 +236,132 @@ $sql = " $log_rowset = DB()->fetch_rowset($sql); $log_count = count($log_rowset); -if ($log_count == $per_page + 1) -{ - $items_count = $start + ($per_page * 2); - $pages = '?'; - array_pop($log_rowset); -} -else -{ - $items_count = $start + $log_count; - $pages = (!$log_count) ? 1 : ceil($items_count / $per_page); +if ($log_count == $per_page + 1) { + $items_count = $start + ($per_page * 2); + $pages = '?'; + array_pop($log_rowset); +} else { + $items_count = $start + $log_count; + $pages = (!$log_count) ? 1 : ceil($items_count / $per_page); } generate_pagination($url, $items_count, $per_page, $start); $filter = array(); -if ($log_rowset) -{ - $log_type = $log_action->log_type; - $log_type_flip = array_flip($log_type); +if ($log_rowset) { + $log_type = $log_action->log_type; + $log_type_flip = array_flip($log_type); - foreach ($log_rowset as $row_num => $row) - { - $msg = ''; - $forum_name = $forum_name_new = ''; - $topic_title = $topic_title_new = ''; + foreach ($log_rowset as $row_num => $row) { + $msg = ''; + $forum_name = $forum_name_new = ''; + $topic_title = $topic_title_new = ''; - $topic_deleted = ($row['log_type_id'] == $log_type['mod_topic_delete']); + $topic_deleted = ($row['log_type_id'] == $log_type['mod_topic_delete']); - switch ($row['log_type_id']) - { - case $log_type['mod_topic_delete']: - case $log_type['mod_topic_move']: - case $log_type['mod_topic_lock']: - case $log_type['mod_topic_unlock']: - case $log_type['mod_post_delete']: - case $log_type['mod_topic_split']: - // topic_title - if (!empty($row['log_topic_title'])) - { - $topic_title = $row['log_topic_title']; - } - // topic_title_new - if (!empty($row['log_topic_title_new'])) - { - $topic_title_new = $row['log_topic_title_new']; - } - // forum_name - if ($fid =& $row['log_forum_id']) - { - $forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id']; - } - // forum_name_new - if ($fid =& $row['log_forum_id_new']) - { - $forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id']; - } + switch ($row['log_type_id']) { + case $log_type['mod_topic_delete']: + case $log_type['mod_topic_move']: + case $log_type['mod_topic_lock']: + case $log_type['mod_topic_unlock']: + case $log_type['mod_post_delete']: + case $log_type['mod_topic_split']: + // topic_title + if (!empty($row['log_topic_title'])) { + $topic_title = $row['log_topic_title']; + } + // topic_title_new + if (!empty($row['log_topic_title_new'])) { + $topic_title_new = $row['log_topic_title_new']; + } + // forum_name + if ($fid =& $row['log_forum_id']) { + $forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id']; + } + // forum_name_new + if ($fid =& $row['log_forum_id_new']) { + $forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id']; + } - break; - } + break; + } - $msg .= " $row[log_msg]"; + $msg .= " $row[log_msg]"; - $row_class = !($row_num & 1) ? $row_class_1 : $row_class_2; + $row_class = !($row_num & 1) ? $row_class_1 : $row_class_2; - $datetime_href_s = url_arg($url, $datetime_key, date($dt_format, $row['log_time'])); - $datetime_href_s = url_arg($datetime_href_s, $daysback_key, 1); + $datetime_href_s = url_arg($url, $datetime_key, date($dt_format, $row['log_time'])); + $datetime_href_s = url_arg($datetime_href_s, $daysback_key, 1); - $template->assign_block_vars('log', array( - 'ACTION_DESC' => $lang['LOG_ACTION']['LOG_TYPE'][$log_type_flip[$row['log_type_id']]], - 'ACTION_HREF_S' => url_arg($url, $type_key, $row['log_type_id']), + $template->assign_block_vars('log', array( + 'ACTION_DESC' => $lang['LOG_ACTION']['LOG_TYPE'][$log_type_flip[$row['log_type_id']]], + 'ACTION_HREF_S' => url_arg($url, $type_key, $row['log_type_id']), - 'USER_ID' => $row['log_user_id'], - 'USERNAME' => $row['log_username'], - 'USER_HREF_S' => url_arg($url, $user_key, $row['log_user_id']), - 'USER_IP' => decode_ip($row['log_user_ip']), + 'USER_ID' => $row['log_user_id'], + 'USERNAME' => $row['log_username'], + 'USER_HREF_S' => url_arg($url, $user_key, $row['log_user_id']), + 'USER_IP' => decode_ip($row['log_user_ip']), - 'FORUM_ID' => $row['log_forum_id'], - 'FORUM_HREF' => BB_ROOT . FORUM_URL . $row['log_forum_id'], - 'FORUM_HREF_S' => url_arg($url, $forum_key, $row['log_forum_id']), - 'FORUM_NAME' => htmlCHR($forum_name), + 'FORUM_ID' => $row['log_forum_id'], + 'FORUM_HREF' => BB_ROOT . FORUM_URL . $row['log_forum_id'], + 'FORUM_HREF_S' => url_arg($url, $forum_key, $row['log_forum_id']), + 'FORUM_NAME' => htmlCHR($forum_name), - 'FORUM_ID_NEW' => $row['log_forum_id_new'], - 'FORUM_HREF_NEW' => BB_ROOT . FORUM_URL . $row['log_forum_id_new'], - 'FORUM_HREF_NEW_S' => url_arg($url, $forum_key, $row['log_forum_id_new']), - 'FORUM_NAME_NEW' => htmlCHR($forum_name_new), + 'FORUM_ID_NEW' => $row['log_forum_id_new'], + 'FORUM_HREF_NEW' => BB_ROOT . FORUM_URL . $row['log_forum_id_new'], + 'FORUM_HREF_NEW_S' => url_arg($url, $forum_key, $row['log_forum_id_new']), + 'FORUM_NAME_NEW' => htmlCHR($forum_name_new), - 'TOPIC_ID' => $row['log_topic_id'], - 'TOPIC_HREF' => (!$topic_deleted) ? BB_ROOT . TOPIC_URL . $row['log_topic_id'] : '', - 'TOPIC_HREF_S' => url_arg($url, $topic_key, $row['log_topic_id']), - 'TOPIC_TITLE' => $topic_title, + 'TOPIC_ID' => $row['log_topic_id'], + 'TOPIC_HREF' => (!$topic_deleted) ? BB_ROOT . TOPIC_URL . $row['log_topic_id'] : '', + 'TOPIC_HREF_S' => url_arg($url, $topic_key, $row['log_topic_id']), + 'TOPIC_TITLE' => $topic_title, - 'TOPIC_ID_NEW' => $row['log_topic_id_new'], - 'TOPIC_HREF_NEW' => BB_ROOT . TOPIC_URL . $row['log_topic_id_new'], - 'TOPIC_HREF_NEW_S' => url_arg($url, $topic_key, $row['log_topic_id_new']), - 'TOPIC_TITLE_NEW' => $topic_title_new, + 'TOPIC_ID_NEW' => $row['log_topic_id_new'], + 'TOPIC_HREF_NEW' => BB_ROOT . TOPIC_URL . $row['log_topic_id_new'], + 'TOPIC_HREF_NEW_S' => url_arg($url, $topic_key, $row['log_topic_id_new']), + 'TOPIC_TITLE_NEW' => $topic_title_new, - 'DATE' => bb_date($row['log_time'], 'j-M'), - 'TIME' => bb_date($row['log_time'], 'H:i'), - 'DATETIME_HREF_S' => $datetime_href_s, - 'MSG' => $msg, - 'ROW_CLASS' => $row_class, + 'DATE' => bb_date($row['log_time'], 'j-M'), + 'TIME' => bb_date($row['log_time'], 'H:i'), + 'DATETIME_HREF_S' => $datetime_href_s, + 'MSG' => $msg, + 'ROW_CLASS' => $row_class, - )); + )); - // Topics - if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) - { - $template->assign_block_vars('topics', array( - 'TOPIC_TITLE' => $row['log_topic_title'], - )); - $filter['topics'][$row['log_topic_title']] = true; - } - // Forums - if ($forum_csv && empty($filter['forums'][$forum_name])) - { - $template->assign_block_vars('forums', array( - 'FORUM_NAME' => htmlCHR($forum_name), - )); - $filter['forums'][$forum_name] = true; - } - // Users - if ($user_csv && empty($filter['users'][$row['log_username']])) - { - $template->assign_block_vars('users', array( - 'USERNAME' => $row['log_username'], - )); - $filter['users'][$row['log_username']] = true; - } - } + // Topics + if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) { + $template->assign_block_vars('topics', array( + 'TOPIC_TITLE' => $row['log_topic_title'], + )); + $filter['topics'][$row['log_topic_title']] = true; + } + // Forums + if ($forum_csv && empty($filter['forums'][$forum_name])) { + $template->assign_block_vars('forums', array( + 'FORUM_NAME' => htmlCHR($forum_name), + )); + $filter['forums'][$forum_name] = true; + } + // Users + if ($user_csv && empty($filter['users'][$row['log_username']])) { + $template->assign_block_vars('users', array( + 'USERNAME' => $row['log_username'], + )); + $filter['users'][$row['log_username']] = true; + } + } - $template->assign_vars(array( - 'FILTERS' => ($topic_csv || $forum_csv || $user_csv), - 'FILTER_TOPICS' => !empty($filter['topics']), - 'FILTER_FORUMS' => !empty($filter['forums']), - 'FILTER_USERS' => !empty($filter['users']), - )); -} -else -{ - $template->assign_block_vars('log_not_found', array()); + $template->assign_vars(array( + 'FILTERS' => ($topic_csv || $forum_csv || $user_csv), + 'FILTER_TOPICS' => !empty($filter['topics']), + 'FILTER_FORUMS' => !empty($filter['forums']), + 'FILTER_USERS' => !empty($filter['users']), + )); +} else { + $template->assign_block_vars('log_not_found', array()); } // @@ -378,36 +370,36 @@ else $log_type_select = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_types) + $log_action->log_type_select; // Order select -$order_options = ''; +$order_options = ''; $template->assign_vars(array( - 'LOG_COLSPAN' => 4, + 'LOG_COLSPAN' => 4, - 'DATETIME_NAME' => $datetime_key, - 'DATETIME_VAL' => date('Y-m-d', $datetime_val), - 'DAYSBACK_NAME' => $daysback_key, - 'DAYSBACK_VAL' => $daysback_val, - 'FIRST_LOG_TIME' => ($first_log_time) ? date('Y-m-d', $first_log_time) : $lang['ACC_NONE'], + 'DATETIME_NAME' => $datetime_key, + 'DATETIME_VAL' => date('Y-m-d', $datetime_val), + 'DAYSBACK_NAME' => $daysback_key, + 'DAYSBACK_VAL' => $daysback_val, + 'FIRST_LOG_TIME' => ($first_log_time) ? date('Y-m-d', $first_log_time) : $lang['ACC_NONE'], - 'TITLE_MATCH_MAX' => $title_match_max_len, - 'TITLE_MATCH_NAME' => $title_match_key, - 'TITLE_MATCH_VAL' => $title_match_val, + 'TITLE_MATCH_MAX' => $title_match_max_len, + 'TITLE_MATCH_NAME' => $title_match_key, + 'TITLE_MATCH_VAL' => $title_match_val, - 'ORDER_NAME' => '', - 'ORDER_OPTIONS' => $order_options, + 'ORDER_NAME' => '', + 'ORDER_OPTIONS' => $order_options, - 'SORT_NAME' => $sort_key, - 'SORT_ASC' => $sort_asc, - 'SORT_DESC' => $sort_desc, - 'SORT_ASC_CHECKED' => ($sort_val == $sort_asc) ? HTML_CHECKED : '', - 'SORT_DESC_CHECKED' => ($sort_val == $sort_desc) ? HTML_CHECKED : '', + 'SORT_NAME' => $sort_key, + 'SORT_ASC' => $sort_asc, + 'SORT_DESC' => $sort_desc, + 'SORT_ASC_CHECKED' => ($sort_val == $sort_asc) ? HTML_CHECKED : '', + 'SORT_DESC_CHECKED' => ($sort_val == $sort_desc) ? HTML_CHECKED : '', - 'SEL_FORUM' => get_forum_select('admin', "{$forum_key}[]", $forum_selected, $max_forum_name_len, $select_max_height, '', $all_forums), - 'SEL_LOG_TYPE' => build_select("{$type_key}[]", $log_type_select, $type_selected, 60, $select_max_height), - 'SEL_USERS' => build_select("{$user_key}[]", $users, $user_selected, 16, $select_max_height), + 'SEL_FORUM' => get_forum_select('admin', "{$forum_key}[]", $forum_selected, $max_forum_name_len, $select_max_height, '', $all_forums), + 'SEL_LOG_TYPE' => build_select("{$type_key}[]", $log_type_select, $type_selected, 60, $select_max_height), + 'SEL_USERS' => build_select("{$user_key}[]", $users, $user_selected, 16, $select_max_height), - 'S_LOG_ACTION' => "admin_log.php", - 'TOPIC_CSV' => $topic_csv, + 'S_LOG_ACTION' => "admin_log.php", + 'TOPIC_CSV' => $topic_csv, )); -print_page('admin_log.tpl', 'admin'); \ No newline at end of file +print_page('admin_log.tpl', 'admin'); diff --git a/admin/admin_mass_email.php b/admin/admin_mass_email.php index a9285ebf0..725ba70d8 100644 --- a/admin/admin_mass_email.php +++ b/admin/admin_mass_email.php @@ -1,102 +1,122 @@ fetch_rowset("SELECT ban_userid FROM ". BB_BANLIST ." WHERE ban_userid != 0"); + if (!$errors) { + $sql = DB()->fetch_rowset("SELECT ban_userid FROM " . BB_BANLIST . " WHERE ban_userid != 0"); - foreach ($sql as $row) - { - $user_id_sql[] = ','. $row['ban_userid']; - } - $user_id_sql = join('', $user_id_sql); + foreach ($sql as $row) { + $user_id_sql[] = ',' . $row['ban_userid']; + } + $user_id_sql = join('', $user_id_sql); - if ($group_id != -1) - { - $user_list = DB()->fetch_rowset(" + if ($group_id != -1) { + $user_list = DB()->fetch_rowset(" SELECT u.username, u.user_email, u.user_lang - FROM ". BB_USERS ." u, ". BB_USER_GROUP ." ug + FROM " . BB_USERS . " u, " . BB_USER_GROUP . " ug WHERE ug.group_id = $group_id AND ug.user_pending = 0 AND u.user_id = ug.user_id AND u.user_active = 1 - AND u.user_id NOT IN(". EXCLUDED_USERS_CSV . $user_id_sql .") + AND u.user_id NOT IN(" . EXCLUDED_USERS_CSV . $user_id_sql . ") "); - } - else - { - $user_list = DB()->fetch_rowset(" + } else { + $user_list = DB()->fetch_rowset(" SELECT username, user_email, user_lang - FROM ". BB_USERS ." + FROM " . BB_USERS . " WHERE user_active = 1 - AND user_id NOT IN(". EXCLUDED_USERS_CSV . $user_id_sql .") + AND user_id NOT IN(" . EXCLUDED_USERS_CSV . $user_id_sql . ") "); - } + } - require(CLASS_DIR .'emailer.php'); + require(CLASS_DIR . 'emailer.php'); - foreach ($user_list as $i => $row) - { - $emailer = new emailer($bb_cfg['smtp_delivery']); + foreach ($user_list as $i => $row) { + $emailer = new emailer($bb_cfg['smtp_delivery']); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - $emailer->use_template('admin_send_email'); + $emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>"); + $emailer->email_address($row['username'] . " <{$row['user_email']}>"); + $emailer->use_template('admin_send_email'); - $emailer->assign_vars(array( - 'SUBJECT' => html_entity_decode($subject), - 'MESSAGE' => html_entity_decode($message), - )); + $emailer->assign_vars(array( + 'SUBJECT' => html_entity_decode($subject), + 'MESSAGE' => html_entity_decode($message), + )); - $emailer->send(); - $emailer->reset(); - } - } + $emailer->send(); + $emailer->reset(); + } + } } // // Generate page // $sql = "SELECT group_id, group_name - FROM ". BB_GROUPS ." + FROM " . BB_GROUPS . " WHERE group_single_user = 0 ORDER BY group_name "; -$groups = array('-- '. $lang['ALL_USERS'] .' --' => -1); -foreach (DB()->fetch_rowset($sql) as $row) -{ - $groups[$row['group_name']] = $row['group_id']; +$groups = array('-- ' . $lang['ALL_USERS'] . ' --' => -1); +foreach (DB()->fetch_rowset($sql) as $row) { + $groups[$row['group_name']] = $row['group_id']; } $template->assign_vars(array( - 'MESSAGE' => $message, - 'SUBJECT' => $subject, + 'MESSAGE' => $message, + 'SUBJECT' => $subject, - 'ERROR_MESSAGE' => ($errors) ? join('
', array_unique($errors)) : '', + 'ERROR_MESSAGE' => ($errors) ? join('
', array_unique($errors)) : '', - 'S_USER_ACTION' => 'admin_mass_email.php', - 'S_GROUP_SELECT' => build_select(POST_GROUPS_URL, $groups), + 'S_USER_ACTION' => 'admin_mass_email.php', + 'S_GROUP_SELECT' => build_select(POST_GROUPS_URL, $groups), )); -print_page('admin_mass_email.tpl', 'admin'); \ No newline at end of file +print_page('admin_mass_email.tpl', 'admin'); diff --git a/admin/admin_phpinfo.php b/admin/admin_phpinfo.php index 1c70efd1e..f2a86a541 100644 --- a/admin/admin_phpinfo.php +++ b/admin/admin_phpinfo.php @@ -1,10 +1,32 @@ sql_query($sql)) - { - bb_die('Could not obtain ranks data #1'); - } + $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain ranks data #1'); + } - $rank_info = DB()->sql_fetchrow($result); - $s_hidden_fields .= ''; - } - else - { - $rank_info['rank_special'] = 0; - } + $rank_info = DB()->sql_fetchrow($result); + $s_hidden_fields .= ''; + } else { + $rank_info['rank_special'] = 0; + } - $s_hidden_fields .= ''; + $s_hidden_fields .= ''; - $rank_is_special = !empty($rank_info['rank_special']) ? HTML_CHECKED : ''; - $rank_is_not_special = empty($rank_info['rank_special']) ? HTML_CHECKED : ''; + $rank_is_special = !empty($rank_info['rank_special']) ? HTML_CHECKED : ''; + $rank_is_not_special = empty($rank_info['rank_special']) ? HTML_CHECKED : ''; - $template->assign_vars(array( - 'TPL_RANKS_EDIT' => true, + $template->assign_vars(array( + 'TPL_RANKS_EDIT' => true, - 'RANK' => !empty($rank_info['rank_title']) ? $rank_info['rank_title'] : '', - 'SPECIAL_RANK' => $rank_is_special, - 'NOT_SPECIAL_RANK' => $rank_is_not_special, - 'MINIMUM' => ($rank_is_special) ? '' : @$rank_info['rank_min'], - 'IMAGE' => !empty($rank_info['rank_image']) ? $rank_info['rank_image'] : 'styles/images/ranks/rank_image.png', - 'STYLE' => !empty($rank_info['rank_style']) ? $rank_info['rank_style'] : '', - 'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '' : '', + 'RANK' => !empty($rank_info['rank_title']) ? $rank_info['rank_title'] : '', + 'SPECIAL_RANK' => $rank_is_special, + 'NOT_SPECIAL_RANK' => $rank_is_not_special, + 'MINIMUM' => ($rank_is_special) ? '' : @$rank_info['rank_min'], + 'IMAGE' => !empty($rank_info['rank_image']) ? $rank_info['rank_image'] : 'styles/images/ranks/rank_image.png', + 'STYLE' => !empty($rank_info['rank_style']) ? $rank_info['rank_style'] : '', + 'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '' : '', - 'S_RANK_ACTION' => "admin_ranks.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - elseif ($mode == 'save') - { - // - // Ok, they sent us our info, let's update it. - // + 'S_RANK_ACTION' => "admin_ranks.php", + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); + } elseif ($mode == 'save') { + // + // Ok, they sent us our info, let's update it. + // - $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : 0; - $rank_title = (isset($_POST['title'])) ? trim($_POST['title']) : ''; - $rank_style = (isset($_POST['style'])) ? trim($_POST['style']) : ''; - $special_rank = ($_POST['special_rank'] == 1) ? TRUE : 0; - $min_posts = (isset($_POST['min_posts'])) ? intval($_POST['min_posts']) : -1; - $rank_image = ((isset($_POST['rank_image']))) ? trim($_POST['rank_image']) : ''; + $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : 0; + $rank_title = (isset($_POST['title'])) ? trim($_POST['title']) : ''; + $rank_style = (isset($_POST['style'])) ? trim($_POST['style']) : ''; + $special_rank = ($_POST['special_rank'] == 1) ? true : 0; + $min_posts = (isset($_POST['min_posts'])) ? intval($_POST['min_posts']) : -1; + $rank_image = ((isset($_POST['rank_image']))) ? trim($_POST['rank_image']) : ''; - if ($rank_title == '') - { - bb_die($lang['MUST_SELECT_RANK']); - } + if ($rank_title == '') { + bb_die($lang['MUST_SELECT_RANK']); + } - if ($special_rank == 1) - { - $max_posts = -1; - $min_posts = -1; - } + if ($special_rank == 1) { + $max_posts = -1; + $min_posts = -1; + } - // - // The rank image has to be a jpg, gif or png - // - if ($rank_image != '') - { - if (!preg_match('/(\.gif|\.png|\.jpg)$/is', $rank_image)) - { - $rank_image = ''; - } - } + // + // The rank image has to be a jpg, gif or png + // + if ($rank_image != '') { + if (!preg_match('/(\.gif|\.png|\.jpg)$/is', $rank_image)) { + $rank_image = ''; + } + } - if ($rank_id) - { - if (!$special_rank) - { - $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['NO_UPDATE_RANKS']); - } - } - $sql = "UPDATE " . BB_RANKS . " - SET rank_title = '". DB()->escape($rank_title) ."', + if ($rank_id) { + if (!$special_rank) { + $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['NO_UPDATE_RANKS']); + } + } + $sql = "UPDATE " . BB_RANKS . " + SET rank_title = '" . DB()->escape($rank_title) . "', rank_special = $special_rank, rank_min = $min_posts, - rank_image = '". DB()->escape($rank_image) . "', - rank_style = '". DB()->escape($rank_style) ."' + rank_image = '" . DB()->escape($rank_image) . "', + rank_style = '" . DB()->escape($rank_style) . "' WHERE rank_id = $rank_id"; - $message = $lang['RANK_UPDATED']; - } - else - { - $sql = "INSERT INTO " . BB_RANKS . " (rank_title, rank_special, rank_min, rank_image, rank_style) - VALUES ('". DB()->escape($rank_title) ."', $special_rank, $min_posts, '". DB()->escape($rank_image) ."', '". DB()->escape($rank_style) ."')"; + $message = $lang['RANK_UPDATED']; + } else { + $sql = "INSERT INTO " . BB_RANKS . " (rank_title, rank_special, rank_min, rank_image, rank_style) + VALUES ('" . DB()->escape($rank_title) . "', $special_rank, $min_posts, '" . DB()->escape($rank_image) . "', '" . DB()->escape($rank_style) . "')"; - $message = $lang['RANK_ADDED']; - } + $message = $lang['RANK_ADDED']; + } - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not update / insert into ranks table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not update / insert into ranks table'); + } - $message .= '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message .= '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - $datastore->update('ranks'); + $datastore->update('ranks'); - bb_die($message); - } - elseif ($mode == 'delete') - { - // - // Ok, they want to delete their rank - // + bb_die($message); + } elseif ($mode == 'delete') { + // + // Ok, they want to delete their rank + // - if (isset($_POST['id']) || isset($_GET['id'])) - { - $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : intval($_GET['id']); - } - else - { - $rank_id = 0; - } + if (isset($_POST['id']) || isset($_GET['id'])) { + $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : intval($_GET['id']); + } else { + $rank_id = 0; + } - if ($rank_id) - { - $sql = "DELETE FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; + if ($rank_id) { + $sql = "DELETE FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not delete rank data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete rank data'); + } - $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['NO_UPDATE_RANKS']); - } + $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['NO_UPDATE_RANKS']); + } - $datastore->update('ranks'); + $datastore->update('ranks'); - bb_die($lang['RANK_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - bb_die($lang['MUST_SELECT_RANK']); - } - } - else - { - bb_die('Invalid mode'); - } -} -else -{ - // - // Show the default page - // - $sql = "SELECT * FROM " . BB_RANKS . " ORDER BY rank_min, rank_title"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain ranks data #2'); - } - $rank_count = DB()->num_rows($result); - $rank_rows = DB()->sql_fetchrowset($result); + bb_die($lang['RANK_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + bb_die($lang['MUST_SELECT_RANK']); + } + } else { + bb_die('Invalid mode'); + } +} else { + // + // Show the default page + // + $sql = "SELECT * FROM " . BB_RANKS . " ORDER BY rank_min, rank_title"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain ranks data #2'); + } + $rank_count = DB()->num_rows($result); + $rank_rows = DB()->sql_fetchrowset($result); - $template->assign_vars(array( - 'TPL_RANKS_LIST' => true, - 'S_RANKS_ACTION' => "admin_ranks.php", - )); + $template->assign_vars(array( + 'TPL_RANKS_LIST' => true, + 'S_RANKS_ACTION' => "admin_ranks.php", + )); - for ($i = 0; $i < $rank_count; $i++) - { - $rank = $rank_rows[$i]['rank_title']; - $special_rank = $rank_rows[$i]['rank_special']; - $rank_id = $rank_rows[$i]['rank_id']; - $rank_min = $rank_rows[$i]['rank_min']; + for ($i = 0; $i < $rank_count; $i++) { + $rank = $rank_rows[$i]['rank_title']; + $special_rank = $rank_rows[$i]['rank_special']; + $rank_id = $rank_rows[$i]['rank_id']; + $rank_min = $rank_rows[$i]['rank_min']; - if ($special_rank == 1) - { - $rank_min = $rank_max = '-'; - } + if ($special_rank == 1) { + $rank_min = $rank_max = '-'; + } - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $rank_is_special = ($special_rank) ? $lang['YES'] : $lang['NO']; + $rank_is_special = ($special_rank) ? $lang['YES'] : $lang['NO']; - $template->assign_block_vars('ranks', array( - 'ROW_CLASS' => $row_class, - 'RANK' => $rank, - 'STYLE' => $rank_rows[$i]['rank_style'], - 'IMAGE_DISPLAY' => ($rank_rows[$i]['rank_image']) ? '' : '', - 'SPECIAL_RANK' => $rank_is_special, - 'RANK_MIN' => $rank_min, + $template->assign_block_vars('ranks', array( + 'ROW_CLASS' => $row_class, + 'RANK' => $rank, + 'STYLE' => $rank_rows[$i]['rank_style'], + 'IMAGE_DISPLAY' => ($rank_rows[$i]['rank_image']) ? '' : '', + 'SPECIAL_RANK' => $rank_is_special, + 'RANK_MIN' => $rank_min, - 'U_RANK_EDIT' => "admin_ranks.php?mode=edit&id=$rank_id", - 'U_RANK_DELETE' => "admin_ranks.php?mode=delete&id=$rank_id", - )); - } + 'U_RANK_EDIT' => "admin_ranks.php?mode=edit&id=$rank_id", + 'U_RANK_DELETE' => "admin_ranks.php?mode=delete&id=$rank_id", + )); + } } -print_page('admin_ranks.tpl', 'admin'); \ No newline at end of file +print_page('admin_ranks.tpl', 'admin'); diff --git a/admin/admin_rebuild_search.php b/admin/admin_rebuild_search.php index 391c2917f..ca785580a 100644 --- a/admin/admin_rebuild_search.php +++ b/admin/admin_rebuild_search.php @@ -1,48 +1,72 @@ query(" - UPDATE ". BB_SEARCH_REBUILD ." SET - rebuild_session_status = ". REBUILD_SEARCH_ABORTED ." +if (isset($_REQUEST['cancel_button'])) { + // update the rebuild_status + if ($last_session_id) { + DB()->query(" + UPDATE " . BB_SEARCH_REBUILD . " SET + rebuild_session_status = " . REBUILD_SEARCH_ABORTED . " WHERE rebuild_session_id = $last_session_id "); - } + } - bb_die(sprintf($lang['REBUILD_SEARCH_ABORTED'], $last_session_data['end_post_id']) .'

'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); + bb_die(sprintf($lang['REBUILD_SEARCH_ABORTED'], $last_session_data['end_post_id']) . '

' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); } // from which post to start processing @@ -52,396 +76,360 @@ $start = abs(intval(@$_REQUEST['start'])); $total_posts = get_total_posts(); // clear the search tables and clear mode (delete or truncate) -$clear_search = isset($_REQUEST['clear_search']) ? (int) $_REQUEST['clear_search'] : 0; +$clear_search = isset($_REQUEST['clear_search']) ? (int)$_REQUEST['clear_search'] : 0; // get the number of total/session posts already processed -$total_posts_processed = ( $start != 0 ) ? get_total_posts('before', $last_session_data['end_post_id']) : 0; -$session_posts_processed = ( $mode == 'refresh' ) ? get_processed_posts('session') : 0; +$total_posts_processed = ($start != 0) ? get_total_posts('before', $last_session_data['end_post_id']) : 0; +$session_posts_processed = ($mode == 'refresh') ? get_processed_posts('session') : 0; // find how many posts aren't processed $total_posts_processing = $total_posts - $total_posts_processed; // how many posts to process in this session -if ($session_posts_processing = @intval($_REQUEST['session_posts_processing'])) -{ - if ($mode == 'submit') - { - // check if we passed over total_posts just after submitting - if ($session_posts_processing + $total_posts_processed > $total_posts) - { - $session_posts_processing = $total_posts - $total_posts_processed; - } - } - // correct it when posts are deleted during processing - $session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing; -} -else -{ - // if we have finished, get all the posts, else only the remaining - $session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing; +if ($session_posts_processing = @intval($_REQUEST['session_posts_processing'])) { + if ($mode == 'submit') { + // check if we passed over total_posts just after submitting + if ($session_posts_processing + $total_posts_processed > $total_posts) { + $session_posts_processing = $total_posts - $total_posts_processed; + } + } + // correct it when posts are deleted during processing + $session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing; +} else { + // if we have finished, get all the posts, else only the remaining + $session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing; } // how many posts to process per cycle -$post_limit = isset($_REQUEST['post_limit']) ? (int) $_REQUEST['post_limit'] : $def_post_limit; +$post_limit = isset($_REQUEST['post_limit']) ? (int)$_REQUEST['post_limit'] : $def_post_limit; // correct the post_limit when we pass over it -if ( $session_posts_processed + $post_limit > $session_posts_processing ) -{ - $post_limit = $session_posts_processing - $session_posts_processed; +if ($session_posts_processed + $post_limit > $session_posts_processing) { + $post_limit = $session_posts_processing - $session_posts_processed; } // how much time to wait per cycle -if (isset($_REQUEST['time_limit'])) -{ - $time_limit = (int) $_REQUEST['time_limit']; -} -else -{ - $time_limit = $def_time_limit; - $time_limit_explain = $lang['TIME_LIMIT_EXPLAIN']; +if (isset($_REQUEST['time_limit'])) { + $time_limit = (int)$_REQUEST['time_limit']; +} else { + $time_limit = $def_time_limit; + $time_limit_explain = $lang['TIME_LIMIT_EXPLAIN']; - // check for safe mode timeout - if ( ini_get('safe_mode') ) - { - // get execution time - $max_execution_time = ini_get('max_execution_time'); - $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_SAFE'], $max_execution_time); + // check for safe mode timeout + if (ini_get('safe_mode')) { + // get execution time + $max_execution_time = ini_get('max_execution_time'); + $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_SAFE'], $max_execution_time); - if ( $time_limit > $max_execution_time ) - { - $time_limit = $max_execution_time; - } - } + if ($time_limit > $max_execution_time) { + $time_limit = $max_execution_time; + } + } - // check for webserver timeout (IE returns null) - if ( isset($_SERVER["HTTP_KEEP_ALIVE"]) ) - { - // get webserver timeout - $webserver_timeout = intval($_SERVER["HTTP_KEEP_ALIVE"]); - $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout); + // check for webserver timeout (IE returns null) + if (isset($_SERVER["HTTP_KEEP_ALIVE"])) { + // get webserver timeout + $webserver_timeout = intval($_SERVER["HTTP_KEEP_ALIVE"]); + $time_limit_explain .= '
' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout); - if ( $time_limit > $webserver_timeout ) - { - $time_limit = $webserver_timeout; - } - } + if ($time_limit > $webserver_timeout) { + $time_limit = $webserver_timeout; + } + } } // how much time to wait between page refreshes -$refresh_rate = isset($_REQUEST['refresh_rate']) ? (int) $_REQUEST['refresh_rate'] : $def_refresh_rate; +$refresh_rate = isset($_REQUEST['refresh_rate']) ? (int)$_REQUEST['refresh_rate'] : $def_refresh_rate; // check if the user gave wrong input -if ($mode == 'submit') -{ - if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) - { - bb_die($lang['WRONG_INPUT'] .'

'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); - } +if ($mode == 'submit') { + if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) { + bb_die($lang['WRONG_INPUT'] . '

' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '', '')); + } } // Increase maximum execution time in case of a lot of posts, but don't complain about it if it isn't allowed. @set_time_limit($time_limit + 20); // check if we are should start processing -if ($mode == 'submit' || $mode == 'refresh') -{ - // check if we are in the beginning of processing - if ($start == 0) - { - $last_session_data = get_empty_last_session_data(); - clear_search_tables($clear_search); - } +if ($mode == 'submit' || $mode == 'refresh') { + // check if we are in the beginning of processing + if ($start == 0) { + $last_session_data = get_empty_last_session_data(); + clear_search_tables($clear_search); + } - // get the db sizes - list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); + // get the db sizes + list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); - // get the post subject/text of each post - $result = DB()->query(" + // get the post subject/text of each post + $result = DB()->query(" SELECT pt.post_id, pt.post_text, IF(p.post_id = t.topic_first_post_id, t.topic_title, '') AS post_subject FROM - ". BB_POSTS_TEXT ." pt, - ". BB_POSTS ." p, - ". BB_TOPICS ." t + " . BB_POSTS_TEXT . " pt, + " . BB_POSTS . " p, + " . BB_TOPICS . " t WHERE p.post_id = pt.post_id AND t.topic_id = p.topic_id - AND p.poster_id NOT IN(". BOT_UID .") + AND p.poster_id NOT IN(" . BOT_UID . ") AND pt.post_id >= $start ORDER BY pt.post_id ASC LIMIT $post_limit "); - $expire_time = $start_time + $time_limit - 5; - $start_post_id = $end_post_id = $num_rows = 0; - $timer_expired = false; - $words_sql = array(); + $expire_time = $start_time + $time_limit - 5; + $start_post_id = $end_post_id = $num_rows = 0; + $timer_expired = false; + $words_sql = array(); - while ($row = DB()->fetch_next($result) AND !$timer_expired) - { - @set_time_limit(600); - $start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id; - $end_post_id = $row['post_id']; + while ($row = DB()->fetch_next($result) and !$timer_expired) { + @set_time_limit(600); + $start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id; + $end_post_id = $row['post_id']; - // Get search words - $s_post_text = str_replace('\n', "\n", $row['post_text']); - $s_post_subject = str_replace('\n', "\n", $row['post_subject']); - $words_sql[] = array( - 'post_id' => (int) $row['post_id'], - 'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true), - ); + // Get search words + $s_post_text = str_replace('\n', "\n", $row['post_text']); + $s_post_subject = str_replace('\n', "\n", $row['post_subject']); + $words_sql[] = array( + 'post_id' => (int)$row['post_id'], + 'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true), + ); - $timer_expired = (TIMENOW > $expire_time); - $num_rows++; - } + $timer_expired = (TIMENOW > $expire_time); + $num_rows++; + } - // Store search words - if ($words_sql) - { - DB()->query("REPLACE INTO ". BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql)); - } + // Store search words + if ($words_sql) { + DB()->query("REPLACE INTO " . BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql)); + } - // find how much time the last cycle took - $last_cycle_time = intval(TIMENOW - $start_time); + // find how much time the last cycle took + $last_cycle_time = intval(TIMENOW - $start_time); - // check if we had any data - if ($num_rows != 0) - { - if ($mode == 'submit') - { - // insert a new session entry - $args = DB()->build_array('INSERT', array( - 'end_post_id' => (int) $end_post_id, - 'end_time' => (int) TIMENOW, - 'last_cycle_time' => (int) $last_cycle_time, - 'session_time' => (int) $last_cycle_time, - 'session_posts' => (int) $num_rows, - 'session_cycles' => (int) 1, - 'start_post_id' => (int) $start_post_id, - 'start_time' => (int) $start_time, - 'search_size' => (int) $search_tables_size, - 'rebuild_session_status' => REBUILD_SEARCH_PROCESSED, - )); - DB()->query("REPLACE INTO ". BB_SEARCH_REBUILD . $args); - } - else // refresh - { - // update the last session entry - DB()->query(" - UPDATE ". BB_SEARCH_REBUILD ." SET + // check if we had any data + if ($num_rows != 0) { + if ($mode == 'submit') { + // insert a new session entry + $args = DB()->build_array('INSERT', array( + 'end_post_id' => (int)$end_post_id, + 'end_time' => (int)TIMENOW, + 'last_cycle_time' => (int)$last_cycle_time, + 'session_time' => (int)$last_cycle_time, + 'session_posts' => (int)$num_rows, + 'session_cycles' => (int)1, + 'start_post_id' => (int)$start_post_id, + 'start_time' => (int)$start_time, + 'search_size' => (int)$search_tables_size, + 'rebuild_session_status' => REBUILD_SEARCH_PROCESSED, + )); + DB()->query("REPLACE INTO " . BB_SEARCH_REBUILD . $args); + } else { + // refresh + + // update the last session entry + DB()->query(" + UPDATE " . BB_SEARCH_REBUILD . " SET end_post_id = $end_post_id, - end_time = ". TIMENOW .", + end_time = " . TIMENOW . ", last_cycle_time = $last_cycle_time, session_time = session_time + $last_cycle_time, session_posts = session_posts + $num_rows, session_cycles = session_cycles + 1, - rebuild_session_status = ". REBUILD_SEARCH_PROCESSED ." + rebuild_session_status = " . REBUILD_SEARCH_PROCESSED . " WHERE rebuild_session_id = $last_session_id "); - } - } + } + } - $last_session_data = get_rebuild_session_details('last', 'all'); - $template->assign_vars(array('TPL_REBUILD_SEARCH_PROGRESS' => true)); + $last_session_data = get_rebuild_session_details('last', 'all'); + $template->assign_vars(array('TPL_REBUILD_SEARCH_PROGRESS' => true)); - $processing_messages = ''; - $processing_messages .= ($timer_expired) ? sprintf($lang['TIMER_EXPIRED'], TIMENOW - $start_time) : ''; - $processing_messages .= ($start == 0 && $clear_search) ? $lang['CLEARED_SEARCH_TABLES'] : ''; + $processing_messages = ''; + $processing_messages .= ($timer_expired) ? sprintf($lang['TIMER_EXPIRED'], TIMENOW - $start_time) : ''; + $processing_messages .= ($start == 0 && $clear_search) ? $lang['CLEARED_SEARCH_TABLES'] : ''; - // check if we have reached the end of our post processing - $session_posts_processed = get_processed_posts('session'); - $total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']); - $total_posts = get_total_posts(); + // check if we have reached the end of our post processing + $session_posts_processed = get_processed_posts('session'); + $total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']); + $total_posts = get_total_posts(); - if ( $session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts ) - { - $form_parameters = '&start='.($end_post_id+1); - $form_parameters .= '&session_posts_processing='.$session_posts_processing; - $form_parameters .= '&post_limit='.$post_limit; - $form_parameters .= '&time_limit='.$time_limit; - $form_parameters .= '&refresh_rate='.$refresh_rate; + if ($session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts) { + $form_parameters = '&start=' . ($end_post_id + 1); + $form_parameters .= '&session_posts_processing=' . $session_posts_processing; + $form_parameters .= '&post_limit=' . $post_limit; + $form_parameters .= '&time_limit=' . $time_limit; + $form_parameters .= '&refresh_rate=' . $refresh_rate; - $form_action = 'admin_rebuild_search.php'.'?mode=refresh'.$form_parameters; - $next_button = $lang['NEXT']; - $progress_bar_img = $images['progress_bar']; + $form_action = 'admin_rebuild_search.php' . '?mode=refresh' . $form_parameters; + $next_button = $lang['NEXT']; + $progress_bar_img = $images['progress_bar']; - $processing_messages .= sprintf($lang['PROCESSING_NEXT_POSTS'], $post_limit); + $processing_messages .= sprintf($lang['PROCESSING_NEXT_POSTS'], $post_limit); meta_refresh($form_action, $refresh_rate); - // create the meta tag for refresh - $template->assign_vars(array( - 'CANCEL_BUTTON' => true, - )); - } - else // end of processing - { - $form_action = "admin_rebuild_search.php"; - $next_button = $lang['FINISHED']; - $progress_bar_img = $images['progress_bar_full']; + // create the meta tag for refresh + $template->assign_vars(array( + 'CANCEL_BUTTON' => true, + )); + } else { + // end of processing - $processing_messages .= ( $session_posts_processed < $session_posts_processing ) ? sprintf($lang['DELETED_POSTS'], $session_posts_processing - $session_posts_processed) : ''; - $processing_messages .= ( $total_posts_processed == $total_posts ) ? $lang['ALL_POSTS_PROCESSED'] : $lang['ALL_SESSION_POSTS_PROCESSED']; + $form_action = "admin_rebuild_search.php"; + $next_button = $lang['FINISHED']; + $progress_bar_img = $images['progress_bar_full']; - // if we have processed all the db posts we need to update the rebuild_status - DB()->query("UPDATE ". BB_SEARCH_REBUILD ." SET - rebuild_session_status = ". REBUILD_SEARCH_COMPLETED ." + $processing_messages .= ($session_posts_processed < $session_posts_processing) ? sprintf($lang['DELETED_POSTS'], $session_posts_processing - $session_posts_processed) : ''; + $processing_messages .= ($total_posts_processed == $total_posts) ? $lang['ALL_POSTS_PROCESSED'] : $lang['ALL_SESSION_POSTS_PROCESSED']; + + // if we have processed all the db posts we need to update the rebuild_status + DB()->query("UPDATE " . BB_SEARCH_REBUILD . " SET + rebuild_session_status = " . REBUILD_SEARCH_COMPLETED . " WHERE rebuild_session_id = $last_session_id AND end_post_id = $max_post_id "); - // optimize all search tables when finished - $table_ary = array(BB_POSTS_SEARCH); + // optimize all search tables when finished + $table_ary = array(BB_POSTS_SEARCH); - foreach ($table_ary as $table) - { - DB()->query("ANALYZE TABLE $table"); - DB()->query("OPTIMIZE TABLE $table"); - } + foreach ($table_ary as $table) { + DB()->query("ANALYZE TABLE $table"); + DB()->query("OPTIMIZE TABLE $table"); + } - $processing_messages .= '
' . $lang['ALL_TABLES_OPTIMIZED']; - } + $processing_messages .= '
' . $lang['ALL_TABLES_OPTIMIZED']; + } - // calculate the percent - $session_percent = ($session_posts_processed / $session_posts_processing) * 100; - $total_percent = ($total_posts_processed / $total_posts) * 100; + // calculate the percent + $session_percent = ($session_posts_processed / $session_posts_processing) * 100; + $total_percent = ($total_posts_processed / $total_posts) * 100; - // get the db sizes - list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); + // get the db sizes + list($search_data_size, $search_index_size, $search_tables_size) = get_db_sizes(); - // calculate the final (estimated) values - $final_search_tables_size = ''; + // calculate the final (estimated) values + $final_search_tables_size = ''; - if ($search_tables_size) - { - $start_search_tables_size = $last_session_data['search_size']; - $final_search_tables_size = $start_search_tables_size + round(($search_tables_size - $start_search_tables_size) * (100 / $session_percent)); - } + if ($search_tables_size) { + $start_search_tables_size = $last_session_data['search_size']; + $final_search_tables_size = $start_search_tables_size + round(($search_tables_size - $start_search_tables_size) * (100 / $session_percent)); + } - // calculate various times - $session_time = $last_session_data['session_time']; - $session_average_cycle_time = round($session_time / $last_session_data['session_cycles']); - $session_estimated_time = round($session_time * (100 / $session_percent)) - $session_time; + // calculate various times + $session_time = $last_session_data['session_time']; + $session_average_cycle_time = round($session_time / $last_session_data['session_cycles']); + $session_estimated_time = round($session_time * (100 / $session_percent)) - $session_time; - // create the percent boxes - create_percent_box('session', create_percent_color($session_percent), $session_percent); - create_percent_box('total', create_percent_color($total_percent), $total_percent); + // create the percent boxes + create_percent_box('session', create_percent_color($session_percent), $session_percent); + create_percent_box('total', create_percent_color($total_percent), $total_percent); - $template->assign_vars(array( - 'L_NEXT' => $next_button, - 'L_TIME_LAST_POSTS_ADMIN' => sprintf($lang['TIME_LAST_POSTS'], $num_rows), + $template->assign_vars(array( + 'L_NEXT' => $next_button, + 'L_TIME_LAST_POSTS_ADMIN' => sprintf($lang['TIME_LAST_POSTS'], $num_rows), - 'PROCESSING_POSTS' => sprintf($lang['PROCESSED_POST_IDS'], $start_post_id, $end_post_id), - 'PROCESSING_MESSAGES' => $processing_messages, - 'PROGRESS_BAR_IMG' => $progress_bar_img, + 'PROCESSING_POSTS' => sprintf($lang['PROCESSED_POST_IDS'], $start_post_id, $end_post_id), + 'PROCESSING_MESSAGES' => $processing_messages, + 'PROGRESS_BAR_IMG' => $progress_bar_img, - 'SESSION_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $session_posts_processed - $num_rows + 1, $session_posts_processed, $session_posts_processing), - 'SESSION_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($session_percent, 2)), + 'SESSION_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $session_posts_processed - $num_rows + 1, $session_posts_processed, $session_posts_processing), + 'SESSION_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($session_percent, 2)), - 'TOTAL_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $total_posts_processed - $num_rows + 1, $total_posts_processed, $total_posts), - 'TOTAL_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($total_percent, 2)), + 'TOTAL_DETAILS' => sprintf($lang['PROCESS_DETAILS'], $total_posts_processed - $num_rows + 1, $total_posts_processed, $total_posts), + 'TOTAL_PERCENT' => sprintf($lang['PERCENT_COMPLETED'], round($total_percent, 2)), - 'LAST_CYCLE_TIME' => delta_time(TIMENOW), - 'SESSION_TIME' => delta_time($last_session_data['start_time']), - 'SESSION_AVERAGE_CYCLE_TIME'=> delta_time($session_average_cycle_time, 0), - 'SESSION_ESTIMATED_TIME' => delta_time($session_estimated_time, 0), + 'LAST_CYCLE_TIME' => delta_time(TIMENOW), + 'SESSION_TIME' => delta_time($last_session_data['start_time']), + 'SESSION_AVERAGE_CYCLE_TIME' => delta_time($session_average_cycle_time, 0), + 'SESSION_ESTIMATED_TIME' => delta_time($session_estimated_time, 0), - 'SEARCH_TABLES_SIZE' => humn_size($search_tables_size), - 'FINAL_SEARCH_TABLES_SIZE' => humn_size($final_search_tables_size), - 'SEARCH_DATA_SIZE' => humn_size($search_data_size), - 'SEARCH_INDEX_SIZE' => humn_size($search_index_size), + 'SEARCH_TABLES_SIZE' => humn_size($search_tables_size), + 'FINAL_SEARCH_TABLES_SIZE' => humn_size($final_search_tables_size), + 'SEARCH_DATA_SIZE' => humn_size($search_data_size), + 'SEARCH_INDEX_SIZE' => humn_size($search_index_size), - 'START_POST' => $last_session_data['start_post_id'], - 'POST_LIMIT' => $num_rows, - 'TIME_LIMIT' => $time_limit, - 'REFRESH_RATE' => $refresh_rate, + 'START_POST' => $last_session_data['start_post_id'], + 'POST_LIMIT' => $num_rows, + 'TIME_LIMIT' => $time_limit, + 'REFRESH_RATE' => $refresh_rate, - 'S_REBUILD_SEARCH_ACTION' => $form_action, - )); -} -else // show the input page -{ - // create the page - // used only with the select input - $post_limit_hidden = ( $def_post_limit > $total_posts ) ? $total_posts : $def_post_limit; + 'S_REBUILD_SEARCH_ACTION' => $form_action, + )); +} else {// show the input page + // create the page + // used only with the select input + $post_limit_hidden = ($def_post_limit > $total_posts) ? $total_posts : $def_post_limit; - $s_hidden_fields = ''; - $s_hidden_fields .= ''; + $s_hidden_fields = ''; + $s_hidden_fields .= ''; - $next_start_post_id = 0; - $last_saved_processing = ''; - $clear_search_disabled = ''; + $next_start_post_id = 0; + $last_saved_processing = ''; + $clear_search_disabled = ''; - if ($last_session_data['rebuild_session_id']) - { - $last_saved_post_id = $last_session_data['end_post_id']; - $next_start_post_id = $last_saved_post_id + 1; - $last_saved_date = bb_date($last_session_data['end_time']); + if ($last_session_data['rebuild_session_id']) { + $last_saved_post_id = $last_session_data['end_post_id']; + $next_start_post_id = $last_saved_post_id + 1; + $last_saved_date = bb_date($last_session_data['end_time']); - // check our last status - if ( $last_session_data['rebuild_session_status'] == REBUILD_SEARCH_PROCESSED ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_STOPPED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); - $clear_search_disabled = 'disabled="disabled"'; + // check our last status + if ($last_session_data['rebuild_session_status'] == REBUILD_SEARCH_PROCESSED) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_STOPPED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); + $clear_search_disabled = 'disabled="disabled"'; - $template->assign_block_vars("start_select_input", array()); - } - elseif ( $last_session_data['rebuild_session_status'] == REBUILD_SEARCH_ABORTED ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_ABORTED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); - // check if the interrupted cycle has finished - if ( TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time'] ) - { - $last_saved_processing .= '
'.$lang['INFO_PROCESSING_ABORTED_SOON']; - } - $clear_search_disabled = 'disabled="disabled"'; + $template->assign_block_vars("start_select_input", array()); + } elseif ($last_session_data['rebuild_session_status'] == REBUILD_SEARCH_ABORTED) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_ABORTED'], $last_saved_post_id, $total_posts_processed, $last_saved_date); + // check if the interrupted cycle has finished + if (TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time']) { + $last_saved_processing .= '
' . $lang['INFO_PROCESSING_ABORTED_SOON']; + } + $clear_search_disabled = 'disabled="disabled"'; - $template->assign_block_vars("start_select_input", array()); - } - else // when finished - { - if ( $last_session_data['end_post_id'] < $max_post_id ) - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED_NEW'], $last_saved_post_id, $total_posts_processed, $last_saved_date, ($total_posts - $total_posts_processed)); - $clear_search_disabled = 'disabled="disabled"'; + $template->assign_block_vars("start_select_input", array()); + } else { + // when finished - $template->assign_block_vars("start_select_input", array()); - } - else - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); + if ($last_session_data['end_post_id'] < $max_post_id) { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED_NEW'], $last_saved_post_id, $total_posts_processed, $last_saved_date, ($total_posts - $total_posts_processed)); + $clear_search_disabled = 'disabled="disabled"'; - $template->assign_block_vars("start_text_input", array()); - } - } + $template->assign_block_vars("start_select_input", array()); + } else { + $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); - $template->assign_block_vars("last_saved_info", array()); - } - else - { - $template->assign_block_vars("start_text_input", array()); - } + $template->assign_block_vars("start_text_input", array()); + } + } - // create the output of page - $template->assign_vars(array( - 'TPL_REBUILD_SEARCH_MAIN' => true, + $template->assign_block_vars("last_saved_info", array()); + } else { + $template->assign_block_vars("start_text_input", array()); + } - 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, + // create the output of page + $template->assign_vars(array( + 'TPL_REBUILD_SEARCH_MAIN' => true, - 'NEXT_START_POST_ID' => $next_start_post_id, - 'CLEAR_SEARCH_DISABLED' => $clear_search_disabled, - 'SESSION_POSTS_PROCESSING' => $session_posts_processing, - 'POST_LIMIT' => $post_limit, - 'REFRESH_RATE' => $refresh_rate, - 'TIME_LIMIT' => $time_limit, + 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, - 'LAST_SAVED_PROCESSING' => $last_saved_processing, + 'NEXT_START_POST_ID' => $next_start_post_id, + 'CLEAR_SEARCH_DISABLED' => $clear_search_disabled, + 'SESSION_POSTS_PROCESSING' => $session_posts_processing, + 'POST_LIMIT' => $post_limit, + 'REFRESH_RATE' => $refresh_rate, + 'TIME_LIMIT' => $time_limit, - 'SESSION_ID' => $userdata['session_id'], + 'LAST_SAVED_PROCESSING' => $last_saved_processing, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_REBUILD_SEARCH_ACTION' => "admin_rebuild_search.php?mode=submit", - )); + 'SESSION_ID' => $userdata['session_id'], + + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_REBUILD_SEARCH_ACTION' => "admin_rebuild_search.php?mode=submit", + )); } print_page('admin_rebuild_search.tpl', 'admin'); @@ -449,124 +437,111 @@ print_page('admin_rebuild_search.tpl', 'admin'); // // Functions // -function get_db_sizes () +function get_db_sizes() { - $search_data_size = $search_index_size = 0; - $search_table_like = DB()->escape(BB_POSTS_SEARCH); + $search_data_size = $search_index_size = 0; + $search_table_like = DB()->escape(BB_POSTS_SEARCH); - $sql = "SHOW TABLE STATUS FROM `". DB()->selected_db ."` LIKE '$search_table_like'"; + $sql = "SHOW TABLE STATUS FROM `" . DB()->selected_db . "` LIKE '$search_table_like'"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $search_data_size += $row['Data_length']; - $search_index_size += $row['Index_length']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $search_data_size += $row['Data_length']; + $search_index_size += $row['Index_length']; + } - return array($search_data_size, $search_index_size, $search_data_size+$search_index_size); + return array($search_data_size, $search_index_size, $search_data_size + $search_index_size); } // get the latest post_id in the forum -function get_latest_post_id () +function get_latest_post_id() { - $row = DB()->fetch_row("SELECT MAX(post_id) as post_id FROM ". BB_POSTS_TEXT); + $row = DB()->fetch_row("SELECT MAX(post_id) as post_id FROM " . BB_POSTS_TEXT); - return (int) $row['post_id']; + return (int)$row['post_id']; } -function get_empty_last_session_data () +function get_empty_last_session_data() { - return array( - 'rebuild_session_id' => 0, - 'start_post_id' => 0, - 'end_post_id' => 0, - 'start_time' => 0, - 'end_time' => 0, - 'last_cycle_time' => 0, - 'session_time' => 0, - 'session_posts' => 0, - 'session_cycles' => 0, - 'search_size' => 0, - 'rebuild_session_status' => REBUILD_SEARCH_COMPLETED, - ); + return array( + 'rebuild_session_id' => 0, + 'start_post_id' => 0, + 'end_post_id' => 0, + 'start_time' => 0, + 'end_time' => 0, + 'last_cycle_time' => 0, + 'session_time' => 0, + 'session_posts' => 0, + 'session_cycles' => 0, + 'search_size' => 0, + 'rebuild_session_status' => REBUILD_SEARCH_COMPLETED, + ); } // get some or all of the rebuild details of a specific session or of the last session // $id is the id or the 'last' id // $details is one of the fields or 'all' of them -function get_rebuild_session_details ($id, $details = 'all') +function get_rebuild_session_details($id, $details = 'all') { - $session_details = get_empty_last_session_data(); + $session_details = get_empty_last_session_data(); - if ($id != 'last') - { - $sql = "SELECT * FROM ". BB_SEARCH_REBUILD ." WHERE rebuild_session_id = $id"; - } - else - { - $sql = "SELECT * FROM ". BB_SEARCH_REBUILD ." ORDER BY rebuild_session_id DESC LIMIT 1"; - } + if ($id != 'last') { + $sql = "SELECT * FROM " . BB_SEARCH_REBUILD . " WHERE rebuild_session_id = $id"; + } else { + $sql = "SELECT * FROM " . BB_SEARCH_REBUILD . " ORDER BY rebuild_session_id DESC LIMIT 1"; + } - if ($row = DB()->fetch_row($sql)) - { - $session_details = ($details == 'all') ? $row : $row[$details]; - } + if ($row = DB()->fetch_row($sql)) { + $session_details = ($details == 'all') ? $row : $row[$details]; + } - return $session_details; + return $session_details; } // get the number of processed posts in the last session or in all sessions // 'total' to get the sum of posts of all sessions // 'session' to get the posts of the last session -function get_processed_posts ($mode = 'session') +function get_processed_posts($mode = 'session') { - global $last_session_data; + global $last_session_data; - if ($mode == 'total') - { - $sql = "SELECT SUM(session_posts) as posts FROM ". BB_SEARCH_REBUILD; - $row = DB()->fetch_row($sql); - } - else - { - $row['posts'] = $last_session_data['session_posts']; - } + if ($mode == 'total') { + $sql = "SELECT SUM(session_posts) as posts FROM " . BB_SEARCH_REBUILD; + $row = DB()->fetch_row($sql); + } else { + $row['posts'] = $last_session_data['session_posts']; + } - return (int) $row['posts']; + return (int)$row['posts']; } // how many posts are in the db before or after a specific post_id // after/before require and the post_id -function get_total_posts ($mode = 'after', $post_id = 0) +function get_total_posts($mode = 'after', $post_id = 0) { - if ($post_id) - { - $sql = "SELECT COUNT(post_id) as total_posts FROM " . BB_POSTS_TEXT . " - WHERE post_id " . (($mode == 'after') ? '>= ' : '<= ' ) . (int) $post_id; - } - else - { - $sql = "SELECT COUNT(*) as total_posts FROM " . BB_POSTS_TEXT; - } + if ($post_id) { + $sql = "SELECT COUNT(post_id) as total_posts FROM " . BB_POSTS_TEXT . " + WHERE post_id " . (($mode == 'after') ? '>= ' : '<= ') . (int)$post_id; + } else { + $sql = "SELECT COUNT(*) as total_posts FROM " . BB_POSTS_TEXT; + } - $row = DB()->fetch_row($sql); + $row = DB()->fetch_row($sql); - return (int) $row['total_posts']; + return (int)$row['total_posts']; } -function clear_search_tables ($mode = '') +function clear_search_tables($mode = '') { - DB()->query("DELETE FROM ". BB_SEARCH_REBUILD); + DB()->query("DELETE FROM " . BB_SEARCH_REBUILD); - if ($mode) - { - $table_ary = array(BB_POSTS_SEARCH); + if ($mode) { + $table_ary = array(BB_POSTS_SEARCH); - foreach ($table_ary as $table) - { - $sql = (($mode == 1) ? "DELETE FROM " : "TRUNCATE TABLE ") . $table; - DB()->query($sql); - } - } + foreach ($table_ary as $table) { + $sql = (($mode == 1) ? "DELETE FROM " : "TRUNCATE TABLE ") . $table; + DB()->query($sql); + } + } } // Create the percent color @@ -576,49 +551,44 @@ function clear_search_tables ($mode = '') // We limit the result to 200, in order to avoid white (255). function create_percent_color($percent) { - $percent_ary = array( - 'r' => array(86, 100), - 'g' => array(0, 50), - 'b' => array(51, 85), - ); + $percent_ary = array( + 'r' => array(86, 100), + 'g' => array(0, 50), + 'b' => array(51, 85), + ); - foreach ($percent_ary as $key => $value) - { - if ( $percent <= $value[1] ) - { - $percent_color = create_color($key, round(200-($percent-$value[0])*(200/($value[1]-$value[0])))); - break; - } - } + foreach ($percent_ary as $key => $value) { + if ($percent <= $value[1]) { + $percent_color = create_color($key, round(200 - ($percent - $value[0]) * (200 / ($value[1] - $value[0])))); + break; + } + } - return $percent_color; + return $percent_color; } // create the hex representation of color function create_color($mode, $code) { - return (($mode == 'r') ? 'FF': sprintf("%02X", $code)) . (($mode == 'g') ? 'FF': sprintf("%02X", $code)) . (($mode == 'b') ? 'FF': sprintf("%02X", $code)); + return (($mode == 'r') ? 'FF' : sprintf("%02X", $code)) . (($mode == 'g') ? 'FF' : sprintf("%02X", $code)) . (($mode == 'b') ? 'FF' : sprintf("%02X", $code)); } // create the percent bar & box function create_percent_box($box, $percent_color, $percent_width) { - global $template; + global $template; - if ($box == 'session') - { - $template->assign_vars(array( - 'SESSION_PERCENT_BOX' => true, - 'SESSION_PERCENT_COLOR' => $percent_color, - 'SESSION_PERCENT_WIDTH' => round($percent_width), - )); - } - else - { - $template->assign_vars(array( - 'TOTAL_PERCENT_BOX' => true, - 'TOTAL_PERCENT_COLOR' => $percent_color, - 'TOTAL_PERCENT_WIDTH' => round($percent_width), - )); - } -} \ No newline at end of file + if ($box == 'session') { + $template->assign_vars(array( + 'SESSION_PERCENT_BOX' => true, + 'SESSION_PERCENT_COLOR' => $percent_color, + 'SESSION_PERCENT_WIDTH' => round($percent_width), + )); + } else { + $template->assign_vars(array( + 'TOTAL_PERCENT_BOX' => true, + 'TOTAL_PERCENT_COLOR' => $percent_color, + 'TOTAL_PERCENT_WIDTH' => round($percent_width), + )); + } +} diff --git a/admin/admin_sitemap.php b/admin/admin_sitemap.php index 3976758af..908042321 100644 --- a/admin/admin_sitemap.php +++ b/admin/admin_sitemap.php @@ -1,52 +1,67 @@ sql_query($sql)) -{ - bb_die('Could not query config information in admin_sitemap'); -} -else -{ - $new_params = array(); +if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query config information in admin_sitemap'); +} else { + $new_params = array(); - while ($row = DB()->sql_fetchrow($result)) - { - $config_name = $row['config_name']; - $config_value = $row['config_value']; - $default_config[$config_name] = $config_value; - $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; + while ($row = DB()->sql_fetchrow($result)) { + $config_name = $row['config_name']; + $config_value = $row['config_value']; + $default_config[$config_name] = $config_value; + $new[$config_name] = isset($_POST[$config_name]) ? $_POST[$config_name] : $default_config[$config_name]; - if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) - { - $new_params[$config_name] = $new[$config_name]; - } - } + if (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) { + $new_params[$config_name] = $new[$config_name]; + } + } - if (isset($_POST['submit'])) - { - if (!empty($new_params)) - { - bb_update_config($new_params); - } - } + if (isset($_POST['submit'])) { + if (!empty($new_params)) { + bb_update_config($new_params); + } + } } -$s_mess = $lang['SITEMAP_CREATED'].': '.bb_date($new['sitemap_time'], $bb_cfg['post_date_format']).' '.$lang['SITEMAP_AVAILABLE'].': '.make_url('sitemap.xml').''; -$message = (@file_exists(BB_ROOT. "/internal_data/sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED']; +$s_mess = $lang['SITEMAP_CREATED'] . ': ' . bb_date($new['sitemap_time'], $bb_cfg['post_date_format']) . ' ' . $lang['SITEMAP_AVAILABLE'] . ': ' . make_url('sitemap.xml') . ''; +$message = (@file_exists(BB_ROOT . "/internal_data/sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED']; $template->assign_vars(array( - 'STATIC_SITEMAP' => $new['static_sitemap'], - 'MESSAGE' => $message, + 'STATIC_SITEMAP' => $new['static_sitemap'], + 'MESSAGE' => $message, )); -print_page('admin_sitemap.tpl', 'admin'); \ No newline at end of file +print_page('admin_sitemap.tpl', 'admin'); diff --git a/admin/admin_smilies.php b/admin/admin_smilies.php index 4d60e7090..1e69fb524 100644 --- a/admin/admin_smilies.php +++ b/admin/admin_smilies.php @@ -1,370 +1,336 @@ sql_query($sql)) - { - bb_die('Could not delete current smilies'); - } - $datastore->update('smile_replacements'); - } - else - { - $sql = "SELECT code FROM ". BB_SMILIES; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get current smilies'); - } + if (!empty($smile_pak)) { + // The user has already selected a smile_pak file.. Import it + if (!empty($clear_current)) { + $sql = "DELETE FROM " . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not delete current smilies'); + } + $datastore->update('smile_replacements'); + } else { + $sql = "SELECT code FROM " . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get current smilies'); + } - $cur_smilies = DB()->sql_fetchrowset($result); + $cur_smilies = DB()->sql_fetchrowset($result); - for ($i = 0; $i < count($cur_smilies); $i++) - { - $k = $cur_smilies[$i]['code']; - $smiles[$k] = 1; - } - } + for ($i = 0; $i < count($cur_smilies); $i++) { + $k = $cur_smilies[$i]['code']; + $smiles[$k] = 1; + } + } - $fcontents = @file(BB_ROOT . $bb_cfg['smilies_path'] . '/'. $smile_pak); + $fcontents = @file(BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smile_pak); - if (empty($fcontents)) - { - bb_die('Could not read smiley pak file'); - } + if (empty($fcontents)) { + bb_die('Could not read smiley pak file'); + } - for ($i = 0; $i < count($fcontents); $i++) - { - $smile_data = explode($delimeter, trim(addslashes($fcontents[$i]))); + for ($i = 0; $i < count($fcontents); $i++) { + $smile_data = explode($delimeter, trim(addslashes($fcontents[$i]))); - for ($j = 2; $j < count($smile_data); $j++) - { - // Replace > and < with the proper html_entities for matching - $smile_data[$j] = str_replace('<', '<', $smile_data[$j]); - $smile_data[$j] = str_replace('>', '>', $smile_data[$j]); - $k = $smile_data[$j]; + for ($j = 2; $j < count($smile_data); $j++) { + // Replace > and < with the proper html_entities for matching + $smile_data[$j] = str_replace('<', '<', $smile_data[$j]); + $smile_data[$j] = str_replace('>', '>', $smile_data[$j]); + $k = $smile_data[$j]; - if (isset($smiles[$k])) - { - if( !empty($replace_existing) ) - { - $sql = "UPDATE " . BB_SMILIES . " + if (isset($smiles[$k])) { + if (!empty($replace_existing)) { + $sql = "UPDATE " . BB_SMILIES . " SET smile_url = '" . DB()->escape($smile_data[0]) . "', emoticon = '" . DB()->escape($smile_data[1]) . "' WHERE code = '" . DB()->escape($smile_data[$j]) . "'"; - } - else - { - $sql = ''; - } - } - else - { - $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) + } else { + $sql = ''; + } + } else { + $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) VALUES('" . DB()->escape($smile_data[$j]) . "', '" . DB()->escape($smile_data[0]) . "', '" . DB()->escape($smile_data[1]) . "')"; - } + } - if ($sql != '') - { - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not update smilies #1'); - } - $datastore->update('smile_replacements'); - } - } - } + if ($sql != '') { + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not update smilies #1'); + } + $datastore->update('smile_replacements'); + } + } + } - bb_die($lang['SMILEY_IMPORT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - // Display the script to get the smile_pak cfg file - $smile_paks_select = ''; + bb_die($lang['SMILEY_IMPORT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + // Display the script to get the smile_pak cfg file + $smile_paks_select = ''; - $hidden_vars = ''; + $hidden_vars = ''; - $template->assign_vars(array( - 'TPL_SMILE_IMPORT' => true, + $template->assign_vars(array( + 'TPL_SMILE_IMPORT' => true, - 'S_SMILEY_ACTION' => 'admin_smilies.php', - 'S_SMILE_SELECT' => $smile_paks_select, - 'S_HIDDEN_FIELDS' => $hidden_vars, - )); - } -} -else if (isset($_POST['export_pack']) || isset($_GET['export_pack'])) -{ - $export_pack = (string) request_var('export_pack', ''); + 'S_SMILEY_ACTION' => 'admin_smilies.php', + 'S_SMILE_SELECT' => $smile_paks_select, + 'S_HIDDEN_FIELDS' => $hidden_vars, + )); + } +} elseif (isset($_POST['export_pack']) || isset($_GET['export_pack'])) { + $export_pack = (string)request_var('export_pack', ''); - if ($export_pack == 'send') - { - $sql = "SELECT * FROM " . BB_SMILIES; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get smiley list'); - } + if ($export_pack == 'send') { + $sql = "SELECT * FROM " . BB_SMILIES; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get smiley list'); + } - $resultset = DB()->sql_fetchrowset($result); + $resultset = DB()->sql_fetchrowset($result); - $smile_pak = ''; - for ($i = 0; $i < count($resultset); $i++) - { - $smile_pak .= $resultset[$i]['smile_url'] . $delimeter; - $smile_pak .= $resultset[$i]['emoticon'] . $delimeter; - $smile_pak .= $resultset[$i]['code'] . "\n"; - } + $smile_pak = ''; + for ($i = 0; $i < count($resultset); $i++) { + $smile_pak .= $resultset[$i]['smile_url'] . $delimeter; + $smile_pak .= $resultset[$i]['emoticon'] . $delimeter; + $smile_pak .= $resultset[$i]['code'] . "\n"; + } - header("Content-Type: text/x-delimtext; name=\"smiles.pak\""); - header("Content-disposition: attachment; filename=smiles.pak"); + header("Content-Type: text/x-delimtext; name=\"smiles.pak\""); + header("Content-disposition: attachment; filename=smiles.pak"); - echo $smile_pak; + echo $smile_pak; - exit; - } + exit; + } - bb_die(sprintf($lang['EXPORT_SMILES'], '', '') . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); -} -else if (isset($_POST['add']) || isset($_GET['add'])) -{ - $filename_list = ''; - for ($i = 0; $i < count($smiley_images); $i++) - { - $filename_list .= ''; - } + bb_die(sprintf($lang['EXPORT_SMILES'], '', '') . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} elseif (isset($_POST['add']) || isset($_GET['add'])) { + $filename_list = ''; + for ($i = 0; $i < count($smiley_images); $i++) { + $filename_list .= ''; + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $template->assign_vars(array( - 'TPL_SMILE_EDIT' => true, - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_images[0], - 'S_SMILEY_ACTION' => "admin_smilies.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_FILENAME_OPTIONS' => $filename_list, - 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'] - )); -} -else if ( $mode != '' ) -{ - switch( $mode ) - { - case 'delete': - $smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; - $smiley_id = intval($smiley_id); + $template->assign_vars(array( + 'TPL_SMILE_EDIT' => true, + 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_images[0], + 'S_SMILEY_ACTION' => "admin_smilies.php", + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_FILENAME_OPTIONS' => $filename_list, + 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'] + )); +} elseif ($mode != '') { + switch ($mode) { + case 'delete': + $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id']; + $smiley_id = intval($smiley_id); - $sql = "DELETE FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not delete smiley'); - } - $datastore->update('smile_replacements'); + $sql = "DELETE FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not delete smiley'); + } + $datastore->update('smile_replacements'); - bb_die($lang['SMILEY_DEL_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + bb_die($lang['SMILEY_DEL_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; - case 'edit': - $smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; - $smiley_id = intval($smiley_id); + case 'edit': + $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id']; + $smiley_id = intval($smiley_id); - $sql = "SELECT * FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not obtain emoticon information'); - } - $smile_data = DB()->sql_fetchrow($result); + $sql = "SELECT * FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not obtain emoticon information'); + } + $smile_data = DB()->sql_fetchrow($result); - $filename_list = ''; - for ($i = 0; $i < count($smiley_images); $i++) - { - if ($smiley_images[$i] == $smile_data['smile_url']) - { - $smiley_selected = 'selected="selected"'; - $smiley_edit_img = $smiley_images[$i]; - } - else - { - $smiley_selected = ''; - } - $filename_list .= ''; - } + $filename_list = ''; + for ($i = 0; $i < count($smiley_images); $i++) { + if ($smiley_images[$i] == $smile_data['smile_url']) { + $smiley_selected = 'selected="selected"'; + $smiley_edit_img = $smiley_images[$i]; + } else { + $smiley_selected = ''; + } + $filename_list .= ''; + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $template->assign_vars(array( - 'TPL_SMILE_EDIT' => true, - 'SMILEY_CODE' => $smile_data['code'], - 'SMILEY_EMOTICON' => $smile_data['emoticon'], - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_edit_img, - 'S_SMILEY_ACTION' => "admin_smilies.php", - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_FILENAME_OPTIONS' => $filename_list, - 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'], - )); + $template->assign_vars(array( + 'TPL_SMILE_EDIT' => true, + 'SMILEY_CODE' => $smile_data['code'], + 'SMILEY_EMOTICON' => $smile_data['emoticon'], + 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smiley_edit_img, + 'S_SMILEY_ACTION' => "admin_smilies.php", + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_FILENAME_OPTIONS' => $filename_list, + 'S_SMILEY_BASEDIR' => BB_ROOT . $bb_cfg['smilies_path'], + )); - break; + break; - case 'save': - $smile_code = ( isset($_POST['smile_code']) ) ? trim($_POST['smile_code']) : trim($_GET['smile_code']); - $smile_url = ( isset($_POST['smile_url']) ) ? trim($_POST['smile_url']) : trim($_GET['smile_url']); - $smile_url = bb_ltrim(basename($smile_url), "'"); - $smile_emotion = ( isset($_POST['smile_emotion']) ) ? trim($_POST['smile_emotion']) : trim($_GET['smile_emotion']); - $smile_id = ( isset($_POST['smile_id']) ) ? intval($_POST['smile_id']) : intval($_GET['smile_id']); + case 'save': + $smile_code = (isset($_POST['smile_code'])) ? trim($_POST['smile_code']) : trim($_GET['smile_code']); + $smile_url = (isset($_POST['smile_url'])) ? trim($_POST['smile_url']) : trim($_GET['smile_url']); + $smile_url = bb_ltrim(basename($smile_url), "'"); + $smile_emotion = (isset($_POST['smile_emotion'])) ? trim($_POST['smile_emotion']) : trim($_GET['smile_emotion']); + $smile_id = (isset($_POST['smile_id'])) ? intval($_POST['smile_id']) : intval($_GET['smile_id']); - // If no code was entered complain - if ($smile_code == '' || $smile_url == '') - { - bb_die($lang['FIELDS_EMPTY']); - } + // If no code was entered complain + if ($smile_code == '' || $smile_url == '') { + bb_die($lang['FIELDS_EMPTY']); + } - // Convert < and > to proper htmlentities for parsing - $smile_code = str_replace('<', '<', $smile_code); - $smile_code = str_replace('>', '>', $smile_code); + // Convert < and > to proper htmlentities for parsing + $smile_code = str_replace('<', '<', $smile_code); + $smile_code = str_replace('>', '>', $smile_code); - // Proceed with updating the smiley table - $sql = "UPDATE " . BB_SMILIES . " + // Proceed with updating the smiley table + $sql = "UPDATE " . BB_SMILIES . " SET code = '" . DB()->escape($smile_code) . "', smile_url = '" . DB()->escape($smile_url) . "', emoticon = '" . DB()->escape($smile_emotion) . "' WHERE smilies_id = $smile_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update smilies #2'); - } - $datastore->update('smile_replacements'); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update smilies #2'); + } + $datastore->update('smile_replacements'); - bb_die($lang['SMILEY_EDIT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; + bb_die($lang['SMILEY_EDIT_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; - case 'savenew': - $smile_code = ( isset($_POST['smile_code']) ) ? $_POST['smile_code'] : $_GET['smile_code']; - $smile_url = ( isset($_POST['smile_url']) ) ? $_POST['smile_url'] : $_GET['smile_url']; - $smile_url = bb_ltrim(basename($smile_url), "'"); - $smile_emotion = ( isset($_POST['smile_emotion']) ) ? $_POST['smile_emotion'] : $_GET['smile_emotion']; - $smile_code = trim($smile_code); - $smile_url = trim($smile_url); - $smile_emotion = trim($smile_emotion); + case 'savenew': + $smile_code = (isset($_POST['smile_code'])) ? $_POST['smile_code'] : $_GET['smile_code']; + $smile_url = (isset($_POST['smile_url'])) ? $_POST['smile_url'] : $_GET['smile_url']; + $smile_url = bb_ltrim(basename($smile_url), "'"); + $smile_emotion = (isset($_POST['smile_emotion'])) ? $_POST['smile_emotion'] : $_GET['smile_emotion']; + $smile_code = trim($smile_code); + $smile_url = trim($smile_url); + $smile_emotion = trim($smile_emotion); - // If no code was entered complain - if ($smile_code == '' || $smile_url == '') - { - bb_die($lang['FIELDS_EMPTY']); - } + // If no code was entered complain + if ($smile_code == '' || $smile_url == '') { + bb_die($lang['FIELDS_EMPTY']); + } - // Convert < and > to proper htmlentities for parsing - $smile_code = str_replace('<', '<', $smile_code); - $smile_code = str_replace('>', '>', $smile_code); + // Convert < and > to proper htmlentities for parsing + $smile_code = str_replace('<', '<', $smile_code); + $smile_code = str_replace('>', '>', $smile_code); - // Save the data to the smiley table - $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) + // Save the data to the smiley table + $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) VALUES ('" . DB()->escape($smile_code) . "', '" . DB()->escape($smile_url) . "', '" . DB()->escape($smile_emotion) . "')"; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not insert new smiley'); - } - $datastore->update('smile_replacements'); + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not insert new smiley'); + } + $datastore->update('smile_replacements'); - bb_die($lang['SMILEY_ADD_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - break; - } -} -else -{ - $sql = "SELECT * FROM " . BB_SMILIES; - $result = DB()->sql_query($sql); - if (!$result) - { - bb_die('Could not obtain smileys from database'); - } + bb_die($lang['SMILEY_ADD_SUCCESS'] . '

' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + break; + } +} else { + $sql = "SELECT * FROM " . BB_SMILIES; + $result = DB()->sql_query($sql); + if (!$result) { + bb_die('Could not obtain smileys from database'); + } - $smilies = DB()->sql_fetchrowset($result); + $smilies = DB()->sql_fetchrowset($result); - $template->assign_vars(array( - 'TPL_SMILE_MAIN' => true, - 'S_HIDDEN_FIELDS' => @$s_hidden_fields, - 'S_SMILEY_ACTION' => 'admin_smilies.php', - )); + $template->assign_vars(array( + 'TPL_SMILE_MAIN' => true, + 'S_HIDDEN_FIELDS' => @$s_hidden_fields, + 'S_SMILEY_ACTION' => 'admin_smilies.php', + )); - // Loop throuh the rows of smilies setting block vars for the template - for ($i = 0; $i < count($smilies); $i++) - { - // Replace htmlentites for < and > with actual character - $smilies[$i]['code'] = str_replace('<', '<', $smilies[$i]['code']); - $smilies[$i]['code'] = str_replace('>', '>', $smilies[$i]['code']); + // Loop throuh the rows of smilies setting block vars for the template + for ($i = 0; $i < count($smilies); $i++) { + // Replace htmlentites for < and > with actual character + $smilies[$i]['code'] = str_replace('<', '<', $smilies[$i]['code']); + $smilies[$i]['code'] = str_replace('>', '>', $smilies[$i]['code']); - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('smiles', array( - 'ROW_CLASS' => $row_class, + $template->assign_block_vars('smiles', array( + 'ROW_CLASS' => $row_class, - 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] .'/'. $smilies[$i]['smile_url'], - 'CODE' => $smilies[$i]['code'], - 'EMOT' => $smilies[$i]['emoticon'], + 'SMILEY_IMG' => BB_ROOT . $bb_cfg['smilies_path'] . '/' . $smilies[$i]['smile_url'], + 'CODE' => $smilies[$i]['code'], + 'EMOT' => $smilies[$i]['emoticon'], - 'U_SMILEY_EDIT' => "admin_smilies.php?mode=edit&id=". $smilies[$i]['smilies_id'], - 'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&id=". $smilies[$i]['smilies_id'], - )); - } + 'U_SMILEY_EDIT' => "admin_smilies.php?mode=edit&id=" . $smilies[$i]['smilies_id'], + 'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&id=" . $smilies[$i]['smilies_id'], + )); + } } -print_page('admin_smilies.tpl', 'admin'); \ No newline at end of file +print_page('admin_smilies.tpl', 'admin'); diff --git a/admin/admin_terms.php b/admin/admin_terms.php index cb9437927..4d212b388 100644 --- a/admin/admin_terms.php +++ b/admin/admin_terms.php @@ -1,25 +1,46 @@ $_POST['message'])); - bb_die($lang['CONFIG_UPDATED']); +if (isset($_POST['post']) && $bb_cfg['terms'] != $_POST['message']) { + bb_update_config(array('terms' => $_POST['message'])); + bb_die($lang['CONFIG_UPDATED']); } $template->assign_vars(array( - 'S_ACTION' => 'admin_terms.php', - 'EXT_LINK_NW' => $bb_cfg['ext_link_new_win'], - 'MESSAGE' => ($bb_cfg['terms']) ? $bb_cfg['terms'] : '', - 'PREVIEW_HTML' => (isset($_REQUEST['preview'])) ? bbcode2html($_POST['message']) : '', + 'S_ACTION' => 'admin_terms.php', + 'EXT_LINK_NW' => $bb_cfg['ext_link_new_win'], + 'MESSAGE' => ($bb_cfg['terms']) ? $bb_cfg['terms'] : '', + 'PREVIEW_HTML' => (isset($_REQUEST['preview'])) ? bbcode2html($_POST['message']) : '', )); -print_page('admin_terms.tpl', 'admin'); \ No newline at end of file +print_page('admin_terms.tpl', 'admin'); diff --git a/admin/admin_ug_auth.php b/admin/admin_ug_auth.php index 1fd568925..f4e0f4aa4 100644 --- a/admin/admin_ug_auth.php +++ b/admin/admin_ug_auth.php @@ -1,474 +1,447 @@ fetch_row($sql)) - { - $group_id = $row['group_id']; - } - else - { - $group_id = create_user_group($user_id); - } + if ($row = DB()->fetch_row($sql)) { + $group_id = $row['group_id']; + } else { + $group_id = create_user_group($user_id); + } - if (!$group_id || !$user_id || is_null($this_user_level)) - { - trigger_error('data missing', E_USER_ERROR); - } + if (!$group_id || !$user_id || is_null($this_user_level)) { + trigger_error('data missing', E_USER_ERROR); + } - // Make user an admin (if already user) - if (@$_POST['userlevel'] === 'admin') - { - if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID) - { - bb_die("Could not update admin status"); - } + // Make user an admin (if already user) + if (@$_POST['userlevel'] === 'admin') { + if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID) { + bb_die("Could not update admin status"); + } - DB()->query("UPDATE ". BB_USERS ." SET user_level = ". ADMIN ." WHERE user_id = $user_id LIMIT 1"); + DB()->query("UPDATE " . BB_USERS . " SET user_level = " . ADMIN . " WHERE user_id = $user_id LIMIT 1"); - // Delete any entries in auth_access, they are not required if user is becoming an admin - delete_permissions($group_id, $user_id); + // Delete any entries in auth_access, they are not required if user is becoming an admin + delete_permissions($group_id, $user_id); - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - // Make admin a user (if already admin) - else if (@$_POST['userlevel'] === 'user') - { - // ignore if you're trying to change yourself from an admin to user! - if ($userdata['user_id'] == $user_id) - { - bb_die("Could not update admin status

Could not change yourself from an admin to user"); - } - // Update users level, reset to USER - DB()->query("UPDATE ". BB_USERS ." SET user_level = ". USER ." WHERE user_id = $user_id LIMIT 1"); + bb_die($message); + } // Make admin a user (if already admin) + elseif (@$_POST['userlevel'] === 'user') { + // ignore if you're trying to change yourself from an admin to user! + if ($userdata['user_id'] == $user_id) { + bb_die("Could not update admin status

Could not change yourself from an admin to user"); + } + // Update users level, reset to USER + DB()->query("UPDATE " . BB_USERS . " SET user_level = " . USER . " WHERE user_id = $user_id LIMIT 1"); - delete_permissions($group_id, $user_id); + delete_permissions($group_id, $user_id); - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } + bb_die($message); + } - // - // Submit new USER permissions - // - $auth = array(); + // + // Submit new USER permissions + // + $auth = array(); - if (is_array(@$_POST['auth'])) - { - array_deep($_POST['auth'], 'intval'); + if (is_array(@$_POST['auth'])) { + array_deep($_POST['auth'], 'intval'); - foreach ($_POST['auth'] as $f_id => $bf_ary) - { - if (array_sum($bf_ary)) - { - $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); - } - } - } + foreach ($_POST['auth'] as $f_id => $bf_ary) { + if (array_sum($bf_ary)) { + $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); + } + } + } - delete_permissions($group_id, null, $cat_id); - store_permissions($group_id, $auth); + delete_permissions($group_id, null, $cat_id); + store_permissions($group_id, $auth); - update_user_level($user_id); + update_user_level($user_id); - $l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH']; - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($l_auth_return, '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH']; + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($l_auth_return, '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + bb_die($message); } // // Submit new GROUP permissions // -else if ($submit && $mode == 'group' && is_array(@$_POST['auth'])) -{ - if (!$group_data = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } +elseif ($submit && $mode == 'group' && is_array(@$_POST['auth'])) { + if (!$group_data = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - $auth = array(); - array_deep($_POST['auth'], 'intval'); + $auth = array(); + array_deep($_POST['auth'], 'intval'); - foreach ($_POST['auth'] as $f_id => $bf_ary) - { - if (array_sum($bf_ary)) - { - $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); - } - } + foreach ($_POST['auth'] as $f_id => $bf_ary) { + if (array_sum($bf_ary)) { + $auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); + } + } - delete_permissions($group_id, null, $cat_id); - store_permissions($group_id, $auth); + delete_permissions($group_id, null, $cat_id); + store_permissions($group_id, $auth); - update_user_level('all'); + update_user_level('all'); - $l_auth_return = $lang['CLICK_RETURN_GROUPAUTH']; - $message = $lang['AUTH_UPDATED'] .'

'; - $message .= sprintf($l_auth_return, '', '') .'

'; - $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $l_auth_return = $lang['CLICK_RETURN_GROUPAUTH']; + $message = $lang['AUTH_UPDATED'] . '

'; + $message .= sprintf($l_auth_return, '', '') . '

'; + $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + bb_die($message); } // // Front end (changing permissions) // -if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) -{ - $page_cfg['quirks_mode'] = true; +if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) { + $page_cfg['quirks_mode'] = true; - if (!empty($_POST['username'])) - { - $this_userdata = get_userdata($_POST['username'], true); - $user_id = $this_userdata['user_id']; - } - else - { - $this_userdata = get_userdata($user_id); - } - if (!$this_userdata) - { - bb_die($lang['NO_SUCH_USER']); - } + if (!empty($_POST['username'])) { + $this_userdata = get_userdata($_POST['username'], true); + $user_id = $this_userdata['user_id']; + } else { + $this_userdata = get_userdata($user_id); + } + if (!$this_userdata) { + bb_die($lang['NO_SUCH_USER']); + } - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - $base_url = basename(__FILE__) ."?mode=user&u=$user_id"; + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } + $base_url = basename(__FILE__) . "?mode=user&u=$user_id"; - $ug_data = $this_userdata; - $ug_data['session_logged_in'] = 1; + $ug_data = $this_userdata; + $ug_data['session_logged_in'] = 1; - $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_USER_ONLY); - $g_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_GROUP_ONLY); + $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_USER_ONLY); + $g_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_GROUP_ONLY); - foreach ($forums['c'] as $c_id => $c_data) - { - $template->assign_block_vars('c', array( - 'CAT_ID' => $c_id, - 'CAT_TITLE' => $forums['cat_title_html'][$c_id], - 'CAT_HREF' => "$base_url&c=$c_id", - )); + foreach ($forums['c'] as $c_id => $c_data) { + $template->assign_block_vars('c', array( + 'CAT_ID' => $c_id, + 'CAT_TITLE' => $forums['cat_title_html'][$c_id], + 'CAT_HREF' => "$base_url&c=$c_id", + )); - if (!$c =& $_REQUEST['c'] OR !in_array($c, array('all', $c_id)) OR empty($c_data['forums'])) - { - continue; - } + if (!$c =& $_REQUEST['c'] or !in_array($c, array('all', $c_id)) or empty($c_data['forums'])) { + continue; + } - foreach ($c_data['forums'] as $f_id) - { - $f_data = $forums['f'][$f_id]; - $auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']); - $disabled = $g_access[$f_id]['auth_mod']; + foreach ($c_data['forums'] as $f_id) { + $f_data = $forums['f'][$f_id]; + $auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']); + $disabled = $g_access[$f_id]['auth_mod']; - $template->assign_block_vars('c.f', array( - 'DISABLED' => $disabled, - 'FORUM_ID' => $f_id, - 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), - 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', - 'IS_MODERATOR' => (bool) $auth_mod, - 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NONE'], - 'MOD_CLASS' => ($auth_mod) ? (($disabled) ? 'yesDisabled' : 'yesMOD') : 'noMOD', - 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, - )); + $template->assign_block_vars('c.f', array( + 'DISABLED' => $disabled, + 'FORUM_ID' => $f_id, + 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), + 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', + 'IS_MODERATOR' => (bool)$auth_mod, + 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NONE'], + 'MOD_CLASS' => ($auth_mod) ? (($disabled) ? 'yesDisabled' : 'yesMOD') : 'noMOD', + 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, + )); - foreach ($forum_auth_fields as $auth_type) - { - $bf_num = $bf['forum_perm'][$auth_type]; - $f_perm = $f_data[$auth_type]; - $auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]); + foreach ($forum_auth_fields as $auth_type) { + $bf_num = $bf['forum_perm'][$auth_type]; + $f_perm = $f_data[$auth_type]; + $auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]); - if ($f_perm == AUTH_ACL) - { - $disabled = ($auth_mod || $g_access[$f_id][$auth_type]); - $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; - } - else - { - $disabled = true; - $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl) ? 'yes' : 'no'; - } + if ($f_perm == AUTH_ACL) { + $disabled = ($auth_mod || $g_access[$f_id][$auth_type]); + $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; + } else { + $disabled = true; + $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl) ? 'yes' : 'no'; + } - $template->assign_block_vars('c.f.acl', array( - 'DISABLED' => $disabled, - 'PERM_SIGN' => $perm_sign, - 'ACL_CLASS' => $acl_class, - 'FORUM_ID' => $f_id, - 'ACL_TYPE_BF' => $bf_num, - 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, - )); - } - } - } + $template->assign_block_vars('c.f.acl', array( + 'DISABLED' => $disabled, + 'PERM_SIGN' => $perm_sign, + 'ACL_CLASS' => $acl_class, + 'FORUM_ID' => $f_id, + 'ACL_TYPE_BF' => $bf_num, + 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, + )); + } + } + } - $template->assign_vars(array( - 'AUTH_MOD_BF' => AUTH_MOD, - )); + $template->assign_vars(array( + 'AUTH_MOD_BF' => AUTH_MOD, + )); - $s_column_span = 2; + $s_column_span = 2; - foreach ($forum_auth_fields as $auth_type) - { - $template->assign_block_vars('acltype', array( - 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), - 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], - )); - $s_column_span++; - } + foreach ($forum_auth_fields as $auth_type) { + $template->assign_block_vars('acltype', array( + 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), + 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], + )); + $s_column_span++; + } - unset($forums, $u_access, $g_access); - $datastore->rm('cat_forums'); + unset($forums, $u_access, $g_access); + $datastore->rm('cat_forums'); - $s_hidden_fields = ' - - + $s_hidden_fields = ' + + '; - $s_user_type = ($this_userdata['user_level'] == ADMIN) ? ' + $s_user_type = ($this_userdata['user_level'] == ADMIN) ? ' ' : ' '; - $template->assign_block_vars('switch_user_auth', array()); + $template->assign_block_vars('switch_user_auth', array()); - $template->assign_vars(array( - 'TPL_AUTH_UG_MAIN' => true, + $template->assign_vars(array( + 'TPL_AUTH_UG_MAIN' => true, - 'USER_OR_GROUPNAME' => $this_userdata['username'], - 'USER_LEVEL' => $lang['USER_LEVEL'] .' : '. $s_user_type, - 'USER_GROUP_MEMBERSHIPS' => $lang['GROUP_MEMBERSHIPS'], - )); + 'USER_OR_GROUPNAME' => $this_userdata['username'], + 'USER_LEVEL' => $lang['USER_LEVEL'] . ' : ' . $s_user_type, + 'USER_GROUP_MEMBERSHIPS' => $lang['GROUP_MEMBERSHIPS'], + )); - $template->assign_vars(array( - 'T_USER_OR_GROUPNAME' => $lang['USERNAME'], - 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'], - 'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'], + $template->assign_vars(array( + 'T_USER_OR_GROUPNAME' => $lang['USERNAME'], + 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'], + 'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'], - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else if ($mode == 'group' && $group_id) -{ - $page_cfg['quirks_mode'] = true; + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); +} elseif ($mode == 'group' && $group_id) { + $page_cfg['quirks_mode'] = true; - if (!$group_data = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } + if (!$group_data = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } - $base_url = basename(__FILE__) ."?mode=group&g=$group_id"; + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } + $base_url = basename(__FILE__) . "?mode=group&g=$group_id"; - $ug_data = array('group_id' => $group_id); - $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data); + $ug_data = array('group_id' => $group_id); + $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data); - foreach ($forums['c'] as $c_id => $c_data) - { - $template->assign_block_vars('c', array( - 'CAT_ID' => $c_id, - 'CAT_TITLE' => $forums['cat_title_html'][$c_id], - 'CAT_HREF' => "$base_url&c=$c_id", - )); + foreach ($forums['c'] as $c_id => $c_data) { + $template->assign_block_vars('c', array( + 'CAT_ID' => $c_id, + 'CAT_TITLE' => $forums['cat_title_html'][$c_id], + 'CAT_HREF' => "$base_url&c=$c_id", + )); - if (!$c =& $_REQUEST['c'] OR !in_array($c, array('all', $c_id)) OR empty($c_data['forums'])) - { - continue; - } + if (!$c =& $_REQUEST['c'] or !in_array($c, array('all', $c_id)) or empty($c_data['forums'])) { + continue; + } - foreach ($c_data['forums'] as $f_id) - { - $f_data = $forums['f'][$f_id]; - $auth_mod = $u_access[$f_id]['auth_mod']; + foreach ($c_data['forums'] as $f_id) { + $f_data = $forums['f'][$f_id]; + $auth_mod = $u_access[$f_id]['auth_mod']; - $template->assign_block_vars('c.f', array( - 'DISABLED' => false, - 'FORUM_ID' => $f_id, - 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), - 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', - 'IS_MODERATOR' => (bool) $auth_mod, - 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NO'], - 'MOD_CLASS' => ($auth_mod) ? 'yesMOD' : 'noMOD', - 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, - )); + $template->assign_block_vars('c.f', array( + 'DISABLED' => false, + 'FORUM_ID' => $f_id, + 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), + 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', + 'IS_MODERATOR' => (bool)$auth_mod, + 'MOD_STATUS' => ($auth_mod) ? $lang['MODERATOR'] : $lang['NO'], + 'MOD_CLASS' => ($auth_mod) ? 'yesMOD' : 'noMOD', + 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, + )); - foreach ($forum_auth_fields as $auth_type) - { - $bf_num = $bf['forum_perm'][$auth_type]; - $f_perm = $f_data[$auth_type]; - $auth_via_acl = $u_access[$f_id][$auth_type]; + foreach ($forum_auth_fields as $auth_type) { + $bf_num = $bf['forum_perm'][$auth_type]; + $f_perm = $f_data[$auth_type]; + $auth_via_acl = $u_access[$f_id][$auth_type]; - if ($f_perm == AUTH_ACL) - { - $disabled = $auth_mod; - $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; - } - else - { - $disabled = true; - $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; - $acl_class = ($auth_via_acl) ? 'yes' : 'no'; - } + if ($f_perm == AUTH_ACL) { + $disabled = $auth_mod; + $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; + } else { + $disabled = true; + $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; + $acl_class = ($auth_via_acl) ? 'yes' : 'no'; + } - $template->assign_block_vars('c.f.acl', array( - 'DISABLED' => $disabled, - 'PERM_SIGN' => $perm_sign, - 'ACL_CLASS' => $acl_class, - 'FORUM_ID' => $f_id, - 'ACL_TYPE_BF' => $bf_num, - 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, - )); - } - } - } + $template->assign_block_vars('c.f.acl', array( + 'DISABLED' => $disabled, + 'PERM_SIGN' => $perm_sign, + 'ACL_CLASS' => $acl_class, + 'FORUM_ID' => $f_id, + 'ACL_TYPE_BF' => $bf_num, + 'ACL_VAL' => ($auth_via_acl) ? 1 : 0, + )); + } + } + } - $template->assign_vars(array( - 'AUTH_MOD_BF' => AUTH_MOD, - )); + $template->assign_vars(array( + 'AUTH_MOD_BF' => AUTH_MOD, + )); - $s_column_span = 2; + $s_column_span = 2; - foreach ($forum_auth_fields as $auth_type) - { - $template->assign_block_vars('acltype', array( - 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), - 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], - )); - $s_column_span++; - } + foreach ($forum_auth_fields as $auth_type) { + $template->assign_block_vars('acltype', array( + 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1
", $lang[strtoupper($auth_type)]), + 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], + )); + $s_column_span++; + } - unset($forums, $ug_data, $u_access); - $datastore->rm('cat_forums'); + unset($forums, $ug_data, $u_access); + $datastore->rm('cat_forums'); - $s_hidden_fields = ' - - + $s_hidden_fields = ' + + '; - $template->assign_vars(array( - 'TPL_AUTH_UG_MAIN' => true, + $template->assign_vars(array( + 'TPL_AUTH_UG_MAIN' => true, - 'T_USER_OR_GROUPNAME' => $lang['GROUP_NAME'], - 'USER_LEVEL' => false, - 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_GROUP'], - 'T_AUTH_EXPLAIN' => $lang['GROUP_AUTH_EXPLAIN'], - 'USER_OR_GROUPNAME' => htmlCHR($group_data['group_name']), - 'S_COLUMN_SPAN' => $s_column_span, - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); -} -else -{ - // Select a user/group - if ($mode == 'user') - { - $template->assign_vars(array( - 'TPL_SELECT_USER' => true, - 'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", - )); - } - else - { - $template->assign_vars(array( - 'TPL_SELECT_GROUP' => true, - 'S_GROUP_SELECT' => get_select('groups'), - )); - } + 'T_USER_OR_GROUPNAME' => $lang['GROUP_NAME'], + 'USER_LEVEL' => false, + 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_GROUP'], + 'T_AUTH_EXPLAIN' => $lang['GROUP_AUTH_EXPLAIN'], + 'USER_OR_GROUPNAME' => htmlCHR($group_data['group_name']), + 'S_COLUMN_SPAN' => $s_column_span, + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); +} else { + // Select a user/group + if ($mode == 'user') { + $template->assign_vars(array( + 'TPL_SELECT_USER' => true, + 'U_SEARCH_USER' => BB_ROOT . "search.php?mode=searchuser", + )); + } else { + $template->assign_vars(array( + 'TPL_SELECT_GROUP' => true, + 'S_GROUP_SELECT' => get_select('groups'), + )); + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $template->assign_vars(array( - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); + $template->assign_vars(array( + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); } $template->assign_vars(array( - 'YES_SIGN' => $yes_sign, - 'NO_SIGN' => $no_sign, - 'T_MOD_YES' => $lang['MODERATOR'], - 'T_MOD_NO' => $lang['NO'], - 'S_AUTH_ACTION' => "admin_ug_auth.php", - 'SELECTED_CAT' => !empty($_REQUEST['c']) ? $_REQUEST['c'] : '', - 'U_ALL_FORUMS' => !empty($base_url) ? "$base_url&c=all" : '', + 'YES_SIGN' => $yes_sign, + 'NO_SIGN' => $no_sign, + 'T_MOD_YES' => $lang['MODERATOR'], + 'T_MOD_NO' => $lang['NO'], + 'S_AUTH_ACTION' => "admin_ug_auth.php", + 'SELECTED_CAT' => !empty($_REQUEST['c']) ? $_REQUEST['c'] : '', + 'U_ALL_FORUMS' => !empty($base_url) ? "$base_url&c=all" : '', )); -print_page('admin_ug_auth.tpl', 'admin'); \ No newline at end of file +print_page('admin_ug_auth.tpl', 'admin'); diff --git a/admin/admin_user_ban.php b/admin/admin_user_ban.php index 72cbac3ff..f1fb850a6 100644 --- a/admin/admin_user_ban.php +++ b/admin/admin_user_ban.php @@ -1,362 +1,318 @@ sql_query($sql))) - { - bb_die('Could not obtain banlist information'); - } + $sql = "SELECT * FROM " . BB_BANLIST; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain banlist information'); + } - $current_banlist = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $current_banlist = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - $kill_session_sql = ''; - for ($i = 0; $i < count($user_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($user_list[$i] == $current_banlist[$j]['ban_userid']) - { - $in_banlist = true; - } - } + $kill_session_sql = ''; + for ($i = 0; $i < count($user_list); $i++) { + $in_banlist = false; + for ($j = 0; $j < count($current_banlist); $j++) { + if ($user_list[$i] == $current_banlist[$j]['ban_userid']) { + $in_banlist = true; + } + } - if (!$in_banlist) - { - $kill_session_sql .= ( ( $kill_session_sql != '' ) ? ' OR ' : '' ) . "session_user_id = " . $user_list[$i]; + if (!$in_banlist) { + $kill_session_sql .= (($kill_session_sql != '') ? ' OR ' : '') . "session_user_id = " . $user_list[$i]; - $sql = "INSERT INTO " . BB_BANLIST . " (ban_userid) VALUES (" . $user_list[$i] . ")"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not insert ban_userid info into database'); - } - } - } + $sql = "INSERT INTO " . BB_BANLIST . " (ban_userid) VALUES (" . $user_list[$i] . ")"; + if (!DB()->sql_query($sql)) { + bb_die('Could not insert ban_userid info into database'); + } + } + } - for ($i = 0; $i < count($ip_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($ip_list[$i] == $current_banlist[$j]['ban_ip']) - { - $in_banlist = true; - } - } + for ($i = 0; $i < count($ip_list); $i++) { + $in_banlist = false; + for ($j = 0; $j < count($current_banlist); $j++) { + if ($ip_list[$i] == $current_banlist[$j]['ban_ip']) { + $in_banlist = true; + } + } - if (!$in_banlist) - { - if (preg_match('/(ff\.)|(\.ff)/is', chunk_split($ip_list[$i], 2, '.'))) - { - $kill_ip_sql = "session_ip LIKE '" . str_replace('.', '', preg_replace('/(ff\.)|(\.ff)/is', '%', chunk_split($ip_list[$i], 2, "."))) . "'"; - } - else - { - $kill_ip_sql = "session_ip = '" . $ip_list[$i] . "'"; - } + if (!$in_banlist) { + if (preg_match('/(ff\.)|(\.ff)/is', chunk_split($ip_list[$i], 2, '.'))) { + $kill_ip_sql = "session_ip LIKE '" . str_replace('.', '', preg_replace('/(ff\.)|(\.ff)/is', '%', chunk_split($ip_list[$i], 2, "."))) . "'"; + } else { + $kill_ip_sql = "session_ip = '" . $ip_list[$i] . "'"; + } - $kill_session_sql .= ( ( $kill_session_sql != '' ) ? ' OR ' : '' ) . $kill_ip_sql; + $kill_session_sql .= (($kill_session_sql != '') ? ' OR ' : '') . $kill_ip_sql; - $sql = "INSERT INTO " . BB_BANLIST . " (ban_ip) VALUES ('" . $ip_list[$i] . "')"; - if ( !DB()->sql_query($sql) ) - { - bb_die('Could not insert ban_ip info into database'); - } - } - } + $sql = "INSERT INTO " . BB_BANLIST . " (ban_ip) VALUES ('" . $ip_list[$i] . "')"; + if (!DB()->sql_query($sql)) { + bb_die('Could not insert ban_ip info into database'); + } + } + } - // Now we'll delete all entries from the session table - if ($kill_session_sql != '') - { - $sql = "DELETE FROM " . BB_SESSIONS . " WHERE $kill_session_sql"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete banned sessions from database'); - } - } + // Now we'll delete all entries from the session table + if ($kill_session_sql != '') { + $sql = "DELETE FROM " . BB_SESSIONS . " WHERE $kill_session_sql"; + if (!DB()->sql_query($sql)) { + bb_die('Could not delete banned sessions from database'); + } + } - for ($i = 0; $i < count($email_list); $i++) - { - $in_banlist = false; - for ($j = 0; $j < count($current_banlist); $j++) - { - if ($email_list[$i] == $current_banlist[$j]['ban_email']) - { - $in_banlist = true; - } - } + for ($i = 0; $i < count($email_list); $i++) { + $in_banlist = false; + for ($j = 0; $j < count($current_banlist); $j++) { + if ($email_list[$i] == $current_banlist[$j]['ban_email']) { + $in_banlist = true; + } + } - if (!$in_banlist) - { - $sql = "INSERT INTO " . BB_BANLIST . " (ban_email) VALUES ('" . DB()->escape($email_list[$i]) . "')"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not insert ban_email info into database'); - } - } - } + if (!$in_banlist) { + $sql = "INSERT INTO " . BB_BANLIST . " (ban_email) VALUES ('" . DB()->escape($email_list[$i]) . "')"; + if (!DB()->sql_query($sql)) { + bb_die('Could not insert ban_email info into database'); + } + } + } - $where_sql = ''; + $where_sql = ''; - if (isset($_POST['unban_user'])) - { - $user_list = $_POST['unban_user']; + if (isset($_POST['unban_user'])) { + $user_list = $_POST['unban_user']; - for ($i = 0; $i < count($user_list); $i++) - { - if ($user_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . intval($user_list[$i]); - } - } - } + for ($i = 0; $i < count($user_list); $i++) { + if ($user_list[$i] != -1) { + $where_sql .= (($where_sql != '') ? ', ' : '') . intval($user_list[$i]); + } + } + } - if (isset($_POST['unban_ip'])) - { - $ip_list = $_POST['unban_ip']; + if (isset($_POST['unban_ip'])) { + $ip_list = $_POST['unban_ip']; - for ($i = 0; $i < count($ip_list); $i++) - { - if ($ip_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($ip_list[$i]); - } - } - } + for ($i = 0; $i < count($ip_list); $i++) { + if ($ip_list[$i] != -1) { + $where_sql .= (($where_sql != '') ? ', ' : '') . DB()->escape($ip_list[$i]); + } + } + } - if (isset($_POST['unban_email'])) - { - $email_list = $_POST['unban_email']; + if (isset($_POST['unban_email'])) { + $email_list = $_POST['unban_email']; - for ($i = 0; $i < count($email_list); $i++) - { - if ($email_list[$i] != -1) - { - $where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($email_list[$i]); - } - } - } + for ($i = 0; $i < count($email_list); $i++) { + if ($email_list[$i] != -1) { + $where_sql .= (($where_sql != '') ? ', ' : '') . DB()->escape($email_list[$i]); + } + } + } - if ($where_sql != '') - { - $sql = "DELETE FROM " . BB_BANLIST . " WHERE ban_id IN ($where_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete ban info from database'); - } - } + if ($where_sql != '') { + $sql = "DELETE FROM " . BB_BANLIST . " WHERE ban_id IN ($where_sql)"; + if (!DB()->sql_query($sql)) { + bb_die('Could not delete ban info from database'); + } + } - bb_die($lang['BAN_UPDATE_SUCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_BANADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); -} -else -{ - $template->assign_vars(array( - 'S_BANLIST_ACTION' => 'admin_user_ban.php', - )); + bb_die($lang['BAN_UPDATE_SUCESSFUL'] . '

' . sprintf($lang['CLICK_RETURN_BANADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); +} else { + $template->assign_vars(array( + 'S_BANLIST_ACTION' => 'admin_user_ban.php', + )); - $userban_count = 0; - $ipban_count = 0; - $emailban_count = 0; + $userban_count = 0; + $ipban_count = 0; + $emailban_count = 0; - $sql = "SELECT b.ban_id, u.user_id, u.username + $sql = "SELECT b.ban_id, u.user_id, u.username FROM " . BB_BANLIST . " b, " . BB_USERS . " u WHERE u.user_id = b.ban_userid AND b.ban_userid <> 0 AND u.user_id <> " . GUEST_UID . " ORDER BY u.username ASC"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select current user_id ban list'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select current user_id ban list'); + } - $user_list = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $user_list = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - $select_userlist = ''; - for ($i = 0; $i < count($user_list); $i++) - { - $select_userlist .= ''; - $userban_count++; - } + $select_userlist = ''; + for ($i = 0; $i < count($user_list); $i++) { + $select_userlist .= ''; + $userban_count++; + } - if ($select_userlist == '') - { - $select_userlist = ''; - } + if ($select_userlist == '') { + $select_userlist = ''; + } - $select_userlist = ''; + $select_userlist = ''; - $sql = "SELECT ban_id, ban_ip, ban_email FROM ". BB_BANLIST ." ORDER BY ban_ip"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select current ip ban list'); - } + $sql = "SELECT ban_id, ban_ip, ban_email FROM " . BB_BANLIST . " ORDER BY ban_ip"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select current ip ban list'); + } - $banlist = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $banlist = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - $select_iplist = ''; - $select_emaillist = ''; + $select_iplist = ''; + $select_emaillist = ''; - for ($i = 0; $i < count($banlist); $i++) - { - $ban_id = $banlist[$i]['ban_id']; + for ($i = 0; $i < count($banlist); $i++) { + $ban_id = $banlist[$i]['ban_id']; - if (!empty($banlist[$i]['ban_ip'])) - { - $ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip'])); - $select_iplist .= ''; - $ipban_count++; - } - else if (!empty($banlist[$i]['ban_email'])) - { - $ban_email = $banlist[$i]['ban_email']; - $select_emaillist .= ''; - $emailban_count++; - } - } + if (!empty($banlist[$i]['ban_ip'])) { + $ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip'])); + $select_iplist .= ''; + $ipban_count++; + } elseif (!empty($banlist[$i]['ban_email'])) { + $ban_email = $banlist[$i]['ban_email']; + $select_emaillist .= ''; + $emailban_count++; + } + } - if ($select_iplist == '') - { - $select_iplist = ''; - } + if ($select_iplist == '') { + $select_iplist = ''; + } - if ($select_emaillist == '') - { - $select_emaillist = ''; - } + if ($select_emaillist == '') { + $select_emaillist = ''; + } - $select_iplist = ''; - $select_emaillist = ''; + $select_iplist = ''; + $select_emaillist = ''; - $template->assign_vars(array( - 'U_SEARCH_USER' => './../search.php?mode=searchuser', - 'S_UNBAN_USERLIST_SELECT' => $select_userlist, - 'S_UNBAN_IPLIST_SELECT' => $select_iplist, - 'S_UNBAN_EMAILLIST_SELECT' => $select_emaillist, - 'S_BAN_ACTION' => 'admin_user_ban.php', - )); + $template->assign_vars(array( + 'U_SEARCH_USER' => './../search.php?mode=searchuser', + 'S_UNBAN_USERLIST_SELECT' => $select_userlist, + 'S_UNBAN_IPLIST_SELECT' => $select_iplist, + 'S_UNBAN_EMAILLIST_SELECT' => $select_emaillist, + 'S_BAN_ACTION' => 'admin_user_ban.php', + )); } -print_page('admin_user_ban.tpl', 'admin'); \ No newline at end of file +print_page('admin_user_ban.tpl', 'admin'); diff --git a/admin/admin_user_search.php b/admin/admin_user_search.php index 31d3465ad..c8a099479 100644 --- a/admin/admin_user_search.php +++ b/admin/admin_user_search.php @@ -1,1052 +1,993 @@ sql_query($sql)) - { - bb_die('Could not select group data #1'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select group data #1'); + } - $group_list = ''; + $group_list = ''; - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('groups_exist', array()); + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('groups_exist', array()); - while ($row = DB()->sql_fetchrow($result)) - { - $group_list .= ''; - } - } + while ($row = DB()->sql_fetchrow($result)) { + $group_list .= ''; + } + } - $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_special = 1 ORDER BY rank_title"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain ranks data'); - } - $rank_select_box = ''; - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('ranks_exist', array()); - while( $row = DB()->sql_fetchrow($result) ) - { - $rank = $row['rank_title']; - $rank_id = $row['rank_id']; - $rank_select_box .= ''; - } - } + $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_special = 1 ORDER BY rank_title"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain ranks data'); + } + $rank_select_box = ''; + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('ranks_exist', array()); + while ($row = DB()->sql_fetchrow($result)) { + $rank = $row['rank_title']; + $rank_id = $row['rank_id']; + $rank_select_box .= ''; + } + } - $language_list = language_select('', 'language_type'); - $timezone_list = tz_select('', 'timezone_type'); + $language_list = language_select('', 'language_type'); + $timezone_list = tz_select('', 'timezone_type'); - $sql = "SELECT f.forum_id, f.forum_name, f.forum_parent, c.cat_id, c.cat_title - FROM ( ". BB_FORUMS ." AS f INNER JOIN ". BB_CATEGORIES ." AS c ON c.cat_id = f.cat_id ) + $sql = "SELECT f.forum_id, f.forum_name, f.forum_parent, c.cat_id, c.cat_title + FROM ( " . BB_FORUMS . " AS f INNER JOIN " . BB_CATEGORIES . " AS c ON c.cat_id = f.cat_id ) ORDER BY c.cat_order, f.forum_order ASC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select forum data'); - } - - $forums = array(); - - if (DB()->num_rows($result) != 0) - { - $template->assign_block_vars('forums_exist', array()); - - $last_cat_id = -1; - $forums_list = ''; - - while ($row = DB()->sql_fetchrow($result)) - { - if ($row['cat_id'] != $last_cat_id) - { - $forums_list .= ''; - $last_cat_id = $row['cat_id']; - } - - $forums_list .= ''; - } - } - - $lastvisited = array(1, 7, 14, 30, 60, 120, 365, 500, 730, 1000); - $lastvisited_list = ''; - - foreach ($lastvisited as $days) - { - $lastvisited_list .= ''; - } - - $template->assign_vars(array( - 'TPL_ADMIN_USER_SEARCH_MAIN' => true, - - 'YEAR' => date("Y"), - 'MONTH' => date("m"), - 'DAY' => date("d"), - 'GROUP_LIST' => $group_list, - 'RANK_SELECT_BOX' => $rank_select_box, - 'LANGUAGE_LIST' => $language_list, - 'TIMEZONE_LIST' => $timezone_list, - 'FORUMS_LIST' => $forums_list, - 'LASTVISITED_LIST' => $lastvisited_list, - - 'S_SEARCH_ACTION' => 'admin_user_search.php', - )); -} -else -{ - $mode = ''; - - // validate mode - if (isset($_REQUEST['search_username'])) - { - $mode = 'search_username'; - } - elseif (isset($_REQUEST['search_email'])) - { - $mode = 'search_email'; - } - elseif (isset($_REQUEST['search_ip'])) - { - $mode = 'search_ip'; - } - elseif (isset($_REQUEST['search_joindate'])) - { - $mode = 'search_joindate'; - } - elseif (isset($_REQUEST['search_group'])) - { - $mode = 'search_group'; - } - elseif (isset($_REQUEST['search_rank'])) - { - $mode = 'search_rank'; - } - elseif (isset($_REQUEST['search_postcount'])) - { - $mode = 'search_postcount'; - } - elseif (isset($_REQUEST['search_userfield'])) - { - $mode = 'search_userfield'; - } - elseif (isset($_REQUEST['search_lastvisited'])) - { - $mode = 'search_lastvisited'; - } - elseif (isset($_REQUEST['search_language'])) - { - $mode = 'search_language'; - } - elseif (isset($_REQUEST['search_timezone'])) - { - $mode = 'search_timezone'; - } - elseif (isset($_REQUEST['search_moderators'])) - { - $mode = 'search_moderators'; - } - elseif (isset($_REQUEST['search_misc'])) - { - $mode = 'search_misc'; - } - - // validate fields (that they exist) - switch ($mode) - { - case 'search_username': - $username = $_REQUEST['username']; - if (!$username) bb_die($lang['SEARCH_INVALID_USERNAME']); - break; - - case 'search_email': - $email = $_REQUEST['email']; - if (!$email) bb_die($lang['SEARCH_INVALID_EMAIL']); - break; - - case 'search_ip': - $ip_address = $_REQUEST['ip_address']; - if (!$ip_address) bb_die($lang['SEARCH_INVALID_IP']); - break; - - case 'search_joindate': - $date_type = $_REQUEST['date_type']; - $date_day = $_REQUEST['date_day']; - $date_month = $_REQUEST['date_month']; - $date_year = $_REQUEST['date_year']; - if (!($date_type || $date_day || $date_month || $date_year)) bb_die($lang['SEARCH_INVALID_DATE']); - break; - - case 'search_group': - $group_id = $_REQUEST['group_id']; - if (!$group_id) bb_die($lang['SEARCH_INVALID_GROUP']); - break; - - case 'search_rank': - $rank_id = $_REQUEST['rank_id']; - if (!$rank_id) bb_die($lang['SEARCH_INVALID_RANK']); - break; - - case 'search_postcount': - $postcount_type = $_REQUEST['postcount_type']; - $postcount_value = $_REQUEST['postcount_value']; - if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) bb_die($lang['SEARCH_INVALID_POSTCOUNT']); - break; - - case 'search_userfield': - $userfield_type = $_REQUEST['userfield_type']; - $userfield_value = $_REQUEST['userfield_value']; - if (!$userfield_type || !$userfield_value) bb_die($lang['SEARCH_INVALID_USERFIELD']); - break; - - case 'search_lastvisited': - $lastvisited_days = $_REQUEST['lastvisited_days']; - $lastvisited_type = $_REQUEST['lastvisited_type']; - if (!$lastvisited_days || !$lastvisited_type) bb_die($lang['SEARCH_INVALID_LASTVISITED']); - break; - - case 'search_language': - $language_type = $_REQUEST['language_type']; - if (!$language_type) bb_die($lang['SEARCH_INVALID_LANGUAGE']); - break; - - case 'search_timezone': - $timezone_type = $_REQUEST['timezone_type']; - if (!$timezone_type && $timezone_type != 0) bb_die($lang['SEARCH_INVALID_TIMEZONE']); - break; - - case 'search_moderators': - $moderators_forum = $_REQUEST['moderators_forum']; - if (!$moderators_forum) bb_die($lang['SEARCH_INVALID_MODERATORS']); - break; - - case 'search_misc': - $misc = $_REQUEST['misc']; - if (!$misc) bb_die($lang['SEARCH_INVALID']); - break; - - default: - bb_die('Invalid mode'); - } - - $base_url = 'admin_user_search.php?dosearch=true'; - - $select_sql = "SELECT u.user_id, u.username, u.user_rank, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit FROM ". BB_USERS ." AS u"; - - $lower_b = 'LOWER('; - $lower_e = ')'; - - // validate data & prepare sql - switch($mode) - { - case 'search_username': - $base_url .= '&search_username=true&username='.rawurlencode(stripslashes($username)); - - $text = sprintf($lang['SEARCH_FOR_USERNAME'], strip_tags(htmlspecialchars(stripslashes($username)))); - - $username = preg_replace('/\*/', '%', trim(strip_tags(strtolower($username)))); - - if (strstr($username, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } - - if ($username == '') bb_die($lang['SEARCH_INVALID_USERNAME']); - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE {$lower_b}username{$lower_e} $op '".DB()->escape($username)."' AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '".DB()->escape($username)."' AND u.user_id <> ".GUEST_UID; - break; - - case 'search_email': - $base_url .= '&search_email=true&email='.rawurlencode(stripslashes($email)); - - $text = sprintf($lang['SEARCH_FOR_EMAIL'], strip_tags(htmlspecialchars(stripslashes($email)))); - - $email = preg_replace('/\*/', '%', trim(strip_tags(strtolower($email)))); - - if (strstr($email, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } - - if ($email == '') bb_die($lang['SEARCH_INVALID_EMAIL']); - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE {$lower_b}user_email{$lower_e} $op '".DB()->escape($email)."' AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '".DB()->escape($email)."' AND u.user_id <> ".GUEST_UID; - break; - - case 'search_ip': - $base_url .= '&search_ip=true&ip_address='.rawurlencode(stripslashes($ip_address)); - - $ip_address = trim($ip_address); - - $text = sprintf($lang['SEARCH_FOR_IP'], strip_tags(htmlspecialchars(stripslashes($ip_address)))); - - unset($users); - $users = array(); - - // Let's see if they entered a full valid IPv4 address - if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) - { - $ip = encode_ip($ip_address); - $users[] = $ip; - } - elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address)) - { - $ip_split = explode('.', $ip_address); - switch (count($ip_split)) - { - case 4: - $users[] = encode_ip($ip_split[0].".".$ip_split[1].".".$ip_split[2].".255"); - break; - case 3: - $users[] = encode_ip($ip_split[0].".".$ip_split[1].".255.255"); - break; - case 2: - $users[] = encode_ip($ip_split[0].".255.255.255"); - break; - } - } - elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) - { - $range = preg_split('/[-\s]+/', $ip_address); - $start_range = explode('.', $range[0]); - $end_range = explode('.', $range[1]); - if (($start_range[0].$start_range[1].$start_range[2] != $end_range[0].$end_range[1].$end_range[2]) || ($start_range[3] > $end_range[3])) bb_die($lang['SEARCH_INVALID_IP']); - for ($i = $start_range[3]; $i <= $end_range[3]; $i++) - { - $users[] = encode_ip($start_range[0].".".$start_range[1 ].".".$start_range[2].".".$i); - } - } - else - { - bb_die($lang['SEARCH_INVALID_IP']); - } - - $ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = ''; - - foreach ($users as $address) - { - if (preg_match('/(ff){1,3}$/i', $address)) - { - if (preg_match('/[0-9a-f]{2}ffffff/i', $address)) - { - $ip_start = substr($address, 0, 2); - } - elseif (preg_match('/[0-9a-f]{4}ffff/i', $address)) - { - $ip_start = substr($address, 0, 4); - } - elseif (preg_match('/[0-9a-f]{6}ff/i', $address)) - { - $ip_start = substr($address, 0, 6); - } - $ip_like_sql_flylast = $ip_like_sql . ( $ip_like_sql != '' ) ? " OR user_last_ip LIKE '".$ip_start."%'" : "user_last_ip LIKE '".$ip_start."%'"; - $ip_like_sql_flyreg = $ip_like_sql . ( $ip_like_sql != '' ) ? " OR user_reg_ip LIKE '".$ip_start."%'" : "user_reg_ip LIKE '".$ip_start."%'"; - $ip_like_sql .= ( $ip_like_sql != '' ) ? " OR poster_ip LIKE '".$ip_start."%'" : "poster_ip LIKE '".$ip_start."%'"; - } - else - { - $ip_in_sql .= ( $ip_in_sql == '' ) ? "'$address'" : ", '$address'"; - } - } - - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "poster_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql" : "$ip_like_sql": ""; - - if (!$where_sql) bb_die('invalid request'); - - // start search - $no_result_search = false; - $ip_users_sql = ''; - $sql = "SELECT poster_id FROM ".BB_POSTS." WHERE poster_id <> ".GUEST_UID." AND ($where_sql) GROUP BY poster_id"; - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #1'); - } - - if (DB()->num_rows($result) == 0) - { - $no_result_search = true; - } - else - { - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - $ip_users_sql = ''; - while($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['poster_id'] : ', '.$row['poster_id']; - } - } - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "user_last_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql_flylast != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql_flylast" : "$ip_like_sql_flylast": ""; - $sql = "SELECT user_id FROM ".BB_USERS." WHERE user_id <> ".GUEST_UID." AND ($where_sql) GROUP BY user_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #2'); - } - if (DB()->num_rows($result) != 0) - { - if ($no_result_search == true) $no_result_search = false; - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - while ($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['user_id'] : ', '.$row['user_id']; - } - } - $where_sql = ''; - $where_sql .= ( $ip_in_sql != '' ) ? "user_reg_ip IN ($ip_in_sql)": ""; - $where_sql .= ( $ip_like_sql_flyreg != '' ) ? ( $where_sql != "" ) ? " OR $ip_like_sql_flyreg" : "$ip_like_sql_flyreg": ""; - $sql = "SELECT user_id FROM ".BB_USERS." WHERE user_id <> ".GUEST_UID." AND ($where_sql) GROUP BY user_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not count users #3'); - } - if (DB()->num_rows($result) != 0) - { - if ($no_result_search == true) $no_result_search = false; - $total_pages['total'] = DB()->num_rows($result); - $total_sql = NULL; - while ($row = DB()->sql_fetchrow($result)) - { - $ip_users_sql .= ( $ip_users_sql == '' ) ? $row['user_id'] : ', '.$row['user_id']; - } - } - if ($no_result_search == true) - { - bb_die($lang['SEARCH_NO_RESULTS']); - } - - $select_sql .= " WHERE u.user_id IN ($ip_users_sql)"; - break; - - case 'search_joindate': - $base_url .= '&search_joindate=true&date_type='. rawurlencode($date_type) .'&date_day='. rawurlencode($date_day) .'&date_month='. rawurlencode($date_month) .'&date_year='. rawurlencode(stripslashes($date_year)); - - $date_type = trim(strtolower($date_type)); - - if ($date_type != 'before' && $date_type != 'after') - { - bb_die($lang['SEARCH_INVALID_DATE']); - } - - $date_day = intval($date_day); - - if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) - { - bb_die($lang['SEARCH_INVALID_DAY']); - } - - $date_month = intval($date_month); - - if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) - { - bb_die($lang['SEARCH_INVALID_MONTH']); - } - - $date_year = intval($date_year); - - if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) - { - bb_die($lang['SEARCH_INVALID_YEAR']); - } - - $text = sprintf($lang['SEARCH_FOR_DATE'], strip_tags(htmlspecialchars(stripslashes($date_type))), $date_year, $date_month, $date_day); - - $time = mktime(0,0,0,$date_month, $date_day, $date_year); - - if ($date_type == 'before') - { - $arg = '<'; - } - else - { - $arg = '>'; - } - - $total_sql .= "SELECT COUNT(user_id) AS total FROM ".BB_USERS." WHERE user_regdate $arg $time AND user_id <> ".GUEST_UID; - $select_sql .= " WHERE u.user_regdate $arg $time AND u.user_id <> ".GUEST_UID; - break; - - case 'search_group': - $group_id = intval($group_id); - - $base_url .= '&search_group=true&group_id='. rawurlencode($group_id); - - if (!$group_id) - { - bb_die($lang['SEARCH_INVALID_GROUP']); - } - - $sql = "SELECT group_name FROM ".BB_GROUPS." WHERE group_id = $group_id AND group_single_user = 0"; - - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select group data #2'); - } - - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_GROUP']); - } - - $group_name = DB()->sql_fetchrow($result); - - $text = sprintf($lang['SEARCH_FOR_GROUP'], strip_tags(htmlspecialchars($group_name['group_name']))); - - $total_sql .= "SELECT COUNT(u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_USER_GROUP." AS ug + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select forum data'); + } + + $forums = array(); + + if (DB()->num_rows($result) != 0) { + $template->assign_block_vars('forums_exist', array()); + + $last_cat_id = -1; + $forums_list = ''; + + while ($row = DB()->sql_fetchrow($result)) { + if ($row['cat_id'] != $last_cat_id) { + $forums_list .= ''; + $last_cat_id = $row['cat_id']; + } + + $forums_list .= ''; + } + } + + $lastvisited = array(1, 7, 14, 30, 60, 120, 365, 500, 730, 1000); + $lastvisited_list = ''; + + foreach ($lastvisited as $days) { + $lastvisited_list .= ''; + } + + $template->assign_vars(array( + 'TPL_ADMIN_USER_SEARCH_MAIN' => true, + + 'YEAR' => date("Y"), + 'MONTH' => date("m"), + 'DAY' => date("d"), + 'GROUP_LIST' => $group_list, + 'RANK_SELECT_BOX' => $rank_select_box, + 'LANGUAGE_LIST' => $language_list, + 'TIMEZONE_LIST' => $timezone_list, + 'FORUMS_LIST' => $forums_list, + 'LASTVISITED_LIST' => $lastvisited_list, + + 'S_SEARCH_ACTION' => 'admin_user_search.php', + )); +} else { + $mode = ''; + + // validate mode + if (isset($_REQUEST['search_username'])) { + $mode = 'search_username'; + } elseif (isset($_REQUEST['search_email'])) { + $mode = 'search_email'; + } elseif (isset($_REQUEST['search_ip'])) { + $mode = 'search_ip'; + } elseif (isset($_REQUEST['search_joindate'])) { + $mode = 'search_joindate'; + } elseif (isset($_REQUEST['search_group'])) { + $mode = 'search_group'; + } elseif (isset($_REQUEST['search_rank'])) { + $mode = 'search_rank'; + } elseif (isset($_REQUEST['search_postcount'])) { + $mode = 'search_postcount'; + } elseif (isset($_REQUEST['search_userfield'])) { + $mode = 'search_userfield'; + } elseif (isset($_REQUEST['search_lastvisited'])) { + $mode = 'search_lastvisited'; + } elseif (isset($_REQUEST['search_language'])) { + $mode = 'search_language'; + } elseif (isset($_REQUEST['search_timezone'])) { + $mode = 'search_timezone'; + } elseif (isset($_REQUEST['search_moderators'])) { + $mode = 'search_moderators'; + } elseif (isset($_REQUEST['search_misc'])) { + $mode = 'search_misc'; + } + + // validate fields (that they exist) + switch ($mode) { + case 'search_username': + $username = $_REQUEST['username']; + if (!$username) { + bb_die($lang['SEARCH_INVALID_USERNAME']); + } + break; + + case 'search_email': + $email = $_REQUEST['email']; + if (!$email) { + bb_die($lang['SEARCH_INVALID_EMAIL']); + } + break; + + case 'search_ip': + $ip_address = $_REQUEST['ip_address']; + if (!$ip_address) { + bb_die($lang['SEARCH_INVALID_IP']); + } + break; + + case 'search_joindate': + $date_type = $_REQUEST['date_type']; + $date_day = $_REQUEST['date_day']; + $date_month = $_REQUEST['date_month']; + $date_year = $_REQUEST['date_year']; + if (!($date_type || $date_day || $date_month || $date_year)) { + bb_die($lang['SEARCH_INVALID_DATE']); + } + break; + + case 'search_group': + $group_id = $_REQUEST['group_id']; + if (!$group_id) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + break; + + case 'search_rank': + $rank_id = $_REQUEST['rank_id']; + if (!$rank_id) { + bb_die($lang['SEARCH_INVALID_RANK']); + } + break; + + case 'search_postcount': + $postcount_type = $_REQUEST['postcount_type']; + $postcount_value = $_REQUEST['postcount_value']; + if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) { + bb_die($lang['SEARCH_INVALID_POSTCOUNT']); + } + break; + + case 'search_userfield': + $userfield_type = $_REQUEST['userfield_type']; + $userfield_value = $_REQUEST['userfield_value']; + if (!$userfield_type || !$userfield_value) { + bb_die($lang['SEARCH_INVALID_USERFIELD']); + } + break; + + case 'search_lastvisited': + $lastvisited_days = $_REQUEST['lastvisited_days']; + $lastvisited_type = $_REQUEST['lastvisited_type']; + if (!$lastvisited_days || !$lastvisited_type) { + bb_die($lang['SEARCH_INVALID_LASTVISITED']); + } + break; + + case 'search_language': + $language_type = $_REQUEST['language_type']; + if (!$language_type) { + bb_die($lang['SEARCH_INVALID_LANGUAGE']); + } + break; + + case 'search_timezone': + $timezone_type = $_REQUEST['timezone_type']; + if (!$timezone_type && $timezone_type != 0) { + bb_die($lang['SEARCH_INVALID_TIMEZONE']); + } + break; + + case 'search_moderators': + $moderators_forum = $_REQUEST['moderators_forum']; + if (!$moderators_forum) { + bb_die($lang['SEARCH_INVALID_MODERATORS']); + } + break; + + case 'search_misc': + $misc = $_REQUEST['misc']; + if (!$misc) { + bb_die($lang['SEARCH_INVALID']); + } + break; + + default: + bb_die('Invalid mode'); + } + + $base_url = 'admin_user_search.php?dosearch=true'; + + $select_sql = "SELECT u.user_id, u.username, u.user_rank, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit FROM " . BB_USERS . " AS u"; + + $lower_b = 'LOWER('; + $lower_e = ')'; + + // validate data & prepare sql + switch ($mode) { + case 'search_username': + $base_url .= '&search_username=true&username=' . rawurlencode(stripslashes($username)); + + $text = sprintf($lang['SEARCH_FOR_USERNAME'], strip_tags(htmlspecialchars(stripslashes($username)))); + + $username = preg_replace('/\*/', '%', trim(strip_tags(strtolower($username)))); + + if (strstr($username, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } + + if ($username == '') { + bb_die($lang['SEARCH_INVALID_USERNAME']); + } + + $total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}username{$lower_e} $op '" . DB()->escape($username) . "' AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '" . DB()->escape($username) . "' AND u.user_id <> " . GUEST_UID; + break; + + case 'search_email': + $base_url .= '&search_email=true&email=' . rawurlencode(stripslashes($email)); + + $text = sprintf($lang['SEARCH_FOR_EMAIL'], strip_tags(htmlspecialchars(stripslashes($email)))); + + $email = preg_replace('/\*/', '%', trim(strip_tags(strtolower($email)))); + + if (strstr($email, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } + + if ($email == '') { + bb_die($lang['SEARCH_INVALID_EMAIL']); + } + + $total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}user_email{$lower_e} $op '" . DB()->escape($email) . "' AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '" . DB()->escape($email) . "' AND u.user_id <> " . GUEST_UID; + break; + + case 'search_ip': + $base_url .= '&search_ip=true&ip_address=' . rawurlencode(stripslashes($ip_address)); + + $ip_address = trim($ip_address); + + $text = sprintf($lang['SEARCH_FOR_IP'], strip_tags(htmlspecialchars(stripslashes($ip_address)))); + + unset($users); + $users = array(); + + // Let's see if they entered a full valid IPv4 address + if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) { + $ip = encode_ip($ip_address); + $users[] = $ip; + } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address)) { + $ip_split = explode('.', $ip_address); + switch (count($ip_split)) { + case 4: + $users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".255"); + break; + case 3: + $users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . ".255.255"); + break; + case 2: + $users[] = encode_ip($ip_split[0] . ".255.255.255"); + break; + } + } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) { + $range = preg_split('/[-\s]+/', $ip_address); + $start_range = explode('.', $range[0]); + $end_range = explode('.', $range[1]); + if (($start_range[0] . $start_range[1] . $start_range[2] != $end_range[0] . $end_range[1] . $end_range[2]) || ($start_range[3] > $end_range[3])) { + bb_die($lang['SEARCH_INVALID_IP']); + } + for ($i = $start_range[3]; $i <= $end_range[3]; $i++) { + $users[] = encode_ip($start_range[0] . "." . $start_range[1] . "." . $start_range[2] . "." . $i); + } + } else { + bb_die($lang['SEARCH_INVALID_IP']); + } + + $ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = ''; + + foreach ($users as $address) { + if (preg_match('/(ff){1,3}$/i', $address)) { + if (preg_match('/[0-9a-f]{2}ffffff/i', $address)) { + $ip_start = substr($address, 0, 2); + } elseif (preg_match('/[0-9a-f]{4}ffff/i', $address)) { + $ip_start = substr($address, 0, 4); + } elseif (preg_match('/[0-9a-f]{6}ff/i', $address)) { + $ip_start = substr($address, 0, 6); + } + $ip_like_sql_flylast = $ip_like_sql . ($ip_like_sql != '') ? " OR user_last_ip LIKE '" . $ip_start . "%'" : "user_last_ip LIKE '" . $ip_start . "%'"; + $ip_like_sql_flyreg = $ip_like_sql . ($ip_like_sql != '') ? " OR user_reg_ip LIKE '" . $ip_start . "%'" : "user_reg_ip LIKE '" . $ip_start . "%'"; + $ip_like_sql .= ($ip_like_sql != '') ? " OR poster_ip LIKE '" . $ip_start . "%'" : "poster_ip LIKE '" . $ip_start . "%'"; + } else { + $ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'"; + } + } + + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : ""; + $where_sql .= ($ip_like_sql != '') ? ($where_sql != "") ? " OR $ip_like_sql" : "$ip_like_sql" : ""; + + if (!$where_sql) { + bb_die('invalid request'); + } + + // start search + $no_result_search = false; + $ip_users_sql = ''; + $sql = "SELECT poster_id FROM " . BB_POSTS . " WHERE poster_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY poster_id"; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #1'); + } + + if (DB()->num_rows($result) == 0) { + $no_result_search = true; + } else { + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + $ip_users_sql = ''; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['poster_id'] : ', ' . $row['poster_id']; + } + } + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "user_last_ip IN ($ip_in_sql)" : ""; + $where_sql .= ($ip_like_sql_flylast != '') ? ($where_sql != "") ? " OR $ip_like_sql_flylast" : "$ip_like_sql_flylast" : ""; + $sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #2'); + } + if (DB()->num_rows($result) != 0) { + if ($no_result_search == true) { + $no_result_search = false; + } + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; + } + } + $where_sql = ''; + $where_sql .= ($ip_in_sql != '') ? "user_reg_ip IN ($ip_in_sql)" : ""; + $where_sql .= ($ip_like_sql_flyreg != '') ? ($where_sql != "") ? " OR $ip_like_sql_flyreg" : "$ip_like_sql_flyreg" : ""; + $sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not count users #3'); + } + if (DB()->num_rows($result) != 0) { + if ($no_result_search == true) { + $no_result_search = false; + } + $total_pages['total'] = DB()->num_rows($result); + $total_sql = null; + while ($row = DB()->sql_fetchrow($result)) { + $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; + } + } + if ($no_result_search == true) { + bb_die($lang['SEARCH_NO_RESULTS']); + } + + $select_sql .= " WHERE u.user_id IN ($ip_users_sql)"; + break; + + case 'search_joindate': + $base_url .= '&search_joindate=true&date_type=' . rawurlencode($date_type) . '&date_day=' . rawurlencode($date_day) . '&date_month=' . rawurlencode($date_month) . '&date_year=' . rawurlencode(stripslashes($date_year)); + + $date_type = trim(strtolower($date_type)); + + if ($date_type != 'before' && $date_type != 'after') { + bb_die($lang['SEARCH_INVALID_DATE']); + } + + $date_day = intval($date_day); + + if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) { + bb_die($lang['SEARCH_INVALID_DAY']); + } + + $date_month = intval($date_month); + + if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) { + bb_die($lang['SEARCH_INVALID_MONTH']); + } + + $date_year = intval($date_year); + + if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) { + bb_die($lang['SEARCH_INVALID_YEAR']); + } + + $text = sprintf($lang['SEARCH_FOR_DATE'], strip_tags(htmlspecialchars(stripslashes($date_type))), $date_year, $date_month, $date_day); + + $time = mktime(0, 0, 0, $date_month, $date_day, $date_year); + + if ($date_type == 'before') { + $arg = '<'; + } else { + $arg = '>'; + } + + $total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE user_regdate $arg $time AND user_id <> " . GUEST_UID; + $select_sql .= " WHERE u.user_regdate $arg $time AND u.user_id <> " . GUEST_UID; + break; + + case 'search_group': + $group_id = intval($group_id); + + $base_url .= '&search_group=true&group_id=' . rawurlencode($group_id); + + if (!$group_id) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + + $sql = "SELECT group_name FROM " . BB_GROUPS . " WHERE group_id = $group_id AND group_single_user = 0"; + + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select group data #2'); + } + + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_GROUP']); + } + + $group_name = DB()->sql_fetchrow($result); + + $text = sprintf($lang['SEARCH_FOR_GROUP'], strip_tags(htmlspecialchars($group_name['group_name']))); + + $total_sql .= "SELECT COUNT(u.user_id) AS total + FROM " . BB_USERS . " AS u, " . BB_USER_GROUP . " AS ug WHERE u.user_id = ug.user_id AND ug.group_id = $group_id - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> " . GUEST_UID; - $select_sql .= ", ".BB_USER_GROUP." AS ug + $select_sql .= ", " . BB_USER_GROUP . " AS ug WHERE u.user_id = ug.user_id AND ug.group_id = $group_id - AND u.user_id <> ".GUEST_UID; - break; + AND u.user_id <> " . GUEST_UID; + break; - case 'search_rank': - $rank_id = intval($rank_id); + case 'search_rank': + $rank_id = intval($rank_id); - $base_url .= '&search_rank=true&rank_id='. rawurlencode($rank_id); + $base_url .= '&search_rank=true&rank_id=' . rawurlencode($rank_id); - if (!$rank_id) - { - bb_die($lang['SEARCH_INVALID_RANK']); - } + if (!$rank_id) { + bb_die($lang['SEARCH_INVALID_RANK']); + } - $sql = "SELECT rank_title FROM ".BB_RANKS." WHERE rank_id = $rank_id AND rank_special = 1"; + $sql = "SELECT rank_title FROM " . BB_RANKS . " WHERE rank_id = $rank_id AND rank_special = 1"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select rank data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select rank data'); + } - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_RANK']); - } + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_RANK']); + } - $rank_title = DB()->sql_fetchrow($result); + $rank_title = DB()->sql_fetchrow($result); - $text = sprintf($lang['SEARCH_FOR_RANK'], strip_tags(htmlspecialchars($rank_title['rank_title']))); + $text = sprintf($lang['SEARCH_FOR_RANK'], strip_tags(htmlspecialchars($rank_title['rank_title']))); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_rank = $rank_id - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_rank = $rank_id - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_rank = $rank_id + AND u.user_id <> " . GUEST_UID; + break; - case 'search_postcount': - $postcount_type = trim(strtolower($postcount_type)); - $postcount_value = trim(strtolower($postcount_value)); + case 'search_postcount': + $postcount_type = trim(strtolower($postcount_type)); + $postcount_value = trim(strtolower($postcount_value)); - $base_url .= '&search_postcount=true&postcount_type='. rawurlencode($postcount_type) .'&postcount_value='. rawurlencode(stripslashes($postcount_value)); + $base_url .= '&search_postcount=true&postcount_type=' . rawurlencode($postcount_type) . '&postcount_value=' . rawurlencode(stripslashes($postcount_value)); - switch($postcount_type) - { - case 'greater': - $postcount_value = intval($postcount_value); + switch ($postcount_type) { + case 'greater': + $postcount_value = intval($postcount_value); - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_GREATER'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_GREATER'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_posts > $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts > $postcount_value - AND u.user_id <> ".GUEST_UID; - break; - case 'lesser': - $postcount_value = intval($postcount_value); + $select_sql .= " WHERE u.user_posts > $postcount_value + AND u.user_id <> " . GUEST_UID; + break; + case 'lesser': + $postcount_value = intval($postcount_value); - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_LESSER'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_LESSER'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_posts < $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts < $postcount_value - AND u.user_id <> ".GUEST_UID; - break; - case 'equals': - // looking for a - - if (strstr($postcount_value, '-')) - { - $range = preg_split('/[-\s]+/', $postcount_value); + $select_sql .= " WHERE u.user_posts < $postcount_value + AND u.user_id <> " . GUEST_UID; + break; + case 'equals': + // looking for a - + if (strstr($postcount_value, '-')) { + $range = preg_split('/[-\s]+/', $postcount_value); - $range_begin = intval($range[0]); - $range_end = intval($range[1]); + $range_begin = intval($range[0]); + $range_end = intval($range[1]); - if ($range_begin > $range_end) - { - bb_die($lang['SEARCH_INVALID_POSTCOUNT']); - } + if ($range_begin > $range_end) { + bb_die($lang['SEARCH_INVALID_POSTCOUNT']); + } - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_RANGE'], $range_begin, $range_end); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_RANGE'], $range_begin, $range_end); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_posts >= $range_begin AND user_posts <= $range_end - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts >= $range_begin + $select_sql .= " WHERE u.user_posts >= $range_begin AND u.user_posts <= $range_end - AND u.user_id <> ".GUEST_UID; - } - else - { - $postcount_value = intval($postcount_value); + AND u.user_id <> " . GUEST_UID; + } else { + $postcount_value = intval($postcount_value); - $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value); + $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_posts = $postcount_value - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_posts = $postcount_value - AND u.user_id <> ".GUEST_UID; - } - break; - default: - bb_die($lang['SEARCH_INVALID']); - } - break; + $select_sql .= " WHERE u.user_posts = $postcount_value + AND u.user_id <> " . GUEST_UID; + } + break; + default: + bb_die($lang['SEARCH_INVALID']); + } + break; - case 'search_userfield': - $base_url .= '&search_userfield=true&userfield_type='. rawurlencode($userfield_type) .'&userfield_value='. rawurlencode(stripslashes($userfield_value)); + case 'search_userfield': + $base_url .= '&search_userfield=true&userfield_type=' . rawurlencode($userfield_type) . '&userfield_value=' . rawurlencode(stripslashes($userfield_value)); - $text = strip_tags(htmlspecialchars(stripslashes($userfield_value))); + $text = strip_tags(htmlspecialchars(stripslashes($userfield_value))); - $userfield_value = preg_replace('/\*/', '%', trim(strip_tags(strtolower($userfield_value)))); + $userfield_value = preg_replace('/\*/', '%', trim(strip_tags(strtolower($userfield_value)))); - if (strstr($userfield_value, '%')) - { - $op = 'LIKE'; - } - else - { - $op = '='; - } + if (strstr($userfield_value, '%')) { + $op = 'LIKE'; + } else { + $op = '='; + } - if ($userfield_value == '') bb_die($lang['SEARCH_INVALID_USERFIELD']); + if ($userfield_value == '') { + bb_die($lang['SEARCH_INVALID_USERFIELD']); + } - $userfield_type = trim(strtolower($userfield_type)); + $userfield_type = trim(strtolower($userfield_type)); - switch ($userfield_type) - { - case 'icq': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'],$text); - $field = 'user_icq'; - break; - case 'skype': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_SKYPE'],$text); - $field = 'user_skype'; - break; - case 'twitter': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_TWITTER'],$text); - $field = 'user_twitter'; - break; - case 'website': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_WEBSITE'],$text); - $field = 'user_website'; - break; - case 'location': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_LOCATION'],$text); - $field = 'user_from'; - break; - case 'interests': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_INTERESTS'],$text); - $field = 'user_interests'; - break; - case 'occupation': - $text = sprintf($lang['SEARCH_FOR_USERFIELD_OCCUPATION'],$text); - $field = 'user_occ'; - break; - default: - bb_die( $lang['SEARCH_INVALID']); - } + switch ($userfield_type) { + case 'icq': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'], $text); + $field = 'user_icq'; + break; + case 'skype': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_SKYPE'], $text); + $field = 'user_skype'; + break; + case 'twitter': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_TWITTER'], $text); + $field = 'user_twitter'; + break; + case 'website': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_WEBSITE'], $text); + $field = 'user_website'; + break; + case 'location': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_LOCATION'], $text); + $field = 'user_from'; + break; + case 'interests': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_INTERESTS'], $text); + $field = 'user_interests'; + break; + case 'occupation': + $text = sprintf($lang['SEARCH_FOR_USERFIELD_OCCUPATION'], $text); + $field = 'user_occ'; + break; + default: + bb_die($lang['SEARCH_INVALID']); + } - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE {$lower_b}$field{$lower_e} $op '".DB()->escape($userfield_value)."' - AND user_id <> ".GUEST_UID; + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " + WHERE {$lower_b}$field{$lower_e} $op '" . DB()->escape($userfield_value) . "' + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE {$lower_b}u.$field{$lower_e} $op '".DB()->escape($userfield_value)."' - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE {$lower_b}u.$field{$lower_e} $op '" . DB()->escape($userfield_value) . "' + AND u.user_id <> " . GUEST_UID; + break; - case 'search_lastvisited': - $lastvisited_type = trim(strtolower($lastvisited_type)); - $lastvisited_days = intval($lastvisited_days); + case 'search_lastvisited': + $lastvisited_type = trim(strtolower($lastvisited_type)); + $lastvisited_days = intval($lastvisited_days); - $base_url .= '&search_lastvisited=true&lastvisited_type='. rawurlencode(stripslashes($lastvisited_type)) .'&lastvisited_days='. rawurlencode($lastvisited_days); + $base_url .= '&search_lastvisited=true&lastvisited_type=' . rawurlencode(stripslashes($lastvisited_type)) . '&lastvisited_days=' . rawurlencode($lastvisited_days); - $lastvisited_seconds = ( TIMENOW - ( ( ( $lastvisited_days * 24 ) * 60 ) * 60 ) ); + $lastvisited_seconds = (TIMENOW - ((($lastvisited_days * 24) * 60) * 60)); - switch($lastvisited_type) - { - case 'in': - $text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], $lastvisited_days, ( ( $lastvisited_days > 1 ) ? $lang['DAYS'] : $lang['DAY'] ) ); + switch ($lastvisited_type) { + case 'in': + $text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], $lastvisited_days, (($lastvisited_days > 1) ? $lang['DAYS'] : $lang['DAY'])); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_lastvisit >= $lastvisited_seconds - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lastvisit >= $lastvisited_seconds - AND u.user_id <> ".GUEST_UID; - break; - case 'after': - $text = sprintf($lang['SEARCH_FOR_LASTVISITED_AFTERTHELAST'], $lastvisited_days, ( ( $lastvisited_days > 1 ) ? $lang['DAYS'] : $lang['DAY'] )); + $select_sql .= " WHERE u.user_lastvisit >= $lastvisited_seconds + AND u.user_id <> " . GUEST_UID; + break; + case 'after': + $text = sprintf($lang['SEARCH_FOR_LASTVISITED_AFTERTHELAST'], $lastvisited_days, (($lastvisited_days > 1) ? $lang['DAYS'] : $lang['DAY'])); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_lastvisit < $lastvisited_seconds - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lastvisit < $lastvisited_seconds - AND u.user_id <> ".GUEST_UID; + $select_sql .= " WHERE u.user_lastvisit < $lastvisited_seconds + AND u.user_id <> " . GUEST_UID; - break; - default: - bb_die($lang['SEARCH_INVALID_LASTVISITED']); - } - break; + break; + default: + bb_die($lang['SEARCH_INVALID_LASTVISITED']); + } + break; - case 'search_language': - $base_url .= '&search_language=true&language_type='. rawurlencode(stripslashes($language_type)); + case 'search_language': + $base_url .= '&search_language=true&language_type=' . rawurlencode(stripslashes($language_type)); - $language_type = trim(strtolower(stripslashes($language_type))); + $language_type = trim(strtolower(stripslashes($language_type))); - if ($language_type == '') - { - bb_die($lang['SEARCH_INVALID_LANGUAGE']); - } + if ($language_type == '') { + bb_die($lang['SEARCH_INVALID_LANGUAGE']); + } - $text = sprintf($lang['SEARCH_FOR_LANGUAGE'], strip_tags(htmlspecialchars($language_type))); + $text = sprintf($lang['SEARCH_FOR_LANGUAGE'], strip_tags(htmlspecialchars($language_type))); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_lang = '".DB()->escape($language_type)."' - AND user_id <> ".GUEST_UID; + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " + WHERE user_lang = '" . DB()->escape($language_type) . "' + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_lang = '".DB()->escape($language_type)."' - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_lang = '" . DB()->escape($language_type) . "' + AND u.user_id <> " . GUEST_UID; + break; - case 'search_timezone': - $base_url .= '&search_timezone=true&timezone_type='. rawurlencode(stripslashes($timezone_type)); - $text = sprintf($lang['SEARCH_FOR_TIMEZONE'], strip_tags(htmlspecialchars(stripslashes($timezone_type)))); + case 'search_timezone': + $base_url .= '&search_timezone=true&timezone_type=' . rawurlencode(stripslashes($timezone_type)); + $text = sprintf($lang['SEARCH_FOR_TIMEZONE'], strip_tags(htmlspecialchars(stripslashes($timezone_type)))); - $timezone_type = intval($timezone_type); + $timezone_type = intval($timezone_type); - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_timezone = $timezone_type - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_timezone = $timezone_type - AND u.user_id <> ".GUEST_UID; - break; + $select_sql .= " WHERE u.user_timezone = $timezone_type + AND u.user_id <> " . GUEST_UID; + break; - case 'search_moderators': - $base_url .= '&search_moderators=true&moderators_forum='. rawurlencode(stripslashes($moderators_forum)); - $moderators_forum = intval($moderators_forum); + case 'search_moderators': + $base_url .= '&search_moderators=true&moderators_forum=' . rawurlencode(stripslashes($moderators_forum)); + $moderators_forum = intval($moderators_forum); - $sql = "SELECT forum_name FROM ".BB_FORUMS." WHERE forum_id = ".$moderators_forum; + $sql = "SELECT forum_name FROM " . BB_FORUMS . " WHERE forum_id = " . $moderators_forum; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select forum data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select forum data'); + } - if (DB()->num_rows($result)==0) - { - bb_die($lang['SEARCH_INVALID_MODERATORS']); - } + if (DB()->num_rows($result) == 0) { + bb_die($lang['SEARCH_INVALID_MODERATORS']); + } - $forum_name = DB()->sql_fetchrow($result); + $forum_name = DB()->sql_fetchrow($result); - $text = sprintf($lang['SEARCH_FOR_MODERATORS'], htmlCHR($forum_name['forum_name'])); + $text = sprintf($lang['SEARCH_FOR_MODERATORS'], htmlCHR($forum_name['forum_name'])); - $total_sql .= "SELECT COUNT(DISTINCT u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_GROUPS." AS g, ".BB_USER_GROUP." AS ug, ".BB_AUTH_ACCESS." AS aa + $total_sql .= "SELECT COUNT(DISTINCT u.user_id) AS total + FROM " . BB_USERS . " AS u, " . BB_GROUPS . " AS g, " . BB_USER_GROUP . " AS ug, " . BB_AUTH_ACCESS . " AS aa WHERE u.user_id = ug.user_id AND ug.group_id = g.group_id AND g.group_id = aa.group_id - AND aa.forum_id = ". $moderators_forum ." - AND aa.forum_perm & ". BF_AUTH_MOD ." - AND u.user_id <> ".GUEST_UID; + AND aa.forum_id = " . $moderators_forum . " + AND aa.forum_perm & " . BF_AUTH_MOD . " + AND u.user_id <> " . GUEST_UID; - $select_sql .= ", ".BB_GROUPS." AS g, ".BB_USER_GROUP." AS ug, ".BB_AUTH_ACCESS." AS aa + $select_sql .= ", " . BB_GROUPS . " AS g, " . BB_USER_GROUP . " AS ug, " . BB_AUTH_ACCESS . " AS aa WHERE u.user_id = ug.user_id AND ug.group_id = g.group_id AND g.group_id = aa.group_id - AND aa.forum_id = ". $moderators_forum ." - AND aa.forum_perm & ". BF_AUTH_MOD ." - AND u.user_id <> ".GUEST_UID." + AND aa.forum_id = " . $moderators_forum . " + AND aa.forum_perm & " . BF_AUTH_MOD . " + AND u.user_id <> " . GUEST_UID . " GROUP BY u.user_id, u.username, u.user_email, u.user_posts, u.user_regdate, u.user_level, u.user_active, u.user_lastvisit"; - break; + break; - case 'search_misc': - default: - $misc = trim(strtolower($misc)); + case 'search_misc': + default: + $misc = trim(strtolower($misc)); - $base_url .= '&search_misc=true&misc='. rawurlencode(stripslashes($misc)); + $base_url .= '&search_misc=true&misc=' . rawurlencode(stripslashes($misc)); - switch ($misc) - { - case 'admins': - $text = $lang['SEARCH_FOR_ADMINS']; + switch ($misc) { + case 'admins': + $text = $lang['SEARCH_FOR_ADMINS']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_level = ".ADMIN." - AND user_id <> ".GUEST_UID; + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " + WHERE user_level = " . ADMIN . " + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_level = ".ADMIN." - AND u.user_id <> ".GUEST_UID; - break; - case 'mods': - $text = $lang['SEARCH_FOR_MODS']; + $select_sql .= " WHERE u.user_level = " . ADMIN . " + AND u.user_id <> " . GUEST_UID; + break; + case 'mods': + $text = $lang['SEARCH_FOR_MODS']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." - WHERE user_level = ".MOD." - AND user_id <> ".GUEST_UID; + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " + WHERE user_level = " . MOD . " + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_level = ".MOD." - AND u.user_id <> ".GUEST_UID; - break; - case 'banned': - $text = $lang['SEARCH_FOR_BANNED']; + $select_sql .= " WHERE u.user_level = " . MOD . " + AND u.user_id <> " . GUEST_UID; + break; + case 'banned': + $text = $lang['SEARCH_FOR_BANNED']; - $total_sql .= "SELECT COUNT(u.user_id) AS total - FROM ".BB_USERS." AS u, ".BB_BANLIST." AS b + $total_sql .= "SELECT COUNT(u.user_id) AS total + FROM " . BB_USERS . " AS u, " . BB_BANLIST . " AS b WHERE u.user_id = b.ban_userid - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> " . GUEST_UID; - $select_sql .= ", ".BB_BANLIST." AS b + $select_sql .= ", " . BB_BANLIST . " AS b WHERE u.user_id = b.ban_userid - AND u.user_id <> ".GUEST_UID; + AND u.user_id <> " . GUEST_UID; - break; - case 'disabled': - $text = $lang['SEARCH_FOR_DISABLED']; + break; + case 'disabled': + $text = $lang['SEARCH_FOR_DISABLED']; - $total_sql .= "SELECT COUNT(user_id) AS total - FROM ".BB_USERS." + $total_sql .= "SELECT COUNT(user_id) AS total + FROM " . BB_USERS . " WHERE user_active = 0 - AND user_id <> ".GUEST_UID; + AND user_id <> " . GUEST_UID; - $select_sql .= " WHERE u.user_active = 0 - AND u.user_id <> ".GUEST_UID; + $select_sql .= " WHERE u.user_active = 0 + AND u.user_id <> " . GUEST_UID; - break; - default: - bb_die($lang['SEARCH_INVALID']); - } - } + break; + default: + bb_die($lang['SEARCH_INVALID']); + } + } - $select_sql .= " ORDER BY "; + $select_sql .= " ORDER BY "; - switch (strtolower(@$_GET['sort'])) - { - case 'regdate': - $sort = 'regdate'; - $select_sql .= 'u.user_regdate'; - break; + switch (strtolower(@$_GET['sort'])) { + case 'regdate': + $sort = 'regdate'; + $select_sql .= 'u.user_regdate'; + break; - case 'posts': - $sort = 'posts'; - $select_sql .= 'u.user_posts'; - break; + case 'posts': + $sort = 'posts'; + $select_sql .= 'u.user_posts'; + break; - case 'user_email': - $sort = 'user_email'; - $select_sql .= 'u.user_email'; - break; + case 'user_email': + $sort = 'user_email'; + $select_sql .= 'u.user_email'; + break; - case 'lastvisit': - $sort = 'lastvisit'; - $select_sql .= 'u.user_lastvisit'; - break; + case 'lastvisit': + $sort = 'lastvisit'; + $select_sql .= 'u.user_lastvisit'; + break; - case 'username': - default: - $sort = 'username'; - $select_sql .= 'u.username'; - } + case 'username': + default: + $sort = 'username'; + $select_sql .= 'u.username'; + } - switch (@$_GET['order']) - { - case 'DESC': - $order = 'DESC'; - $o_order = 'ASC'; - break; + switch (@$_GET['order']) { + case 'DESC': + $order = 'DESC'; + $o_order = 'ASC'; + break; - default: - $o_order = 'DESC'; - $order = 'ASC'; - } + default: + $o_order = 'DESC'; + $order = 'ASC'; + } - $select_sql .= " $order"; + $select_sql .= " $order"; - $page = ( isset($_GET['page']) ) ? intval($_GET['page']) : intval(trim(@$_POST['page'])); + $page = (isset($_GET['page'])) ? intval($_GET['page']) : intval(trim(@$_POST['page'])); - if ($page < 1) - { - $page = 1; - } + if ($page < 1) { + $page = 1; + } - if ($page == 1) - { - $offset = 0; - } - else - { - $offset = ( ($page - 1) * $bb_cfg['topics_per_page']); - } + if ($page == 1) { + $offset = 0; + } else { + $offset = (($page - 1) * $bb_cfg['topics_per_page']); + } - $limit = "LIMIT $offset, ".$bb_cfg['topics_per_page']; + $limit = "LIMIT $offset, " . $bb_cfg['topics_per_page']; - $select_sql .= " $limit"; + $select_sql .= " $limit"; - if (!is_null($total_sql)) - { - if (!$result = DB()->sql_query($total_sql)) - { - bb_die('Could not count users'); - } + if (!is_null($total_sql)) { + if (!$result = DB()->sql_query($total_sql)) { + bb_die('Could not count users'); + } - $total_pages = DB()->sql_fetchrow($result); + $total_pages = DB()->sql_fetchrow($result); - if ($total_pages['total'] == 0) - { - bb_die($lang['SEARCH_NO_RESULTS']); - } - } - $num_pages = ceil( ( $total_pages['total'] / $bb_cfg['topics_per_page'] ) ); + if ($total_pages['total'] == 0) { + bb_die($lang['SEARCH_NO_RESULTS']); + } + } + $num_pages = ceil(($total_pages['total'] / $bb_cfg['topics_per_page'])); - $pagination = ''; + $pagination = ''; - if ($page > 1) - { - $pagination .= ''. $lang['PREVIOUS'] .''; - } - if ($page < $num_pages) - { - $pagination .= ( $pagination == '' ) ? ''.$lang['NEXT'].'' : ' | '.$lang['NEXT'].''; - } - if ($num_pages > 2) - { - $pagination .= '   '; - } - $template->assign_vars(array( - 'TPL_ADMIN_USER_SEARCH_RESULTS' => true, + if ($page > 1) { + $pagination .= '' . $lang['PREVIOUS'] . ''; + } + if ($page < $num_pages) { + $pagination .= ($pagination == '') ? '' . $lang['NEXT'] . '' : ' | ' . $lang['NEXT'] . ''; + } + if ($num_pages > 2) { + $pagination .= '   '; + } + $template->assign_vars(array( + 'TPL_ADMIN_USER_SEARCH_RESULTS' => true, - 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], $page, $num_pages), - 'PAGINATION' => $pagination, - 'NEW_SEARCH' => sprintf($lang['SEARCH_USERS_NEW'],$text, $total_pages['total'], 'admin_user_search.php'), + 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], $page, $num_pages), + 'PAGINATION' => $pagination, + 'NEW_SEARCH' => sprintf($lang['SEARCH_USERS_NEW'], $text, $total_pages['total'], 'admin_user_search.php'), - 'U_USERNAME' => ($sort == 'username') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=username&order=$order", - 'U_EMAIL' => ($sort == 'user_email') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=user_email&order=$order", - 'U_POSTS' => ($sort == 'posts') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=posts&order=$order", - 'U_JOINDATE' => ($sort == 'regdate') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=regdate&order=$order", - 'U_LASTVISIT' => ($sort == 'lastvisit') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=lastvisit&order=$order", + 'U_USERNAME' => ($sort == 'username') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=username&order=$order", + 'U_EMAIL' => ($sort == 'user_email') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=user_email&order=$order", + 'U_POSTS' => ($sort == 'posts') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=posts&order=$order", + 'U_JOINDATE' => ($sort == 'regdate') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=regdate&order=$order", + 'U_LASTVISIT' => ($sort == 'lastvisit') ? "$base_url&sort=$sort&order=$o_order" : "$base_url&sort=lastvisit&order=$order", - 'S_POST_ACTION' => "$base_url&sort=$sort&order=$order" - )); + 'S_POST_ACTION' => "$base_url&sort=$sort&order=$order" + )); - if (!$result = DB()->sql_query($select_sql)) - { - bb_die('Could not select user data'); - } + if (!$result = DB()->sql_query($select_sql)) { + bb_die('Could not select user data'); + } - $rowset = DB()->sql_fetchrowset($result); + $rowset = DB()->sql_fetchrowset($result); - $users_sql = ''; + $users_sql = ''; - foreach ($rowset as $array) - { - $users_sql .= ( $users_sql == '' ) ? $array['user_id'] : ', '.$array['user_id']; - } + foreach ($rowset as $array) { + $users_sql .= ($users_sql == '') ? $array['user_id'] : ', ' . $array['user_id']; + } - $sql = "SELECT ban_userid AS user_id FROM ". BB_BANLIST ." WHERE ban_userid IN ($users_sql)"; + $sql = "SELECT ban_userid AS user_id FROM " . BB_BANLIST . " WHERE ban_userid IN ($users_sql)"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not select banned data'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not select banned data'); + } - unset($banned); + unset($banned); - $banned = array(); + $banned = array(); - while ($row = DB()->sql_fetchrow($result)) - { - $banned[$row['user_id']] = true; - } + while ($row = DB()->sql_fetchrow($result)) { + $banned[$row['user_id']] = true; + } - for ($i = 0; $i < count($rowset); $i++) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + for ($i = 0; $i < count($rowset); $i++) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('userrow', array( - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($rowset[$i]), - 'EMAIL' => $rowset[$i]['user_email'], - 'JOINDATE' => bb_date($rowset[$i]['user_regdate']), - 'LASTVISIT' => bb_date($rowset[$i]['user_lastvisit']), - 'POSTS' => $rowset[$i]['user_posts'], - 'BAN' => ( ( !isset($banned[$rowset[$i]['user_id']]) ) ? $lang['NOT_BANNED'] : $lang['BANNED'] ), - 'ABLED' => ( ( $rowset[$i]['user_active'] ) ? $lang['ENABLED'] : $lang['DISABLED'] ), + $template->assign_block_vars('userrow', array( + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($rowset[$i]), + 'EMAIL' => $rowset[$i]['user_email'], + 'JOINDATE' => bb_date($rowset[$i]['user_regdate']), + 'LASTVISIT' => bb_date($rowset[$i]['user_lastvisit']), + 'POSTS' => $rowset[$i]['user_posts'], + 'BAN' => ((!isset($banned[$rowset[$i]['user_id']])) ? $lang['NOT_BANNED'] : $lang['BANNED']), + 'ABLED' => (($rowset[$i]['user_active']) ? $lang['ENABLED'] : $lang['DISABLED']), - 'U_VIEWPOSTS' => "../search.php?search_author=1&uid={$rowset[$i]['user_id']}", - 'U_MANAGE' => '../profile.php?mode=editprofile&'. POST_USERS_URL .'='.$rowset[$i]['user_id'].'&admin=1', - 'U_PERMISSIONS' => 'admin_ug_auth.php?mode=user&'. POST_USERS_URL .'='. $rowset[$i]['user_id'], - )); - } + 'U_VIEWPOSTS' => "../search.php?search_author=1&uid={$rowset[$i]['user_id']}", + 'U_MANAGE' => '../profile.php?mode=editprofile&' . POST_USERS_URL . '=' . $rowset[$i]['user_id'] . '&admin=1', + 'U_PERMISSIONS' => 'admin_ug_auth.php?mode=user&' . POST_USERS_URL . '=' . $rowset[$i]['user_id'], + )); + } } -print_page('admin_user_search.tpl', 'admin'); \ No newline at end of file +print_page('admin_user_search.tpl', 'admin'); diff --git a/admin/admin_words.php b/admin/admin_words.php index e46de3025..23891efe0 100644 --- a/admin/admin_words.php +++ b/admin/admin_words.php @@ -1,157 +1,151 @@
($bb_cfg[\'use_word_censor\'] in config.php)'); +if (!$bb_cfg['use_word_censor']) { + bb_die('Word censor disabled

($bb_cfg[\'use_word_censor\'] in config.php)'); } $mode = request_var('mode', ''); $mode = htmlspecialchars($mode); -if (isset($_POST['add'])) -{ - $mode = 'add'; -} -else if (isset($_POST['save'])) -{ - $mode = 'save'; +if (isset($_POST['add'])) { + $mode = 'add'; +} elseif (isset($_POST['save'])) { + $mode = 'save'; } -if ($mode != '') -{ - if ($mode == 'edit' || $mode == 'add') - { - $word_id = intval(request_var('id', 0)); +if ($mode != '') { + if ($mode == 'edit' || $mode == 'add') { + $word_id = intval(request_var('id', 0)); - $s_hidden_fields = $word = $replacement = ''; + $s_hidden_fields = $word = $replacement = ''; - if ($mode == 'edit') - { - if ($word_id) - { - $sql = "SELECT * FROM " . BB_WORDS . " WHERE word_id = $word_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not query words table #1'); - } + if ($mode == 'edit') { + if ($word_id) { + $sql = "SELECT * FROM " . BB_WORDS . " WHERE word_id = $word_id"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query words table #1'); + } - $word_info = DB()->sql_fetchrow($result); - $s_hidden_fields .= ''; - $word = $word_info['word']; - $replacement = $word_info['replacement']; - } - else - { - bb_die($lang['NO_WORD_SELECTED']); - } - } + $word_info = DB()->sql_fetchrow($result); + $s_hidden_fields .= ''; + $word = $word_info['word']; + $replacement = $word_info['replacement']; + } else { + bb_die($lang['NO_WORD_SELECTED']); + } + } - $template->assign_vars(array( - 'TPL_ADMIN_WORDS_EDIT' => true, - 'WORD' => $word, - 'REPLACEMENT' => $replacement, - 'S_WORDS_ACTION' => 'admin_words.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - else if ($mode == 'save') - { - $word_id = intval(request_var('id', 0)); - $word = trim(request_var('word', '')); - $replacement = trim(request_var('replacement', '')); + $template->assign_vars(array( + 'TPL_ADMIN_WORDS_EDIT' => true, + 'WORD' => $word, + 'REPLACEMENT' => $replacement, + 'S_WORDS_ACTION' => 'admin_words.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); + } elseif ($mode == 'save') { + $word_id = intval(request_var('id', 0)); + $word = trim(request_var('word', '')); + $replacement = trim(request_var('replacement', '')); - if ($word == '' || $replacement == '') - { - bb_die($lang['MUST_ENTER_WORD']); - } + if ($word == '' || $replacement == '') { + bb_die($lang['MUST_ENTER_WORD']); + } - if ($word_id) - { - $sql = "UPDATE " . BB_WORDS . " + if ($word_id) { + $sql = "UPDATE " . BB_WORDS . " SET word = '" . DB()->escape($word) . "', replacement = '" . DB()->escape($replacement) . "' WHERE word_id = $word_id"; - $message = $lang['WORD_UPDATED']; - } - else - { - $sql = "INSERT INTO " . BB_WORDS . " (word, replacement) + $message = $lang['WORD_UPDATED']; + } else { + $sql = "INSERT INTO " . BB_WORDS . " (word, replacement) VALUES ('" . DB()->escape($word) . "', '" . DB()->escape($replacement) . "')"; - $message = $lang['WORD_ADDED']; - } + $message = $lang['WORD_ADDED']; + } - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not insert data into words table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not insert data into words table'); + } - CACHE('bb_cache')->rm('censored'); - $message .= '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + CACHE('bb_cache')->rm('censored'); + $message .= '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); - } - else if ($mode == 'delete') - { - $word_id = intval(request_var('id', 0)); + bb_die($message); + } elseif ($mode == 'delete') { + $word_id = intval(request_var('id', 0)); - if ($word_id) - { - $sql = "DELETE FROM " . BB_WORDS . " WHERE word_id = $word_id"; + if ($word_id) { + $sql = "DELETE FROM " . BB_WORDS . " WHERE word_id = $word_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not remove data from words table'); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not remove data from words table'); + } - CACHE('bb_cache')->rm('censored'); + CACHE('bb_cache')->rm('censored'); - bb_die($lang['WORD_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); - } - else - { - bb_die($lang['NO_WORD_SELECTED']); - } - } -} -else -{ - $sql = "SELECT * FROM " . BB_WORDS . " ORDER BY word"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not query words table #2'); - } + bb_die($lang['WORD_REMOVED'] . '

' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '', '') . '

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', '')); + } else { + bb_die($lang['NO_WORD_SELECTED']); + } + } +} else { + $sql = "SELECT * FROM " . BB_WORDS . " ORDER BY word"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query words table #2'); + } - $word_rows = DB()->sql_fetchrowset($result); - $word_count = count($word_rows); + $word_rows = DB()->sql_fetchrowset($result); + $word_count = count($word_rows); - $template->assign_vars(array( - 'TPL_ADMIN_WORDS_LIST' => true, - 'S_WORDS_ACTION' => 'admin_words.php', - 'S_HIDDEN_FIELDS' => '', - )); + $template->assign_vars(array( + 'TPL_ADMIN_WORDS_LIST' => true, + 'S_WORDS_ACTION' => 'admin_words.php', + 'S_HIDDEN_FIELDS' => '', + )); - for ($i = 0; $i < $word_count; $i++) - { - $word = $word_rows[$i]['word']; - $replacement = $word_rows[$i]['replacement']; - $word_id = $word_rows[$i]['word_id']; + for ($i = 0; $i < $word_count; $i++) { + $word = $word_rows[$i]['word']; + $replacement = $word_rows[$i]['replacement']; + $word_id = $word_rows[$i]['word_id']; - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('words', array( - 'ROW_CLASS' => $row_class, - 'WORD' => $word, - 'REPLACEMENT' => $replacement, - 'U_WORD_EDIT' => "admin_words.php?mode=edit&id=$word_id", - 'U_WORD_DELETE' => "admin_words.php?mode=delete&id=$word_id", - )); - } + $template->assign_block_vars('words', array( + 'ROW_CLASS' => $row_class, + 'WORD' => $word, + 'REPLACEMENT' => $replacement, + 'U_WORD_EDIT' => "admin_words.php?mode=edit&id=$word_id", + 'U_WORD_DELETE' => "admin_words.php?mode=delete&id=$word_id", + )); + } } -print_page('admin_words.tpl', 'admin'); \ No newline at end of file +print_page('admin_words.tpl', 'admin'); diff --git a/admin/index.php b/admin/index.php index 33c3cd5f7..5e838b41a 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,292 +1,272 @@ get('admin_module')) - { - $dir = @opendir('.'); - $setmodules = 1; - while ($file = @readdir($dir)) - { - if (preg_match('/^admin_.*?\.php$/', $file)) - { - include('./' . $file); - } - } - unset($setmodules); - @closedir($dir); - CACHE('bb_cache')->set('admin_module', $module, 600); - } +if (isset($_GET['pane']) && $_GET['pane'] == 'left') { + if (!$module = CACHE('bb_cache')->get('admin_module')) { + $dir = @opendir('.'); + $setmodules = 1; + while ($file = @readdir($dir)) { + if (preg_match('/^admin_.*?\.php$/', $file)) { + include('./' . $file); + } + } + unset($setmodules); + @closedir($dir); + CACHE('bb_cache')->set('admin_module', $module, 600); + } - $template->assign_vars(array( - 'TPL_ADMIN_NAVIGATE' => true, - 'U_FORUM_INDEX' => '../index.php', - 'U_ADMIN_INDEX' => 'index.php?pane=right', - )); + $template->assign_vars(array( + 'TPL_ADMIN_NAVIGATE' => true, + 'U_FORUM_INDEX' => '../index.php', + 'U_ADMIN_INDEX' => 'index.php?pane=right', + )); - ksort($module); + ksort($module); - while (list($cat, $action_array) = each($module)) - { - $cat = (!empty($lang[$cat])) ? $lang[$cat] : preg_replace('/_/', ' ', $cat); + while (list($cat, $action_array) = each($module)) { + $cat = (!empty($lang[$cat])) ? $lang[$cat] : preg_replace('/_/', ' ', $cat); - $template->assign_block_vars('catrow', array( - 'ADMIN_CATEGORY' => $cat, - )); + $template->assign_block_vars('catrow', array( + 'ADMIN_CATEGORY' => $cat, + )); - ksort($action_array); + ksort($action_array); - $row_count = 0; - while (list($action, $file) = each($action_array)) - { - $row_class = !($row_count % 2) ? 'row1' : 'row2'; + $row_count = 0; + while (list($action, $file) = each($action_array)) { + $row_class = !($row_count % 2) ? 'row1' : 'row2'; - $action = (!empty($lang[$action])) ? $lang[$action] : preg_replace('/_/', ' ', $action); + $action = (!empty($lang[$action])) ? $lang[$action] : preg_replace('/_/', ' ', $action); - $template->assign_block_vars('catrow.modulerow', array( - 'ROW_CLASS' => $row_class, - 'ADMIN_MODULE' => $action, - 'U_ADMIN_MODULE' => $file, - )); - $row_count++; - } - } -} -elseif (isset($_GET['pane']) && $_GET['pane'] == 'right') -{ - $template->assign_vars(array( - 'TPL_ADMIN_MAIN' => true, - 'ADMIN_LOCK' => ($bb_cfg['board_disable']) ? true : false, - 'ADMIN_LOCK_CRON' => (file_exists(BB_DISABLED)) ? true :false, - )); + $template->assign_block_vars('catrow.modulerow', array( + 'ROW_CLASS' => $row_class, + 'ADMIN_MODULE' => $action, + 'U_ADMIN_MODULE' => $file, + )); + $row_count++; + } + } +} elseif (isset($_GET['pane']) && $_GET['pane'] == 'right') { + $template->assign_vars(array( + 'TPL_ADMIN_MAIN' => true, + 'ADMIN_LOCK' => ($bb_cfg['board_disable']) ? true : false, + 'ADMIN_LOCK_CRON' => (file_exists(BB_DISABLED)) ? true : false, + )); - // Get forum statistics - $total_posts = get_db_stat('postcount'); - $total_users = get_db_stat('usercount'); - $total_topics = get_db_stat('topiccount'); - $start_date = bb_date($bb_cfg['board_startdate']); - $boarddays = (TIMENOW - $bb_cfg['board_startdate']) / 86400; + // Get forum statistics + $total_posts = get_db_stat('postcount'); + $total_users = get_db_stat('usercount'); + $total_topics = get_db_stat('topiccount'); + $start_date = bb_date($bb_cfg['board_startdate']); + $boarddays = (TIMENOW - $bb_cfg['board_startdate']) / 86400; - $posts_per_day = sprintf('%.2f', $total_posts / $boarddays); - $topics_per_day = sprintf('%.2f', $total_topics / $boarddays); - $users_per_day = sprintf('%.2f', $total_users / $boarddays); + $posts_per_day = sprintf('%.2f', $total_posts / $boarddays); + $topics_per_day = sprintf('%.2f', $total_topics / $boarddays); + $users_per_day = sprintf('%.2f', $total_users / $boarddays); - $avatar_dir_size = 0; + $avatar_dir_size = 0; - if ($avatar_dir = @opendir(BB_ROOT . $bb_cfg['avatar_path'])) - { - while( $file = @readdir($avatar_dir) ) - { - if( $file != '.' && $file != '..' ) - { - $avatar_dir_size += @filesize(BB_ROOT . $bb_cfg['avatar_path'] . '/' . $file); - } - } - @closedir($avatar_dir); + if ($avatar_dir = @opendir(BB_ROOT . $bb_cfg['avatar_path'])) { + while ($file = @readdir($avatar_dir)) { + if ($file != '.' && $file != '..') { + $avatar_dir_size += @filesize(BB_ROOT . $bb_cfg['avatar_path'] . '/' . $file); + } + } + @closedir($avatar_dir); - $avatar_dir_size = humn_size($avatar_dir_size); - } - else - { - $avatar_dir_size = $lang['NOT_AVAILABLE']; - } + $avatar_dir_size = humn_size($avatar_dir_size); + } else { + $avatar_dir_size = $lang['NOT_AVAILABLE']; + } - if (intval($posts_per_day) > $total_posts) - { - $posts_per_day = $total_posts; - } + if (intval($posts_per_day) > $total_posts) { + $posts_per_day = $total_posts; + } - if (intval($topics_per_day) > $total_topics) - { - $topics_per_day = $total_topics; - } + if (intval($topics_per_day) > $total_topics) { + $topics_per_day = $total_topics; + } - if ($users_per_day > $total_users) - { - $users_per_day = $total_users; - } + if ($users_per_day > $total_users) { + $users_per_day = $total_users; + } - // DB size ... MySQL only - $sql = "SELECT VERSION() AS mysql_version"; - if ($result = DB()->sql_query($sql)) - { - $row = DB()->sql_fetchrow($result); - $version = $row['mysql_version']; + // DB size ... MySQL only + $sql = "SELECT VERSION() AS mysql_version"; + if ($result = DB()->sql_query($sql)) { + $row = DB()->sql_fetchrow($result); + $version = $row['mysql_version']; - if (preg_match('/^(3\.23|4\.|5\.|10\.)/', $version)) - { - $dblist = array(); - foreach ($bb_cfg['db'] as $name => $row) - { - $sql = "SHOW TABLE STATUS FROM {$row[1]}"; - if ($result = DB()->sql_query($sql)) - { - $tabledata_ary = DB()->sql_fetchrowset($result); + if (preg_match('/^(3\.23|4\.|5\.|10\.)/', $version)) { + $dblist = array(); + foreach ($bb_cfg['db'] as $name => $row) { + $sql = "SHOW TABLE STATUS FROM {$row[1]}"; + if ($result = DB()->sql_query($sql)) { + $tabledata_ary = DB()->sql_fetchrowset($result); - $dbsize = 0; - for ($i = 0; $i < count($tabledata_ary); $i++) - { - if( @$tabledata_ary[$i]['Type'] != 'MRG_MYISAM' ) - { - $dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length']; - } - } - $dblist[] = ''. humn_size($dbsize) .''; - } - } - $dbsize = implode(' | ', $dblist); - } - else - { - $dbsize = $lang['NOT_AVAILABLE']; - } - } - else - { - $dbsize = $lang['NOT_AVAILABLE']; - } + $dbsize = 0; + for ($i = 0; $i < count($tabledata_ary); $i++) { + if (@$tabledata_ary[$i]['Type'] != 'MRG_MYISAM') { + $dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length']; + } + } + $dblist[] = '' . humn_size($dbsize) . ''; + } + } + $dbsize = implode(' | ', $dblist); + } else { + $dbsize = $lang['NOT_AVAILABLE']; + } + } else { + $dbsize = $lang['NOT_AVAILABLE']; + } - $template->assign_vars(array( - 'NUMBER_OF_POSTS' => $total_posts, - 'NUMBER_OF_TOPICS' => $total_topics, - 'NUMBER_OF_USERS' => $total_users, - 'START_DATE' => $start_date, - 'POSTS_PER_DAY' => $posts_per_day, - 'TOPICS_PER_DAY' => $topics_per_day, - 'USERS_PER_DAY' => $users_per_day, - 'AVATAR_DIR_SIZE' => $avatar_dir_size, - 'DB_SIZE' => $dbsize, - 'GZIP_COMPRESSION' => ($bb_cfg['gzip_compress']) ? $lang['ON'] : $lang['OFF'], - )); + $template->assign_vars(array( + 'NUMBER_OF_POSTS' => $total_posts, + 'NUMBER_OF_TOPICS' => $total_topics, + 'NUMBER_OF_USERS' => $total_users, + 'START_DATE' => $start_date, + 'POSTS_PER_DAY' => $posts_per_day, + 'TOPICS_PER_DAY' => $topics_per_day, + 'USERS_PER_DAY' => $users_per_day, + 'AVATAR_DIR_SIZE' => $avatar_dir_size, + 'DB_SIZE' => $dbsize, + 'GZIP_COMPRESSION' => ($bb_cfg['gzip_compress']) ? $lang['ON'] : $lang['OFF'], + )); - if (@$_GET['users_online']) - { - $template->assign_vars(array( - 'SHOW_USERS_ONLINE' => true, - )); + if (@$_GET['users_online']) { + $template->assign_vars(array( + 'SHOW_USERS_ONLINE' => true, + )); - // Get users online information. - $sql = "SELECT u.user_id, u.username, u.user_rank, s.session_time AS user_session_time, u.user_opt, s.session_logged_in, s.session_ip, s.session_start + // Get users online information. + $sql = "SELECT u.user_id, u.username, u.user_rank, s.session_time AS user_session_time, u.user_opt, s.session_logged_in, s.session_ip, s.session_start FROM " . BB_USERS . " u, " . BB_SESSIONS . " s WHERE s.session_logged_in = 1 AND u.user_id = s.session_user_id AND u.user_id <> " . GUEST_UID . " - AND s.session_time >= " . ( TIMENOW - 300 ) . " + AND s.session_time >= " . (TIMENOW - 300) . " ORDER BY s.session_ip ASC, s.session_time DESC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain reged user / online information'); - } - $onlinerow_reg = DB()->sql_fetchrowset($result); + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain reged user / online information'); + } + $onlinerow_reg = DB()->sql_fetchrowset($result); - $sql = "SELECT session_logged_in, session_time, session_ip, session_start + $sql = "SELECT session_logged_in, session_time, session_ip, session_start FROM " . BB_SESSIONS . " WHERE session_logged_in = 0 - AND session_time >= " . ( TIMENOW - 300 ) . " + AND session_time >= " . (TIMENOW - 300) . " ORDER BY session_ip ASC, session_time DESC"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain guest user / online information'); - } - $onlinerow_guest = DB()->sql_fetchrowset($result); + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain guest user / online information'); + } + $onlinerow_guest = DB()->sql_fetchrowset($result); - $reg_userid_ary = array(); + $reg_userid_ary = array(); - if (count($onlinerow_reg)) - { - $registered_users = $hidden_users = 0; + if (count($onlinerow_reg)) { + $registered_users = $hidden_users = 0; - for ($i = 0, $cnt = count($onlinerow_reg); $i < $cnt; $i++) - { - if (!in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary)) - { - $reg_userid_ary[] = $onlinerow_reg[$i]['user_id']; + for ($i = 0, $cnt = count($onlinerow_reg); $i < $cnt; $i++) { + if (!in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary)) { + $reg_userid_ary[] = $onlinerow_reg[$i]['user_id']; - $username = $onlinerow_reg[$i]['username']; + $username = $onlinerow_reg[$i]['username']; - if (bf($onlinerow_reg[$i]['user_opt'], 'user_opt', 'user_viewonline')) - { - $hidden_users++; - $hidden = TRUE; - } - else - { - $registered_users++; - $hidden = FALSE; - } + if (bf($onlinerow_reg[$i]['user_opt'], 'user_opt', 'user_viewonline')) { + $hidden_users++; + $hidden = true; + } else { + $registered_users++; + $hidden = false; + } - $row_class = 'row1'; + $row_class = 'row1'; - $reg_ip = decode_ip($onlinerow_reg[$i]['session_ip']); + $reg_ip = decode_ip($onlinerow_reg[$i]['session_ip']); - $template->assign_block_vars('reg_user_row', array( - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($onlinerow_reg[$i]), - 'STARTED' => bb_date($onlinerow_reg[$i]['session_start'], 'H:i', false), - 'LASTUPDATE' => bb_date($onlinerow_reg[$i]['user_session_time'], 'H:i', false), - 'IP_ADDRESS' => $reg_ip, - 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $reg_ip, - )); - } - } - } + $template->assign_block_vars('reg_user_row', array( + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($onlinerow_reg[$i]), + 'STARTED' => bb_date($onlinerow_reg[$i]['session_start'], 'H:i', false), + 'LASTUPDATE' => bb_date($onlinerow_reg[$i]['user_session_time'], 'H:i', false), + 'IP_ADDRESS' => $reg_ip, + 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $reg_ip, + )); + } + } + } - // Guest users - if (count($onlinerow_guest)) - { - $guest_users = 0; + // Guest users + if (count($onlinerow_guest)) { + $guest_users = 0; - for ($i = 0; $i < count($onlinerow_guest); $i++) - { - $guest_userip_ary[] = $onlinerow_guest[$i]['session_ip']; - $guest_users++; + for ($i = 0; $i < count($onlinerow_guest); $i++) { + $guest_userip_ary[] = $onlinerow_guest[$i]['session_ip']; + $guest_users++; - $row_class = 'row2'; + $row_class = 'row2'; - $guest_ip = decode_ip($onlinerow_guest[$i]['session_ip']); + $guest_ip = decode_ip($onlinerow_guest[$i]['session_ip']); - $template->assign_block_vars('guest_user_row', array( - 'ROW_CLASS' => $row_class, - 'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'H:i', false), - 'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'H:i' , false), - 'IP_ADDRESS' => $guest_ip, - 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $guest_ip, - )); - } - } - } - else - { - $template->assign_vars(array( - 'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1', - )); - } -} -else -{ - // Generate frameset - $template->assign_vars(array( - 'CONTENT_ENCODING' => $bb_cfg['lang'][$userdata['user_lang']]['encoding'], - 'TPL_ADMIN_FRAMESET' => true, - )); - send_no_cache_headers(); - print_page('index.tpl', 'admin', 'no_header'); + $template->assign_block_vars('guest_user_row', array( + 'ROW_CLASS' => $row_class, + 'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'H:i', false), + 'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'H:i', false), + 'IP_ADDRESS' => $guest_ip, + 'U_WHOIS_IP' => $bb_cfg['whois_info'] . $guest_ip, + )); + } + } + } else { + $template->assign_vars(array( + 'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1', + )); + } +} else { + // Generate frameset + $template->assign_vars(array( + 'CONTENT_ENCODING' => $bb_cfg['lang'][$userdata['user_lang']]['encoding'], + 'TPL_ADMIN_FRAMESET' => true, + )); + send_no_cache_headers(); + print_page('index.tpl', 'admin', 'no_header'); } print_page('index.tpl', 'admin'); // Functions -function inarray ($needle, $haystack) +function inarray($needle, $haystack) { - for ($i = 0; $i < sizeof($haystack); $i++) - { - if ($haystack[$i] == $needle) - { - return true; - } - } - return false; -} \ No newline at end of file + for ($i = 0; $i < sizeof($haystack); $i++) { + if ($haystack[$i] == $needle) { + return true; + } + } + return false; +} diff --git a/admin/pagestart.php b/admin/pagestart.php index 40449b461..c8c38371c 100644 --- a/admin/pagestart.php +++ b/admin/pagestart.php @@ -1,28 +1,48 @@ session_start(); -if (IS_GUEST) -{ - redirect(LOGIN_URL . "?redirect=admin/index.php"); +if (IS_GUEST) { + redirect(LOGIN_URL . "?redirect=admin/index.php"); } -if (!IS_ADMIN) -{ - bb_die($lang['NOT_ADMIN']); +if (!IS_ADMIN) { + bb_die($lang['NOT_ADMIN']); } -if (!$userdata['session_admin']) -{ - $redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1); - redirect("login.php?redirect=$redirect"); -} \ No newline at end of file +if (!$userdata['session_admin']) { + $redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1); + redirect("login.php?redirect=$redirect"); +} diff --git a/admin/stats/tr_stats.php b/admin/stats/tr_stats.php index 523a395a4..e3c4c093f 100644 --- a/admin/stats/tr_stats.php +++ b/admin/stats/tr_stats.php @@ -1,48 +1,70 @@ session_start(); -if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); +if (!IS_ADMIN) { + bb_die($lang['NOT_AUTHORISED']); +} -$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000'; -$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000'; -$sql[] = 'SELECT round(avg(size)/1048576) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(*) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(distinct(topic_id)) FROM `'.BB_BT_TRACKER_SNAP.'` WHERE seeders > 0'; -$sql[] = 'SELECT count(distinct(topic_id)) FROM `'.BB_BT_TRACKER_SNAP.'` WHERE seeders > 5'; -$sql[] = 'SELECT count(distinct(poster_id)) FROM `'.BB_BT_TORRENTS.'`'; -$sql[] = 'SELECT count(distinct(poster_id)) FROM `'.BB_BT_TORRENTS.'` WHERE reg_time >= UNIX_TIMESTAMP()-2592000'; +$sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000'; +$sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000'; +$sql[] = 'SELECT round(avg(size)/1048576) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(*) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(distinct(topic_id)) FROM `' . BB_BT_TRACKER_SNAP . '` WHERE seeders > 0'; +$sql[] = 'SELECT count(distinct(topic_id)) FROM `' . BB_BT_TRACKER_SNAP . '` WHERE seeders > 5'; +$sql[] = 'SELECT count(distinct(poster_id)) FROM `' . BB_BT_TORRENTS . '`'; +$sql[] = 'SELECT count(distinct(poster_id)) FROM `' . BB_BT_TORRENTS . '` WHERE reg_time >= UNIX_TIMESTAMP()-2592000'; echo ''; echo '

'; -foreach ($sql as $i => $query) -{ - $row = mysqli_fetch_row(DB()->query($query)); - echo ""; +foreach ($sql as $i => $query) { + $row = mysqli_fetch_row(DB()->query($query)); + echo ""; } echo '
{$lang['TR_STATS'][$i]}{$row[0]}
{$lang['TR_STATS'][$i]}{$row[0]}
'; echo '
';
 
-if ($l = sys('la'))
-{
-	$l = explode(' ', $l);
-	for ($i=0; $i < 3; $i++)
-	{
-		$l[$i] = round($l[$i], 1);
-	}
-	echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
+if ($l = sys('la')) {
+    $l = explode(' ', $l);
+    for ($i = 0; $i < 3; $i++) {
+        $l[$i] = round($l[$i], 1);
+    }
+    echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
 }
 
-echo 'gen time: '. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ." sec\n";
+echo 'gen time: ' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . " sec\n";
 
 echo '
'; echo ''; diff --git a/admin/stats/tracker.php b/admin/stats/tracker.php index 69d9922d8..2e892f4dc 100644 --- a/admin/stats/tracker.php +++ b/admin/stats/tracker.php @@ -1,12 +1,37 @@ session_start(); -if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); +if (!IS_ADMIN) { + bb_die($lang['NOT_AUTHORISED']); +} $peers_in_last_minutes = array(30, 15, 5, 1); $peers_in_last_sec_limit = 300; @@ -17,7 +42,7 @@ $stat = array(); define('TMP_TRACKER_TABLE', 'tmp_tracker'); DB()->query(" - CREATE TEMPORARY TABLE ". TMP_TRACKER_TABLE ." ( + CREATE TEMPORARY TABLE " . TMP_TRACKER_TABLE . " ( `topic_id` mediumint(8) unsigned NOT NULL default '0', `user_id` mediumint(9) NOT NULL default '0', `ip` char(8) binary NOT NULL default '0', @@ -28,53 +53,53 @@ DB()->query(" ) SELECT topic_id, user_id, ip, seeder, speed_up, speed_down, update_time - FROM ". BB_BT_TRACKER ." + FROM " . BB_BT_TRACKER . " "); // Peers within announce interval -$stat += DB()->fetch_row("SELECT COUNT(*) AS p_within_ann FROM ". TMP_TRACKER_TABLE ." WHERE update_time >= ". (TIMENOW - $announce_interval)); +$stat += DB()->fetch_row("SELECT COUNT(*) AS p_within_ann FROM " . TMP_TRACKER_TABLE . " WHERE update_time >= " . (TIMENOW - $announce_interval)); // All peers, "max_peer_time" -$stat += DB()->fetch_row("SELECT COUNT(*) AS p_all, SUM(speed_up) as speed_up, SUM(speed_down) as speed_down, UNIX_TIMESTAMP() - MIN(update_time) AS max_peer_time, UNIX_TIMESTAMP() - MAX(update_time) AS last_peer_time FROM ". TMP_TRACKER_TABLE); +$stat += DB()->fetch_row("SELECT COUNT(*) AS p_all, SUM(speed_up) as speed_up, SUM(speed_down) as speed_down, UNIX_TIMESTAMP() - MIN(update_time) AS max_peer_time, UNIX_TIMESTAMP() - MAX(update_time) AS last_peer_time FROM " . TMP_TRACKER_TABLE); // Active users -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT user_id) AS u_bt_active FROM ". TMP_TRACKER_TABLE); +$stat += DB()->fetch_row("SELECT COUNT(DISTINCT user_id) AS u_bt_active FROM " . TMP_TRACKER_TABLE); // All bt-users -$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bt_all FROM ". BB_BT_USERS); +$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bt_all FROM " . BB_BT_USERS); // All bb-users -$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bb_all FROM ". BB_USERS); +$stat += DB()->fetch_row("SELECT COUNT(*) AS u_bb_all FROM " . BB_USERS); // Active torrents -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_active FROM ". TMP_TRACKER_TABLE); +$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_active FROM " . TMP_TRACKER_TABLE); // With seeder -$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_with_seeder FROM ". TMP_TRACKER_TABLE ." WHERE seeder = 1"); +$stat += DB()->fetch_row("SELECT COUNT(DISTINCT topic_id) AS tor_with_seeder FROM " . TMP_TRACKER_TABLE . " WHERE seeder = 1"); // All torrents -$stat += DB()->fetch_row("SELECT COUNT(*) AS tor_all, SUM(size) AS torrents_size FROM ". BB_BT_TORRENTS); +$stat += DB()->fetch_row("SELECT COUNT(*) AS tor_all, SUM(size) AS torrents_size FROM " . BB_BT_TORRENTS); // Last xx minutes $peers_in_last_min = array(); -foreach ($peers_in_last_minutes as $t) -{ - $row = DB()->fetch_row(" - SELECT COUNT(*) AS peers FROM ". TMP_TRACKER_TABLE ." WHERE update_time >= ". (TIMENOW - 60*$t) ." +foreach ($peers_in_last_minutes as $t) { + $row = DB()->fetch_row(" + SELECT COUNT(*) AS peers FROM " . TMP_TRACKER_TABLE . " WHERE update_time >= " . (TIMENOW - 60 * $t) . " "); - $peers_in_last_min[$t] = (int) $row['peers']; + $peers_in_last_min[$t] = (int)$row['peers']; } // Last xx seconds $peers_in_last_sec = array(); -$rowset = DB()->fetch_rowset("SELECT COUNT(*) AS peers FROM ". TMP_TRACKER_TABLE ." GROUP BY update_time DESC LIMIT $peers_in_last_sec_limit"); -foreach ($rowset as $cnt => $row) -{ - $peers_in_last_sec[] = sprintf('%3s', $row['peers']) . (($cnt && !(++$cnt%15)) ? " \n" : ''); +$rowset = DB()->fetch_rowset("SELECT COUNT(*) AS peers FROM " . TMP_TRACKER_TABLE . " GROUP BY update_time DESC LIMIT $peers_in_last_sec_limit"); +foreach ($rowset as $cnt => $row) { + $peers_in_last_sec[] = sprintf('%3s', $row['peers']) . (($cnt && !(++$cnt % 15)) ? " \n" : ''); } -function commify_callback ($matches) +function commify_callback($matches) { - return commify($matches[0]); + return commify($matches[0]); } -function commify_ob ($contents) + +function commify_ob($contents) { - return preg_replace_callback("#\b\d+\b#", 'commify_callback', $contents); + return preg_replace_callback("#\b\d+\b#", 'commify_callback', $contents); } + ob_start('commify_ob'); echo ''; @@ -92,7 +117,7 @@ echo "\n $stat[tor_all] / $stat[tor_active] / $stat[tor_with_seeder]   - [ ". humn_size($stat['torrents_size']) ." ] + [ " . humn_size($stat['torrents_size']) . " ] \n"; @@ -101,36 +126,34 @@ echo "\n $stat[p_all] / $stat[p_within_ann]   - [ up: ". humn_size($stat['speed_up']) ."/s, - down: ". humn_size($stat['speed_down']) ."/s ] + [ up: " . humn_size($stat['speed_up']) . "/s, + down: " . humn_size($stat['speed_down']) . "/s ] \n"; -echo "\n peers: in last ". join(' / ', $peers_in_last_minutes) ." min\n"; -echo "\n". join(' / ', $peers_in_last_min) ."\n"; +echo "\n peers: in last " . join(' / ', $peers_in_last_minutes) . " min\n"; +echo "\n" . join(' / ', $peers_in_last_min) . "\n"; -echo "\n peers in last $peers_in_last_sec_limit sec
[ per second, DESC order --> ]
last peer: $stat[last_peer_time] seconds ago
". date("j M H:i:s [T O]") ." \n"; -echo '
 '. join(' ', $peers_in_last_sec) ."
\n"; +echo "\n peers in last $peers_in_last_sec_limit sec
[ per second, DESC order --> ]
last peer: $stat[last_peer_time] seconds ago
" . date("j M H:i:s [T O]") . " \n"; +echo '
 ' . join(' ', $peers_in_last_sec) . "
\n"; echo ''; echo '
';
 
-if ($l = sys('la'))
-{
-	$l = explode(' ', $l);
-	for ($i=0; $i < 3; $i++)
-	{
-		$l[$i] = round($l[$i], 1);
-	}
-	echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
+if ($l = sys('la')) {
+    $l = explode(' ', $l);
+    for ($i = 0; $i < 3; $i++) {
+        $l[$i] = round($l[$i], 1);
+    }
+    echo "\n\nloadavg: $l[0] $l[1] $l[2]\n\n";
 }
 
-echo 'gen time: '. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ." sec\n";
+echo 'gen time: ' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . " sec\n";
 
 echo '
'; echo ''; -DB()->query("DROP TEMPORARY TABLE ". TMP_TRACKER_TABLE); +DB()->query("DROP TEMPORARY TABLE " . TMP_TRACKER_TABLE); -bb_exit(); \ No newline at end of file +bb_exit(); diff --git a/ajax.php b/ajax.php index b0d3e8b0b..92b6fb2ac 100644 --- a/ajax.php +++ b/ajax.php @@ -1,4 +1,27 @@ init(); $user->session_start(); // Exit if board is disabled via ON/OFF trigger or by admin -if ($ajax->action != 'manage_admin') -{ - if ($bb_cfg['board_disable']) - { - $ajax->ajax_die($lang['BOARD_DISABLE']); - } - else if (file_exists(BB_DISABLED)) - { - $ajax->ajax_die($lang['BOARD_DISABLE_CRON']); - } +if ($ajax->action != 'manage_admin') { + if ($bb_cfg['board_disable']) { + $ajax->ajax_die($lang['BOARD_DISABLE']); + } elseif (file_exists(BB_DISABLED)) { + $ajax->ajax_die($lang['BOARD_DISABLE_CRON']); + } } // Load actions required modules -switch ($ajax->action) -{ - case 'view_post': - require(INC_DIR . 'bbcode.php'); - break; +switch ($ajax->action) { + case 'view_post': + require(INC_DIR . 'bbcode.php'); + break; - case 'posts': - case 'post_mod_comment': - require(INC_DIR . 'bbcode.php'); - require(INC_DIR . 'functions_post.php'); - require(INC_DIR . 'functions_admin.php'); - break; + case 'posts': + case 'post_mod_comment': + require(INC_DIR . 'bbcode.php'); + require(INC_DIR . 'functions_post.php'); + require(INC_DIR . 'functions_admin.php'); + break; - case 'view_torrent': - case 'mod_action': - case 'change_tor_status': - case 'gen_passkey': - require(ATTACH_DIR . 'attachment_mod.php'); - require(INC_DIR . 'functions_torrent.php'); - break; + case 'view_torrent': + case 'mod_action': + case 'change_tor_status': + case 'gen_passkey': + require(ATTACH_DIR . 'attachment_mod.php'); + require(INC_DIR . 'functions_torrent.php'); + break; - case 'change_torrent': - require(ATTACH_DIR . 'attachment_mod.php'); - require(INC_DIR . 'functions_torrent.php'); - break; + case 'change_torrent': + require(ATTACH_DIR . 'attachment_mod.php'); + require(INC_DIR . 'functions_torrent.php'); + break; - case 'user_register': - require(INC_DIR . 'functions_validate.php'); - break; + case 'user_register': + require(INC_DIR . 'functions_validate.php'); + break; - case 'manage_user': - case 'manage_admin': - require(INC_DIR . 'functions_admin.php'); - break; + case 'manage_user': + case 'manage_admin': + require(INC_DIR . 'functions_admin.php'); + break; - case 'group_membership': - case 'manage_group': - require(INC_DIR . 'functions_group.php'); - break; + case 'group_membership': + case 'manage_group': + require(INC_DIR . 'functions_group.php'); + break; - case 'sitemap'; - require(CLASS_DIR .'sitemap.php'); - break; + case 'sitemap'; + require(CLASS_DIR . 'sitemap.php'); + break; } // Position in $ajax->valid_actions['xxx'] @@ -81,348 +99,330 @@ $ajax->exec(); // class ajax_common { - var $request = array(); - var $response = array(); + public $request = array(); + public $response = array(); - var $valid_actions = array( - // ACTION NAME AJAX_AUTH - 'edit_user_profile' => array('admin'), - 'change_user_rank' => array('admin'), - 'change_user_opt' => array('admin'), - 'manage_user' => array('admin'), - 'manage_admin' => array('admin'), - 'sitemap' => array('admin'), + public $valid_actions = array( + // ACTION NAME AJAX_AUTH + 'edit_user_profile' => array('admin'), + 'change_user_rank' => array('admin'), + 'change_user_opt' => array('admin'), + 'manage_user' => array('admin'), + 'manage_admin' => array('admin'), + 'sitemap' => array('admin'), - 'mod_action' => array('mod'), - 'topic_tpl' => array('mod'), - 'group_membership' => array('mod'), - 'post_mod_comment' => array('mod'), + 'mod_action' => array('mod'), + 'topic_tpl' => array('mod'), + 'group_membership' => array('mod'), + 'post_mod_comment' => array('mod'), - 'avatar' => array('user'), - 'gen_passkey' => array('user'), - 'change_torrent' => array('user'), - 'change_tor_status' => array('user'), - 'manage_group' => array('user'), + 'avatar' => array('user'), + 'gen_passkey' => array('user'), + 'change_torrent' => array('user'), + 'change_tor_status' => array('user'), + 'manage_group' => array('user'), - 'view_post' => array('guest'), - 'view_torrent' => array('guest'), - 'user_register' => array('guest'), - 'posts' => array('guest'), - 'index_data' => array('guest'), - ); + 'view_post' => array('guest'), + 'view_torrent' => array('guest'), + 'user_register' => array('guest'), + 'posts' => array('guest'), + 'index_data' => array('guest'), + ); - var $action = null; + public $action = null; - /** - * Constructor - */ - function ajax_common() - { - ob_start(array(&$this, 'ob_handler')); - header('Content-Type: text/plain'); - } + /** + * Constructor + */ + public function ajax_common() + { + ob_start(array(&$this, 'ob_handler')); + header('Content-Type: text/plain'); + } - /** - * Perform action - */ - function exec() - { - global $lang; + /** + * Perform action + */ + public function exec() + { + global $lang; - // Exit if we already have errors - if (!empty($this->response['error_code'])) - { - $this->send(); - } + // Exit if we already have errors + if (!empty($this->response['error_code'])) { + $this->send(); + } - // Check that requested action is valid - $action = $this->action; + // Check that requested action is valid + $action = $this->action; - if (!$action || !is_string($action)) - { - $this->ajax_die('no action specified'); - } - elseif (!$action_params =& $this->valid_actions[$action]) - { - $this->ajax_die('invalid action: ' . $action); - } + if (!$action || !is_string($action)) { + $this->ajax_die('no action specified'); + } elseif (!$action_params =& $this->valid_actions[$action]) { + $this->ajax_die('invalid action: ' . $action); + } - // Auth check - switch ($action_params[AJAX_AUTH]) - { - // GUEST - case 'guest': - break; + // Auth check + switch ($action_params[AJAX_AUTH]) { + // GUEST + case 'guest': + break; - // USER - case 'user': - if (IS_GUEST) - { - $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); - } - break; + // USER + case 'user': + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } + break; - // MOD - case 'mod': - if (!IS_AM) - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } - $this->check_admin_session(); - break; + // MOD + case 'mod': + if (!IS_AM) { + $this->ajax_die($lang['ONLY_FOR_MOD']); + } + $this->check_admin_session(); + break; - // ADMIN - case 'admin': - if (!IS_ADMIN) - { - $this->ajax_die($lang['ONLY_FOR_ADMIN']); - } - $this->check_admin_session(); - break; + // ADMIN + case 'admin': + if (!IS_ADMIN) { + $this->ajax_die($lang['ONLY_FOR_ADMIN']); + } + $this->check_admin_session(); + break; - // SUPER_ADMIN - case 'super_admin': - if (!IS_SUPER_ADMIN) - { - $this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']); - } - $this->check_admin_session(); - break; + // SUPER_ADMIN + case 'super_admin': + if (!IS_SUPER_ADMIN) { + $this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']); + } + $this->check_admin_session(); + break; - default: - trigger_error("invalid auth type for $action", E_USER_ERROR); - } + default: + trigger_error("invalid auth type for $action", E_USER_ERROR); + } - // Run action - $this->$action(); + // Run action + $this->$action(); - // Send output - $this->send(); - } + // Send output + $this->send(); + } - /** - * Exit on error - */ - function ajax_die($error_msg, $error_code = E_AJAX_GENERAL_ERROR) - { - $this->response['error_code'] = $error_code; - $this->response['error_msg'] = $error_msg; + /** + * Exit on error + */ + public function ajax_die($error_msg, $error_code = E_AJAX_GENERAL_ERROR) + { + $this->response['error_code'] = $error_code; + $this->response['error_msg'] = $error_msg; - $this->send(); - } + $this->send(); + } - /** - * Initialization - */ - function init() - { - $this->request = $_POST; - $this->action =& $this->request['action']; - } + /** + * Initialization + */ + public function init() + { + $this->request = $_POST; + $this->action =& $this->request['action']; + } - /** - * Send data - */ - function send() - { - $this->response['action'] = $this->action; + /** + * Send data + */ + public function send() + { + $this->response['action'] = $this->action; - if (DBG_USER && SQL_DEBUG && !empty($_COOKIE['sql_log'])) - { - $this->response['sql_log'] = get_sql_log(); - } + if (DBG_USER && SQL_DEBUG && !empty($_COOKIE['sql_log'])) { + $this->response['sql_log'] = get_sql_log(); + } - // sending output will be handled by $this->ob_handler() - exit(); - } + // sending output will be handled by $this->ob_handler() + exit(); + } - /** - * OB Handler - */ - function ob_handler($contents) - { - if (DBG_USER) - { - if ($contents) - { - $this->response['raw_output'] = $contents; - } - } + /** + * OB Handler + */ + public function ob_handler($contents) + { + if (DBG_USER) { + if ($contents) { + $this->response['raw_output'] = $contents; + } + } - $response_js = Zend\Json\Json::encode($this->response); + $response_js = Zend\Json\Json::encode($this->response); - if (GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) - { - if (UA_GZIP_SUPPORTED && strlen($response_js) > 2000) - { - header('Content-Encoding: gzip'); - $response_js = gzencode($response_js, 1); - } - } + if (GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) { + if (UA_GZIP_SUPPORTED && strlen($response_js) > 2000) { + header('Content-Encoding: gzip'); + $response_js = gzencode($response_js, 1); + } + } - return $response_js; - } + return $response_js; + } - /** - * Admin session - */ - function check_admin_session() - { - global $user; + /** + * Admin session + */ + public function check_admin_session() + { + global $user; - if (!$user->data['session_admin']) - { - if (empty($this->request['user_password'])) - { - $this->prompt_for_password(); - } - else - { - $login_args = array( - 'login_username' => $user->data['username'], - 'login_password' => $_POST['user_password'], - ); - if (!$user->login($login_args, true)) - { - $this->ajax_die('Wrong password'); - } - } - } - } + if (!$user->data['session_admin']) { + if (empty($this->request['user_password'])) { + $this->prompt_for_password(); + } else { + $login_args = array( + 'login_username' => $user->data['username'], + 'login_password' => $_POST['user_password'], + ); + if (!$user->login($login_args, true)) { + $this->ajax_die('Wrong password'); + } + } + } + } - /** - * Prompt for password - */ - function prompt_for_password() - { - $this->response['prompt_password'] = 1; - $this->send(); - } + /** + * Prompt for password + */ + public function prompt_for_password() + { + $this->response['prompt_password'] = 1; + $this->send(); + } - /** - * Prompt for confirmation - */ - function prompt_for_confirm($confirm_msg) - { - if (empty($confirm_msg)) $this->ajax_die('false'); + /** + * Prompt for confirmation + */ + public function prompt_for_confirm($confirm_msg) + { + if (empty($confirm_msg)) { + $this->ajax_die('false'); + } - $this->response['prompt_confirm'] = 1; - $this->response['confirm_msg'] = $confirm_msg; - $this->send(); - } + $this->response['prompt_confirm'] = 1; + $this->response['confirm_msg'] = $confirm_msg; + $this->send(); + } - /** - * Verify mod rights - */ - function verify_mod_rights($forum_id) - { - global $userdata, $lang; + /** + * Verify mod rights + */ + public function verify_mod_rights($forum_id) + { + global $userdata, $lang; - $is_auth = auth(AUTH_MOD, $forum_id, $userdata); + $is_auth = auth(AUTH_MOD, $forum_id, $userdata); - if (!$is_auth['auth_mod']) - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } - } + if (!$is_auth['auth_mod']) { + $this->ajax_die($lang['ONLY_FOR_MOD']); + } + } - function edit_user_profile() - { - require(AJAX_DIR . 'edit_user_profile.php'); - } + public function edit_user_profile() + { + require(AJAX_DIR . 'edit_user_profile.php'); + } - function change_user_rank() - { - require(AJAX_DIR . 'change_user_rank.php'); - } + public function change_user_rank() + { + require(AJAX_DIR . 'change_user_rank.php'); + } - function change_user_opt() - { - require(AJAX_DIR . 'change_user_opt.php'); - } + public function change_user_opt() + { + require(AJAX_DIR . 'change_user_opt.php'); + } - function gen_passkey() - { - require(AJAX_DIR . 'gen_passkey.php'); - } + public function gen_passkey() + { + require(AJAX_DIR . 'gen_passkey.php'); + } - function group_membership() - { - require(AJAX_DIR . 'group_membership.php'); - } + public function group_membership() + { + require(AJAX_DIR . 'group_membership.php'); + } - function manage_group() - { - require(AJAX_DIR . 'edit_group_profile.php'); - } + public function manage_group() + { + require(AJAX_DIR . 'edit_group_profile.php'); + } - function post_mod_comment() - { - require(AJAX_DIR . 'post_mod_comment.php'); - } + public function post_mod_comment() + { + require(AJAX_DIR . 'post_mod_comment.php'); + } - function view_post() - { - require(AJAX_DIR . 'view_post.php'); - } + public function view_post() + { + require(AJAX_DIR . 'view_post.php'); + } - function change_tor_status() - { - require(AJAX_DIR . 'change_tor_status.php'); - } + public function change_tor_status() + { + require(AJAX_DIR . 'change_tor_status.php'); + } - function change_torrent() - { - require(AJAX_DIR . 'change_torrent.php'); - } + public function change_torrent() + { + require(AJAX_DIR . 'change_torrent.php'); + } - function view_torrent() - { - require(AJAX_DIR . 'view_torrent.php'); - } + public function view_torrent() + { + require(AJAX_DIR . 'view_torrent.php'); + } - function user_register() - { - require(AJAX_DIR . 'user_register.php'); - } + public function user_register() + { + require(AJAX_DIR . 'user_register.php'); + } - function mod_action() - { - require(AJAX_DIR . 'mod_action.php'); - } + public function mod_action() + { + require(AJAX_DIR . 'mod_action.php'); + } - function posts() - { - require(AJAX_DIR . 'posts.php'); - } + public function posts() + { + require(AJAX_DIR . 'posts.php'); + } - function manage_user() - { - require(AJAX_DIR . 'manage_user.php'); - } + public function manage_user() + { + require(AJAX_DIR . 'manage_user.php'); + } - function manage_admin() - { - require(AJAX_DIR . 'manage_admin.php'); - } + public function manage_admin() + { + require(AJAX_DIR . 'manage_admin.php'); + } - function topic_tpl() - { - require(AJAX_DIR . 'topic_tpl.php'); - } + public function topic_tpl() + { + require(AJAX_DIR . 'topic_tpl.php'); + } - function index_data() - { - require(AJAX_DIR . 'index_data.php'); - } + public function index_data() + { + require(AJAX_DIR . 'index_data.php'); + } - function avatar() - { - require(AJAX_DIR . 'avatar.php'); - } + public function avatar() + { + require(AJAX_DIR . 'avatar.php'); + } - function sitemap() - { - require(AJAX_DIR .'sitemap.php'); - } -} \ No newline at end of file + public function sitemap() + { + require(AJAX_DIR . 'sitemap.php'); + } +} diff --git a/bt/announce.php b/bt/announce.php index 70fc72331..a66fd5c9a 100644 --- a/bt/announce.php +++ b/bt/announce.php @@ -1,185 +1,190 @@ 0xFFFF) -{ - msg_die('Invalid port'); +if (!isset($port) || $port < 0 || $port > 0xFFFF) { + msg_die('Invalid port'); } -if (!isset($uploaded) || $uploaded < 0 || $uploaded > $max_up_down_val || $uploaded == 1844674407370) -{ - msg_die('Invalid uploaded value'); +if (!isset($uploaded) || $uploaded < 0 || $uploaded > $max_up_down_val || $uploaded == 1844674407370) { + msg_die('Invalid uploaded value'); } -if (!isset($downloaded) || $downloaded < 0 || $downloaded > $max_up_down_val || $downloaded == 1844674407370) -{ - msg_die('Invalid downloaded value'); +if (!isset($downloaded) || $downloaded < 0 || $downloaded > $max_up_down_val || $downloaded == 1844674407370) { + msg_die('Invalid downloaded value'); } -if (!isset($left) || $left < 0 || $left > $max_left_val) -{ - msg_die('Invalid left value'); +if (!isset($left) || $left < 0 || $left > $max_left_val) { + msg_die('Invalid left value'); } -if (!verify_id($passkey, BT_AUTH_KEY_LENGTH)) -{ - msg_die('Invalid passkey'); +if (!verify_id($passkey, BT_AUTH_KEY_LENGTH)) { + msg_die('Invalid passkey'); } // IP $ip = $_SERVER['REMOTE_ADDR']; -if (!$bb_cfg['ignore_reported_ip'] && isset($_GET['ip']) && $ip !== $_GET['ip']) -{ - if (!$bb_cfg['verify_reported_ip']) - { - $ip = $_GET['ip']; - } - elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) - { - foreach ($matches[0] as $x_ip) - { - if ($x_ip === $_GET['ip']) - { - if (!$bb_cfg['allow_internal_ip'] && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip)) - { - break; - } - $ip = $x_ip; - break; - } - } - } +if (!$bb_cfg['ignore_reported_ip'] && isset($_GET['ip']) && $ip !== $_GET['ip']) { + if (!$bb_cfg['verify_reported_ip']) { + $ip = $_GET['ip']; + } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) { + foreach ($matches[0] as $x_ip) { + if ($x_ip === $_GET['ip']) { + if (!$bb_cfg['allow_internal_ip'] && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip)) { + break; + } + $ip = $x_ip; + break; + } + } + } } // Check that IP format is valid -if (!verify_ip($ip)) -{ - msg_die("Invalid IP: $ip"); +if (!verify_ip($ip)) { + msg_die("Invalid IP: $ip"); } // Convert IP to HEX format $ip_sql = encode_ip($ip); // Peer unique id $peer_hash = md5( - rtrim($info_hash, ' ') . $passkey . $ip . $port + rtrim($info_hash, ' ') . $passkey . $ip . $port ); // Get cached peer info from previous announce (last peer info) $lp_info = CACHE('tr_cache')->get(PEER_HASH_PREFIX . $peer_hash); -if (DBG_LOG) dbg_log(' ', '$lp_info-get_from-CACHE-'. ($lp_info ? 'hit' : 'miss')); +if (DBG_LOG) { + dbg_log(' ', '$lp_info-get_from-CACHE-' . ($lp_info ? 'hit' : 'miss')); +} // Drop fast announce -if ($lp_info && (!isset($event) || $event !== 'stopped')) -{ - drop_fast_announce($lp_info); +if ($lp_info && (!isset($event) || $event !== 'stopped')) { + drop_fast_announce($lp_info); } // Functions -function drop_fast_announce ($lp_info) +function drop_fast_announce($lp_info) { - global $announce_interval; + global $announce_interval; - if ($lp_info['update_time'] < (TIMENOW - $announce_interval + 60)) - { - return; // if announce interval correct - } + if ($lp_info['update_time'] < (TIMENOW - $announce_interval + 60)) { + return; // if announce interval correct + } - $new_ann_intrv = $lp_info['update_time'] + $announce_interval - TIMENOW; + $new_ann_intrv = $lp_info['update_time'] + $announce_interval - TIMENOW; - dummy_exit($new_ann_intrv); + dummy_exit($new_ann_intrv); } -function msg_die ($msg) +function msg_die($msg) { - if (DBG_LOG) dbg_log(' ', '!die-'. clean_filename($msg)); + if (DBG_LOG) { + dbg_log(' ', '!die-' . clean_filename($msg)); + } - $output = bencode(array( + $output = bencode(array( # 'interval' => (int) 1800, - 'min interval' => (int) 1800, + 'min interval' => (int)1800, # 'peers' => (string) DUMMY_PEER, - 'failure reason' => (string) $msg, - 'warning message' => (string) $msg, - )); + 'failure reason' => (string)$msg, + 'warning message' => (string)$msg, + )); - die($output); + die($output); } # $agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-'; @@ -189,160 +194,137 @@ function msg_die ($msg) define('TR_ROOT', './'); require(TR_ROOT . 'includes/init_tr.php'); -$seeder = ($left == 0) ? 1 : 0; +$seeder = ($left == 0) ? 1 : 0; $stopped = ($event === 'stopped'); // Stopped event -if ($stopped) -{ - CACHE('tr_cache')->rm(PEER_HASH_PREFIX . $peer_hash); - if (DBG_LOG) dbg_log(' ', 'stopped'); +if ($stopped) { + CACHE('tr_cache')->rm(PEER_HASH_PREFIX . $peer_hash); + if (DBG_LOG) { + dbg_log(' ', 'stopped'); + } } // Get last peer info from DB -if (!CACHE('tr_cache')->used && !$lp_info) -{ - $lp_info = DB()->fetch_row(" - SELECT * FROM ". BB_BT_TRACKER ." WHERE peer_hash = '$peer_hash' LIMIT 1 +if (!CACHE('tr_cache')->used && !$lp_info) { + $lp_info = DB()->fetch_row(" + SELECT * FROM " . BB_BT_TRACKER . " WHERE peer_hash = '$peer_hash' LIMIT 1 "); - if (DBG_LOG) dbg_log(' ', '$lp_info-get_from-DB-'. ($lp_info ? 'hit' : 'miss')); + if (DBG_LOG) { + dbg_log(' ', '$lp_info-get_from-DB-' . ($lp_info ? 'hit' : 'miss')); + } } -if ($lp_info) -{ - if (!$stopped) - { - drop_fast_announce($lp_info); - } +if ($lp_info) { + if (!$stopped) { + drop_fast_announce($lp_info); + } - $user_id = $lp_info['user_id']; - $topic_id = $lp_info['topic_id']; - $releaser = $lp_info['releaser']; - $tor_type = $lp_info['tor_type']; -} -else -{ - // Verify if torrent registered on tracker and user authorized - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - $passkey_sql = DB()->escape($passkey); + $user_id = $lp_info['user_id']; + $topic_id = $lp_info['topic_id']; + $releaser = $lp_info['releaser']; + $tor_type = $lp_info['tor_type']; +} else { + // Verify if torrent registered on tracker and user authorized + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + $passkey_sql = DB()->escape($passkey); - $sql = " + $sql = " SELECT tor.topic_id, tor.poster_id, tor.tor_type, u.* - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_BT_USERS ." u ON u.auth_key = '$passkey_sql' + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_BT_USERS . " u ON u.auth_key = '$passkey_sql' WHERE tor.info_hash = '$info_hash_sql' LIMIT 1 "; - $row = DB()->fetch_row($sql); + $row = DB()->fetch_row($sql); - if (empty($row['topic_id'])) - { - msg_die('Torrent not registered, info_hash = ' . bin2hex($info_hash_sql)); - } - if (empty($row['user_id'])) - { - msg_die('Please LOG IN and REDOWNLOAD this torrent (user not found)'); - } + if (empty($row['topic_id'])) { + msg_die('Torrent not registered, info_hash = ' . bin2hex($info_hash_sql)); + } + if (empty($row['user_id'])) { + msg_die('Please LOG IN and REDOWNLOAD this torrent (user not found)'); + } - $user_id = $row['user_id']; - $topic_id = $row['topic_id']; - $releaser = (int) ($user_id == $row['poster_id']); - $tor_type = $row['tor_type']; + $user_id = $row['user_id']; + $topic_id = $row['topic_id']; + $releaser = (int)($user_id == $row['poster_id']); + $tor_type = $row['tor_type']; - // Ratio limits - if ((TR_RATING_LIMITS || $tr_cfg['limit_concurrent_ips']) && !$stopped) - { - $user_ratio = ($row['u_down_total'] && $row['u_down_total'] > MIN_DL_FOR_RATIO) ? ($row['u_up_total'] + $row['u_up_release'] + $row['u_up_bonus']) / $row['u_down_total'] : 1; - $rating_msg = ''; + // Ratio limits + if ((TR_RATING_LIMITS || $tr_cfg['limit_concurrent_ips']) && !$stopped) { + $user_ratio = ($row['u_down_total'] && $row['u_down_total'] > MIN_DL_FOR_RATIO) ? ($row['u_up_total'] + $row['u_up_release'] + $row['u_up_bonus']) / $row['u_down_total'] : 1; + $rating_msg = ''; - if (!$seeder) - { - foreach ($rating_limits as $ratio => $limit) - { - if ($user_ratio < $ratio) - { - $tr_cfg['limit_active_tor'] = 1; - $tr_cfg['limit_leech_count'] = $limit; - $rating_msg = " (ratio < $ratio)"; - break; - } - } - } + if (!$seeder) { + foreach ($rating_limits as $ratio => $limit) { + if ($user_ratio < $ratio) { + $tr_cfg['limit_active_tor'] = 1; + $tr_cfg['limit_leech_count'] = $limit; + $rating_msg = " (ratio < $ratio)"; + break; + } + } + } - // Limit active torrents - if (!isset($bb_cfg['unlimited_users'][$user_id]) && $tr_cfg['limit_active_tor'] && (($tr_cfg['limit_seed_count'] && $seeder) || ($tr_cfg['limit_leech_count'] && !$seeder))) - { - $sql = "SELECT COUNT(DISTINCT topic_id) AS active_torrents - FROM ". BB_BT_TRACKER ." + // Limit active torrents + if (!isset($bb_cfg['unlimited_users'][$user_id]) && $tr_cfg['limit_active_tor'] && (($tr_cfg['limit_seed_count'] && $seeder) || ($tr_cfg['limit_leech_count'] && !$seeder))) { + $sql = "SELECT COUNT(DISTINCT topic_id) AS active_torrents + FROM " . BB_BT_TRACKER . " WHERE user_id = $user_id AND seeder = $seeder AND topic_id != $topic_id"; - if (!$seeder && $tr_cfg['leech_expire_factor'] && $user_ratio < 0.5) - { - $sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']); - } - $sql .= " GROUP BY user_id"; + if (!$seeder && $tr_cfg['leech_expire_factor'] && $user_ratio < 0.5) { + $sql .= " AND update_time > " . (TIMENOW - 60 * $tr_cfg['leech_expire_factor']); + } + $sql .= " GROUP BY user_id"; - if ($row = DB()->fetch_row($sql)) - { - if ($seeder && $tr_cfg['limit_seed_count'] && $row['active_torrents'] >= $tr_cfg['limit_seed_count']) - { - msg_die('Only '. $tr_cfg['limit_seed_count'] .' torrent(s) allowed for seeding'); - } - elseif (!$seeder && $tr_cfg['limit_leech_count'] && $row['active_torrents'] >= $tr_cfg['limit_leech_count']) - { - msg_die('Only '. $tr_cfg['limit_leech_count'] .' torrent(s) allowed for leeching'. $rating_msg); - } - } - } + if ($row = DB()->fetch_row($sql)) { + if ($seeder && $tr_cfg['limit_seed_count'] && $row['active_torrents'] >= $tr_cfg['limit_seed_count']) { + msg_die('Only ' . $tr_cfg['limit_seed_count'] . ' torrent(s) allowed for seeding'); + } elseif (!$seeder && $tr_cfg['limit_leech_count'] && $row['active_torrents'] >= $tr_cfg['limit_leech_count']) { + msg_die('Only ' . $tr_cfg['limit_leech_count'] . ' torrent(s) allowed for leeching' . $rating_msg); + } + } + } - // Limit concurrent IPs - if ($tr_cfg['limit_concurrent_ips'] && (($tr_cfg['limit_seed_ips'] && $seeder) || ($tr_cfg['limit_leech_ips'] && !$seeder))) - { - $sql = "SELECT COUNT(DISTINCT ip) AS ips - FROM ". BB_BT_TRACKER ." + // Limit concurrent IPs + if ($tr_cfg['limit_concurrent_ips'] && (($tr_cfg['limit_seed_ips'] && $seeder) || ($tr_cfg['limit_leech_ips'] && !$seeder))) { + $sql = "SELECT COUNT(DISTINCT ip) AS ips + FROM " . BB_BT_TRACKER . " WHERE topic_id = $topic_id AND user_id = $user_id AND seeder = $seeder AND ip != '$ip_sql'"; - if (!$seeder && $tr_cfg['leech_expire_factor']) - { - $sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']); - } - $sql .= " GROUP BY topic_id"; + if (!$seeder && $tr_cfg['leech_expire_factor']) { + $sql .= " AND update_time > " . (TIMENOW - 60 * $tr_cfg['leech_expire_factor']); + } + $sql .= " GROUP BY topic_id"; - if ($row = DB()->fetch_row($sql)) - { - if ($seeder && $tr_cfg['limit_seed_ips'] && $row['ips'] >= $tr_cfg['limit_seed_ips']) - { - msg_die('You can seed only from '. $tr_cfg['limit_seed_ips'] ." IP's"); - } - elseif (!$seeder && $tr_cfg['limit_leech_ips'] && $row['ips'] >= $tr_cfg['limit_leech_ips']) - { - msg_die('You can leech only from '. $tr_cfg['limit_leech_ips'] ." IP's"); - } - } - } - } + if ($row = DB()->fetch_row($sql)) { + if ($seeder && $tr_cfg['limit_seed_ips'] && $row['ips'] >= $tr_cfg['limit_seed_ips']) { + msg_die('You can seed only from ' . $tr_cfg['limit_seed_ips'] . " IP's"); + } elseif (!$seeder && $tr_cfg['limit_leech_ips'] && $row['ips'] >= $tr_cfg['limit_leech_ips']) { + msg_die('You can leech only from ' . $tr_cfg['limit_leech_ips'] . " IP's"); + } + } + } + } } // Up/Down speed $speed_up = $speed_down = 0; -if ($lp_info && $lp_info['update_time'] < TIMENOW) -{ - if ($uploaded > $lp_info['uploaded']) - { - $speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time'])); - } - if ($downloaded > $lp_info['downloaded']) - { - $speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time'])); - } +if ($lp_info && $lp_info['update_time'] < TIMENOW) { + if ($uploaded > $lp_info['uploaded']) { + $speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time'])); + } + if ($downloaded > $lp_info['downloaded']) { + $speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time'])); + } } // Up/Down addition @@ -350,156 +332,152 @@ $up_add = ($lp_info && $uploaded > $lp_info['uploaded']) ? $uploaded - $lp_info[ $down_add = ($lp_info && $downloaded > $lp_info['downloaded']) ? $downloaded - $lp_info['downloaded'] : 0; // Gold/Silver releases -if ($tr_cfg['gold_silver_enabled'] && $down_add) -{ - if ($tor_type == TOR_TYPE_GOLD) - { - $down_add = 0; - } - // Silver releases - elseif ($tor_type == TOR_TYPE_SILVER) - { - $down_add = ceil($down_add/2); - } +if ($tr_cfg['gold_silver_enabled'] && $down_add) { + if ($tor_type == TOR_TYPE_GOLD) { + $down_add = 0; + } // Silver releases + elseif ($tor_type == TOR_TYPE_SILVER) { + $down_add = ceil($down_add / 2); + } } // Insert/update peer info $peer_info_updated = false; $update_time = ($stopped) ? 0 : TIMENOW; -if ($lp_info) -{ - $sql = "UPDATE ". BB_BT_TRACKER ." SET update_time = $update_time"; +if ($lp_info) { + $sql = "UPDATE " . BB_BT_TRACKER . " SET update_time = $update_time"; - $sql .= ", seeder = $seeder"; - $sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : ''; + $sql .= ", seeder = $seeder"; + $sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : ''; - $sql .= ($tor_type != $lp_info['tor_type']) ? ", tor_type = $tor_type" : ''; + $sql .= ($tor_type != $lp_info['tor_type']) ? ", tor_type = $tor_type" : ''; - $sql .= ($uploaded != $lp_info['uploaded']) ? ", uploaded = $uploaded" : ''; - $sql .= ($downloaded != $lp_info['downloaded']) ? ", downloaded = $downloaded" : ''; - $sql .= ", remain = $left"; + $sql .= ($uploaded != $lp_info['uploaded']) ? ", uploaded = $uploaded" : ''; + $sql .= ($downloaded != $lp_info['downloaded']) ? ", downloaded = $downloaded" : ''; + $sql .= ", remain = $left"; - $sql .= ($up_add) ? ", up_add = up_add + $up_add" : ''; - $sql .= ($down_add) ? ", down_add = down_add + $down_add" : ''; + $sql .= ($up_add) ? ", up_add = up_add + $up_add" : ''; + $sql .= ($down_add) ? ", down_add = down_add + $down_add" : ''; - $sql .= ", speed_up = $speed_up"; - $sql .= ", speed_down = $speed_down"; + $sql .= ", speed_up = $speed_up"; + $sql .= ", speed_down = $speed_down"; - $sql .= " WHERE peer_hash = '$peer_hash'"; - $sql .= " LIMIT 1"; + $sql .= " WHERE peer_hash = '$peer_hash'"; + $sql .= " LIMIT 1"; - DB()->query($sql); + DB()->query($sql); - $peer_info_updated = DB()->affected_rows(); + $peer_info_updated = DB()->affected_rows(); - if (DBG_LOG) dbg_log(' ', 'this_peer-update'. ($peer_info_updated ? '' : '-FAIL')); + if (DBG_LOG) { + dbg_log(' ', 'this_peer-update' . ($peer_info_updated ? '' : '-FAIL')); + } } -if (!$lp_info || !$peer_info_updated) -{ - $columns = 'peer_hash, topic_id, user_id, ip, port, seeder, releaser, tor_type, uploaded, downloaded, remain, speed_up, speed_down, up_add, down_add, update_time'; - $values = "'$peer_hash', $topic_id, $user_id, '$ip_sql', $port, $seeder, $releaser, $tor_type, $uploaded, $downloaded, $left, $speed_up, $speed_down, $up_add, $down_add, $update_time"; +if (!$lp_info || !$peer_info_updated) { + $columns = 'peer_hash, topic_id, user_id, ip, port, seeder, releaser, tor_type, uploaded, downloaded, remain, speed_up, speed_down, up_add, down_add, update_time'; + $values = "'$peer_hash', $topic_id, $user_id, '$ip_sql', $port, $seeder, $releaser, $tor_type, $uploaded, $downloaded, $left, $speed_up, $speed_down, $up_add, $down_add, $update_time"; - DB()->query("REPLACE INTO ". BB_BT_TRACKER ." ($columns) VALUES ($values)"); + DB()->query("REPLACE INTO " . BB_BT_TRACKER . " ($columns) VALUES ($values)"); - if (DBG_LOG) dbg_log(' ', 'this_peer-insert'); + if (DBG_LOG) { + dbg_log(' ', 'this_peer-insert'); + } } // Exit if stopped -if ($stopped) -{ - silent_exit(); +if ($stopped) { + silent_exit(); } // Store peer info in cache $lp_info = array( - 'downloaded' => (float) $downloaded, - 'releaser' => (int) $releaser, - 'seeder' => (int) $seeder, - 'topic_id' => (int) $topic_id, - 'update_time' => (int) TIMENOW, - 'uploaded' => (float) $uploaded, - 'user_id' => (int) $user_id, - 'tor_type' => (int) $tor_type, + 'downloaded' => (float)$downloaded, + 'releaser' => (int)$releaser, + 'seeder' => (int)$seeder, + 'topic_id' => (int)$topic_id, + 'update_time' => (int)TIMENOW, + 'uploaded' => (float)$uploaded, + 'user_id' => (int)$user_id, + 'tor_type' => (int)$tor_type, ); $lp_info_cached = CACHE('tr_cache')->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, PEER_HASH_EXPIRE); -if (DBG_LOG && !$lp_info_cached) dbg_log(' ', '$lp_info-caching-FAIL'); +if (DBG_LOG && !$lp_info_cached) { + dbg_log(' ', '$lp_info-caching-FAIL'); +} // Get cached output $output = CACHE('tr_cache')->get(PEERS_LIST_PREFIX . $topic_id); -if (DBG_LOG) dbg_log(' ', '$output-get_from-CACHE-'. ($output !== false ? 'hit' : 'miss')); +if (DBG_LOG) { + dbg_log(' ', '$output-get_from-CACHE-' . ($output !== false ? 'hit' : 'miss')); +} -if (!$output) -{ - // Retrieve peers - $numwant = (int) $tr_cfg['numwant']; - $compact_mode = ($tr_cfg['compact_mode'] || !empty($compact)); +if (!$output) { + // Retrieve peers + $numwant = (int)$tr_cfg['numwant']; + $compact_mode = ($tr_cfg['compact_mode'] || !empty($compact)); - $rowset = DB()->fetch_rowset(" + $rowset = DB()->fetch_rowset(" SELECT ip, port - FROM ". BB_BT_TRACKER ." + FROM " . BB_BT_TRACKER . " WHERE topic_id = $topic_id ORDER BY RAND() LIMIT $numwant "); - if ($compact_mode) - { - $peers = ''; + if ($compact_mode) { + $peers = ''; - foreach ($rowset as $peer) - { - $peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']); - } - } - else - { - $peers = array(); + foreach ($rowset as $peer) { + $peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']); + } + } else { + $peers = array(); - foreach ($rowset as $peer) - { - $peers[] = array( - 'ip' => decode_ip($peer['ip']), - 'port' => intval($peer['port']), - ); - } - } + foreach ($rowset as $peer) { + $peers[] = array( + 'ip' => decode_ip($peer['ip']), + 'port' => intval($peer['port']), + ); + } + } - $seeders = 0; - $leechers = 0; + $seeders = 0; + $leechers = 0; - if ($tr_cfg['scrape']) - { - $row = DB()->fetch_row(" + if ($tr_cfg['scrape']) { + $row = DB()->fetch_row(" SELECT seeders, leechers - FROM ". BB_BT_TRACKER_SNAP ." + FROM " . BB_BT_TRACKER_SNAP . " WHERE topic_id = $topic_id LIMIT 1 "); - $seeders = $row['seeders']; - $leechers = $row['leechers']; - } + $seeders = $row['seeders']; + $leechers = $row['leechers']; + } - $output = array( - 'interval' => (int) $announce_interval, - 'min interval' => (int) $announce_interval, - 'peers' => $peers, - 'complete' => (int) $seeders, - 'incomplete' => (int) $leechers, - ); + $output = array( + 'interval' => (int)$announce_interval, + 'min interval' => (int)$announce_interval, + 'peers' => $peers, + 'complete' => (int)$seeders, + 'incomplete' => (int)$leechers, + ); - $peers_list_cached = CACHE('tr_cache')->set(PEERS_LIST_PREFIX . $topic_id, $output, PEERS_LIST_EXPIRE); + $peers_list_cached = CACHE('tr_cache')->set(PEERS_LIST_PREFIX . $topic_id, $output, PEERS_LIST_EXPIRE); - if (DBG_LOG && !$peers_list_cached) dbg_log(' ', '$output-caching-FAIL'); + if (DBG_LOG && !$peers_list_cached) { + dbg_log(' ', '$output-caching-FAIL'); + } } // Return data to client echo bencode($output); tracker_exit(); -exit; \ No newline at end of file +exit; diff --git a/bt/includes/init_tr.php b/bt/includes/init_tr.php index 12e2cd139..29f4fa902 100644 --- a/bt/includes/init_tr.php +++ b/bt/includes/init_tr.php @@ -1,489 +1,495 @@ sql_inittime*100/$gen_time); - $sql_total_perc = round($DBS->sql_timetotal*100/$gen_time); + if (DBG_LOG && DBG_TRACKER) { + if ($gen_time = utime() - TIMESTART) { + $sql_init_perc = round($DBS->sql_inittime * 100 / $gen_time); + $sql_total_perc = round($DBS->sql_timetotal * 100 / $gen_time); - $str = array(); - $str[] = substr(TIMENOW, -4, 4); - $str[] = sprintf('%.4f', $gen_time); - $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_inittime, $sql_init_perc); - $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_timetotal, $sql_total_perc); - $str[] = $DBS->num_queries; - $str[] = sprintf('%.1f', sys('la')); - $str = join(LOG_SEPR, $str) . LOG_LF; - dbg_log($str, '!!gentime'); - } - } - exit; + $str = array(); + $str[] = substr(TIMENOW, -4, 4); + $str[] = sprintf('%.4f', $gen_time); + $str[] = sprintf('%.4f' . LOG_SEPR . '%02d%%', $DBS->sql_inittime, $sql_init_perc); + $str[] = sprintf('%.4f' . LOG_SEPR . '%02d%%', $DBS->sql_timetotal, $sql_total_perc); + $str[] = $DBS->num_queries; + $str[] = sprintf('%.1f', sys('la')); + $str = join(LOG_SEPR, $str) . LOG_LF; + dbg_log($str, '!!gentime'); + } + } + exit; } -function silent_exit () +function silent_exit() { - while (@ob_end_clean()); + while (@ob_end_clean()) ; - tracker_exit(); + tracker_exit(); } -function error_exit ($msg = '') +function error_exit($msg = '') { - if (DBG_LOG) dbg_log(' ', '!err-'. clean_filename($msg)); + if (DBG_LOG) { + dbg_log(' ', '!err-' . clean_filename($msg)); + } - silent_exit(); + silent_exit(); - echo bencode(array('failure reason' => str_compact($msg))); + echo bencode(array('failure reason' => str_compact($msg))); - tracker_exit(); + tracker_exit(); } // Database class sql_db { - public $cfg = array(); - public $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); - public $link = null; - public $result = null; - public $db_server = ''; - public $selected_db = null; + public $cfg = array(); + public $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); + public $link = null; + public $result = null; + public $db_server = ''; + public $selected_db = null; - public $locked = false; + public $locked = false; - public $num_queries = 0; - public $sql_starttime = 0; - public $sql_inittime = 0; - public $sql_timetotal = 0; - public $sql_last_time = 0; - public $slow_time = 0; + public $num_queries = 0; + public $sql_starttime = 0; + public $sql_inittime = 0; + public $sql_timetotal = 0; + public $sql_last_time = 0; + public $slow_time = 0; - public $dbg = array(); - public $dbg_id = 0; - public $dbg_enabled = false; - public $cur_query = null; + public $dbg = array(); + public $dbg_id = 0; + public $dbg_enabled = false; + public $cur_query = null; - public $DBS = array(); + public $DBS = array(); - /** - * Constructor - */ - function __construct ($cfg_values) - { - global $DBS; + /** + * Constructor + */ + public function __construct($cfg_values) + { + global $DBS; - $this->cfg = array_combine($this->cfg_keys, $cfg_values); - $this->dbg_enabled = sql_dbg_enabled(); - $this->slow_time = SQL_SLOW_QUERY_TIME; + $this->cfg = array_combine($this->cfg_keys, $cfg_values); + $this->dbg_enabled = sql_dbg_enabled(); + $this->slow_time = SQL_SLOW_QUERY_TIME; - $this->DBS['num_queries'] =& $DBS->num_queries; - $this->DBS['sql_inittime'] =& $DBS->sql_inittime; - $this->DBS['sql_timetotal'] =& $DBS->sql_timetotal; - } + $this->DBS['num_queries'] =& $DBS->num_queries; + $this->DBS['sql_inittime'] =& $DBS->sql_inittime; + $this->DBS['sql_timetotal'] =& $DBS->sql_timetotal; + } - /** - * Initialize connection - */ - function init () - { - // Connect to server - $this->link = $this->connect(); + /** + * Initialize connection + */ + public function init() + { + // Connect to server + $this->link = $this->connect(); - // Select database - $this->selected_db = $this->select_db(); + // Select database + $this->selected_db = $this->select_db(); - // Set charset - if ($this->cfg['charset'] && !@mysql_set_charset($this->cfg['charset'], $this->link)) - { - if (!$this->sql_query("SET NAMES {$this->cfg['charset']}")) - { - error_exit("Could not set charset {$this->cfg['charset']}"); - } - } + // Set charset + if ($this->cfg['charset'] && !@mysql_set_charset($this->cfg['charset'], $this->link)) { + if (!$this->sql_query("SET NAMES {$this->cfg['charset']}")) { + error_exit("Could not set charset {$this->cfg['charset']}"); + } + } - $this->num_queries = 0; - $this->sql_inittime = $this->sql_timetotal; - $this->DBS['sql_inittime'] += $this->sql_inittime; - } + $this->num_queries = 0; + $this->sql_inittime = $this->sql_timetotal; + $this->DBS['sql_inittime'] += $this->sql_inittime; + } - /** - * Open connection - */ - function connect () - { - $this->cur_query = 'connect'; - $this->debug('start'); + /** + * Open connection + */ + public function connect() + { + $this->cur_query = 'connect'; + $this->debug('start'); - $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; + $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; - if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) - { - $this->log_error(); - } + if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) { + $this->log_error(); + } - register_shutdown_function(array(&$this, 'close')); + register_shutdown_function(array(&$this, 'close')); - $this->debug('end'); - $this->cur_query = null; + $this->debug('end'); + $this->cur_query = null; # if (DBG_LOG) dbg_log(' ', 'DB-connect'. ($link ? '' : '-FAIL')); - if (!$link) - { - if (function_exists('dummy_exit')) - { - dummy_exit(mt_rand(1200, 2400)); - } - else - { - die; - } - } + if (!$link) { + if (function_exists('dummy_exit')) { + dummy_exit(mt_rand(1200, 2400)); + } else { + die; + } + } - return $link; - } + return $link; + } - /** - * Select database - */ - function select_db () - { - $this->cur_query = 'select db'; - $this->debug('start'); + /** + * Select database + */ + public function select_db() + { + $this->cur_query = 'select db'; + $this->debug('start'); - if (!mysql_select_db($this->cfg['dbname'], $this->link)) - { - $this->log_error(); - error_exit("Could not select database '{$this->cfg['dbname']}'"); - } + if (!mysql_select_db($this->cfg['dbname'], $this->link)) { + $this->log_error(); + error_exit("Could not select database '{$this->cfg['dbname']}'"); + } - $this->debug('end'); - $this->cur_query = null; + $this->debug('end'); + $this->cur_query = null; - return $this->cfg['dbname']; - } + return $this->cfg['dbname']; + } - /** - * Base query method - */ - function sql_query ($query) - { - if (!is_resource($this->link)) - { - $this->init(); - } - $this->cur_query = $query; - $this->debug('start'); + /** + * Base query method + */ + public function sql_query($query) + { + if (!is_resource($this->link)) { + $this->init(); + } + $this->cur_query = $query; + $this->debug('start'); - if (!$this->result = mysql_query($query, $this->link)) - { - $this->log_error(); - } + if (!$this->result = mysql_query($query, $this->link)) { + $this->log_error(); + } - $this->debug('end'); - $this->cur_query = null; + $this->debug('end'); + $this->cur_query = null; - $this->num_queries++; - $this->DBS['num_queries']++; + $this->num_queries++; + $this->DBS['num_queries']++; - return $this->result; - } + return $this->result; + } - /** - * Execute query WRAPPER (with error handling) - */ - function query ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } + /** + * Execute query WRAPPER (with error handling) + */ + public function query($query) + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } - return $result; - } + return $result; + } - /** - * Return number of rows - */ - function num_rows ($result = false) - { - $num_rows = false; + /** + * Return number of rows + */ + public function num_rows($result = false) + { + $num_rows = false; - if ($result OR $result = $this->result) - { - $num_rows = is_resource($result) ? mysql_num_rows($result) : false; - } + if ($result or $result = $this->result) { + $num_rows = is_resource($result) ? mysql_num_rows($result) : false; + } - return $num_rows; - } + return $num_rows; + } - /** - * Return number of affected rows - */ - function affected_rows () - { - return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; - } + /** + * Return number of affected rows + */ + public function affected_rows() + { + return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; + } - /** - * Fetch current row - */ - function sql_fetchrow ($result) - { - return is_resource($result) ? mysql_fetch_assoc($result) : false; - } + /** + * Fetch current row + */ + public function sql_fetchrow($result) + { + return is_resource($result) ? mysql_fetch_assoc($result) : false; + } - /** - * Alias of sql_fetchrow() - */ - function fetch_next ($result) - { - return $this->sql_fetchrow($result); - } + /** + * Alias of sql_fetchrow() + */ + public function fetch_next($result) + { + return $this->sql_fetchrow($result); + } - /** - * Fetch row WRAPPER (with error handling) - */ - function fetch_row ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } + /** + * Fetch row WRAPPER (with error handling) + */ + public function fetch_row($query) + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } - return $this->sql_fetchrow($result); - } + return $this->sql_fetchrow($result); + } - /** - * Fetch all rows - */ - function sql_fetchrowset ($result) - { - $rowset = array(); + /** + * Fetch all rows + */ + public function sql_fetchrowset($result) + { + $rowset = array(); - while ($row = mysql_fetch_assoc($result)) - { - $rowset[] = $row; - } + while ($row = mysql_fetch_assoc($result)) { + $rowset[] = $row; + } - return $rowset; - } + return $rowset; + } - /** - * Fetch all rows WRAPPER (with error handling) - */ - function fetch_rowset ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } + /** + * Fetch all rows WRAPPER (with error handling) + */ + public function fetch_rowset($query) + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } - return $this->sql_fetchrowset($result); - } + return $this->sql_fetchrowset($result); + } - /** - * Escape string used in sql query - */ - function escape ($v, $check_type = false) - { - if (!is_resource($this->link)) - { - $this->init(); - } - if (!$check_type) - { - return mysql_real_escape_string($v); - } + /** + * Escape string used in sql query + */ + public function escape($v, $check_type = false) + { + if (!is_resource($this->link)) { + $this->init(); + } + if (!$check_type) { + return mysql_real_escape_string($v); + } - switch (true) - { - case is_string ($v): return "'". mysql_real_escape_string($v) ."'"; - case is_int ($v): return "$v"; - case is_bool ($v): return ($v) ? '1' : '0'; - case is_float ($v): return "'$v'"; - case is_null ($v): return 'NULL'; - } - // if $v has unsuitable type - $this->trigger_error(__FUNCTION__ .' - wrong params'); - } + switch (true) { + case is_string($v): + return "'" . mysql_real_escape_string($v) . "'"; + case is_int($v): + return "$v"; + case is_bool($v): + return ($v) ? '1' : '0'; + case is_float($v): + return "'$v'"; + case is_null($v): + return 'NULL'; + } + // if $v has unsuitable type + $this->trigger_error(__FUNCTION__ . ' - wrong params'); + } - /** - * Return sql error array - */ - function sql_error () - { - $return_ary = array( - 'code' => '', - 'message' => 'not connected', - ); + /** + * Return sql error array + */ + public function sql_error() + { + $return_ary = array( + 'code' => '', + 'message' => 'not connected', + ); - if (is_resource($this->link)) - { - $return_ary = array( - 'code' => mysql_errno($this->link), - 'message' => mysql_error($this->link), - ); - } + if (is_resource($this->link)) { + $return_ary = array( + 'code' => mysql_errno($this->link), + 'message' => mysql_error($this->link), + ); + } - return $return_ary; - } + return $return_ary; + } - /** - * Close sql connection - */ - function close () - { - if (is_resource($this->link)) - { - mysql_close($this->link); - } + /** + * Close sql connection + */ + public function close() + { + if (is_resource($this->link)) { + mysql_close($this->link); + } - $this->link = $this->selected_db = null; + $this->link = $this->selected_db = null; - if (DBG_LOG) dbg_log(str_repeat(' ', $this->num_queries), 'DB-num_queries-'. php_sapi_name()); - } + if (DBG_LOG) { + dbg_log(str_repeat(' ', $this->num_queries), 'DB-num_queries-' . php_sapi_name()); + } + } - /** - * Get info about last query - */ - function query_info () - { - $info = array(); + /** + * Get info about last query + */ + public function query_info() + { + $info = array(); - if ($num = $this->num_rows($this->result)) - { - $info[] = "$num rows"; - } + if ($num = $this->num_rows($this->result)) { + $info[] = "$num rows"; + } - if (is_resource($this->link) AND $ext = mysql_info($this->link)) - { - $info[] = "$ext"; - } - elseif (!$num && ($aff = $this->affected_rows($this->result) AND $aff != -1)) - { - $info[] = "$aff rows"; - } + if (is_resource($this->link) and $ext = mysql_info($this->link)) { + $info[] = "$ext"; + } elseif (!$num && ($aff = $this->affected_rows($this->result) and $aff != -1)) { + $info[] = "$aff rows"; + } - return join(', ', $info); - } + return join(', ', $info); + } - /** - * Store debug info - */ - function debug ($mode) - { - if (!SQL_DEBUG) return; + /** + * Store debug info + */ + public function debug($mode) + { + if (!SQL_DEBUG) { + return; + } - if ($mode == 'start') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->sql_starttime = utime(); - $this->sql_last_time = 0; - } - } - elseif ($mode == 'end') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->sql_last_time = utime() - $this->sql_starttime; - $this->sql_timetotal += $this->sql_last_time; - $this->DBS['sql_timetotal'] += $this->sql_last_time; + if ($mode == 'start') { + if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { + $this->sql_starttime = utime(); + $this->sql_last_time = 0; + } + } elseif ($mode == 'end') { + if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { + $this->sql_last_time = utime() - $this->sql_starttime; + $this->sql_timetotal += $this->sql_last_time; + $this->DBS['sql_timetotal'] += $this->sql_last_time; - if (SQL_LOG_SLOW_QUERIES && $this->sql_last_time > $this->slow_time) - { - $msg = date('m-d H:i:s') . LOG_SEPR; - $msg .= sprintf('%03d', round($this->sql_last_time)); - $msg .= LOG_SEPR . sprintf('%.1f', sys('la')); - $msg .= LOG_SEPR . str_compact($this->cur_query); - $msg .= LOG_SEPR .' # '. $this->query_info(); - $msg .= LOG_SEPR . $this->debug_find_source(); - bb_log($msg . LOG_LF, 'sql_slow_tr'); - } - } - } - return; - } + if (SQL_LOG_SLOW_QUERIES && $this->sql_last_time > $this->slow_time) { + $msg = date('m-d H:i:s') . LOG_SEPR; + $msg .= sprintf('%03d', round($this->sql_last_time)); + $msg .= LOG_SEPR . sprintf('%.1f', sys('la')); + $msg .= LOG_SEPR . str_compact($this->cur_query); + $msg .= LOG_SEPR . ' # ' . $this->query_info(); + $msg .= LOG_SEPR . $this->debug_find_source(); + bb_log($msg . LOG_LF, 'sql_slow_tr'); + } + } + } + return; + } - /** - * Trigger error - */ - function trigger_error ($msg = '') - { - if (error_reporting()) - { - if (!$msg) $msg = 'DB Error'; + /** + * Trigger error + */ + public function trigger_error($msg = '') + { + if (error_reporting()) { + if (!$msg) { + $msg = 'DB Error'; + } - if (DBG_TRACKER === true) - { - $err = $this->sql_error(); - $msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message'])); - } - else - { - $msg .= " [". $this->debug_find_source() ."]"; - } + if (DBG_TRACKER === true) { + $err = $this->sql_error(); + $msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message'])); + } else { + $msg .= " [" . $this->debug_find_source() . "]"; + } - error_exit($msg); - } - } + error_exit($msg); + } + } - /** - * Find caller source - */ - function debug_find_source () - { - $source = ''; - $backtrace = debug_backtrace(); + /** + * Find caller source + */ + public function debug_find_source() + { + $source = ''; + $backtrace = debug_backtrace(); - foreach ($backtrace as $trace) - { - if ($trace['file'] !== __FILE__) - { - $source = str_replace(BB_PATH, '', $trace['file']) .'('. $trace['line'] .')'; - break; - } - } + foreach ($backtrace as $trace) { + if ($trace['file'] !== __FILE__) { + $source = str_replace(BB_PATH, '', $trace['file']) . '(' . $trace['line'] . ')'; + break; + } + } - return $source; - } + return $source; + } - /** - * Log error - */ - function log_error () - { - if (!SQL_LOG_ERRORS) return; - if (!error_reporting()) return; + /** + * Log error + */ + public function log_error() + { + if (!SQL_LOG_ERRORS) { + return; + } + if (!error_reporting()) { + return; + } - $msg = array(); - $err = $this->sql_error(); - $msg[] = str_compact(sprintf('#%06d %s', $err['code'], $err['message'])); - $msg[] = ''; - $msg[] = str_compact($this->cur_query); - $msg[] = ''; - $msg[] = 'Source : '. $this->debug_find_source(); - $msg[] = 'IP : '. @$_SERVER['REMOTE_ADDR']; - $msg[] = 'Date : '. date('Y-m-d H:i:s'); - $msg[] = 'Agent : '. @$_SERVER['HTTP_USER_AGENT']; - $msg[] = 'Req_URI : '. @$_SERVER['REQUEST_URI']; - $msg[] = 'Referer : '. @$_SERVER['HTTP_REFERER']; - $msg[] = 'Method : '. @$_SERVER['REQUEST_METHOD']; - $msg[] = 'Request : '. trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; - $msg[] = ''; - bb_log($msg, 'sql_error_tr'); - } + $msg = array(); + $err = $this->sql_error(); + $msg[] = str_compact(sprintf('#%06d %s', $err['code'], $err['message'])); + $msg[] = ''; + $msg[] = str_compact($this->cur_query); + $msg[] = ''; + $msg[] = 'Source : ' . $this->debug_find_source(); + $msg[] = 'IP : ' . @$_SERVER['REMOTE_ADDR']; + $msg[] = 'Date : ' . date('Y-m-d H:i:s'); + $msg[] = 'Agent : ' . @$_SERVER['HTTP_USER_AGENT']; + $msg[] = 'Req_URI : ' . @$_SERVER['REQUEST_URI']; + $msg[] = 'Referer : ' . @$_SERVER['HTTP_REFERER']; + $msg[] = 'Method : ' . @$_SERVER['REQUEST_METHOD']; + $msg[] = 'Request : ' . trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; + $msg[] = ''; + bb_log($msg, 'sql_error_tr'); + } } diff --git a/bt/index.php b/bt/index.php index 7e44c5d1d..91bcd590d 100644 --- a/bt/index.php +++ b/bt/index.php @@ -1,3 +1,26 @@ (int) 1800, - 'failure reason' => (string) $msg, - 'warning message' => (string) $msg, - )); + $output = bencode(array( + 'min interval' => (int)1800, + 'failure reason' => (string)$msg, + 'warning message' => (string)$msg, + )); - die($output); + die($output); } define('TR_ROOT', './'); @@ -39,19 +64,19 @@ $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); $row = DB()->fetch_row(" SELECT tor.complete_count, snap.seeders, snap.leechers - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_BT_TRACKER_SNAP ." snap ON (snap.topic_id = tor.topic_id) + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_BT_TRACKER_SNAP . " snap ON (snap.topic_id = tor.topic_id) WHERE tor.info_hash = '$info_hash_sql' LIMIT 1 "); $output['files'][$info_hash] = array( - 'complete' => (int) $row['seeders'], - 'downloaded' => (int) $row['complete_count'], - 'incomplete' => (int) $row['leechers'], + 'complete' => (int)$row['seeders'], + 'downloaded' => (int)$row['complete_count'], + 'incomplete' => (int)$row['leechers'], ); echo bencode($output); tracker_exit(); -exit; \ No newline at end of file +exit; diff --git a/callseed.php b/callseed.php index 0db99f1cd..dce73885b 100644 --- a/callseed.php +++ b/callseed.php @@ -1,4 +1,27 @@ session_start(array('req_login' => true)); -$topic_id = (int) request_var('t', 0); -$t_data = topic_info($topic_id); +$topic_id = (int)request_var('t', 0); +$t_data = topic_info($topic_id); $forum_id = $t_data['forum_id']; set_die_append_msg($forum_id, $topic_id); -if ($t_data['seeders'] > 2) -{ - bb_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders'])); -} -elseif ($t_data['call_seed_time'] > (TIMENOW - 86400)) -{ - $time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days'); - bb_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left)); +if ($t_data['seeders'] > 2) { + bb_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders'])); +} elseif ($t_data['call_seed_time'] > (TIMENOW - 86400)) { + $time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days'); + bb_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left)); } $ban_user_id = array(); -$sql = DB()->fetch_rowset("SELECT ban_userid FROM ". BB_BANLIST ." WHERE ban_userid != 0"); +$sql = DB()->fetch_rowset("SELECT ban_userid FROM " . BB_BANLIST . " WHERE ban_userid != 0"); -foreach ($sql as $row) -{ - $ban_user_id[] = ','. $row['ban_userid']; +foreach ($sql as $row) { + $ban_user_id[] = ',' . $row['ban_userid']; } $ban_user_id = join('', $ban_user_id); $user_list = DB()->fetch_rowset(" SELECT DISTINCT dl.user_id, u.user_opt, tr.user_id as active_dl - FROM ". BB_BT_DLSTATUS ." dl - LEFT JOIN ". BB_USERS ." u ON(u.user_id = dl.user_id) - LEFT JOIN ". BB_BT_TRACKER ." tr ON(tr.user_id = dl.user_id) + FROM " . BB_BT_DLSTATUS . " dl + LEFT JOIN " . BB_USERS . " u ON(u.user_id = dl.user_id) + LEFT JOIN " . BB_BT_TRACKER . " tr ON(tr.user_id = dl.user_id) WHERE dl.topic_id = $topic_id - AND dl.user_status IN (". DL_STATUS_COMPLETE.", ". DL_STATUS_DOWN.") - AND dl.user_id NOT IN ({$userdata['user_id']}, ". EXCLUDED_USERS_CSV . $ban_user_id .") + AND dl.user_status IN (" . DL_STATUS_COMPLETE . ", " . DL_STATUS_DOWN . ") + AND dl.user_id NOT IN ({$userdata['user_id']}, " . EXCLUDED_USERS_CSV . $ban_user_id . ") AND u.user_active = 1 GROUP BY dl.user_id "); @@ -49,46 +68,42 @@ $user_list = DB()->fetch_rowset(" $subject = sprintf($lang['CALLSEED_SUBJECT'], $t_data['topic_title']); $message = sprintf($lang['CALLSEED_TEXT'], make_url(TOPIC_URL . $topic_id), $t_data['topic_title'], make_url(DOWNLOAD_URL . $t_data['attach_id'])); -if ($user_list) -{ - foreach ($user_list as $row) - { - if (!empty($row['active_dl'])) continue; +if ($user_list) { + foreach ($user_list as $row) { + if (!empty($row['active_dl'])) { + continue; + } - if (bf($row['user_opt'], 'user_opt', 'user_callseed')) - { - send_pm($row['user_id'], $subject, $message, BOT_UID); - } - } -} -else -{ - send_pm($t_data['poster_id'], $subject, $message, BOT_UID); + if (bf($row['user_opt'], 'user_opt', 'user_callseed')) { + send_pm($row['user_id'], $subject, $message, BOT_UID); + } + } +} else { + send_pm($t_data['poster_id'], $subject, $message, BOT_UID); } -DB()->query("UPDATE ". BB_BT_TORRENTS ." SET call_seed_time = ". TIMENOW ." WHERE topic_id = $topic_id LIMIT 1"); +DB()->query("UPDATE " . BB_BT_TORRENTS . " SET call_seed_time = " . TIMENOW . " WHERE topic_id = $topic_id LIMIT 1"); meta_refresh(TOPIC_URL . $topic_id); bb_die($lang['CALLSEED_MSG_OK']); -function topic_info ($topic_id) +function topic_info($topic_id) { - global $lang; + global $lang; - $sql = " + $sql = " SELECT tor.poster_id, tor.forum_id, tor.attach_id, tor.call_seed_time, t.topic_title, sn.seeders - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_TOPICS ." t USING(topic_id) - LEFT JOIN ". BB_BT_TRACKER_SNAP ." sn USING(topic_id) + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_TOPICS . " t USING(topic_id) + LEFT JOIN " . BB_BT_TRACKER_SNAP . " sn USING(topic_id) WHERE tor.topic_id = $topic_id "; - if (!$torrent = DB()->fetch_row($sql)) - { - bb_die($lang['TOPIC_POST_NOT_EXIST']); - } + if (!$torrent = DB()->fetch_row($sql)) { + bb_die($lang['TOPIC_POST_NOT_EXIST']); + } - return $torrent; + return $torrent; } diff --git a/common.php b/common.php index b1e961d7c..462007360 100644 --- a/common.php +++ b/common.php @@ -1,18 +1,55 @@ true)); $loader->register(); @@ -38,29 +76,29 @@ unset($server_protocol, $server_port); define('DBG_USER', (isset($_COOKIE[COOKIE_DBG]))); // Board/Tracker shared constants and functions -define('BB_BT_TORRENTS', 'bb_bt_torrents'); -define('BB_BT_TRACKER', 'bb_bt_tracker'); +define('BB_BT_TORRENTS', 'bb_bt_torrents'); +define('BB_BT_TRACKER', 'bb_bt_tracker'); define('BB_BT_TRACKER_SNAP', 'bb_bt_tracker_snap'); -define('BB_BT_USERS', 'bb_bt_users'); +define('BB_BT_USERS', 'bb_bt_users'); define('BT_AUTH_KEY_LENGTH', 10); -define('PEER_HASH_PREFIX', 'peer_'); -define('PEERS_LIST_PREFIX', 'peers_list_'); -define('PEER_HASH_EXPIRE', round($bb_cfg['announce_interval'] * (0.85 * $tr_cfg['expire_factor']))); // sec -define('PEERS_LIST_EXPIRE', round($bb_cfg['announce_interval'] * 0.7)); // sec +define('PEER_HASH_PREFIX', 'peer_'); +define('PEERS_LIST_PREFIX', 'peers_list_'); +define('PEER_HASH_EXPIRE', round($bb_cfg['announce_interval'] * (0.85 * $tr_cfg['expire_factor']))); // sec +define('PEERS_LIST_EXPIRE', round($bb_cfg['announce_interval'] * 0.7)); // sec define('DL_STATUS_RELEASER', -1); -define('DL_STATUS_DOWN', 0); -define('DL_STATUS_COMPLETE', 1); -define('DL_STATUS_CANCEL', 3); -define('DL_STATUS_WILL', 4); +define('DL_STATUS_DOWN', 0); +define('DL_STATUS_COMPLETE', 1); +define('DL_STATUS_CANCEL', 3); +define('DL_STATUS_WILL', 4); -define('TOR_TYPE_GOLD', 1); -define('TOR_TYPE_SILVER', 2); +define('TOR_TYPE_GOLD', 1); +define('TOR_TYPE_SILVER', 2); define('GUEST_UID', -1); -define('BOT_UID', -746); +define('BOT_UID', -746); /** * Database @@ -69,10 +107,10 @@ define('BOT_UID', -746); require(CORE_DIR . 'dbs.php'); $DBS = new DBS($bb_cfg); -function DB ($db_alias = 'db1') +function DB($db_alias = 'db1') { - global $DBS; - return $DBS->get_db_obj($db_alias); + global $DBS; + return $DBS->get_db_obj($db_alias); } /** @@ -87,10 +125,10 @@ require(INC_DIR . 'datastore/common.php'); require(CORE_DIR . 'caches.php'); $CACHES = new CACHES($bb_cfg); -function CACHE ($cache_name) +function CACHE($cache_name) { - global $CACHES; - return $CACHES->get_cache_obj($cache_name); + global $CACHES; + return $CACHES->get_cache_obj($cache_name); } // Common cache classes @@ -102,8 +140,8 @@ require(INC_DIR . 'cache/xcache.php'); require(INC_DIR . 'cache/file.php'); /** -* Datastore -*/ + * Datastore + */ // Common datastore classes require(INC_DIR . 'datastore/memcache.php'); require(INC_DIR . 'datastore/sqlite.php'); @@ -113,398 +151,354 @@ require(INC_DIR . 'datastore/xcache.php'); require(INC_DIR . 'datastore/file.php'); // Initialize datastore -switch ($bb_cfg['datastore_type']) -{ - case 'memcache': - $datastore = new datastore_memcache($bb_cfg['cache']['memcache'], $bb_cfg['cache']['prefix']); - break; +switch ($bb_cfg['datastore_type']) { + case 'memcache': + $datastore = new datastore_memcache($bb_cfg['cache']['memcache'], $bb_cfg['cache']['prefix']); + break; - case 'sqlite': - $default_cfg = array( - 'db_file_path' => $bb_cfg['cache']['db_dir'] .'datastore.sqlite.db', - 'pconnect' => true, - 'con_required' => true, - ); - $datastore = new datastore_sqlite($default_cfg, $bb_cfg['cache']['prefix']); - break; + case 'sqlite': + $default_cfg = array( + 'db_file_path' => $bb_cfg['cache']['db_dir'] . 'datastore.sqlite.db', + 'pconnect' => true, + 'con_required' => true, + ); + $datastore = new datastore_sqlite($default_cfg, $bb_cfg['cache']['prefix']); + break; - case 'redis': - $datastore = new datastore_redis($bb_cfg['cache']['redis'], $bb_cfg['cache']['prefix']); - break; + case 'redis': + $datastore = new datastore_redis($bb_cfg['cache']['redis'], $bb_cfg['cache']['prefix']); + break; - case 'apc': - $datastore = new datastore_apc($bb_cfg['cache']['prefix']); - break; + case 'apc': + $datastore = new datastore_apc($bb_cfg['cache']['prefix']); + break; - case 'xcache': - $datastore = new datastore_xcache($bb_cfg['cache']['prefix']); - break; + case 'xcache': + $datastore = new datastore_xcache($bb_cfg['cache']['prefix']); + break; - case 'filecache': - default: $datastore = new datastore_file($bb_cfg['cache']['db_dir'] . 'datastore/', $bb_cfg['cache']['prefix']); + case 'filecache': + default: + $datastore = new datastore_file($bb_cfg['cache']['db_dir'] . 'datastore/', $bb_cfg['cache']['prefix']); } -function sql_dbg_enabled () +function sql_dbg_enabled() { - return (SQL_DEBUG && DBG_USER && !empty($_COOKIE['sql_log'])); + return (SQL_DEBUG && DBG_USER && !empty($_COOKIE['sql_log'])); } -function short_query ($sql, $esc_html = false) +function short_query($sql, $esc_html = false) { - $max_len = 100; - $sql = str_compact($sql); + $max_len = 100; + $sql = str_compact($sql); - if (!empty($_COOKIE['sql_log_full'])) - { - if (mb_strlen($sql, 'UTF-8') > $max_len) - { - $sql = mb_substr($sql, 0, 50) .' [...cut...] '. mb_substr($sql, -50); - } - } + if (!empty($_COOKIE['sql_log_full'])) { + if (mb_strlen($sql, 'UTF-8') > $max_len) { + $sql = mb_substr($sql, 0, 50) . ' [...cut...] ' . mb_substr($sql, -50); + } + } - return ($esc_html) ? htmlCHR($sql, true) : $sql; + return ($esc_html) ? htmlCHR($sql, true) : $sql; } // Functions -function utime () +function utime() { - return array_sum(explode(' ', microtime())); + return array_sum(explode(' ', microtime())); } -function bb_log ($msg, $file_name) +function bb_log($msg, $file_name) { - if (is_array($msg)) - { - $msg = join(LOG_LF, $msg); - } - $file_name .= (LOG_EXT) ? '.'. LOG_EXT : ''; - return file_write($msg, LOG_DIR . $file_name); + if (is_array($msg)) { + $msg = join(LOG_LF, $msg); + } + $file_name .= (LOG_EXT) ? '.' . LOG_EXT : ''; + return file_write($msg, LOG_DIR . $file_name); } -function file_write ($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replace_content = false) +function file_write($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replace_content = false) { - $bytes_written = false; + $bytes_written = false; - if ($max_size && @filesize($file) >= $max_size) - { - $old_name = $file; $ext = ''; - if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) - { - $old_name = $matches[1]; $ext = $matches[2]; - } - $new_name = $old_name .'_[old]_'. date('Y-m-d_H-i-s_') . getmypid() . $ext; - clearstatcache(); - if (@file_exists($file) && @filesize($file) >= $max_size && !@file_exists($new_name)) - { - @rename($file, $new_name); - } - } - if (!$fp = @fopen($file, 'ab')) - { - if ($dir_created = bb_mkdir(dirname($file))) - { - $fp = @fopen($file, 'ab'); - } - } - if ($fp) - { - if ($lock) - { - @flock($fp, LOCK_EX); - } - if ($replace_content) - { - @ftruncate($fp, 0); - @fseek($fp, 0, SEEK_SET); - } - $bytes_written = @fwrite($fp, $str); - @fclose($fp); - } + if ($max_size && @filesize($file) >= $max_size) { + $old_name = $file; + $ext = ''; + if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) { + $old_name = $matches[1]; + $ext = $matches[2]; + } + $new_name = $old_name . '_[old]_' . date('Y-m-d_H-i-s_') . getmypid() . $ext; + clearstatcache(); + if (@file_exists($file) && @filesize($file) >= $max_size && !@file_exists($new_name)) { + @rename($file, $new_name); + } + } + if (!$fp = @fopen($file, 'ab')) { + if ($dir_created = bb_mkdir(dirname($file))) { + $fp = @fopen($file, 'ab'); + } + } + if ($fp) { + if ($lock) { + @flock($fp, LOCK_EX); + } + if ($replace_content) { + @ftruncate($fp, 0); + @fseek($fp, 0, SEEK_SET); + } + $bytes_written = @fwrite($fp, $str); + @fclose($fp); + } - return $bytes_written; + return $bytes_written; } -function bb_mkdir ($path, $mode = 0777) +function bb_mkdir($path, $mode = 0777) { - $old_um = umask(0); - $dir = mkdir_rec($path, $mode); - umask($old_um); - return $dir; + $old_um = umask(0); + $dir = mkdir_rec($path, $mode); + umask($old_um); + return $dir; } -function mkdir_rec ($path, $mode) +function mkdir_rec($path, $mode) { - if (is_dir($path)) - { - return ($path !== '.' && $path !== '..') ? is_writable($path) : false; - } - else - { - return (mkdir_rec(dirname($path), $mode)) ? @mkdir($path, $mode) : false; - } + if (is_dir($path)) { + return ($path !== '.' && $path !== '..') ? is_writable($path) : false; + } else { + return (mkdir_rec(dirname($path), $mode)) ? @mkdir($path, $mode) : false; + } } -function verify_id ($id, $length) +function verify_id($id, $length) { - return (is_string($id) && preg_match('#^[a-zA-Z0-9]{'. $length .'}$#', $id)); + return (is_string($id) && preg_match('#^[a-zA-Z0-9]{' . $length . '}$#', $id)); } -function clean_filename ($fname) +function clean_filename($fname) { - static $s = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '); - return str_replace($s, '_', str_compact($fname)); + static $s = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '); + return str_replace($s, '_', str_compact($fname)); } -function encode_ip ($ip) +function encode_ip($ip) { - $d = explode('.', $ip); - return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); + $d = explode('.', $ip); + return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); } -function decode_ip ($ip) +function decode_ip($ip) { - return long2ip("0x{$ip}"); + return long2ip("0x{$ip}"); } -function ip2int ($ip) +function ip2int($ip) { - return (float) sprintf('%u', ip2long($ip)); // для совместимости с 32 битными системами + return (float)sprintf('%u', ip2long($ip)); // для совместимости с 32 битными системами } // long2ip( mask_ip_int(ip2int('1.2.3.4'), 24) ) = '1.2.3.255' -function mask_ip_int ($ip, $mask) +function mask_ip_int($ip, $mask) { - $ip_int = is_numeric($ip) ? $ip : ip2int($ip); - $ip_masked = $ip_int | ((1 << (32 - $mask)) - 1); - return (float) sprintf('%u', $ip_masked); + $ip_int = is_numeric($ip) ? $ip : ip2int($ip); + $ip_masked = $ip_int | ((1 << (32 - $mask)) - 1); + return (float)sprintf('%u', $ip_masked); } -function bb_crc32 ($str) +function bb_crc32($str) { - return (float) sprintf('%u', crc32($str)); + return (float)sprintf('%u', crc32($str)); } -function hexhex ($value) +function hexhex($value) { - return dechex(hexdec($value)); + return dechex(hexdec($value)); } -function verify_ip ($ip) +function verify_ip($ip) { - return preg_match('#^(\d{1,3}\.){3}\d{1,3}$#', $ip); + return preg_match('#^(\d{1,3}\.){3}\d{1,3}$#', $ip); } -function str_compact ($str) +function str_compact($str) { - return preg_replace('#\s+#u', ' ', trim($str)); + return preg_replace('#\s+#u', ' ', trim($str)); } -function make_rand_str ($len = 10) +function make_rand_str($len = 10) { - $str = ''; - while (strlen($str) < $len) - { - $str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', password_hash(uniqid(mt_rand(), true), PASSWORD_BCRYPT))); - } - return substr($str, 0, $len); + $str = ''; + while (strlen($str) < $len) { + $str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', password_hash(uniqid(mt_rand(), true), PASSWORD_BCRYPT))); + } + return substr($str, 0, $len); } // bencode: based on OpenTracker -function bencode ($var) +function bencode($var) { - if (is_string($var)) - { - return strlen($var) .':'. $var; - } - else if (is_int($var)) - { - return 'i'. $var .'e'; - } - else if (is_float($var)) - { - return 'i'. sprintf('%.0f', $var) .'e'; - } - else if (is_array($var)) - { - if (count($var) == 0) - { - return 'de'; - } - else - { - $assoc = false; + if (is_string($var)) { + return strlen($var) . ':' . $var; + } elseif (is_int($var)) { + return 'i' . $var . 'e'; + } elseif (is_float($var)) { + return 'i' . sprintf('%.0f', $var) . 'e'; + } elseif (is_array($var)) { + if (count($var) == 0) { + return 'de'; + } else { + $assoc = false; - foreach ($var as $key => $val) - { - if (!is_int($key)) - { - $assoc = true; - break; - } - } + foreach ($var as $key => $val) { + if (!is_int($key)) { + $assoc = true; + break; + } + } - if ($assoc) - { - ksort($var, SORT_REGULAR); - $ret = 'd'; + if ($assoc) { + ksort($var, SORT_REGULAR); + $ret = 'd'; - foreach ($var as $key => $val) - { - $ret .= bencode($key) . bencode($val); - } - return $ret .'e'; - } - else - { - $ret = 'l'; + foreach ($var as $key => $val) { + $ret .= bencode($key) . bencode($val); + } + return $ret . 'e'; + } else { + $ret = 'l'; - foreach ($var as $val) - { - $ret .= bencode($val); - } - return $ret .'e'; - } - } - } - else - { - trigger_error('bencode error: wrong data type', E_USER_ERROR); - } + foreach ($var as $val) { + $ret .= bencode($val); + } + return $ret . 'e'; + } + } + } else { + trigger_error('bencode error: wrong data type', E_USER_ERROR); + } } -function array_deep (&$var, $fn, $one_dimensional = false, $array_only = false) +function array_deep(&$var, $fn, $one_dimensional = false, $array_only = false) { - if (is_array($var)) - { - foreach ($var as $k => $v) - { - if (is_array($v)) - { - if ($one_dimensional) - { - unset($var[$k]); - } - else if ($array_only) - { - $var[$k] = $fn($v); - } - else - { - array_deep($var[$k], $fn); - } - } - else if (!$array_only) - { - $var[$k] = $fn($v); - } - } - } - else if (!$array_only) - { - $var = $fn($var); - } + if (is_array($var)) { + foreach ($var as $k => $v) { + if (is_array($v)) { + if ($one_dimensional) { + unset($var[$k]); + } elseif ($array_only) { + $var[$k] = $fn($v); + } else { + array_deep($var[$k], $fn); + } + } elseif (!$array_only) { + $var[$k] = $fn($v); + } + } + } elseif (!$array_only) { + $var = $fn($var); + } } -function hide_bb_path ($path) +function hide_bb_path($path) { - return ltrim(str_replace(BB_PATH, '', $path), '/\\'); + return ltrim(str_replace(BB_PATH, '', $path), '/\\'); } -function sys ($param) +function sys($param) { - switch ($param) - { - case 'la': - return function_exists('sys_getloadavg') ? join(' ', sys_getloadavg()) : 0; - break; - case 'mem': - return function_exists('memory_get_usage') ? memory_get_usage() : 0; - break; - case 'mem_peak': - return function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; - break; - default: - trigger_error("invalid param: $param", E_USER_ERROR); - } + switch ($param) { + case 'la': + return function_exists('sys_getloadavg') ? join(' ', sys_getloadavg()) : 0; + break; + case 'mem': + return function_exists('memory_get_usage') ? memory_get_usage() : 0; + break; + case 'mem_peak': + return function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; + break; + default: + trigger_error("invalid param: $param", E_USER_ERROR); + } } -function ver_compare ($version1, $operator, $version2) +function ver_compare($version1, $operator, $version2) { - return version_compare($version1, $version2, $operator); + return version_compare($version1, $version2, $operator); } -function dbg_log ($str, $file) +function dbg_log($str, $file) { - $dir = LOG_DIR . (defined('IN_TRACKER') ? 'dbg_tr/' : 'dbg_bb/') . date('m-d_H') .'/'; - return file_write($str, $dir . $file, false, false); + $dir = LOG_DIR . (defined('IN_TRACKER') ? 'dbg_tr/' : 'dbg_bb/') . date('m-d_H') . '/'; + return file_write($str, $dir . $file, false, false); } -function log_get ($file = '', $prepend_str = false) +function log_get($file = '', $prepend_str = false) { - log_request($file, $prepend_str, false); + log_request($file, $prepend_str, false); } -function log_post ($file = '', $prepend_str = false) +function log_post($file = '', $prepend_str = false) { - log_request($file, $prepend_str, true); + log_request($file, $prepend_str, true); } -function log_request ($file = '', $prepend_str = false, $add_post = true) +function log_request($file = '', $prepend_str = false, $add_post = true) { - global $user; + global $user; - $file = ($file) ? $file : 'req/'. date('m-d'); - $str = array(); - $str[] = date('m-d H:i:s'); - if ($prepend_str !== false) $str[] = $prepend_str; - if (!empty($user->data)) $str[] = $user->id ."\t". html_entity_decode($user->name); - $str[] = sprintf('%-15s', $_SERVER['REMOTE_ADDR']); + $file = ($file) ? $file : 'req/' . date('m-d'); + $str = array(); + $str[] = date('m-d H:i:s'); + if ($prepend_str !== false) { + $str[] = $prepend_str; + } + if (!empty($user->data)) { + $str[] = $user->id . "\t" . html_entity_decode($user->name); + } + $str[] = sprintf('%-15s', $_SERVER['REMOTE_ADDR']); - if (isset($_SERVER['REQUEST_URI'])) { - $str[] = $_SERVER['REQUEST_URI']; - } - if (isset($_SERVER['HTTP_USER_AGENT'])) { - $str[] = $_SERVER['HTTP_USER_AGENT']; - } - if (isset($_SERVER['HTTP_REFERER'])) { - $str[] = $_SERVER['HTTP_REFERER']; - } + if (isset($_SERVER['REQUEST_URI'])) { + $str[] = $_SERVER['REQUEST_URI']; + } + if (isset($_SERVER['HTTP_USER_AGENT'])) { + $str[] = $_SERVER['HTTP_USER_AGENT']; + } + if (isset($_SERVER['HTTP_REFERER'])) { + $str[] = $_SERVER['HTTP_REFERER']; + } - if (!empty($_POST) && $add_post) $str[] = "post: ". str_compact(urldecode(http_build_query($_POST))); - $str = join("\t", $str) . "\n"; - bb_log($str, $file); + if (!empty($_POST) && $add_post) { + $str[] = "post: " . str_compact(urldecode(http_build_query($_POST))); + } + $str = join("\t", $str) . "\n"; + bb_log($str, $file); } // Board init -if (defined('IN_FORUM')) -{ - require(INC_DIR .'init_bb.php'); -} -// Tracker init -else if (defined('IN_TRACKER')) -{ - define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? intval($_GET['port']) : mt_rand(1000, 65000))); - - function dummy_exit ($interval = 1800) - { - $output = bencode(array( - 'interval' => (int) $interval, - 'min interval' => (int) $interval, - 'peers' => (string) DUMMY_PEER, - )); - - die($output); - } - - header('Content-Type: text/plain'); - header('Pragma: no-cache'); - - if (!defined('IN_ADMIN')) - { - // Exit if tracker is disabled via ON/OFF trigger - if (file_exists(BB_DISABLED)) - { - dummy_exit(mt_rand(60, 2400)); - } - } +if (defined('IN_FORUM')) { + require(INC_DIR . 'init_bb.php'); +} // Tracker init +elseif (defined('IN_TRACKER')) { + define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? intval($_GET['port']) : mt_rand(1000, 65000))); + + function dummy_exit($interval = 1800) + { + $output = bencode(array( + 'interval' => (int)$interval, + 'min interval' => (int)$interval, + 'peers' => (string)DUMMY_PEER, + )); + + die($output); + } + + header('Content-Type: text/plain'); + header('Pragma: no-cache'); + + if (!defined('IN_ADMIN')) { + // Exit if tracker is disabled via ON/OFF trigger + if (file_exists(BB_DISABLED)) { + dummy_exit(mt_rand(60, 2400)); + } + } } diff --git a/cron.php b/cron.php index d500aeb14..191fafe90 100644 --- a/cron.php +++ b/cron.php @@ -1,6 +1,29 @@ - - - + + + \ No newline at end of file diff --git a/dl.php b/dl.php index c46645bb7..6c0097307 100644 --- a/dl.php +++ b/dl.php @@ -1,14 +1,37 @@ enqueue(array( - 'attach_extensions', + 'attach_extensions', )); $download_id = request_var('id', 0); @@ -17,62 +40,53 @@ $thumbnail = request_var('thumb', 0); // Send file to browser function send_file_to_browser($attachment, $upload_dir) { - global $bb_cfg, $lang, $userdata; + global $bb_cfg, $lang, $userdata; - $filename = ($upload_dir == '') ? $attachment['physical_filename'] : $upload_dir . '/' . $attachment['physical_filename']; + $filename = ($upload_dir == '') ? $attachment['physical_filename'] : $upload_dir . '/' . $attachment['physical_filename']; - $gotit = false; + $gotit = false; - if (@!file_exists(@amod_realpath($filename))) - { - bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename. "

" .$lang['TOR_NOT_FOUND']); - } - else - { - $gotit = true; - } + if (@!file_exists(@amod_realpath($filename))) { + bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename . "

" . $lang['TOR_NOT_FOUND']); + } else { + $gotit = true; + } - // Correct the mime type - we force application/octet-stream for all files, except images - // Please do not change this, it is a security precaution - if (!strstr($attachment['mimetype'], 'image')) - { - $attachment['mimetype'] = 'application/octet-stream'; - } + // Correct the mime type - we force application/octet-stream for all files, except images + // Please do not change this, it is a security precaution + if (!strstr($attachment['mimetype'], 'image')) { + $attachment['mimetype'] = 'application/octet-stream'; + } - //bt - if (!(isset($_GET['original']) && !IS_USER)) - { - include(INC_DIR .'functions_torrent.php'); - send_torrent_with_passkey($filename); - } + //bt + if (!(isset($_GET['original']) && !IS_USER)) { + include(INC_DIR . 'functions_torrent.php'); + send_torrent_with_passkey($filename); + } - // Now the tricky part... let's dance - header('Pragma: public'); - $real_filename = clean_filename(basename($attachment['real_filename'])); - $mimetype = $attachment['mimetype'].';'; - $charset = "charset={$bb_cfg['lang'][$userdata['user_lang']]['encoding']};"; + // Now the tricky part... let's dance + header('Pragma: public'); + $real_filename = clean_filename(basename($attachment['real_filename'])); + $mimetype = $attachment['mimetype'] . ';'; + $charset = "charset={$bb_cfg['lang'][$userdata['user_lang']]['encoding']};"; - // Send out the Headers - header("Content-Type: $mimetype $charset name=\"$real_filename\""); - header("Content-Disposition: inline; filename=\"$real_filename\""); - unset($real_filename); + // Send out the Headers + header("Content-Type: $mimetype $charset name=\"$real_filename\""); + header("Content-Disposition: inline; filename=\"$real_filename\""); + unset($real_filename); - // Now send the File Contents to the Browser - if ($gotit) - { - $size = @filesize($filename); - if ($size) - { - header("Content-length: $size"); - } - readfile($filename); - } - else - { - bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename. "

" .$lang['TOR_NOT_FOUND']); - } + // Now send the File Contents to the Browser + if ($gotit) { + $size = @filesize($filename); + if ($size) { + header("Content-length: $size"); + } + readfile($filename); + } else { + bb_die($lang['ERROR_NO_ATTACHMENT'] . "

" . $filename . "

" . $lang['TOR_NOT_FOUND']); + } - exit; + exit; } // @@ -82,26 +96,22 @@ $user->session_start(); set_die_append_msg(); -if (!$download_id) -{ - bb_die($lang['NO_ATTACHMENT_SELECTED']); +if (!$download_id) { + bb_die($lang['NO_ATTACHMENT_SELECTED']); } -if ($attach_config['disable_mod'] && !IS_ADMIN) -{ - bb_die($lang['ATTACHMENT_FEATURE_DISABLED']); +if ($attach_config['disable_mod'] && !IS_ADMIN) { + bb_die($lang['ATTACHMENT_FEATURE_DISABLED']); } -$sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int) $download_id; +$sql = 'SELECT * FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int)$download_id; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information #1'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information #1'); } -if (!($attachment = DB()->sql_fetchrow($result))) -{ - bb_die($lang['ERROR_NO_ATTACHMENT']); +if (!($attachment = DB()->sql_fetchrow($result))) { + bb_die($lang['ERROR_NO_ATTACHMENT']); } $attachment['physical_filename'] = basename($attachment['physical_filename']); @@ -111,48 +121,42 @@ DB()->sql_freeresult($result); // get forum_id for attachment authorization or private message authorization $authorised = false; -$sql = 'SELECT * FROM ' . BB_ATTACHMENTS . ' WHERE attach_id = ' . (int) $attachment['attach_id']; +$sql = 'SELECT * FROM ' . BB_ATTACHMENTS . ' WHERE attach_id = ' . (int)$attachment['attach_id']; -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not query attachment information #2'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information #2'); } $auth_pages = DB()->sql_fetchrowset($result); $num_auth_pages = DB()->num_rows($result); -for ($i = 0; $i < $num_auth_pages && $authorised == false; $i++) -{ - $auth_pages[$i]['post_id'] = intval($auth_pages[$i]['post_id']); +for ($i = 0; $i < $num_auth_pages && $authorised == false; $i++) { + $auth_pages[$i]['post_id'] = intval($auth_pages[$i]['post_id']); - if ($auth_pages[$i]['post_id'] != 0) - { - $sql = 'SELECT forum_id, topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int) $auth_pages[$i]['post_id']; + if ($auth_pages[$i]['post_id'] != 0) { + $sql = 'SELECT forum_id, topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int)$auth_pages[$i]['post_id']; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query post information'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query post information'); + } - $row = DB()->sql_fetchrow($result); + $row = DB()->sql_fetchrow($result); - $topic_id = $row['topic_id']; - $forum_id = $row['forum_id']; + $topic_id = $row['topic_id']; + $forum_id = $row['forum_id']; - $is_auth = array(); - $is_auth = auth(AUTH_ALL, $forum_id, $userdata); - set_die_append_msg($forum_id, $topic_id); + $is_auth = array(); + $is_auth = auth(AUTH_ALL, $forum_id, $userdata); + set_die_append_msg($forum_id, $topic_id); - if ($is_auth['auth_download']) - { - $authorised = TRUE; - } - } + if ($is_auth['auth_download']) { + $authorised = true; + } + } } -if (!$authorised) -{ - bb_die($lang['SORRY_AUTH_VIEW_ATTACH']); +if (!$authorised) { + bb_die($lang['SORRY_AUTH_VIEW_ATTACH']); } $datastore->rm('cat_forums'); @@ -163,67 +167,58 @@ $datastore->rm('cat_forums'); $rows = get_extension_informations(); $num_rows = count($rows); -for ($i = 0; $i < $num_rows; $i++) -{ - $extension = strtolower(trim($rows[$i]['extension'])); - $allowed_extensions[] = $extension; - $download_mode[$extension] = $rows[$i]['download_mode']; +for ($i = 0; $i < $num_rows; $i++) { + $extension = strtolower(trim($rows[$i]['extension'])); + $allowed_extensions[] = $extension; + $download_mode[$extension] = $rows[$i]['download_mode']; } // Disallowed -if (!in_array($attachment['extension'], $allowed_extensions) && !IS_ADMIN) -{ - bb_die(sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])); +if (!in_array($attachment['extension'], $allowed_extensions) && !IS_ADMIN) { + bb_die(sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])); } $download_mode = intval($download_mode[$attachment['extension']]); -if ($thumbnail) -{ - $attachment['physical_filename'] = THUMB_DIR . '/t_' . $attachment['physical_filename']; +if ($thumbnail) { + $attachment['physical_filename'] = THUMB_DIR . '/t_' . $attachment['physical_filename']; } // Update download count -if (!$thumbnail) -{ - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 WHERE attach_id = ' . (int) $attachment['attach_id']; +if (!$thumbnail) { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 WHERE attach_id = ' . (int)$attachment['attach_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update attachment download count'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update attachment download count'); + } } // Determine the 'presenting'-method -if ($download_mode == PHYSICAL_LINK) -{ - $url = make_url($upload_dir . '/' . $attachment['physical_filename']); - header('Location: ' . $url); - exit; +if ($download_mode == PHYSICAL_LINK) { + $url = make_url($upload_dir . '/' . $attachment['physical_filename']); + header('Location: ' . $url); + exit; +} else { + if (IS_GUEST && !bb_captcha('check')) { + global $template; + + $redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/'); + $message = '
'; + $message .= $lang['CAPTCHA'] . ':'; + $message .= '
' . bb_captcha('get') . '
'; + $message .= ''; + $message .= '  '; + $message .= ''; + $message .= '
'; + + $template->assign_vars(array( + 'ERROR_MESSAGE' => $message, + )); + + require(PAGE_HEADER); + require(PAGE_FOOTER); + } + + send_file_to_browser($attachment, $upload_dir); + exit; } -else -{ - if (IS_GUEST && !bb_captcha('check')) - { - global $template; - - $redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/'); - $message = '
'; - $message .= $lang['CAPTCHA'].':'; - $message .= '
'. bb_captcha('get') .'
'; - $message .= ''; - $message .= '  '; - $message .= ''; - $message .= '
'; - - $template->assign_vars(array( - 'ERROR_MESSAGE' => $message, - )); - - require(PAGE_HEADER); - require(PAGE_FOOTER); - } - - send_file_to_browser($attachment, $upload_dir); - exit; -} \ No newline at end of file diff --git a/dl_list.php b/dl_list.php index d4db8fd9c..1be83ddd7 100644 --- a/dl_list.php +++ b/dl_list.php @@ -1,56 +1,66 @@ session_start(); set_die_append_msg(); // Check if user logged in -if (!$userdata['session_logged_in']) -{ - redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect"); +if (!$userdata['session_logged_in']) { + redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect"); } // Check if user did not confirm -if (isset($_POST['cancel']) && $_POST['cancel']) -{ - redirect("$redirect_type?$redirect"); +if (isset($_POST['cancel']) && $_POST['cancel']) { + redirect("$redirect_type?$redirect"); } // Delete DL-list -if ($mode == 'dl_delete' && $topic_id) -{ - if (!IS_ADMIN) - { - $sql = "SELECT forum_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1"; +if ($mode == 'dl_delete' && $topic_id) { + if (!IS_ADMIN) { + $sql = "SELECT forum_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1"; - if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) - { - bb_die('Could not obtain forum_id for this topic'); - } + if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) { + bb_die('Could not obtain forum_id for this topic'); + } - $is_auth = auth(AUTH_ALL, $row['forum_id'], $userdata); + $is_auth = auth(AUTH_ALL, $row['forum_id'], $userdata); - if (!$is_auth['auth_mod']) - { - bb_die($lang['NOT_MODERATOR']); - } - } + if (!$is_auth['auth_mod']) { + bb_die($lang['NOT_MODERATOR']); + } + } - if (!$confirmed) - { - $hidden_fields = array( - 't' => $topic_id, - 'mode' => 'dl_delete', - ); + if (!$confirmed) { + $hidden_fields = array( + 't' => $topic_id, + 'mode' => 'dl_delete', + ); - print_confirmation(array( - 'QUESTION' => $lang['DL_LIST_DEL_CONFIRM'], - 'FORM_ACTION' => 'dl_list.php', - 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - )); - } + print_confirmation(array( + 'QUESTION' => $lang['DL_LIST_DEL_CONFIRM'], + 'FORM_ACTION' => 'dl_list.php', + 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + )); + } - clear_dl_list($topic_id); - redirect("$redirect_type?$redirect"); + clear_dl_list($topic_id); + redirect("$redirect_type?$redirect"); } // Update DL status $req_topics_ary = $topics_ary = array(); // Get topics selected by user -if ($mode == 'set_topics_dl_status') -{ - if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list'])) - { - bb_die($lang['NONE_SELECTED']); - } +if ($mode == 'set_topics_dl_status') { + if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list'])) { + bb_die($lang['NONE_SELECTED']); + } - foreach ($_POST['dl_topics_id_list'] as $topic_id) - { - $req_topics_ary[] = (int) $topic_id; - } -} -elseif ($mode == 'set_dl_status') -{ - $req_topics_ary[] = (int) $topic_id; + foreach ($_POST['dl_topics_id_list'] as $topic_id) { + $req_topics_ary[] = (int)$topic_id; + } +} elseif ($mode == 'set_dl_status') { + $req_topics_ary[] = (int)$topic_id; } // Get existing topics -if ($req_topics_sql = join(',', $req_topics_ary)) -{ - $sql = "SELECT topic_id FROM ". BB_TOPICS ." WHERE topic_id IN($req_topics_sql)"; +if ($req_topics_sql = join(',', $req_topics_ary)) { + $sql = "SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_id IN($req_topics_sql)"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $topics_ary[] = $row['topic_id']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topics_ary[] = $row['topic_id']; + } } -if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) -{ - $new_dlstatus_ary = array(); +if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) { + $new_dlstatus_ary = array(); - foreach ($topics_ary as $topic_id) - { - $new_dlstatus_ary[] = array( - 'user_id' => (int) $user->id, - 'topic_id' => (int) $topic_id, - 'user_status' => (int) $new_dl_status, - ); - } - $new_dlstatus_sql = DB()->build_array('MULTI_INSERT', $new_dlstatus_ary); + foreach ($topics_ary as $topic_id) { + $new_dlstatus_ary[] = array( + 'user_id' => (int)$user->id, + 'topic_id' => (int)$topic_id, + 'user_status' => (int)$new_dl_status, + ); + } + $new_dlstatus_sql = DB()->build_array('MULTI_INSERT', $new_dlstatus_ary); - DB()->query("REPLACE INTO ". BB_BT_DLSTATUS ." $new_dlstatus_sql"); + DB()->query("REPLACE INTO " . BB_BT_DLSTATUS . " $new_dlstatus_sql"); - redirect("$redirect_type?$redirect"); + redirect("$redirect_type?$redirect"); } -redirect("index.php"); \ No newline at end of file +redirect("index.php"); diff --git a/feed.php b/feed.php index 454c6dd56..986398301 100644 --- a/feed.php +++ b/feed.php @@ -1,68 +1,85 @@ session_start(array('req_login' => true)); $mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : ''; $type = isset($_POST['type']) ? $_POST['type'] : ''; -$id = isset($_POST['id']) ? $_POST['id'] : 0; +$id = isset($_POST['id']) ? $_POST['id'] : 0; $timecheck = TIMENOW - 600; -if (!$mode) bb_simple_die($lang['ATOM_NO_MODE']); - -if ($mode == 'get_feed_url' && ($type == 'f' || $type == 'u') && $id >= 0) -{ - if ($type == 'f') - { - // Check if the user has actually sent a forum ID - $sql = "SELECT allow_reg_tracker, forum_name FROM ". BB_FORUMS ." WHERE forum_id = $id LIMIT 1"; - if (!$forum_data = DB()->fetch_row($sql)) - { - if ($id == 0) - { - $forum_data = array(); - } - else bb_simple_die($lang['ATOM_ERROR'].' #1'); - } - if (file_exists($bb_cfg['atom']['path'] .'/f/'. $id .'.atom') && filemtime($bb_cfg['atom']['path'] .'/f/'. $id .'.atom') > $timecheck) - { - redirect($bb_cfg['atom']['url'] .'/f/'. $id .'.atom'); - } - else - { - require_once(INC_DIR .'functions_atom.php'); - if (update_forum_feed($id, $forum_data)) redirect($bb_cfg['atom']['url'] .'/f/'. $id .'.atom'); - else bb_simple_die($lang['ATOM_NO_FORUM']); - } - } - if ($type == 'u') - { - // Check if the user has actually sent a user ID - if ($id < 1) - { - bb_simple_die($lang['ATOM_ERROR'].' #2'); - } - if (!$username = get_username($id)) - { - bb_simple_die($lang['ATOM_ERROR'].' #3'); - } - if (file_exists($bb_cfg['atom']['path'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom') && filemtime($bb_cfg['atom']['path'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom') > $timecheck) - { - redirect($bb_cfg['atom']['url'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom'); - } - else - { - require_once(INC_DIR .'functions_atom.php'); - if (update_user_feed($id, $username)) redirect($bb_cfg['atom']['url'] .'/u/'. floor($id/5000) .'/'. ($id % 100) .'/'. $id .'.atom'); - else bb_simple_die($lang['ATOM_NO_USER']); - } - } +if (!$mode) { + bb_simple_die($lang['ATOM_NO_MODE']); +} + +if ($mode == 'get_feed_url' && ($type == 'f' || $type == 'u') && $id >= 0) { + if ($type == 'f') { + // Check if the user has actually sent a forum ID + $sql = "SELECT allow_reg_tracker, forum_name FROM " . BB_FORUMS . " WHERE forum_id = $id LIMIT 1"; + if (!$forum_data = DB()->fetch_row($sql)) { + if ($id == 0) { + $forum_data = array(); + } else { + bb_simple_die($lang['ATOM_ERROR'] . ' #1'); + } + } + if (file_exists($bb_cfg['atom']['path'] . '/f/' . $id . '.atom') && filemtime($bb_cfg['atom']['path'] . '/f/' . $id . '.atom') > $timecheck) { + redirect($bb_cfg['atom']['url'] . '/f/' . $id . '.atom'); + } else { + require_once(INC_DIR . 'functions_atom.php'); + if (update_forum_feed($id, $forum_data)) { + redirect($bb_cfg['atom']['url'] . '/f/' . $id . '.atom'); + } else { + bb_simple_die($lang['ATOM_NO_FORUM']); + } + } + } + if ($type == 'u') { + // Check if the user has actually sent a user ID + if ($id < 1) { + bb_simple_die($lang['ATOM_ERROR'] . ' #2'); + } + if (!$username = get_username($id)) { + bb_simple_die($lang['ATOM_ERROR'] . ' #3'); + } + if (file_exists($bb_cfg['atom']['path'] . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom') && filemtime($bb_cfg['atom']['path'] . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom') > $timecheck) { + redirect($bb_cfg['atom']['url'] . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom'); + } else { + require_once(INC_DIR . 'functions_atom.php'); + if (update_user_feed($id, $username)) { + redirect($bb_cfg['atom']['url'] . '/u/' . floor($id / 5000) . '/' . ($id % 100) . '/' . $id . '.atom'); + } else { + bb_simple_die($lang['ATOM_NO_USER']); + } + } + } +} else { + bb_simple_die($lang['ATOM_ERROR'] . ' #4'); } -else -{ - bb_simple_die($lang['ATOM_ERROR'].' #4'); -} \ No newline at end of file diff --git a/group.php b/group.php index 38778d453..33a548b7e 100644 --- a/group.php +++ b/group.php @@ -1,11 +1,34 @@ '. $lang['SEND_PM_TXTB'] .'' : '' . $lang['SEND_PRIVATE_MESSAGE'] . ''; - $avatar = get_avatar($row['user_id'], $row['avatar_ext_id'], !bf($row['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50); + $from = (!empty($row['user_from'])) ? $row['user_from'] : ''; + $joined = bb_date($row['user_regdate']); + $user_time = (!empty($row['user_time'])) ? bb_date($row['user_time']) : $lang['NONE']; + $posts = ($row['user_posts']) ? $row['user_posts'] : 0; + $pm = ($bb_cfg['text_buttons']) ? '' . $lang['SEND_PM_TXTB'] . '' : '' . $lang['SEND_PRIVATE_MESSAGE'] . ''; + $avatar = get_avatar($row['user_id'], $row['avatar_ext_id'], !bf($row['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50); - if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || $group_mod) - { - $email_uri = ($bb_cfg['board_email_form']) ? ("profile.php?mode=email&". POST_USERS_URL ."=".$row['user_id']) : 'mailto:'. $row['user_email']; - $email = ''. $row['user_email'] .''; - } - else $email = ''; + if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || $group_mod) { + $email_uri = ($bb_cfg['board_email_form']) ? ("profile.php?mode=email&" . POST_USERS_URL . "=" . $row['user_id']) : 'mailto:' . $row['user_email']; + $email = '' . $row['user_email'] . ''; + } else { + $email = ''; + } - if ($row['user_website']) - { - $www = ($bb_cfg['text_buttons']) ? ''. $lang['VISIT_WEBSITE_TXTB'] .'' : '' . $lang['VISIT_WEBSITE'] . ''; - } - else $www = ''; + if ($row['user_website']) { + $www = ($bb_cfg['text_buttons']) ? '' . $lang['VISIT_WEBSITE_TXTB'] . '' : '' . $lang['VISIT_WEBSITE'] . ''; + } else { + $www = ''; + } - return; + return; } $user->session_start(array('req_login' => true)); set_die_append_msg(); -$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null; -$start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; -$per_page = $bb_cfg['group_members_per_page']; -$view_mode = isset($_REQUEST['view']) ? (string) $_REQUEST['view'] : null; +$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null; +$start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; +$per_page = $bb_cfg['group_members_per_page']; +$view_mode = isset($_REQUEST['view']) ? (string)$_REQUEST['view'] : null; $rel_limit = 50; $group_info = array(); $is_moderator = false; -if ($group_id) -{ - if (!$group_info = get_group_data($group_id)) - { - bb_die($lang['GROUP_NOT_EXIST']); - } - if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) - { - bb_die("Invalid group data [group_id: $group_id]"); - } - $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); +if ($group_id) { + if (!$group_info = get_group_data($group_id)) { + bb_die($lang['GROUP_NOT_EXIST']); + } + if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) { + bb_die("Invalid group data [group_id: $group_id]"); + } + $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); } -if (!$group_id) -{ - // Show the main screen where the user can select a group. - $groups = array(); - $pending = 10; - $member = 20; +if (!$group_id) { + // Show the main screen where the user can select a group. + $groups = array(); + $pending = 10; + $member = 20; - $sql = " + $sql = " SELECT g.group_name, g.group_description, g.group_id, g.group_type, g.release_group, IF(ug.user_id IS NOT NULL, IF(ug.user_pending = 1, $pending, $member), 0) AS membership, @@ -80,16 +99,16 @@ if (!$group_id) IF(g.group_moderator = ug.user_id, 1, 0) AS is_group_mod, COUNT(ug2.user_id) AS members, SUM(ug2.user_pending) AS candidates FROM - ". BB_GROUPS ." g + " . BB_GROUPS . " g LEFT JOIN - ". BB_USER_GROUP ." ug ON + " . BB_USER_GROUP . " ug ON ug.group_id = g.group_id - AND ug.user_id = ". $userdata['user_id'] ." + AND ug.user_id = " . $userdata['user_id'] . " LEFT JOIN - ". BB_USER_GROUP ." ug2 ON + " . BB_USER_GROUP . " ug2 ON ug2.group_id = g.group_id LEFT JOIN - ". BB_USERS ." u ON g.group_moderator = u.user_id + " . BB_USERS . " u ON g.group_moderator = u.user_id WHERE g.group_single_user = 0 GROUP BY g.group_id @@ -100,597 +119,516 @@ if (!$group_id) g.group_name ASC "; - foreach (DB()->fetch_rowset($sql) as $row) - { - if ($row['is_group_mod']) - { - $type = 'MOD'; - } - else if ($row['membership'] == $member) - { - $type = 'MEMBER'; - } - else if ($row['membership'] == $pending) - { - $type = 'PENDING'; - } - else if ($row['group_type'] == GROUP_OPEN) - { - $type = 'OPEN'; - } - else if ($row['group_type'] == GROUP_CLOSED) - { - $type = 'CLOSED'; - } - else if ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) - { - $type = 'HIDDEN'; - } - else - { - continue; - } + foreach (DB()->fetch_rowset($sql) as $row) { + if ($row['is_group_mod']) { + $type = 'MOD'; + } elseif ($row['membership'] == $member) { + $type = 'MEMBER'; + } elseif ($row['membership'] == $pending) { + $type = 'PENDING'; + } elseif ($row['group_type'] == GROUP_OPEN) { + $type = 'OPEN'; + } elseif ($row['group_type'] == GROUP_CLOSED) { + $type = 'CLOSED'; + } elseif ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) { + $type = 'HIDDEN'; + } else { + continue; + } - $data = array('id' => $row['group_id'], 'm' => ($row['members'] - $row['candidates']), 'c' => $row['candidates'], 'rg' => $row['release_group']); + $data = array('id' => $row['group_id'], 'm' => ($row['members'] - $row['candidates']), 'c' => $row['candidates'], 'rg' => $row['release_group']); - $groups[$type][$row['group_name']] = $data; - } + $groups[$type][$row['group_name']] = $data; + } - function build_group($params) - { - global $lang; + function build_group($params) + { + global $lang; - $options = ''; - foreach ($params as $name => $data) - { - $text = htmlCHR(str_short(rtrim($name), HTML_SELECT_MAX_LENGTH)); + $options = ''; + foreach ($params as $name => $data) { + $text = htmlCHR(str_short(rtrim($name), HTML_SELECT_MAX_LENGTH)); - $members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] .': '. $data['m'] : $lang['NO_GROUP_MEMBERS']; - $candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] .': '. $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS']; + $members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] . ': ' . $data['m'] : $lang['NO_GROUP_MEMBERS']; + $candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] . ': ' . $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS']; - $options .= '
  • '. $text .'
  • '; - $options .= ($data['rg']) ? '
    • '. $lang['RELEASE_GROUP'] .'
    • ' : '
        '; - $options .= '
      • '. $members .'
      • '; - if (IS_AM) - { - $options .= '
      • '. $candidates .'
      • '; - } - $options .= '
      '; - } - return $options; - } + $options .= '
    • ' . $text . '
    • '; + $options .= ($data['rg']) ? '
      • ' . $lang['RELEASE_GROUP'] . '
      • ' : '
          '; + $options .= '
        • ' . $members . '
        • '; + if (IS_AM) { + $options .= '
        • ' . $candidates . '
        • '; + } + $options .= '
        '; + } + return $options; + } - if ($groups) - { - $s_hidden_fields = ''; + if ($groups) { + $s_hidden_fields = ''; - foreach ($groups as $type => $grp) - { - $template->assign_block_vars('groups', array( - 'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"], - 'GROUP_SELECT' => build_group($grp), - )); - } + foreach ($groups as $type => $grp) { + $template->assign_block_vars('groups', array( + 'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"], + 'GROUP_SELECT' => build_group($grp), + )); + } - $template->assign_vars(array( - 'SELECT_GROUP' => true, - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'S_USERGROUP_ACTION' => 'group.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - )); - } - else - { - if(IS_ADMIN) - { - redirect('admin/admin_groups.php'); - } - else bb_die($lang['NO_GROUPS_EXIST']); - } -} -else if (isset($_POST['joingroup']) && $_POST['joingroup']) -{ - if ($group_info['group_type'] != GROUP_OPEN) - { - bb_die($lang['THIS_CLOSED_GROUP']); - } + $template->assign_vars(array( + 'SELECT_GROUP' => true, + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'S_USERGROUP_ACTION' => 'group.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + )); + } else { + if (IS_ADMIN) { + redirect('admin/admin_groups.php'); + } else { + bb_die($lang['NO_GROUPS_EXIST']); + } + } +} elseif (isset($_POST['joingroup']) && $_POST['joingroup']) { + if ($group_info['group_type'] != GROUP_OPEN) { + bb_die($lang['THIS_CLOSED_GROUP']); + } - $sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang - FROM ". BB_GROUPS ." g - LEFT JOIN ". BB_USERS ." u ON(u.user_id = g.group_moderator) - LEFT JOIN ". BB_USER_GROUP ." ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']}) + $sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang + FROM " . BB_GROUPS . " g + LEFT JOIN " . BB_USERS . " u ON(u.user_id = g.group_moderator) + LEFT JOIN " . BB_USER_GROUP . " ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']}) WHERE g.group_id = $group_id AND group_single_user = 0 - AND g.group_type = ". GROUP_OPEN ." + AND g.group_type = " . GROUP_OPEN . " LIMIT 1"; - $row = $moderator = DB()->fetch_row($sql); + $row = $moderator = DB()->fetch_row($sql); - if (!$row['group_id']) - { - bb_die($lang['NO_GROUPS_EXIST']); - } - if ($row['user_id']) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['ALREADY_MEMBER_GROUP']); - } + if (!$row['group_id']) { + bb_die($lang['NO_GROUPS_EXIST']); + } + if ($row['user_id']) { + set_die_append_msg(false, false, $group_id); + bb_die($lang['ALREADY_MEMBER_GROUP']); + } - add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW); + add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW); - if ($bb_cfg['group_send_email']) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + if ($bb_cfg['group_send_email']) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($bb_cfg['smtp_delivery']); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($moderator['username'] ." <{$moderator['user_email']}>"); + $emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>"); + $emailer->email_address($moderator['username'] . " <{$moderator['user_email']}>"); - $emailer->use_template('group_request', $moderator['user_lang']); + $emailer->use_template('group_request', $moderator['user_lang']); - $emailer->assign_vars(array( - 'USER' => $userdata['username'], - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_MODERATOR' => $moderator['username'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'USER' => $userdata['username'], + 'SITENAME' => $bb_cfg['sitename'], + 'GROUP_MODERATOR' => $moderator['username'], + 'U_GROUP' => make_url(GROUP_URL . $group_id), + )); - $emailer->send(); - $emailer->reset(); - } + $emailer->send(); + $emailer->reset(); + } - set_die_append_msg(false, false, $group_id); - bb_die($lang['GROUP_JOINED']); -} -else if (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) -{ - delete_user_group($group_id, $userdata['user_id']); + set_die_append_msg(false, false, $group_id); + bb_die($lang['GROUP_JOINED']); +} elseif (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) { + delete_user_group($group_id, $userdata['user_id']); - set_die_append_msg(false, false, $group_id); - bb_die($lang['UNSUB_SUCCESS']); -} -else -{ - // Handle Additions, removals, approvals and denials - $group_moderator = $group_info['group_moderator']; + set_die_append_msg(false, false, $group_id); + bb_die($lang['UNSUB_SUCCESS']); +} else { + // Handle Additions, removals, approvals and denials + $group_moderator = $group_info['group_moderator']; - if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) - { - if (!$is_moderator) - { - bb_die($lang['NOT_GROUP_MODERATOR']); - } + if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) { + if (!$is_moderator) { + bb_die($lang['NOT_GROUP_MODERATOR']); + } - if (!empty($_POST['add'])) - { - if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true))) - { - bb_die($lang['COULD_NOT_ADD_USER']); - } + if (!empty($_POST['add'])) { + if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true))) { + bb_die($lang['COULD_NOT_ADD_USER']); + } - add_user_into_group($group_id, $row['user_id']); + add_user_into_group($group_id, $row['user_id']); - if ($bb_cfg['group_send_email']) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + if ($bb_cfg['group_send_email']) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($bb_cfg['smtp_delivery']); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); + $emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>"); + $emailer->email_address($row['username'] . " <{$row['user_email']}>"); - $emailer->use_template('group_added', $row['user_lang']); + $emailer->use_template('group_added', $row['user_lang']); - $emailer->assign_vars(array( - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'SITENAME' => $bb_cfg['sitename'], + 'GROUP_NAME' => $group_info['group_name'], + 'U_GROUP' => make_url(GROUP_URL . $group_id), + )); - $emailer->send(); - $emailer->reset(); - } - } - else - { - if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) - { - $members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members']; + $emailer->send(); + $emailer->reset(); + } + } else { + if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) { + $members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members']; - $sql_in = array(); - foreach ($members as $members_id) - { - $sql_in[] = (int) $members_id; - } - if (!$sql_in = join(',', $sql_in)) - { - bb_die($lang['NONE_SELECTED']); - } + $sql_in = array(); + foreach ($members as $members_id) { + $sql_in[] = (int)$members_id; + } + if (!$sql_in = join(',', $sql_in)) { + bb_die($lang['NONE_SELECTED']); + } - if (!empty($_POST['approve'])) - { - DB()->query(" - UPDATE ". BB_USER_GROUP ." SET + if (!empty($_POST['approve'])) { + DB()->query(" + UPDATE " . BB_USER_GROUP . " SET user_pending = 0 WHERE user_id IN($sql_in) AND group_id = $group_id "); - update_user_level($sql_in); - } - else if (!empty($_POST['deny']) || !empty($_POST['remove'])) - { - DB()->query(" - DELETE FROM ". BB_USER_GROUP ." + update_user_level($sql_in); + } elseif (!empty($_POST['deny']) || !empty($_POST['remove'])) { + DB()->query(" + DELETE FROM " . BB_USER_GROUP . " WHERE user_id IN($sql_in) AND group_id = $group_id "); - if (!empty($_POST['remove'])) - { - update_user_level($sql_in); - } - } - // Email users when they are approved - if (!empty($_POST['approve']) && $bb_cfg['group_send_email']) - { - $sql_select = "SELECT username, user_email, user_lang - FROM ". BB_USERS ." + if (!empty($_POST['remove'])) { + update_user_level($sql_in); + } + } + // Email users when they are approved + if (!empty($_POST['approve']) && $bb_cfg['group_send_email']) { + $sql_select = "SELECT username, user_email, user_lang + FROM " . BB_USERS . " WHERE user_id IN($sql_in)"; - if (!$result = DB()->sql_query($sql_select)) - { - bb_die('Could not get user email information'); - } + if (!$result = DB()->sql_query($sql_select)) { + bb_die('Could not get user email information'); + } - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($bb_cfg['smtp_delivery']); + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($bb_cfg['smtp_delivery']); - $emailer->from($bb_cfg['sitename'] ." <{$bb_cfg['board_email']}>"); + $emailer->from($bb_cfg['sitename'] . " <{$bb_cfg['board_email']}>"); - foreach (DB()->fetch_rowset($sql_select) as $row) - { - $emailer->use_template('group_approved', $row['user_lang']); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - } + foreach (DB()->fetch_rowset($sql_select) as $row) { + $emailer->use_template('group_approved', $row['user_lang']); + $emailer->email_address($row['username'] . " <{$row['user_email']}>"); + } - $emailer->assign_vars(array( - 'SITENAME' => $bb_cfg['sitename'], - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'SITENAME' => $bb_cfg['sitename'], + 'GROUP_NAME' => $group_info['group_name'], + 'U_GROUP' => make_url(GROUP_URL . $group_id), + )); - $emailer->send(); - $emailer->reset(); - } - } - } - } - // END approve or deny + $emailer->send(); + $emailer->reset(); + } + } + } + } + // END approve or deny - // Get moderator details for this group - $group_moderator = DB()->fetch_row(" + // Get moderator details for this group + $group_moderator = DB()->fetch_row(" SELECT * - FROM ". BB_USERS ." - WHERE user_id = ". $group_info['group_moderator'] ." + FROM " . BB_USERS . " + WHERE user_id = " . $group_info['group_moderator'] . " "); - // Current user membership - $is_group_member = $is_group_pending_member = false; + // Current user membership + $is_group_member = $is_group_pending_member = false; - $sql = "SELECT user_pending - FROM ". BB_USER_GROUP ." + $sql = "SELECT user_pending + FROM " . BB_USER_GROUP . " WHERE group_id = $group_id - AND user_id = ". $userdata['user_id'] ." + AND user_id = " . $userdata['user_id'] . " LIMIT 1"; - if ($row = DB()->fetch_row($sql)) - { - if ($row['user_pending'] == 0) - { - $is_group_member = true; - } - else - { - $is_group_pending_member = true; - } - } + if ($row = DB()->fetch_row($sql)) { + if ($row['user_pending'] == 0) { + $is_group_member = true; + } else { + $is_group_pending_member = true; + } + } - if ($userdata['user_id'] == $group_moderator['user_id']) - { - $group_details = $lang['ARE_GROUP_MODERATOR']; - $s_hidden_fields = ''; - } - else if ($is_group_member || $is_group_pending_member) - { - $template->assign_vars(array( - 'SHOW_UNSUBSCRIBE_CONTROLS' => true, - 'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending', - )); - $group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP']; - $s_hidden_fields = ''; - } - else if (IS_GUEST) - { - $group_details = $lang['LOGIN_TO_JOIN']; - $s_hidden_fields = ''; - } - else - { - if ($group_info['group_type'] == GROUP_OPEN) - { - $template->assign_var('SHOW_SUBSCRIBE_CONTROLS'); + if ($userdata['user_id'] == $group_moderator['user_id']) { + $group_details = $lang['ARE_GROUP_MODERATOR']; + $s_hidden_fields = ''; + } elseif ($is_group_member || $is_group_pending_member) { + $template->assign_vars(array( + 'SHOW_UNSUBSCRIBE_CONTROLS' => true, + 'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending', + )); + $group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP']; + $s_hidden_fields = ''; + } elseif (IS_GUEST) { + $group_details = $lang['LOGIN_TO_JOIN']; + $s_hidden_fields = ''; + } else { + if ($group_info['group_type'] == GROUP_OPEN) { + $template->assign_var('SHOW_SUBSCRIBE_CONTROLS'); - $group_details = $lang['THIS_OPEN_GROUP']; - $s_hidden_fields = ''; - } - else if ($group_info['group_type'] == GROUP_CLOSED) - { - $group_details = $lang['THIS_CLOSED_GROUP']; - $s_hidden_fields = ''; - } - else if ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_details = $lang['THIS_HIDDEN_GROUP']; - $s_hidden_fields = ''; - } - } + $group_details = $lang['THIS_OPEN_GROUP']; + $s_hidden_fields = ''; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_details = $lang['THIS_CLOSED_GROUP']; + $s_hidden_fields = ''; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_details = $lang['THIS_HIDDEN_GROUP']; + $s_hidden_fields = ''; + } + } - // Add the moderator - $username = $group_moderator['username']; - $user_id = $group_moderator['user_id']; + // Add the moderator + $username = $group_moderator['username']; + $user_id = $group_moderator['user_id']; - generate_user_info($group_moderator, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($group_moderator, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); - $group_type = ''; - if ($group_info['group_type'] == GROUP_OPEN) - { - $group_type = $lang['GROUP_OPEN']; - } - elseif ($group_info['group_type'] == GROUP_CLOSED) - { - $group_type = $lang['GROUP_CLOSED']; - } - elseif ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_type = $lang['GROUP_HIDDEN']; - } + $group_type = ''; + if ($group_info['group_type'] == GROUP_OPEN) { + $group_type = $lang['GROUP_OPEN']; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_type = $lang['GROUP_CLOSED']; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_type = $lang['GROUP_HIDDEN']; + } - $i = 0; - $template->assign_vars(array( - 'ROW_NUMBER' => $i + ($start + 1), - 'GROUP_INFO' => true, - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'GROUP_NAME' => htmlCHR($group_info['group_name']), - 'GROUP_DESCRIPTION' => bbcode2html($group_info['group_description']), - 'GROUP_SIGNATURE' => bbcode2html($group_info['group_signature']), - 'GROUP_AVATAR' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id'], true), - 'GROUP_DETAILS' => $group_details, - 'GROUP_TIME' => (!empty($group_info['group_time'])) ? sprintf('%s (%s)', bb_date($group_info['group_time']), delta_time($group_info['group_time'])) : $lang['NONE'], - 'MOD_USER' => profile_url($group_moderator), - 'MOD_AVATAR' => $avatar, - 'MOD_FROM' => $from, - 'MOD_JOINED' => $joined, - 'MOD_POSTS' => $posts, - 'MOD_PM' => $pm, - 'MOD_EMAIL' => $email, - 'MOD_WWW' => $www, - 'MOD_TIME' => (!empty($group_info['mod_time'])) ? bb_date($group_info['mod_time']) : $lang['NONE'], - 'U_SEARCH_USER' => "search.php?mode=searchuser", - 'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id", - 'U_GROUP_RELEASES' => "group.php?view=releases&". POST_GROUPS_URL ."=$group_id", - 'U_GROUP_MEMBERS' => "group.php?view=members&". POST_GROUPS_URL ."=$group_id", - 'U_GROUP_CONFIG' => "group_edit.php?g=$group_id", - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'GROUP_TYPE' => $group_type, + $i = 0; + $template->assign_vars(array( + 'ROW_NUMBER' => $i + ($start + 1), + 'GROUP_INFO' => true, + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'GROUP_NAME' => htmlCHR($group_info['group_name']), + 'GROUP_DESCRIPTION' => bbcode2html($group_info['group_description']), + 'GROUP_SIGNATURE' => bbcode2html($group_info['group_signature']), + 'GROUP_AVATAR' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id'], true), + 'GROUP_DETAILS' => $group_details, + 'GROUP_TIME' => (!empty($group_info['group_time'])) ? sprintf('%s (%s)', bb_date($group_info['group_time']), delta_time($group_info['group_time'])) : $lang['NONE'], + 'MOD_USER' => profile_url($group_moderator), + 'MOD_AVATAR' => $avatar, + 'MOD_FROM' => $from, + 'MOD_JOINED' => $joined, + 'MOD_POSTS' => $posts, + 'MOD_PM' => $pm, + 'MOD_EMAIL' => $email, + 'MOD_WWW' => $www, + 'MOD_TIME' => (!empty($group_info['mod_time'])) ? bb_date($group_info['mod_time']) : $lang['NONE'], + 'U_SEARCH_USER' => "search.php?mode=searchuser", + 'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id", + 'U_GROUP_RELEASES' => "group.php?view=releases&" . POST_GROUPS_URL . "=$group_id", + 'U_GROUP_MEMBERS' => "group.php?view=members&" . POST_GROUPS_URL . "=$group_id", + 'U_GROUP_CONFIG' => "group_edit.php?g=$group_id", + 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, + 'GROUP_TYPE' => $group_type, - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, - 'S_GROUP_ACTION' => "group.php?" . POST_GROUPS_URL . "=$group_id", - )); + 'S_GROUP_ACTION' => "group.php?" . POST_GROUPS_URL . "=$group_id", + )); - switch ($view_mode) - { - case 'releases': - // TODO Correct SQL to posts with attach and limit them, optimization + switch ($view_mode) { + case 'releases': + // TODO Correct SQL to posts with attach and limit them, optimization - if (!$group_info['release_group']) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['NOT_A_RELEASE_GROUP']); - } + if (!$group_info['release_group']) { + set_die_append_msg(false, false, $group_id); + bb_die($lang['NOT_A_RELEASE_GROUP']); + } - // Count releases for pagination - $all_releases = DB()->fetch_rowset(" + // Count releases for pagination + $all_releases = DB()->fetch_rowset(" SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) - LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) - LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id) + LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id) + LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id) WHERE p.poster_rg_id = $group_id ORDER BY t.topic_time DESC LIMIT $rel_limit "); - $count_releases = count($all_releases); + $count_releases = count($all_releases); - generate_pagination(GROUP_URL . $group_id ."&view=releases", $count_releases, $per_page, $start); + generate_pagination(GROUP_URL . $group_id . "&view=releases", $count_releases, $per_page, $start); - $sql = " + $sql = " SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) - LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) - LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id) + LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id) + LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id) WHERE p.poster_rg_id = $group_id ORDER BY t.topic_time DESC LIMIT $start, $per_page "; - if (!$releases = DB()->fetch_rowset($sql)) - { - set_die_append_msg(false, false, $group_id); - bb_die($lang['NO_SEARCH_MATCH']); - } + if (!$releases = DB()->fetch_rowset($sql)) { + set_die_append_msg(false, false, $group_id); + bb_die($lang['NO_SEARCH_MATCH']); + } - foreach ($releases as $i => $release) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + foreach ($releases as $i => $release) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('releases', array( - 'ROW_NUMBER' => $i + ( $start + 1 ), - 'ROW_CLASS' => $row_class, - 'RELEASER' => profile_url(array('user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank'])), - 'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50), - 'RELEASE_NAME' => sprintf('%s', TOPIC_URL . $release['topic_id'], htmlCHR($release['topic_title'])), - 'RELEASE_TIME' => bb_date($release['topic_time']), - 'RELEASE_FORUM' => sprintf('%s', FORUM_URL . $release['forum_id'], htmlCHR($release['forum_name'])), - )); - } + $template->assign_block_vars('releases', array( + 'ROW_NUMBER' => $i + ($start + 1), + 'ROW_CLASS' => $row_class, + 'RELEASER' => profile_url(array('user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank'])), + 'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50), + 'RELEASE_NAME' => sprintf('%s', TOPIC_URL . $release['topic_id'], htmlCHR($release['topic_title'])), + 'RELEASE_TIME' => bb_date($release['topic_time']), + 'RELEASE_FORUM' => sprintf('%s', FORUM_URL . $release['forum_id'], htmlCHR($release['forum_name'])), + )); + } - $template->assign_vars(array( - 'RELEASES' => true, - )); + $template->assign_vars(array( + 'RELEASES' => true, + )); - break; + break; - case 'members': - default: + case 'members': + default: - // Members - $count_members = DB()->fetch_rowset(" + // Members + $count_members = DB()->fetch_rowset(" SELECT u.username, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 0 - AND ug.user_id <> ". $group_moderator['user_id'] ." + AND ug.user_id <> " . $group_moderator['user_id'] . " AND u.user_id = ug.user_id ORDER BY u.username "); - $count_members = count($count_members); + $count_members = count($count_members); - // Get user information for this group - $modgroup_pending_count = 0; + // Get user information for this group + $modgroup_pending_count = 0; - // Members - $group_members = DB()->fetch_rowset(" + // Members + $group_members = DB()->fetch_rowset(" SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 0 - AND ug.user_id <> ". $group_moderator['user_id'] ." + AND ug.user_id <> " . $group_moderator['user_id'] . " AND u.user_id = ug.user_id ORDER BY u.username LIMIT $start, $per_page "); - $members_count = count($group_members); + $members_count = count($group_members); - generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start); + generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start); - // Dump out the remaining users - foreach ($group_members as $i => $member) - { - $user_id = $member['user_id']; + // Dump out the remaining users + foreach ($group_members as $i => $member) { + $user_id = $member['user_id']; - generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); - if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) - { - $row_class = !($i % 2) ? 'row1' : 'row2'; + if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) { + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('member', array( - 'ROW_NUMBER' => $i + ( $start + 1 ), - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($member), - 'AVATAR_IMG' => $avatar, - 'FROM' => $from, - 'JOINED' => $joined, - 'POSTS' => $posts, - 'USER_ID' => $user_id, - 'PM' => $pm, - 'EMAIL' => $email, - 'WWW' => $www, - 'TIME' => $user_time, - )); + $template->assign_block_vars('member', array( + 'ROW_NUMBER' => $i + ($start + 1), + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($member), + 'AVATAR_IMG' => $avatar, + 'FROM' => $from, + 'JOINED' => $joined, + 'POSTS' => $posts, + 'USER_ID' => $user_id, + 'PM' => $pm, + 'EMAIL' => $email, + 'WWW' => $www, + 'TIME' => $user_time, + )); - if ($is_moderator) - { - $template->assign_block_vars('member.switch_mod_option', array()); - } - } - } + if ($is_moderator) { + $template->assign_block_vars('member.switch_mod_option', array()); + } + } + } - // No group members - if (!$members_count) - { - $template->assign_block_vars('switch_no_members', array()); - } + // No group members + if (!$members_count) { + $template->assign_block_vars('switch_no_members', array()); + } - // No group members - if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) - { - $template->assign_block_vars('switch_hidden_group', array()); - } + // No group members + if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) { + $template->assign_block_vars('switch_hidden_group', array()); + } - // Pending - if ($is_moderator) - { - $modgroup_pending_list = DB()->fetch_rowset(" + // Pending + if ($is_moderator) { + $modgroup_pending_list = DB()->fetch_rowset(" SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email - FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u + FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u WHERE ug.group_id = $group_id AND ug.user_pending = 1 AND u.user_id = ug.user_id ORDER BY u.username LIMIT 200 "); - $modgroup_pending_count = count($modgroup_pending_list); - } + $modgroup_pending_count = count($modgroup_pending_list); + } - if ($is_moderator && $modgroup_pending_list) - { - foreach ($modgroup_pending_list as $i => $member) - { - $user_id = $member['user_id']; + if ($is_moderator && $modgroup_pending_list) { + foreach ($modgroup_pending_list as $i => $member) { + $user_id = $member['user_id']; - generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($member, $bb_cfg['default_dateformat'], $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $user_select = ''; + $user_select = ''; - $template->assign_block_vars('pending', array( - 'ROW_CLASS' => $row_class, - 'AVATAR_IMG'=> $avatar, - 'USER' => profile_url($member), - 'FROM' => $from, - 'JOINED' => $joined, - 'POSTS' => $posts, - 'USER_ID' => $user_id, - 'PM' => $pm, - 'EMAIL' => $email, - )); - } + $template->assign_block_vars('pending', array( + 'ROW_CLASS' => $row_class, + 'AVATAR_IMG' => $avatar, + 'USER' => profile_url($member), + 'FROM' => $from, + 'JOINED' => $joined, + 'POSTS' => $posts, + 'USER_ID' => $user_id, + 'PM' => $pm, + 'EMAIL' => $email, + )); + } - $template->assign_vars(array( - 'PENDING_USERS' => true, - )); - } + $template->assign_vars(array( + 'PENDING_USERS' => true, + )); + } - $template->assign_vars(array('MEMBERS' => true)); - } + $template->assign_vars(array('MEMBERS' => true)); + } - if ($is_moderator) - { - $template->assign_block_vars('switch_mod_option', array()); - $template->assign_block_vars('switch_add_member', array()); - } + if ($is_moderator) { + $template->assign_block_vars('switch_mod_option', array()); + $template->assign_block_vars('switch_add_member', array()); + } } -print_page('group.tpl'); \ No newline at end of file +print_page('group.tpl'); diff --git a/group_edit.php b/group_edit.php index 801e62f69..eb2f0906e 100644 --- a/group_edit.php +++ b/group_edit.php @@ -1,10 +1,33 @@ init($bb_cfg['group_avatars'], $_FILES['avatar']) AND $upload->store('avatar', array("user_id" => GROUP_AVATAR_MASK . $group_id, "avatar_ext_id" => $group_info['avatar_ext_id']))) - { - $avatar_ext_id = (int) $upload->file_ext_id; - } - else - { - bb_die(implode($upload->errors)); - } + if ($upload->init($bb_cfg['group_avatars'], $_FILES['avatar']) and $upload->store('avatar', array("user_id" => GROUP_AVATAR_MASK . $group_id, "avatar_ext_id" => $group_info['avatar_ext_id']))) { + $avatar_ext_id = (int)$upload->file_ext_id; + } else { + bb_die(implode($upload->errors)); + } - DB()->query("UPDATE ". BB_GROUPS ." SET avatar_ext_id = $avatar_ext_id WHERE group_id = $group_id LIMIT 1"); - } - } + DB()->query("UPDATE " . BB_GROUPS . " SET avatar_ext_id = $avatar_ext_id WHERE group_id = $group_id LIMIT 1"); + } + } - $group_type = ''; - if ($group_info['group_type'] == GROUP_OPEN) - { - $group_type = $lang['GROUP_OPEN']; - } - elseif ($group_info['group_type'] == GROUP_CLOSED) - { - $group_type = $lang['GROUP_CLOSED']; - } - elseif ($group_info['group_type'] == GROUP_HIDDEN) - { - $group_type = $lang['GROUP_HIDDEN']; - } + $group_type = ''; + if ($group_info['group_type'] == GROUP_OPEN) { + $group_type = $lang['GROUP_OPEN']; + } elseif ($group_info['group_type'] == GROUP_CLOSED) { + $group_type = $lang['GROUP_CLOSED']; + } elseif ($group_info['group_type'] == GROUP_HIDDEN) { + $group_type = $lang['GROUP_HIDDEN']; + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - $template->assign_vars(array( - 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], - 'GROUP_NAME' => htmlCHR($group_info['group_name']), - 'GROUP_ID' => $group_id, - 'GROUP_DESCRIPTION' => htmlCHR($group_info['group_description']), - 'GROUP_SIGNATURE' => htmlCHR($group_info['group_signature']), - 'U_GROUP_URL' => GROUP_URL . $group_id, - 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, - 'GROUP_TYPE' => $group_type, - 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, - 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, - 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, - 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', - 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', - 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_GROUP_CONFIG_ACTION' => "group_edit.php?" . POST_GROUPS_URL . "=$group_id", + $template->assign_vars(array( + 'PAGE_TITLE' => $lang['GROUP_CONTROL_PANEL'], + 'GROUP_NAME' => htmlCHR($group_info['group_name']), + 'GROUP_ID' => $group_id, + 'GROUP_DESCRIPTION' => htmlCHR($group_info['group_description']), + 'GROUP_SIGNATURE' => htmlCHR($group_info['group_signature']), + 'U_GROUP_URL' => GROUP_URL . $group_id, + 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, + 'GROUP_TYPE' => $group_type, + 'S_GROUP_OPEN_TYPE' => GROUP_OPEN, + 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, + 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, + 'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? ' checked="checked"' : '', + 'S_GROUP_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? ' checked="checked"' : '', + 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? ' checked="checked"' : '', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_GROUP_CONFIG_ACTION' => "group_edit.php?" . POST_GROUPS_URL . "=$group_id", - 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], $bb_cfg['group_avatars']['max_width'], $bb_cfg['group_avatars']['max_height'], (round($bb_cfg['group_avatars']['max_size'] / 1024))), - 'AVATAR_IMG' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']), - )); + 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], $bb_cfg['group_avatars']['max_width'], $bb_cfg['group_avatars']['max_height'], (round($bb_cfg['group_avatars']['max_size'] / 1024))), + 'AVATAR_IMG' => get_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']), + )); - $template->set_filenames(array('body' => 'group_edit.tpl')); - $template->assign_vars(array('PAGE_TITLE' => $lang['GROUP_CONFIGURATION'])); + $template->set_filenames(array('body' => 'group_edit.tpl')); + $template->assign_vars(array('PAGE_TITLE' => $lang['GROUP_CONFIGURATION'])); - require(PAGE_HEADER); + require(PAGE_HEADER); - $template->pparse('body'); + $template->pparse('body'); - require(PAGE_FOOTER); + require(PAGE_FOOTER); +} else { + $redirect = 'index.php'; + + if ($group_id) { + $redirect = GROUP_URL . $group_id; + } + redirect($redirect); } -else -{ - $redirect = 'index.php'; - - if ($group_id) - { - $redirect = GROUP_URL . $group_id; - } - redirect($redirect); -} \ No newline at end of file diff --git a/index.php b/index.php index 7dc7b44a9..71995e8fc 100644 --- a/index.php +++ b/index.php @@ -1,37 +1,58 @@ enqueue(array( - 'stats', - 'moderators', + 'stats', + 'moderators', )); -if ($bb_cfg['show_latest_news']) -{ - $datastore->enqueue('latest_news'); +if ($bb_cfg['show_latest_news']) { + $datastore->enqueue('latest_news'); } -if ($bb_cfg['show_network_news']) -{ - $datastore->enqueue('network_news'); +if ($bb_cfg['show_network_news']) { + $datastore->enqueue('network_news'); } // Init userdata $user->session_start(); // Init main vars -$viewcat = isset($_GET['c']) ? (int) $_GET['c'] : 0; +$viewcat = isset($_GET['c']) ? (int)$_GET['c'] : 0; $lastvisit = (IS_GUEST) ? TIMENOW : $userdata['user_lastvisit']; // Caching output @@ -39,28 +60,26 @@ $req_page = 'index_page'; $req_page .= ($viewcat) ? "_c{$viewcat}" : ''; define('REQUESTED_PAGE', $req_page); -caching_output(IS_GUEST, 'send', REQUESTED_PAGE .'_guest_'. $bb_cfg['default_lang']); +caching_output(IS_GUEST, 'send', REQUESTED_PAGE . '_guest_' . $bb_cfg['default_lang']); -$hide_cat_opt = isset($user->opt_js['h_cat']) ? (string) $user->opt_js['h_cat'] : 0; +$hide_cat_opt = isset($user->opt_js['h_cat']) ? (string)$user->opt_js['h_cat'] : 0; $hide_cat_user = array_flip(explode('-', $hide_cat_opt)); -$showhide = isset($_GET['sh']) ? (int) $_GET['sh'] : 0; +$showhide = isset($_GET['sh']) ? (int)$_GET['sh'] : 0; // Topics read tracks $tracking_topics = get_tracks('topic'); $tracking_forums = get_tracks('forum'); // Statistics -if (!$stats = $datastore->get('stats')) -{ - $datastore->update('stats'); - $stats = $datastore->get('stats'); +if (!$stats = $datastore->get('stats')) { + $datastore->update('stats'); + $stats = $datastore->get('stats'); } // Forums data -if (!$forums = $datastore->get('cat_forums')) -{ - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); +if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); } $cat_title_html = $forums['cat_title_html']; $forum_name_html = $forums['forum_name_html']; @@ -70,9 +89,8 @@ $excluded_forums_csv = $user->get_excluded_forums(AUTH_VIEW); $only_new = $user->opt_js['only_new']; // Validate requested category id -if ($viewcat AND !$viewcat =& $forums['c'][$viewcat]['cat_id']) -{ - redirect("index.php"); +if ($viewcat and !$viewcat =& $forums['c'][$viewcat]['cat_id']) { + redirect("index.php"); } // Forums @@ -106,96 +124,78 @@ $sql = " t.topic_id AS last_topic_id, t.topic_title AS last_topic_title, u.user_id AS last_post_user_id, u.user_rank AS last_post_user_rank, IF(p.poster_id = $anon, p.post_username, u.username) AS last_post_username - FROM ". BB_CATEGORIES ." c - INNER JOIN ". BB_FORUMS ." f ON($forums_join_sql) - $join_p_type ". BB_POSTS ." p ON($posts_join_sql) - $join_t_type ". BB_TOPICS ." t ON($topics_join_sql) - LEFT JOIN ". BB_USERS ." u ON(u.user_id = p.poster_id) + FROM " . BB_CATEGORIES . " c + INNER JOIN " . BB_FORUMS . " f ON($forums_join_sql) + $join_p_type " . BB_POSTS . " p ON($posts_join_sql) + $join_t_type " . BB_TOPICS . " t ON($topics_join_sql) + LEFT JOIN " . BB_USERS . " u ON(u.user_id = p.poster_id) ORDER BY c.cat_order, f.forum_order "; $replace_in_parent = array( - 'last_post_id', - 'last_post_time', - 'last_post_user_id', - 'last_post_username', - 'last_post_user_rank', - 'last_topic_title', - 'last_topic_id', + 'last_post_id', + 'last_post_time', + 'last_post_user_id', + 'last_post_username', + 'last_post_user_rank', + 'last_topic_title', + 'last_topic_id', ); $cache_name = 'index_sql_' . md5($sql); -if (!$cat_forums = CACHE('bb_cache')->get($cache_name)) -{ - $cat_forums = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - if (!$cat_id = $row['cat_id'] OR !$forum_id = $row['forum_id']) - { - continue; - } +if (!$cat_forums = CACHE('bb_cache')->get($cache_name)) { + $cat_forums = array(); + foreach (DB()->fetch_rowset($sql) as $row) { + if (!$cat_id = $row['cat_id'] or !$forum_id = $row['forum_id']) { + continue; + } - if ($parent_id = $row['forum_parent']) - { - if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id]) - { - $parent = $forums['f'][$parent_id]; - $parent['last_post_time'] = 0; - } - if ($row['last_post_time'] > $parent['last_post_time']) - { - foreach ($replace_in_parent as $key) - { - $parent[$key] = $row[$key]; - } - } - if ($show_subforums && $row['show_on_index']) - { - $parent['last_sf_id'] = $forum_id; - } - else - { - continue; - } - } - else - { - $f =& $forums['f'][$forum_id]; - $row['forum_desc'] = $f['forum_desc']; - $row['forum_posts'] = $f['forum_posts']; - $row['forum_topics'] = $f['forum_topics']; - } - $cat_forums[$cat_id]['f'][$forum_id] = $row; - } - CACHE('bb_cache')->set($cache_name, $cat_forums, 180); - unset($row, $forums); - $datastore->rm('cat_forums'); + if ($parent_id = $row['forum_parent']) { + if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id]) { + $parent = $forums['f'][$parent_id]; + $parent['last_post_time'] = 0; + } + if ($row['last_post_time'] > $parent['last_post_time']) { + foreach ($replace_in_parent as $key) { + $parent[$key] = $row[$key]; + } + } + if ($show_subforums && $row['show_on_index']) { + $parent['last_sf_id'] = $forum_id; + } else { + continue; + } + } else { + $f =& $forums['f'][$forum_id]; + $row['forum_desc'] = $f['forum_desc']; + $row['forum_posts'] = $f['forum_posts']; + $row['forum_topics'] = $f['forum_topics']; + } + $cat_forums[$cat_id]['f'][$forum_id] = $row; + } + CACHE('bb_cache')->set($cache_name, $cat_forums, 180); + unset($row, $forums); + $datastore->rm('cat_forums'); } // Obtain list of moderators $moderators = array(); -if (!$mod = $datastore->get('moderators')) -{ - $datastore->update('moderators'); - $mod = $datastore->get('moderators'); +if (!$mod = $datastore->get('moderators')) { + $datastore->update('moderators'); + $mod = $datastore->get('moderators'); } -if (!empty($mod)) -{ - foreach ($mod['mod_users'] as $forum_id => $user_ids) - { - foreach ($user_ids as $user_id) - { - $moderators[$forum_id][] = ''. $mod['name_users'][$user_id] .''; - } - } - foreach ($mod['mod_groups'] as $forum_id => $group_ids) - { - foreach ($group_ids as $group_id) - { - $moderators[$forum_id][] = ''. $mod['name_groups'][$group_id] .''; - } - } +if (!empty($mod)) { + foreach ($mod['mod_users'] as $forum_id => $user_ids) { + foreach ($user_ids as $user_id) { + $moderators[$forum_id][] = '' . $mod['name_users'][$user_id] . ''; + } + } + foreach ($mod['mod_groups'] as $forum_id => $group_ids) { + foreach ($group_ids as $group_id) { + $moderators[$forum_id][] = '' . $mod['name_groups'][$group_id] . ''; + } + } } unset($mod); @@ -203,229 +203,209 @@ $datastore->rm('moderators'); // Build index page $forums_count = 0; -foreach ($cat_forums as $cid => $c) -{ - $template->assign_block_vars('h_c', array( - 'H_C_ID' => $cid, - 'H_C_TITLE' => $cat_title_html[$cid], - 'H_C_CHEKED' => in_array($cid, preg_split("/[-]+/", $hide_cat_opt)) ? 'checked' : '', - )); +foreach ($cat_forums as $cid => $c) { + $template->assign_block_vars('h_c', array( + 'H_C_ID' => $cid, + 'H_C_TITLE' => $cat_title_html[$cid], + 'H_C_CHEKED' => in_array($cid, preg_split("/[-]+/", $hide_cat_opt)) ? 'checked' : '', + )); - $template->assign_vars(array( - 'H_C_AL_MESS' => ($hide_cat_opt && !$showhide) ? true : false, - )); + $template->assign_vars(array( + 'H_C_AL_MESS' => ($hide_cat_opt && !$showhide) ? true : false, + )); - if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) - { - continue; - } + if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) { + continue; + } - $template->assign_block_vars('c', array( - 'CAT_ID' => $cid, - 'CAT_TITLE' => $cat_title_html[$cid], - 'U_VIEWCAT' => CAT_URL . $cid, - )); + $template->assign_block_vars('c', array( + 'CAT_ID' => $cid, + 'CAT_TITLE' => $cat_title_html[$cid], + 'U_VIEWCAT' => CAT_URL . $cid, + )); - foreach ($c['f'] as $fid => $f) - { - if (!$fname_html =& $forum_name_html[$fid]) - { - continue; - } - $is_sf = $f['forum_parent']; + foreach ($c['f'] as $fid => $f) { + if (!$fname_html =& $forum_name_html[$fid]) { + continue; + } + $is_sf = $f['forum_parent']; - $forums_count++; - $new = is_unread($f['last_post_time'], $f['last_topic_id'], $f['forum_id']) ? '_new' : ''; - $folder_image = ($is_sf) ? $images["icon_minipost{$new}"] : $images["forum{$new}"]; + $forums_count++; + $new = is_unread($f['last_post_time'], $f['last_topic_id'], $f['forum_id']) ? '_new' : ''; + $folder_image = ($is_sf) ? $images["icon_minipost{$new}"] : $images["forum{$new}"]; - if ($f['forum_status'] == FORUM_LOCKED) - { - $folder_image = ($is_sf) ? $images['icon_minipost'] : $images['forum_locked']; - } + if ($f['forum_status'] == FORUM_LOCKED) { + $folder_image = ($is_sf) ? $images['icon_minipost'] : $images['forum_locked']; + } - if ($is_sf) - { - $template->assign_block_vars('c.f.sf', array( - 'SF_ID' => $fid, - 'SF_NAME' => $fname_html, - 'SF_NEW' => $new ? ' new' : '', - )); - continue; - } + if ($is_sf) { + $template->assign_block_vars('c.f.sf', array( + 'SF_ID' => $fid, + 'SF_NAME' => $fname_html, + 'SF_NEW' => $new ? ' new' : '', + )); + continue; + } - $template->assign_block_vars('c.f', array( - 'FORUM_FOLDER_IMG' => $folder_image, - 'FORUM_ID' => $fid, - 'FORUM_NAME' => $fname_html, - 'FORUM_DESC' => $f['forum_desc'], - 'POSTS' => commify($f['forum_posts']), - 'TOPICS' => commify($f['forum_topics']), - 'LAST_SF_ID' => isset($f['last_sf_id']) ? $f['last_sf_id'] : null, - 'MODERATORS' => isset($moderators[$fid]) ? join(', ', $moderators[$fid]) : '', - 'FORUM_FOLDER_ALT' => ($new) ? $lang['NEW'] : $lang['OLD'], - )); + $template->assign_block_vars('c.f', array( + 'FORUM_FOLDER_IMG' => $folder_image, + 'FORUM_ID' => $fid, + 'FORUM_NAME' => $fname_html, + 'FORUM_DESC' => $f['forum_desc'], + 'POSTS' => commify($f['forum_posts']), + 'TOPICS' => commify($f['forum_topics']), + 'LAST_SF_ID' => isset($f['last_sf_id']) ? $f['last_sf_id'] : null, + 'MODERATORS' => isset($moderators[$fid]) ? join(', ', $moderators[$fid]) : '', + 'FORUM_FOLDER_ALT' => ($new) ? $lang['NEW'] : $lang['OLD'], + )); - if ($f['last_post_id']) - { - $template->assign_block_vars('c.f.last', array( - 'LAST_TOPIC_ID' => $f['last_topic_id'], - 'LAST_TOPIC_TIP' => $f['last_topic_title'], - 'LAST_TOPIC_TITLE' => wbr(str_short($f['last_topic_title'], $last_topic_max_len)), - 'LAST_POST_TIME' => bb_date($f['last_post_time'], $bb_cfg['last_post_date_format']), - 'LAST_POST_USER' => profile_url(array('username' => str_short($f['last_post_username'], 15), 'user_id' => $f['last_post_user_id'], 'user_rank' => $f['last_post_user_rank'])), - )); - } - } + if ($f['last_post_id']) { + $template->assign_block_vars('c.f.last', array( + 'LAST_TOPIC_ID' => $f['last_topic_id'], + 'LAST_TOPIC_TIP' => $f['last_topic_title'], + 'LAST_TOPIC_TITLE' => wbr(str_short($f['last_topic_title'], $last_topic_max_len)), + 'LAST_POST_TIME' => bb_date($f['last_post_time'], $bb_cfg['last_post_date_format']), + 'LAST_POST_USER' => profile_url(array('username' => str_short($f['last_post_username'], 15), 'user_id' => $f['last_post_user_id'], 'user_rank' => $f['last_post_user_rank'])), + )); + } + } } $template->assign_vars(array( - 'SHOW_FORUMS' => $forums_count, - 'SHOW_MAP' => (isset($_GET['map']) && !IS_GUEST), - 'PAGE_TITLE' => ($viewcat) ? $cat_title_html[$viewcat] : $lang['HOME'], - 'NO_FORUMS_MSG' => ($only_new) ? $lang['NO_NEW_POSTS'] : $lang['NO_FORUMS'], + 'SHOW_FORUMS' => $forums_count, + 'SHOW_MAP' => (isset($_GET['map']) && !IS_GUEST), + 'PAGE_TITLE' => ($viewcat) ? $cat_title_html[$viewcat] : $lang['HOME'], + 'NO_FORUMS_MSG' => ($only_new) ? $lang['NO_NEW_POSTS'] : $lang['NO_FORUMS'], - 'TOTAL_TOPICS' => sprintf($lang['POSTED_TOPICS_TOTAL'], $stats['topiccount']), - 'TOTAL_POSTS' => sprintf($lang['POSTED_ARTICLES_TOTAL'], $stats['postcount']), - 'TOTAL_USERS' => sprintf($lang['REGISTERED_USERS_TOTAL'], $stats['usercount']), - 'TOTAL_GENDER' => ($bb_cfg['gender']) ? sprintf($lang['USERS_TOTAL_GENDER'], $stats['male'], $stats['female'], $stats['unselect']) : '', - 'NEWEST_USER' => sprintf($lang['NEWEST_USER'], profile_url($stats['newestuser'])), + 'TOTAL_TOPICS' => sprintf($lang['POSTED_TOPICS_TOTAL'], $stats['topiccount']), + 'TOTAL_POSTS' => sprintf($lang['POSTED_ARTICLES_TOTAL'], $stats['postcount']), + 'TOTAL_USERS' => sprintf($lang['REGISTERED_USERS_TOTAL'], $stats['usercount']), + 'TOTAL_GENDER' => ($bb_cfg['gender']) ? sprintf($lang['USERS_TOTAL_GENDER'], $stats['male'], $stats['female'], $stats['unselect']) : '', + 'NEWEST_USER' => sprintf($lang['NEWEST_USER'], profile_url($stats['newestuser'])), - // Tracker stats - 'TORRENTS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', - 'PEERS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['PEERS_STAT'], $stats['peers'], $stats['seeders'], $stats['leechers']) : '', - 'SPEED_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['SPEED_STAT'], humn_size($stats['speed']) .'/s') : '', - 'SHOW_MOD_INDEX' => $bb_cfg['show_mod_index'], - 'FORUM_IMG' => $images['forum'], - 'FORUM_NEW_IMG' => $images['forum_new'], - 'FORUM_LOCKED_IMG' => $images['forum_locked'], + // Tracker stats + 'TORRENTS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', + 'PEERS_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['PEERS_STAT'], $stats['peers'], $stats['seeders'], $stats['leechers']) : '', + 'SPEED_STAT' => ($bb_cfg['tor_stats']) ? sprintf($lang['SPEED_STAT'], humn_size($stats['speed']) . '/s') : '', + 'SHOW_MOD_INDEX' => $bb_cfg['show_mod_index'], + 'FORUM_IMG' => $images['forum'], + 'FORUM_NEW_IMG' => $images['forum_new'], + 'FORUM_LOCKED_IMG' => $images['forum_locked'], - 'SHOW_ONLY_NEW_MENU' => true, - 'ONLY_NEW_POSTS_ON' => ($only_new == ONLY_NEW_POSTS), - 'ONLY_NEW_TOPICS_ON' => ($only_new == ONLY_NEW_TOPICS), + 'SHOW_ONLY_NEW_MENU' => true, + 'ONLY_NEW_POSTS_ON' => ($only_new == ONLY_NEW_POSTS), + 'ONLY_NEW_TOPICS_ON' => ($only_new == ONLY_NEW_TOPICS), - 'U_SEARCH_NEW' => "search.php?new=1", - 'U_SEARCH_SELF_BY_MY' => "search.php?uid={$userdata['user_id']}&o=1", - 'U_SEARCH_LATEST' => "search.php?search_id=latest", - 'U_SEARCH_UNANSWERED' => "search.php?search_id=unanswered", + 'U_SEARCH_NEW' => "search.php?new=1", + 'U_SEARCH_SELF_BY_MY' => "search.php?uid={$userdata['user_id']}&o=1", + 'U_SEARCH_LATEST' => "search.php?search_id=latest", + 'U_SEARCH_UNANSWERED' => "search.php?search_id=unanswered", - 'SHOW_LAST_TOPIC' => $show_last_topic, + 'SHOW_LAST_TOPIC' => $show_last_topic, )); // Set tpl vars for bt_userdata -if ($bb_cfg['bt_show_dl_stat_on_index'] && !IS_GUEST) -{ - show_bt_userdata($userdata['user_id']); +if ($bb_cfg['bt_show_dl_stat_on_index'] && !IS_GUEST) { + show_bt_userdata($userdata['user_id']); } // Latest news -if ($bb_cfg['show_latest_news']) -{ - if (!$latest_news = $datastore->get('latest_news')) - { - $datastore->update('latest_news'); - $latest_news = $datastore->get('latest_news'); - } +if ($bb_cfg['show_latest_news']) { + if (!$latest_news = $datastore->get('latest_news')) { + $datastore->update('latest_news'); + $latest_news = $datastore->get('latest_news'); + } - $template->assign_vars(array( - 'SHOW_LATEST_NEWS' => true, - )); + $template->assign_vars(array( + 'SHOW_LATEST_NEWS' => true, + )); - foreach ($latest_news as $news) - { - $template->assign_block_vars('news', array( - 'NEWS_TOPIC_ID' => $news['topic_id'], - 'NEWS_TITLE' => str_short($news['topic_title'], $bb_cfg['max_news_title']), - 'NEWS_TIME' => bb_date($news['topic_time'], 'd-M', false), - 'NEWS_IS_NEW' => is_unread($news['topic_time'], $news['topic_id'], $news['forum_id']), - )); - } + foreach ($latest_news as $news) { + $template->assign_block_vars('news', array( + 'NEWS_TOPIC_ID' => $news['topic_id'], + 'NEWS_TITLE' => str_short($news['topic_title'], $bb_cfg['max_news_title']), + 'NEWS_TIME' => bb_date($news['topic_time'], 'd-M', false), + 'NEWS_IS_NEW' => is_unread($news['topic_time'], $news['topic_id'], $news['forum_id']), + )); + } } // Network news -if ($bb_cfg['show_network_news']) -{ - if (!$network_news = $datastore->get('network_news')) - { - $datastore->update('network_news'); - $network_news = $datastore->get('network_news'); - } +if ($bb_cfg['show_network_news']) { + if (!$network_news = $datastore->get('network_news')) { + $datastore->update('network_news'); + $network_news = $datastore->get('network_news'); + } - $template->assign_vars(array( - 'SHOW_NETWORK_NEWS' => true, - )); + $template->assign_vars(array( + 'SHOW_NETWORK_NEWS' => true, + )); - foreach ($network_news as $net) - { - $template->assign_block_vars('net', array( - 'NEWS_TOPIC_ID' => $net['topic_id'], - 'NEWS_TITLE' => str_short($net['topic_title'], $bb_cfg['max_net_title']), - 'NEWS_TIME' => bb_date($net['topic_time'], 'd-M', false), - 'NEWS_IS_NEW' => is_unread($net['topic_time'], $net['topic_id'], $net['forum_id']), - )); - } + foreach ($network_news as $net) { + $template->assign_block_vars('net', array( + 'NEWS_TOPIC_ID' => $net['topic_id'], + 'NEWS_TITLE' => str_short($net['topic_title'], $bb_cfg['max_net_title']), + 'NEWS_TIME' => bb_date($net['topic_time'], 'd-M', false), + 'NEWS_IS_NEW' => is_unread($net['topic_time'], $net['topic_id'], $net['forum_id']), + )); + } } -if ($bb_cfg['birthday_check_day'] && $bb_cfg['birthday_enabled']) -{ - $week_list = $today_list = array(); - $week_all = $today_all = false; +if ($bb_cfg['birthday_check_day'] && $bb_cfg['birthday_enabled']) { + $week_list = $today_list = array(); + $week_all = $today_all = false; - if ($stats['birthday_week_list']) - { - shuffle($stats['birthday_week_list']); - foreach ($stats['birthday_week_list'] as $i => $week) - { - if ($i >= 5) - { - $week_all = true; - continue; - } - $week_list[] = profile_url($week) .' ('. birthday_age($week['user_birthday']-1) .')'; - } - $week_all = ($week_all) ? ' ...' : ''; - $week_list = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $week_list)) . $week_all; - } - else $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); + if ($stats['birthday_week_list']) { + shuffle($stats['birthday_week_list']); + foreach ($stats['birthday_week_list'] as $i => $week) { + if ($i >= 5) { + $week_all = true; + continue; + } + $week_list[] = profile_url($week) . ' (' . birthday_age($week['user_birthday'] - 1) . ')'; + } + $week_all = ($week_all) ? ' ...' : ''; + $week_list = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $week_list)) . $week_all; + } else { + $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); + } - if ($stats['birthday_today_list']) - { - shuffle($stats['birthday_today_list']); - foreach ($stats['birthday_today_list'] as $i => $today) - { - if ($i >= 5) - { - $today_all = true; - continue; - } - $today_list[] = profile_url($today) .' ('. birthday_age($today['user_birthday']) .')'; - } - $today_all = ($today_all) ? ' ...' : ''; - $today_list = $lang['BIRTHDAY_TODAY'] . join(', ', $today_list) . $today_all; - } - else $today_list = $lang['NOBIRTHDAY_TODAY']; + if ($stats['birthday_today_list']) { + shuffle($stats['birthday_today_list']); + foreach ($stats['birthday_today_list'] as $i => $today) { + if ($i >= 5) { + $today_all = true; + continue; + } + $today_list[] = profile_url($today) . ' (' . birthday_age($today['user_birthday']) . ')'; + } + $today_all = ($today_all) ? ' ...' : ''; + $today_list = $lang['BIRTHDAY_TODAY'] . join(', ', $today_list) . $today_all; + } else { + $today_list = $lang['NOBIRTHDAY_TODAY']; + } - $template->assign_vars(array( - 'WHOSBIRTHDAY_WEEK' => $week_list, - 'WHOSBIRTHDAY_TODAY' => $today_list, - )); + $template->assign_vars(array( + 'WHOSBIRTHDAY_WEEK' => $week_list, + 'WHOSBIRTHDAY_TODAY' => $today_list, + )); } // Allow cron -if (IS_AM) -{ - if (file_exists(CRON_RUNNING)) - { - if (file_exists(CRON_ALLOWED)) - { - unlink (CRON_ALLOWED); - } - rename(CRON_RUNNING, CRON_ALLOWED); - } +if (IS_AM) { + if (file_exists(CRON_RUNNING)) { + if (file_exists(CRON_ALLOWED)) { + unlink(CRON_ALLOWED); + } + rename(CRON_RUNNING, CRON_ALLOWED); + } } // Display page define('SHOW_ONLINE', $show_online_users); -if (isset($_GET['map'])) $template->assign_vars(array('PAGE_TITLE' => $lang['FORUM_MAP'])); +if (isset($_GET['map'])) { + $template->assign_vars(array('PAGE_TITLE' => $lang['FORUM_MAP'])); +} -print_page('index.tpl'); \ No newline at end of file +print_page('index.tpl'); diff --git a/info.php b/info.php index 500596c8d..b2cddacf2 100644 --- a/info.php +++ b/info.php @@ -1,8 +1,31 @@ session_start(); @@ -11,32 +34,31 @@ global $lang; $info = array(); $html_dir = LANG_DIR . 'html/'; -$req_mode = !empty($_REQUEST['show']) ? (string) $_REQUEST['show'] : 'not_found'; +$req_mode = !empty($_REQUEST['show']) ? (string)$_REQUEST['show'] : 'not_found'; -switch ($req_mode) -{ - case 'advert': - $info['title'] = $lang['ADVERT']; - $info['src'] = 'advert.html'; - break; +switch ($req_mode) { + case 'advert': + $info['title'] = $lang['ADVERT']; + $info['src'] = 'advert.html'; + break; - case 'copyright_holders': - $info['title'] = $lang['COPYRIGHT_HOLDERS']; - $info['src'] = 'copyright_holders.html'; - break; + case 'copyright_holders': + $info['title'] = $lang['COPYRIGHT_HOLDERS']; + $info['src'] = 'copyright_holders.html'; + break; - case 'not_found': - $info['title'] = $lang['NOT_FOUND']; - $info['src'] = 'not_found.html'; - break; + case 'not_found': + $info['title'] = $lang['NOT_FOUND']; + $info['src'] = 'not_found.html'; + break; - case 'user_agreement': - $info['title'] = $lang['USER_AGREEMENT']; - $info['src'] = 'user_agreement.html'; - break; + case 'user_agreement': + $info['title'] = $lang['USER_AGREEMENT']; + $info['src'] = 'user_agreement.html'; + break; - default: - bb_simple_die('Invalid request'); + default: + bb_simple_die('Invalid request'); } $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $html_dir . 'not_found.html'; @@ -44,28 +66,40 @@ $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $h ?> - - - + + + -
        +
        -
        - -
        - -
        -
        -

        [ ]

        +
        + +
        + +
        +
        +

        [ ] +

        \ No newline at end of file diff --git a/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php b/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php index f419ab6d9..ac21cfafb 100644 --- a/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php +++ b/install/other/converter/TBDevYSE_pre6/for_tbdev/announce.php @@ -1,34 +1,55 @@
        -
        +
        '; -} -else -{ - if (!file_exists('passwords.php')) stderr($tracker_lang['error'], 'passwords.php not exists'); +} else { + if (!file_exists('passwords.php')) { + stderr($tracker_lang['error'], 'passwords.php not exists'); + } - include('passwords.php'); - stdhead(); - foreach ($passwords as $user) - { - $msg_sql = sprintf($msg, $user['username'], $user['new_passwd']); - sql_query("INSERT INTO messages (receiver, added, subject, msg) VALUES({$user['tb_user_id']}, NOW(), ".sqlesc($subject).", ".sqlesc($msg_sql).")"); - } - stdmsg('OK', 'Mass PM succesful'); + include('passwords.php'); + stdhead(); + foreach ($passwords as $user) { + $msg_sql = sprintf($msg, $user['username'], $user['new_passwd']); + sql_query("INSERT INTO messages (receiver, added, subject, msg) VALUES({$user['tb_user_id']}, NOW(), " . sqlesc($subject) . ", " . sqlesc($msg_sql) . ")"); + } + stdmsg('OK', 'Mass PM succesful'); } -stdfoot(); \ No newline at end of file +stdfoot(); diff --git a/install/other/converter/TBDevYSE_pre6/root/convert.php b/install/other/converter/TBDevYSE_pre6/root/convert.php index 48192b3a2..091fa1ac4 100644 --- a/install/other/converter/TBDevYSE_pre6/root/convert.php +++ b/install/other/converter/TBDevYSE_pre6/root/convert.php @@ -1,8 +1,31 @@ session_start(); -if (!IS_ADMIN) die("Restricted access"); -while (@ob_end_flush()); +if (!IS_ADMIN) { + die("Restricted access"); +} +while (@ob_end_flush()) ; ob_implicit_flush(); error_reporting(E_ALL); @ini_set('display_errors', 1); ?> - - - - - - - + + + + + + +
        -
        +
        '; - exit; -} -else -{ - -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); + exit; +} else { + @ini_set('memory_limit', '512M'); + @ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); // Step 1: Converting Users -if (CONVERT_USERS) -{ - if (CLEAN) - { - tp_users_cleanup(); - print_ok ("Users cleared"); - } + if (CONVERT_USERS) { + if (CLEAN) { + tp_users_cleanup(); + print_ok("Users cleared"); + } - $max_uid = (int) get_max_val(BB_USERS, 'user_id'); - $max_uid = ($max_uid > 1) ? $max_uid : 1; + $max_uid = (int)get_max_val(BB_USERS, 'user_id'); + $max_uid = ($max_uid > 1) ? $max_uid : 1; - $users_count = (int) get_count(TB_USERS_TABLE, 'id'); - $loops = (int) ceil($users_count / C_USERS_PER_ONCE); - $pass = array(); + $users_count = (int)get_count(TB_USERS_TABLE, 'id'); + $loops = (int)ceil($users_count / C_USERS_PER_ONCE); + $pass = array(); - switch(TR_TYPE) - { - case 'yse': - $_sql = 'avatar, '; - break; + switch (TR_TYPE) { + case 'yse': + $_sql = 'avatar, '; + break; - default: - $_sql = ''; - break; - } + default: + $_sql = ''; + break; + } - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_USERS_PER_ONCE; - $offset = C_USERS_PER_ONCE; + for ($i = 0; $i < $loops; $i++) { + $start = $i * C_USERS_PER_ONCE; + $offset = C_USERS_PER_ONCE; - $sql = " + $sql = " SELECT id, username, email, status, UNIX_TIMESTAMP(added) AS added, UNIX_TIMESTAMP(last_access) AS last_access, class, icq, msn, aim, yahoo, website, $_sql uploaded, downloaded, enabled, language - FROM ". TB_USERS_TABLE ." + FROM " . TB_USERS_TABLE . " ORDER BY id LIMIT $start, $offset"; - $users = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); + $users = DB()->fetch_rowset($sql); + DB()->sql_freeresult(); - foreach ($users as $user) - { - $user['id'] += $max_uid; - $user['password'] = make_rand_str(15); - convert_user($user); - $pass[] = array( - 'tb_user_id' => $user['id'] - $max_uid, - 'username' => $user['username'], - 'new_passwd' => $user['password'], - ); - } - } - $passf = fopen('./converter/passwords.php', 'w'); - $to_write = " $user['id'] - $max_uid, + 'username' => $user['username'], + 'new_passwd' => $user['password'], + ); + } + } + $passf = fopen('./converter/passwords.php', 'w'); + $to_write = " $tr_cat_id, - "cat_title" => 'Tracker', - ); - tp_add_category($tp_cat_data); - set_auto_increment(BB_CATEGORIES, 'cat_id'); - unset($tp_cat_data); + $tp_cat_data = array( + "cat_id" => $tr_cat_id, + "cat_title" => 'Tracker', + ); + tp_add_category($tp_cat_data); + set_auto_increment(BB_CATEGORIES, 'cat_id'); + unset($tp_cat_data); - $cats = $db->fetch_rowset("SELECT id, sort, name FROM ". TB_CATEGORIES_TABLE); - DB()->sql_freeresult(); + $cats = $db->fetch_rowset("SELECT id, sort, name FROM " . TB_CATEGORIES_TABLE); + DB()->sql_freeresult(); - $max_forum_id = (int) get_max_val(BB_FORUMS, 'forum_id'); + $max_forum_id = (int)get_max_val(BB_FORUMS, 'forum_id'); - foreach ($cats as $cat) - { - $cat['id'] += $max_forum_id; - $cat['cat_id'] = $tr_cat_id; - convert_cat($cat); - } - set_auto_increment(BB_FORUMS, 'forum_id'); - print_ok ("Categories from TBDev converted"); - unset($cats); + foreach ($cats as $cat) { + $cat['id'] += $max_forum_id; + $cat['cat_id'] = $tr_cat_id; + convert_cat($cat); + } + set_auto_increment(BB_FORUMS, 'forum_id'); + print_ok("Categories from TBDev converted"); + unset($cats); - // Start of torrents converting - switch(TR_TYPE) - { - case 'yse': - $_sql = 'image1, image2, '; - break; + // Start of torrents converting + switch (TR_TYPE) { + case 'yse': + $_sql = 'image1, image2, '; + break; - case 'sky': - $_sql = 'poster, screenshot1, screenshot2, screenshot3, screenshot4, '; - break; + case 'sky': + $_sql = 'poster, screenshot1, screenshot2, screenshot3, screenshot4, '; + break; - default: - $_sql = ''; - break; - } + default: + $_sql = ''; + break; + } - $max_topic_id = (int) get_max_val(BB_TOPICS, 'topic_id'); - $max_post_id = (int) get_max_val(BB_POSTS, 'post_id'); - $max_attach_id = (int) get_max_val(BB_ATTACHMENTS, 'attach_id'); + $max_topic_id = (int)get_max_val(BB_TOPICS, 'topic_id'); + $max_post_id = (int)get_max_val(BB_POSTS, 'post_id'); + $max_attach_id = (int)get_max_val(BB_ATTACHMENTS, 'attach_id'); - $torrents_count = (int) get_count(TB_TORRENTS_TABLE, 'id'); - $loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); + $torrents_count = (int)get_count(TB_TORRENTS_TABLE, 'id'); + $loops = (int)ceil($torrents_count / C_TORRENTS_PER_ONCE); - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - $sql = " + for ($i = 0; $i < $loops; $i++) { + $start = $i * C_TORRENTS_PER_ONCE; + $offset = C_TORRENTS_PER_ONCE; + $sql = " SELECT id, info_hash, name, filename, search_text, descr, $_sql category, UNIX_TIMESTAMP(added) AS added, size, views, UNIX_TIMESTAMP(last_action) AS lastseed, times_completed, owner, sticky - FROM ". TB_TORRENTS_TABLE ." + FROM " . TB_TORRENTS_TABLE . " ORDER BY id LIMIT $start, $offset"; - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); + $torrents = DB()->fetch_rowset($sql); + DB()->sql_freeresult(); - foreach ($torrents as $torrent) - { - $torrent['topic_id'] = $torrent['id'] + $max_topic_id; - $torrent['post_id'] = $torrent['id'] + $max_post_id; - $torrent['attach_id'] = $torrent['id'] + $max_attach_id; - $torrent['owner'] += $max_uid; - $torrent['descr'] = append_images($torrent); - convert_torrent($torrent); - //print_r($torrent); - } - } - set_auto_increment(BB_TOPICS, 'topic_id'); - set_auto_increment(BB_POSTS, 'post_id'); - print_ok ("Total $torrents_count torrents from TBDev converted"); - unset($torrents); + foreach ($torrents as $torrent) { + $torrent['topic_id'] = $torrent['id'] + $max_topic_id; + $torrent['post_id'] = $torrent['id'] + $max_post_id; + $torrent['attach_id'] = $torrent['id'] + $max_attach_id; + $torrent['owner'] += $max_uid; + $torrent['descr'] = append_images($torrent); + convert_torrent($torrent); + //print_r($torrent); + } + } + set_auto_increment(BB_TOPICS, 'topic_id'); + set_auto_increment(BB_POSTS, 'post_id'); + print_ok("Total $torrents_count torrents from TBDev converted"); + unset($torrents); - if (CONVERT_COMMENTS) - { - $max_post_id = (int) get_max_val(BB_POSTS, 'post_id'); - $max_topic_id = (int) get_max_val(BB_TOPICS, 'topic_id'); - $max_attach_id = (int) get_max_val(BB_ATTACHMENTS, 'attach_id'); + if (CONVERT_COMMENTS) { + $max_post_id = (int)get_max_val(BB_POSTS, 'post_id'); + $max_topic_id = (int)get_max_val(BB_TOPICS, 'topic_id'); + $max_attach_id = (int)get_max_val(BB_ATTACHMENTS, 'attach_id'); - $comments_count = (int) get_count(TB_COMMENTS_TABLE, 'id'); - $loops = (int) ceil($comments_count / C_COMMENTS_PER_ONCE); + $comments_count = (int)get_count(TB_COMMENTS_TABLE, 'id'); + $loops = (int)ceil($comments_count / C_COMMENTS_PER_ONCE); - for ($i = 0; $i < $loops; $i++) - { - $start = $i * C_COMMENTS_PER_ONCE; - $offset = C_COMMENTS_PER_ONCE; - $sql = " + for ($i = 0; $i < $loops; $i++) { + $start = $i * C_COMMENTS_PER_ONCE; + $offset = C_COMMENTS_PER_ONCE; + $sql = " SELECT c.id, c.user, c.torrent, c.text, tor.category, UNIX_TIMESTAMP(c.added) AS added, UNIX_TIMESTAMP(c.editedat) AS editedat, c.ip - FROM ". TB_COMMENTS_TABLE ." c - LEFT JOIN ". TB_TORRENTS_TABLE ." tor ON(tor.id = c.torrent) + FROM " . TB_COMMENTS_TABLE . " c + LEFT JOIN " . TB_TORRENTS_TABLE . " tor ON(tor.id = c.torrent) WHERE c.torrent <> 0 ORDER BY c.id LIMIT $start, $offset"; - $comments = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); + $comments = DB()->fetch_rowset($sql); + DB()->sql_freeresult(); - foreach ($comments as $comment) - { - $comment['user'] += $max_uid; - $comment['id'] += $max_post_id; - convert_comment($comment); - } - } - unset($comments); - set_auto_increment(BB_POSTS, 'post_id'); - print_ok ("Total $comments_count comments from TBDev converted"); - } -} + foreach ($comments as $comment) { + $comment['user'] += $max_uid; + $comment['id'] += $max_post_id; + convert_comment($comment); + } + } + unset($comments); + set_auto_increment(BB_POSTS, 'post_id'); + print_ok("Total $comments_count comments from TBDev converted"); + } + } -?> - -
        -Converting completed. - - - \ No newline at end of file + ?> + +
        + Converting completed. + + + \ No newline at end of file diff --git a/install/other/converter/TBDevYSE_pre6/root/converter/constants.php b/install/other/converter/TBDevYSE_pre6/root/converter/constants.php index 106438984..e4b53187d 100644 --- a/install/other/converter/TBDevYSE_pre6/root/converter/constants.php +++ b/install/other/converter/TBDevYSE_pre6/root/converter/constants.php @@ -1,8 +1,33 @@ " : ''; - $err = ''; + echo ($err) ? "\n
        " : ''; + $err = ''; - echo '
        '; - echo "OK - $sql". str_repeat(' ', 256) ."\n
        "; - echo '
        '; + echo '
        '; + echo "OK - $sql" . str_repeat(' ', 256) . "\n
        "; + echo '
        '; } function hex2bin($h) { - if (!is_string($h)) return null; - $r=''; - for ($a=0; $afetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; + $row = DB()->fetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); + return $row[$column]; } function get_count($table_name, $column) { - $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; + $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); + return $row[$column]; } function set_auto_increment($table_name, $column, $val = null) { - if (empty($val)) - { - $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); - DB()->sql_freeresult(); - $val = (int) $row['val'] + 1; - } - DB()->query("ALTER TABLE $table_name auto_increment = $val"); + if (empty($val)) { + $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); + DB()->sql_freeresult(); + $val = (int)$row['val'] + 1; + } + DB()->query("ALTER TABLE $table_name auto_increment = $val"); } // Users functions function tp_users_cleanup() { - DB()->query('DELETE FROM '. BB_USERS .' WHERE user_id NOT IN('. EXCLUDED_USERS_CSV .')'); - DB()->query('TRUNCATE '. BB_BT_USERS); + DB()->query('DELETE FROM ' . BB_USERS . ' WHERE user_id NOT IN(' . EXCLUDED_USERS_CSV . ')'); + DB()->query('TRUNCATE ' . BB_BT_USERS); } function tp_user_level($tb_class) { - switch($tb_class) - { - case 0: - case 1: - case 2: - case 3: - $level = 0; - break; - case 4: - $level = 2; - break; - case 5: - case 6: - case 7: - $level = 1; - break; - default: - $level = 0; - break; - } - return $level; + switch ($tb_class) { + case 0: + case 1: + case 2: + case 3: + $level = 0; + break; + case 4: + $level = 2; + break; + case 5: + case 6: + case 7: + $level = 1; + break; + default: + $level = 0; + break; + } + return $level; } function convert_user($user) { - $user_data = array( - "user_id" => $user['id'], - "user_active" => ($user['enabled'] == 'yes') ? true : false, - "username" => $user['username'], - "user_password" => md5($user['password']), - "user_lastvisit" => $user['last_access'], - "user_regdate" => $user['added'], - "user_level" => tp_user_level($user['class']), - "user_lang" => $user['language'], - "user_dateformat" => "Y-m-d H:i", - "user_opt" => 0, - "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, - "user_avatar_type" => !empty($user['avatar']) ? 2 : null, - "user_email" => $user['email'], - "user_website" => $user['website'], - ); + $user_data = array( + "user_id" => $user['id'], + "user_active" => ($user['enabled'] == 'yes') ? true : false, + "username" => $user['username'], + "user_password" => md5($user['password']), + "user_lastvisit" => $user['last_access'], + "user_regdate" => $user['added'], + "user_level" => tp_user_level($user['class']), + "user_lang" => $user['language'], + "user_dateformat" => "Y-m-d H:i", + "user_opt" => 0, + "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, + "user_avatar_type" => !empty($user['avatar']) ? 2 : null, + "user_email" => $user['email'], + "user_website" => $user['website'], + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($user_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_USERS . " ($sql_columns) VALUES($sql_values);"); + DB()->query("INSERT IGNORE INTO " . BB_USERS . " ($sql_columns) VALUES($sql_values);"); - $bt_user_data = array( - "user_id" => $user['id'], - "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), - "u_up_total" => $user['uploaded'], - "u_down_total" => $user['downloaded'], - ); - $columns = $values = array(); + $bt_user_data = array( + "user_id" => $user['id'], + "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), + "u_up_total" => $user['uploaded'], + "u_down_total" => $user['downloaded'], + ); + $columns = $values = array(); - foreach ($bt_user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); + foreach ($bt_user_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_bt_columns = implode(',', $columns); + $sql_bt_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_BT_USERS . " ($sql_bt_columns) VALUES($sql_bt_values);"); + DB()->query("INSERT IGNORE INTO " . BB_BT_USERS . " ($sql_bt_columns) VALUES($sql_bt_values);"); } //Torrents and categories functions function tp_categories_cleanup() { - DB()->query('DELETE FROM '. BB_CATEGORIES); + DB()->query('DELETE FROM ' . BB_CATEGORIES); } function tp_add_category_old($id, $cat_title) { - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES ." (cat_id, cat_title) - VALUES ($id, '". DB()->escape($cat_title) ."')"); - return; + DB()->query("INSERT IGNORE INTO " . BB_CATEGORIES . " (cat_id, cat_title) + VALUES ($id, '" . DB()->escape($cat_title) . "')"); + return; } function tp_add_category($cat_data) { - $columns = $values = array(); + $columns = $values = array(); - foreach ($cat_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); + foreach ($cat_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_bt_columns = implode(',', $columns); + $sql_bt_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES . " ($sql_bt_columns) VALUES($sql_bt_values);"); + DB()->query("INSERT IGNORE INTO " . BB_CATEGORIES . " ($sql_bt_columns) VALUES($sql_bt_values);"); } function tp_topics_cleanup() { - DB()->query("TRUNCATE ". BB_ATTACHMENTS); - DB()->query("TRUNCATE ". BB_ATTACHMENTS_DESC); - DB()->query("TRUNCATE ". BB_BT_TORRENTS); - DB()->query("TRUNCATE ". BB_POSTS); - DB()->query("TRUNCATE ". BB_POSTS_HTML); - DB()->query("TRUNCATE ". BB_POSTS_SEARCH); - DB()->query("TRUNCATE ". BB_POSTS_TEXT); - DB()->query("TRUNCATE ". BB_TOPICS); + DB()->query("TRUNCATE " . BB_ATTACHMENTS); + DB()->query("TRUNCATE " . BB_ATTACHMENTS_DESC); + DB()->query("TRUNCATE " . BB_BT_TORRENTS); + DB()->query("TRUNCATE " . BB_POSTS); + DB()->query("TRUNCATE " . BB_POSTS_HTML); + DB()->query("TRUNCATE " . BB_POSTS_SEARCH); + DB()->query("TRUNCATE " . BB_POSTS_TEXT); + DB()->query("TRUNCATE " . BB_TOPICS); - return; + return; } function tp_add_topic($topic_data) { - $columns = $values = array(); - foreach ($topic_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + $columns = $values = array(); + foreach ($topic_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_TOPICS . " ($sql_columns) VALUES($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_TOPICS . " ($sql_columns) VALUES($sql_values);"); + return; } function tp_add_post($post_data) { - foreach ($post_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($post_data as $key => $data) { + $columns = $values = array(); + foreach ($data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); - } - return; + DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); + } + return; } function tp_add_attach($attach_data) { - foreach ($attach_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($attach_data as $key => $data) { + $columns = $values = array(); + foreach ($data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); - } - return; + DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES($sql_values);"); + } + return; } -function make_img_path ($name) +function make_img_path($name) { - global $bb_cfg; + global $bb_cfg; - return make_url("files/images/" . $name); + return make_url("files/images/" . $name); } function append_images($tor) { - $poster = $screens = ''; - switch(TR_TYPE) - { - case 'yse': - if (!empty($tor['image1'])) - { - $poster = "[img=right]".make_img_path($tor['image1'])."[/img]"; - } - if (!empty($tor['image2'])) - { - $screens = '[spoiler="Скриншоты"][img]'.make_img_path($tor['image2'])."[/img][/spoiler]"; - } - break; - case 'sky': - if (!empty($tor['poster'])) - { - $poster = "[img=right]".make_img_path($tor['poster'])."[/img]"; - } - $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); - if ($has_screens) - { - $screens .= '[spoiler="Скриншоты"]'; - for ($i = 1; $i <= 4; $i++) - { - if (!empty($tor['screenshot'.$i])) - { - $screens .= "[img]".make_img_path($tor['screenshot'.$i])."[/img] \n"; - } - } - $screens .= "[/spoiler]"; - } - break; - } - return ($poster . $tor['descr'] . $screens); + $poster = $screens = ''; + switch (TR_TYPE) { + case 'yse': + if (!empty($tor['image1'])) { + $poster = "[img=right]" . make_img_path($tor['image1']) . "[/img]"; + } + if (!empty($tor['image2'])) { + $screens = '[spoiler="Скриншоты"][img]' . make_img_path($tor['image2']) . "[/img][/spoiler]"; + } + break; + case 'sky': + if (!empty($tor['poster'])) { + $poster = "[img=right]" . make_img_path($tor['poster']) . "[/img]"; + } + $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); + if ($has_screens) { + $screens .= '[spoiler="Скриншоты"]'; + for ($i = 1; $i <= 4; $i++) { + if (!empty($tor['screenshot' . $i])) { + $screens .= "[img]" . make_img_path($tor['screenshot' . $i]) . "[/img] \n"; + } + } + $screens .= "[/spoiler]"; + } + break; + } + return ($poster . $tor['descr'] . $screens); } function convert_torrent($torrent) { - $topic_data = array( - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "topic_title" => $torrent['name'], - "topic_poster" => $torrent['owner'], - "topic_time" => $torrent['added'], - "topic_views" => $torrent['views'], - "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, - "topic_first_post_id" => $torrent['id'], - "topic_last_post_id" => $torrent['id'], - "topic_attachment" => 1, - "topic_dl_type" => 1, - "topic_last_post_time" => $torrent['added'], - ); - tp_add_topic($topic_data); - $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); + $topic_data = array( + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "topic_title" => $torrent['name'], + "topic_poster" => $torrent['owner'], + "topic_time" => $torrent['added'], + "topic_views" => $torrent['views'], + "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, + "topic_first_post_id" => $torrent['id'], + "topic_last_post_id" => $torrent['id'], + "topic_attachment" => 1, + "topic_dl_type" => 1, + "topic_last_post_time" => $torrent['added'], + ); + tp_add_topic($topic_data); + $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); - $post_data = array( - "posts" => array( - "post_id" => $torrent['post_id'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "poster_id" => $torrent['owner'], - "post_time" => $torrent['added'], - "post_attachment" => 1, - ), - "posts_text" => array( - "post_id" => $torrent['post_id'], - "post_text" => $post_text, - ), - "posts_search" => array( - "post_id" => $torrent['post_id'], - "search_words" => $torrent['search_text'], - ), - ); - tp_add_post($post_data); + $post_data = array( + "posts" => array( + "post_id" => $torrent['post_id'], + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "poster_id" => $torrent['owner'], + "post_time" => $torrent['added'], + "post_attachment" => 1, + ), + "posts_text" => array( + "post_id" => $torrent['post_id'], + "post_text" => $post_text, + ), + "posts_search" => array( + "post_id" => $torrent['post_id'], + "search_words" => $torrent['search_text'], + ), + ); + tp_add_post($post_data); - $attach_data = array( - "attachments" => array( - "attach_id" => $torrent['attach_id'], - "post_id" => $torrent['post_id'], - "user_id_1" => $torrent['owner'], - ), - "attachments_desc" => array( - "attach_id" => $torrent['attach_id'], - "physical_filename" => $torrent['id'] . ".torrent", - "real_filename" => $torrent['filename'], - "extension" => "torrent", - "mimetype" => "application/x-bittorrent", - "filesize" => @filesize(get_attachments_dir() .'/'. $torrent['id'] .".torrent"), - "filetime" => $torrent['added'], - "tracker_status" => 1, - ), - ); - tp_add_attach($attach_data); + $attach_data = array( + "attachments" => array( + "attach_id" => $torrent['attach_id'], + "post_id" => $torrent['post_id'], + "user_id_1" => $torrent['owner'], + ), + "attachments_desc" => array( + "attach_id" => $torrent['attach_id'], + "physical_filename" => $torrent['id'] . ".torrent", + "real_filename" => $torrent['filename'], + "extension" => "torrent", + "mimetype" => "application/x-bittorrent", + "filesize" => @filesize(get_attachments_dir() . '/' . $torrent['id'] . ".torrent"), + "filetime" => $torrent['added'], + "tracker_status" => 1, + ), + ); + tp_add_attach($attach_data); - //Torrents - if (BDECODE) - { - $filename = get_attachments_dir() .'/'. $torrent['id'] .".torrent"; - if (!file_exists($filename)) - { - return; - } - if (!function_exists('bdecode_file')) include_once(INC_DIR .'functions_torrent.php'); - $tor = bdecode_file($filename); - $info = ($tor['info']) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - } - else - { - $info_hash_sql = hex2bin($torrent['info_hash']); - } + //Torrents + if (BDECODE) { + $filename = get_attachments_dir() . '/' . $torrent['id'] . ".torrent"; + if (!file_exists($filename)) { + return; + } + if (!function_exists('bdecode_file')) include_once(INC_DIR . 'functions_torrent.php'); + $tor = bdecode_file($filename); + $info = ($tor['info']) ? $tor['info'] : array(); + $info_hash = pack('H*', sha1(bencode($info))); + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + } else { + $info_hash_sql = hex2bin($torrent['info_hash']); + } - $torrent_data = array( - "info_hash" => $info_hash_sql, - "post_id" => $torrent['post_id'], - "poster_id" => $torrent['owner'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "attach_id" => $torrent['attach_id'], - "size" => $torrent['size'], - "reg_time" => $torrent['added'], - "complete_count" => $torrent['times_completed'], - "seeder_last_seen" => $torrent['lastseed'], - ); + $torrent_data = array( + "info_hash" => $info_hash_sql, + "post_id" => $torrent['post_id'], + "poster_id" => $torrent['owner'], + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "attach_id" => $torrent['attach_id'], + "size" => $torrent['size'], + "reg_time" => $torrent['added'], + "complete_count" => $torrent['times_completed'], + "seeder_last_seen" => $torrent['lastseed'], + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($torrent_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". $db->escape($value) ."'"; - } - $sql_columns = implode(', ', $columns); - $sql_values = implode(', ', $values); + foreach ($torrent_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . $db->escape($value) . "'"; + } + $sql_columns = implode(', ', $columns); + $sql_values = implode(', ', $values); - DB()->query("INSERT IGNORE INTO ". BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); + return; } // Comments functions function convert_comment($comment) { - $post_text = prepare_message($comment['text'], true, true); + $post_text = prepare_message($comment['text'], true, true); - $post_data = array( - "posts" => array( - "post_id" => $comment['id'], - "topic_id" => $comment['torrent'], - "forum_id" => $comment['category'], - "poster_id" => $comment['user'], - "post_time" => $comment['added'], - "poster_ip" => encode_ip($comment['ip']), - "post_edit_time" => $comment['editedat'], - "post_edit_count" => $comment['editedat'] ? 1 : 0, - ), - "posts_text" => array( - "post_id" => $comment['id'], - "post_text" => $post_text, - ), - ); - tp_add_post($post_data); - return; + $post_data = array( + "posts" => array( + "post_id" => $comment['id'], + "topic_id" => $comment['torrent'], + "forum_id" => $comment['category'], + "poster_id" => $comment['user'], + "post_time" => $comment['added'], + "poster_ip" => encode_ip($comment['ip']), + "post_edit_time" => $comment['editedat'], + "post_edit_count" => $comment['editedat'] ? 1 : 0, + ), + "posts_text" => array( + "post_id" => $comment['id'], + "post_text" => $post_text, + ), + ); + tp_add_post($post_data); + return; } //Forums functions function tp_forums_cleanup() { - DB()->query('TRUNCATE '. BB_FORUMS); + DB()->query('TRUNCATE ' . BB_FORUMS); } function convert_cat($forum, $allow_torrents = true) { - $forum_data = array( - "forum_id" => $forum['id'], - "cat_id" => $forum['cat_id'], - "forum_name" => $forum['name'], - "forum_order" => $forum['sort'], - "allow_reg_tracker" => $allow_torrents, - "allow_porno_topic" => $allow_torrents, - ); + $forum_data = array( + "forum_id" => $forum['id'], + "cat_id" => $forum['cat_id'], + "forum_name" => $forum['name'], + "forum_order" => $forum['sort'], + "allow_reg_tracker" => $allow_torrents, + "allow_porno_topic" => $allow_torrents, + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($forum_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($forum_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_FORUMS . " ($sql_columns) VALUES($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_FORUMS . " ($sql_columns) VALUES($sql_values);"); + return; } diff --git a/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php b/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php index 63c2de744..6f367c1be 100644 --- a/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php +++ b/install/other/converter/TBDevYSE_pre6/root/converter/passwords.php @@ -1,3 +1,26 @@ session_start(); -while (@ob_end_flush()); +while (@ob_end_flush()) ; ob_implicit_flush(); ?> - - - - - - - - + + + + + + + +
        -
        +
        '; - exit; -} -else -{ + exit; +} else { + @ini_set('memory_limit', '512M'); + @ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); + $torrents_count = (int)get_count(BB_BT_TORRENTS, 'attach_id'); + $loops = (int)ceil($torrents_count / C_TORRENTS_PER_ONCE); -$torrents_count = (int) get_count(BB_BT_TORRENTS, 'attach_id'); -$loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); + $not_exist = array(); -$not_exist = array(); + $attach_dir = get_attachments_dir() . '/'; -$attach_dir = get_attachments_dir() .'/'; + for ($i = 0; $i < $loops; $i++) { + $start = $i * C_TORRENTS_PER_ONCE; + $offset = C_TORRENTS_PER_ONCE; -for ($i = 0; $i < $loops; $i++) -{ - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - - $sql = "SELECT + $sql = "SELECT tor.attach_id, tor.topic_id, ad.physical_filename - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_ATTACHMENTS_DESC ." ad ON(ad.attach_id = tor.attach_id) + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_ATTACHMENTS_DESC . " ad ON(ad.attach_id = tor.attach_id) ORDER BY tor.attach_id LIMIT $start, $offset"; - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); + $torrents = DB()->fetch_rowset($sql); + DB()->sql_freeresult(); - foreach ($torrents as $torrent) - { - $filename = $attach_dir . $torrent['physical_filename']; - if (!file_exists($filename)) - { - $not_exist[] = ''. $filename .''; - } - else - { - $tor = bdecode_file($filename); - $info = (!empty($tor['info'])) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + foreach ($torrents as $torrent) { + $filename = $attach_dir . $torrent['physical_filename']; + if (!file_exists($filename)) { + $not_exist[] = '' . $filename . ''; + } else { + $tor = bdecode_file($filename); + $info = (!empty($tor['info'])) ? $tor['info'] : array(); + $info_hash = pack('H*', sha1(bencode($info))); + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - DB()->query("UPDATE ". BB_BT_TORRENTS ." + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET info_hash = '$info_hash_sql' WHERE attach_id = {$torrent['attach_id']}"); - } - } + } + } + } + + print_ok("Completed"); + + if (!empty($not_exist)) { + print_ok("These torrents doesn't exist in filesystem: " . implode(', ', array_unique($not_exist))); + } } - -print_ok ("Completed"); - -if (!empty($not_exist)) -{ - print_ok ("These torrents doesn't exist in filesystem: ". implode(', ', array_unique($not_exist))); -} - -} \ No newline at end of file diff --git a/install/other/recover/converter/constants.php b/install/other/recover/converter/constants.php index 106438984..e4b53187d 100644 --- a/install/other/recover/converter/constants.php +++ b/install/other/recover/converter/constants.php @@ -1,8 +1,33 @@ " : ''; - $err = ''; + echo ($err) ? "\n
        " : ''; + $err = ''; - echo '
        '; - echo "OK - $sql". str_repeat(' ', 256) ."\n
        "; - echo '
        '; + echo '
        '; + echo "OK - $sql" . str_repeat(' ', 256) . "\n
        "; + echo '
        '; } function hex2bin($h) { - if (!is_string($h)) return null; - $r=''; - for ($a=0; $afetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; + $row = DB()->fetch_row("SELECT MAX($column) AS $column FROM $table_name LIMIT 1"); + return $row[$column]; } function get_count($table_name, $column) { - $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); - return $row[$column]; + $row = DB()->fetch_row("SELECT COUNT($column) AS $column FROM $table_name LIMIT 1"); + return $row[$column]; } function set_auto_increment($table_name, $column, $val = null) { - if (empty($val)) - { - $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); - DB()->sql_freeresult(); - $val = (int) $row['val'] + 1; - } - DB()->query("ALTER TABLE $table_name auto_increment = $val"); + if (empty($val)) { + $row = DB()->fetch_row("SELECT MAX($column) AS val FROM $table_name LIMIT 1"); + DB()->sql_freeresult(); + $val = (int)$row['val'] + 1; + } + DB()->query("ALTER TABLE $table_name auto_increment = $val"); } //Users functions function tp_users_cleanup() { - DB()->query('DELETE FROM '. BB_USERS .' WHERE user_id NOT IN('. EXCLUDED_USERS_CSV .')'); - DB()->query('TRUNCATE '. BB_BT_USERS); + DB()->query('DELETE FROM ' . BB_USERS . ' WHERE user_id NOT IN(' . EXCLUDED_USERS_CSV . ')'); + DB()->query('TRUNCATE ' . BB_BT_USERS); } function tp_user_level($tb_class) { - switch($tb_class) - { - case 0: - case 1: - case 2: - case 3: - $level = 0; - break; - case 4: - $level = 2; - break; - case 5: - case 6: - case 7: - $level = 1; - break; - default: - $level = 0; - break; - } - return $level; + switch ($tb_class) { + case 0: + case 1: + case 2: + case 3: + $level = 0; + break; + case 4: + $level = 2; + break; + case 5: + case 6: + case 7: + $level = 1; + break; + default: + $level = 0; + break; + } + return $level; } function convert_user($user) { - $user_data = array( - "user_id" => $user['id'], - "user_active" => ($user['enabled'] == 'yes') ? true : false, - "username" => $user['username'], - "user_password" => md5($user['password']), - "user_lastvisit" => $user['last_access'], - "user_regdate" => $user['added'], - "user_level" => tp_user_level($user['class']), - "user_lang" => $user['language'], - "user_dateformat" => "Y-m-d H:i", - "user_opt" => $user['opt'], // Added - "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, - "user_avatar_type" => !empty($user['avatar']) ? 2 : null, - "user_email" => $user['email'], - "user_website" => $user['website'], - "user_icq" => $user['icq'], - "user_skype" => $user['skype'], - "user_twitter" => $user['twitter'], - "user_gender" => $user['gender'], - "user_birthday" => $user['user_birthday'], - ); + $user_data = array( + "user_id" => $user['id'], + "user_active" => ($user['enabled'] == 'yes') ? true : false, + "username" => $user['username'], + "user_password" => md5($user['password']), + "user_lastvisit" => $user['last_access'], + "user_regdate" => $user['added'], + "user_level" => tp_user_level($user['class']), + "user_lang" => $user['language'], + "user_dateformat" => "Y-m-d H:i", + "user_opt" => $user['opt'], // Added + "user_avatar" => !empty($user['avatar']) ? $user['avatar'] : null, + "user_avatar_type" => !empty($user['avatar']) ? 2 : null, + "user_email" => $user['email'], + "user_website" => $user['website'], + "user_icq" => $user['icq'], + "user_skype" => $user['skype'], + "user_twitter" => $user['twitter'], + "user_gender" => $user['gender'], + "user_birthday" => $user['user_birthday'], + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($user_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_USERS . " ($sql_columns) VALUES ($sql_values);"); + DB()->query("INSERT IGNORE INTO " . BB_USERS . " ($sql_columns) VALUES ($sql_values);"); - $bt_user_data = array( - "user_id" => $user['id'], - "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), - "u_up_total" => $user['uploaded'], - "u_down_total" => $user['downloaded'], - ); - $columns = $values = array(); + $bt_user_data = array( + "user_id" => $user['id'], + "auth_key" => make_rand_str(BT_AUTH_KEY_LENGTH), + "u_up_total" => $user['uploaded'], + "u_down_total" => $user['downloaded'], + ); + $columns = $values = array(); - foreach ($bt_user_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); + foreach ($bt_user_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_bt_columns = implode(',', $columns); + $sql_bt_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_BT_USERS . " ($sql_bt_columns) VALUES ($sql_bt_values);"); + DB()->query("INSERT IGNORE INTO " . BB_BT_USERS . " ($sql_bt_columns) VALUES ($sql_bt_values);"); } //Torrents and categories functions function tp_categories_cleanup() { - DB()->query('DELETE FROM '. BB_CATEGORIES); + DB()->query('DELETE FROM ' . BB_CATEGORIES); } function tp_add_category_old($id, $cat_title) { - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES ." (cat_id, cat_title) - VALUES ($id, '". DB()->escape($cat_title) ."')"); - return; + DB()->query("INSERT IGNORE INTO " . BB_CATEGORIES . " (cat_id, cat_title) + VALUES ($id, '" . DB()->escape($cat_title) . "')"); + return; } function tp_add_category($cat_data) { - $columns = $values = array(); + $columns = $values = array(); - foreach ($cat_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_bt_columns = implode(',', $columns); - $sql_bt_values = implode(',', $values); + foreach ($cat_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_bt_columns = implode(',', $columns); + $sql_bt_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_CATEGORIES . " ($sql_bt_columns) VALUES ($sql_bt_values);"); + DB()->query("INSERT IGNORE INTO " . BB_CATEGORIES . " ($sql_bt_columns) VALUES ($sql_bt_values);"); } function tp_topics_cleanup() { - DB()->query("TRUNCATE ". BB_ATTACHMENTS); - DB()->query("TRUNCATE ". BB_ATTACHMENTS_DESC); - DB()->query("TRUNCATE ". BB_BT_TORRENTS); - DB()->query("TRUNCATE ". BB_POSTS); - DB()->query("TRUNCATE ". BB_POSTS_HTML); - DB()->query("TRUNCATE ". BB_POSTS_SEARCH); - DB()->query("TRUNCATE ". BB_POSTS_TEXT); - DB()->query("TRUNCATE ". BB_TOPICS); + DB()->query("TRUNCATE " . BB_ATTACHMENTS); + DB()->query("TRUNCATE " . BB_ATTACHMENTS_DESC); + DB()->query("TRUNCATE " . BB_BT_TORRENTS); + DB()->query("TRUNCATE " . BB_POSTS); + DB()->query("TRUNCATE " . BB_POSTS_HTML); + DB()->query("TRUNCATE " . BB_POSTS_SEARCH); + DB()->query("TRUNCATE " . BB_POSTS_TEXT); + DB()->query("TRUNCATE " . BB_TOPICS); - return; + return; } function tp_add_topic($topic_data) { - $columns = $values = array(); - foreach ($topic_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + $columns = $values = array(); + foreach ($topic_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_TOPICS . " ($sql_columns) VALUES ($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_TOPICS . " ($sql_columns) VALUES ($sql_values);"); + return; } function tp_add_post($post_data) { - foreach ($post_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($post_data as $key => $data) { + $columns = $values = array(); + foreach ($data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); - } - return; + DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); + } + return; } function tp_add_attach($attach_data) { - foreach ($attach_data as $key => $data) - { - $columns = $values = array(); - foreach ($data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($attach_data as $key => $data) { + $columns = $values = array(); + foreach ($data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); - } - return; + DB()->query("INSERT IGNORE INTO bb_{$key} ($sql_columns) VALUES ($sql_values);"); + } + return; } -function make_img_path ($name) +function make_img_path($name) { - global $bb_cfg; + global $bb_cfg; - return make_url("files/images/" . $name); + return make_url("files/images/" . $name); } function append_images($tor) { - $poster = $screens = ''; - switch(TR_TYPE) - { - case 'yse': - if (!empty($tor['image1'])) - { - $poster = "[img=right]".make_img_path($tor['image1'])."[/img]"; - } - if (!empty($tor['image2'])) - { - $screens = '[spoiler="Скриншоты"][img]'.make_img_path($tor['image2'])."[/img][/spoiler]"; - } - break; - case 'sky': - if (!empty($tor['poster'])) - { - $poster = "[img=right]".make_img_path($tor['poster'])."[/img]"; - } - $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); - if ($has_screens) - { - $screens .= '[spoiler="Скриншоты"]'; - for ($i = 1; $i <= 4; $i++) - { - if (!empty($tor['screenshot'.$i])) - { - $screens .= "[img]".make_img_path($tor['screenshot'.$i])."[/img] \n"; - } - } - $screens .= "[/spoiler]"; - } - break; - } - return ($poster . $tor['descr'] . $screens); + $poster = $screens = ''; + switch (TR_TYPE) { + case 'yse': + if (!empty($tor['image1'])) { + $poster = "[img=right]" . make_img_path($tor['image1']) . "[/img]"; + } + if (!empty($tor['image2'])) { + $screens = '[spoiler="Скриншоты"][img]' . make_img_path($tor['image2']) . "[/img][/spoiler]"; + } + break; + case 'sky': + if (!empty($tor['poster'])) { + $poster = "[img=right]" . make_img_path($tor['poster']) . "[/img]"; + } + $has_screens = !empty($tor['screenshot1']) || !empty($tor['screenshot2']) || !empty($tor['screenshot3']) || !empty($tor['screenshot4']); + if ($has_screens) { + $screens .= '[spoiler="Скриншоты"]'; + for ($i = 1; $i <= 4; $i++) { + if (!empty($tor['screenshot' . $i])) { + $screens .= "[img]" . make_img_path($tor['screenshot' . $i]) . "[/img] \n"; + } + } + $screens .= "[/spoiler]"; + } + break; + } + return ($poster . $tor['descr'] . $screens); } function convert_torrent($torrent) { - $topic_data = array( - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "topic_title" => $torrent['name'], - "topic_poster" => $torrent['owner'], - "topic_time" => $torrent['added'], - "topic_views" => $torrent['views'], - "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, - "topic_first_post_id" => $torrent['id'], - "topic_last_post_id" => $torrent['id'], - "topic_attachment" => 1, - "topic_dl_type" => 1, - "topic_last_post_time" => $torrent['added'], - ); - tp_add_topic($topic_data); + $topic_data = array( + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "topic_title" => $torrent['name'], + "topic_poster" => $torrent['owner'], + "topic_time" => $torrent['added'], + "topic_views" => $torrent['views'], + "topic_type" => ($torrent['sticky'] == 'yes') ? 1 : 0, + "topic_first_post_id" => $torrent['id'], + "topic_last_post_id" => $torrent['id'], + "topic_attachment" => 1, + "topic_dl_type" => 1, + "topic_last_post_time" => $torrent['added'], + ); + tp_add_topic($topic_data); - $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); + $post_text = stripslashes(prepare_message(addslashes(unprepare_message($torrent['descr'])), true, true)); - $post_data = array( - "posts" => array( - "post_id" => $torrent['post_id'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "poster_id" => $torrent['owner'], - "post_time" => $torrent['added'], - "post_attachment" => 1, - ), - "posts_text" => array( - "post_id" => $torrent['post_id'], - "post_text" => $post_text, - ), - "posts_search" => array( - "post_id" => $torrent['post_id'], - "search_words" => $torrent['search_text'], - ), - ); - tp_add_post($post_data); + $post_data = array( + "posts" => array( + "post_id" => $torrent['post_id'], + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "poster_id" => $torrent['owner'], + "post_time" => $torrent['added'], + "post_attachment" => 1, + ), + "posts_text" => array( + "post_id" => $torrent['post_id'], + "post_text" => $post_text, + ), + "posts_search" => array( + "post_id" => $torrent['post_id'], + "search_words" => $torrent['search_text'], + ), + ); + tp_add_post($post_data); - $attach_data = array( - "attachments" => array( - "attach_id" => $torrent['attach_id'], - "post_id" => $torrent['post_id'], - "user_id_1" => $torrent['owner'], - ), - "attachments_desc" => array( - "attach_id" => $torrent['attach_id'], - "physical_filename" => $torrent['id'] . ".torrent", - "real_filename" => $torrent['filename'], - "extension" => "torrent", - "mimetype" => "application/x-bittorrent", - "filesize" => @filesize(get_attachments_dir() .'/'. $torrent['id'] .".torrent"), - "filetime" => $torrent['added'], - "tracker_status" => 1, - ), - ); - tp_add_attach($attach_data); + $attach_data = array( + "attachments" => array( + "attach_id" => $torrent['attach_id'], + "post_id" => $torrent['post_id'], + "user_id_1" => $torrent['owner'], + ), + "attachments_desc" => array( + "attach_id" => $torrent['attach_id'], + "physical_filename" => $torrent['id'] . ".torrent", + "real_filename" => $torrent['filename'], + "extension" => "torrent", + "mimetype" => "application/x-bittorrent", + "filesize" => @filesize(get_attachments_dir() . '/' . $torrent['id'] . ".torrent"), + "filetime" => $torrent['added'], + "tracker_status" => 1, + ), + ); + tp_add_attach($attach_data); - //Torrents - if (BDECODE) - { - $filename = get_attachments_dir() .'/'. $torrent['id'] .".torrent"; - if (!file_exists($filename)) - { - return; - } - if (!function_exists('bdecode_file')) include_once('./includes/functions_torrent.php'); - $tor = bdecode_file($filename); - $info = ($tor['info']) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - } - else - { - $info_hash_sql = hex2bin($torrent['info_hash']); - } + //Torrents + if (BDECODE) { + $filename = get_attachments_dir() . '/' . $torrent['id'] . ".torrent"; + if (!file_exists($filename)) { + return; + } + if (!function_exists('bdecode_file')) include_once('./includes/functions_torrent.php'); + $tor = bdecode_file($filename); + $info = ($tor['info']) ? $tor['info'] : array(); + $info_hash = pack('H*', sha1(bencode($info))); + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + } else { + $info_hash_sql = hex2bin($torrent['info_hash']); + } - $torrent_data = array( - "info_hash" => $info_hash_sql, - "post_id" => $torrent['post_id'], - "poster_id" => $torrent['owner'], - "topic_id" => $torrent['topic_id'], - "forum_id" => $torrent['category'], - "attach_id" => $torrent['attach_id'], - "size" => $torrent['size'], - "reg_time" => $torrent['added'], - "complete_count" => $torrent['times_completed'], - "seeder_last_seen" => $torrent['lastseed'], - ); + $torrent_data = array( + "info_hash" => $info_hash_sql, + "post_id" => $torrent['post_id'], + "poster_id" => $torrent['owner'], + "topic_id" => $torrent['topic_id'], + "forum_id" => $torrent['category'], + "attach_id" => $torrent['attach_id'], + "size" => $torrent['size'], + "reg_time" => $torrent['added'], + "complete_count" => $torrent['times_completed'], + "seeder_last_seen" => $torrent['lastseed'], + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($torrent_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(', ', $columns); - $sql_values = implode(', ', $values); + foreach ($torrent_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(', ', $columns); + $sql_values = implode(', ', $values); - DB()->query("INSERT IGNORE INTO ". BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_BT_TORRENTS . " ($sql_columns) VALUES($sql_values);"); + return; } //Comments functions function convert_comment($comment) { - $post_text = prepare_message($comment['text'], true, true); + $post_text = prepare_message($comment['text'], true, true); - $post_data = array( - "posts" => array( - "post_id" => $comment['id'], - "topic_id" => $comment['torrent'], - "forum_id" => $comment['category'], - "poster_id" => $comment['user'], - "post_time" => $comment['added'], - "poster_ip" => encode_ip($comment['ip']), - "post_edit_time" => $comment['editedat'], - "post_edit_count" => $comment['editedat'] ? 1 : 0, - ), - "posts_text" => array( - "post_id" => $comment['id'], - "post_text" => $post_text, - ), - ); - tp_add_post($post_data); - return; + $post_data = array( + "posts" => array( + "post_id" => $comment['id'], + "topic_id" => $comment['torrent'], + "forum_id" => $comment['category'], + "poster_id" => $comment['user'], + "post_time" => $comment['added'], + "poster_ip" => encode_ip($comment['ip']), + "post_edit_time" => $comment['editedat'], + "post_edit_count" => $comment['editedat'] ? 1 : 0, + ), + "posts_text" => array( + "post_id" => $comment['id'], + "post_text" => $post_text, + ), + ); + tp_add_post($post_data); + return; } //Forums functions function tp_forums_cleanup() { - DB()->query('TRUNCATE '. BB_FORUMS); + DB()->query('TRUNCATE ' . BB_FORUMS); } function convert_cat($forum, $allow_torrents = true) { - $forum_data = array( - "forum_id" => $forum['id'], - "cat_id" => $forum['cat_id'], - "forum_name" => $forum['name'], - "forum_order" => $forum['sort'], - "allow_reg_tracker" => $allow_torrents, - "allow_dl_topic" => $allow_torrents, - ); + $forum_data = array( + "forum_id" => $forum['id'], + "cat_id" => $forum['cat_id'], + "forum_name" => $forum['name'], + "forum_order" => $forum['sort'], + "allow_reg_tracker" => $allow_torrents, + "allow_dl_topic" => $allow_torrents, + ); - $columns = $values = array(); + $columns = $values = array(); - foreach ($forum_data as $column => $value) - { - $columns[] = $column; - $values[] = "'". DB()->escape($value) ."'"; - } - $sql_columns = implode(',', $columns); - $sql_values = implode(',', $values); + foreach ($forum_data as $column => $value) { + $columns[] = $column; + $values[] = "'" . DB()->escape($value) . "'"; + } + $sql_columns = implode(',', $columns); + $sql_values = implode(',', $values); - DB()->query("INSERT IGNORE INTO ". BB_FORUMS . " ($sql_columns) VALUES ($sql_values);"); - return; + DB()->query("INSERT IGNORE INTO " . BB_FORUMS . " ($sql_columns) VALUES ($sql_values);"); + return; } \ No newline at end of file diff --git a/install/other/recover/converter/passwords.php b/install/other/recover/converter/passwords.php index 63c2de744..6f367c1be 100644 --- a/install/other/recover/converter/passwords.php +++ b/install/other/recover/converter/passwords.php @@ -1,3 +1,26 @@ session_start(); -while (@ob_end_flush()); +while (@ob_end_flush()) ; ob_implicit_flush(); ?> - - - + + +
        -
        +
        '; - exit; -} -else -{ + exit; +} else { + @ini_set('memory_limit', '512M'); + @ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); -@ini_set('memory_limit', '512M'); -@ini_set('max_execution_time', @ini_get('max_execution_time') + 1200); + $torrents_count = (int)get_count(BB_BT_TORRENTS, 'attach_id'); + $loops = (int)ceil($torrents_count / C_TORRENTS_PER_ONCE); -$torrents_count = (int) get_count(BB_BT_TORRENTS, 'attach_id'); -$loops = (int) ceil($torrents_count / C_TORRENTS_PER_ONCE); + $not_exist = array(); -$not_exist = array(); + $attach_dir = get_attachments_dir() . '/'; -$attach_dir = get_attachments_dir() .'/'; + for ($i = 0; $i < $loops; $i++) { + $start = $i * C_TORRENTS_PER_ONCE; + $offset = C_TORRENTS_PER_ONCE; -for ($i = 0; $i < $loops; $i++) -{ - $start = $i * C_TORRENTS_PER_ONCE; - $offset = C_TORRENTS_PER_ONCE; - - $sql = "SELECT + $sql = "SELECT tor.attach_id, tor.topic_id, ad.physical_filename - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_ATTACHMENTS_DESC ." ad ON(ad.attach_id = tor.attach_id) + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_ATTACHMENTS_DESC . " ad ON(ad.attach_id = tor.attach_id) ORDER BY tor.attach_id LIMIT $start, $offset"; - $torrents = DB()->fetch_rowset($sql); - DB()->sql_freeresult(); + $torrents = DB()->fetch_rowset($sql); + DB()->sql_freeresult(); - foreach ($torrents as $torrent) - { - $filename = $attach_dir . $torrent['physical_filename']; - if (!file_exists($filename)) - { - $not_exist[] = ''. $filename .''; - } - else - { - $tor = bdecode_file($filename); - $info = (!empty($tor['info'])) ? $tor['info'] : array(); - $info_hash = pack('H*', sha1(bencode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + foreach ($torrents as $torrent) { + $filename = $attach_dir . $torrent['physical_filename']; + if (!file_exists($filename)) { + $not_exist[] = '' . $filename . ''; + } else { + $tor = bdecode_file($filename); + $info = (!empty($tor['info'])) ? $tor['info'] : array(); + $info_hash = pack('H*', sha1(bencode($info))); + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - DB()->query("UPDATE ". BB_BT_TORRENTS ." + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET info_hash = '$info_hash_sql' WHERE attach_id = {$torrent['attach_id']}"); - } - } + } + } + } + + print_ok("Completed"); + + if (!empty($not_exist)) { + print_ok("These torrents doesn't exist in filesystem: " . implode(', ', array_unique($not_exist))); + } } - -print_ok ("Completed"); - -if (!empty($not_exist)) -{ - print_ok ("These torrents doesn't exist in filesystem: ". implode(', ', array_unique($not_exist))); -} - -} \ No newline at end of file diff --git a/install/sql/mysql.sql b/install/sql/mysql.sql index 9763848dc..01b8fa8b9 100644 --- a/install/sql/mysql.sql +++ b/install/sql/mysql.sql @@ -5,15 +5,17 @@ SET SQL_MODE = ""; -- ---------------------------- DROP TABLE IF EXISTS `bb_ads`; CREATE TABLE IF NOT EXISTS `bb_ads` ( - `ad_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `ad_block_ids` varchar(255) NOT NULL DEFAULT '', - `ad_start_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `ad_active_days` smallint(6) NOT NULL DEFAULT '0', - `ad_status` tinyint(4) NOT NULL DEFAULT '1', - `ad_desc` varchar(255) NOT NULL DEFAULT '', - `ad_html` text NOT NULL, + `ad_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `ad_block_ids` VARCHAR(255) NOT NULL DEFAULT '', + `ad_start_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `ad_active_days` SMALLINT(6) NOT NULL DEFAULT '0', + `ad_status` TINYINT(4) NOT NULL DEFAULT '1', + `ad_desc` VARCHAR(255) NOT NULL DEFAULT '', + `ad_html` TEXT NOT NULL, PRIMARY KEY (`ad_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_ads @@ -24,11 +26,13 @@ CREATE TABLE IF NOT EXISTS `bb_ads` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_attachments`; CREATE TABLE IF NOT EXISTS `bb_attachments` ( - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id_1` mediumint(8) NOT NULL DEFAULT '0', - PRIMARY KEY (`attach_id`,`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `attach_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_id_1` MEDIUMINT(8) NOT NULL DEFAULT '0', + PRIMARY KEY (`attach_id`, `post_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_attachments @@ -39,10 +43,12 @@ CREATE TABLE IF NOT EXISTS `bb_attachments` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_attachments_config`; CREATE TABLE IF NOT EXISTS `bb_attachments_config` ( - `config_name` varchar(255) NOT NULL DEFAULT '', - `config_value` varchar(255) NOT NULL DEFAULT '', + `config_name` VARCHAR(255) NOT NULL DEFAULT '', + `config_value` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`config_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_attachments_config @@ -78,22 +84,24 @@ INSERT INTO `bb_attachments_config` VALUES ('flash_autoplay', '0'); -- ---------------------------- DROP TABLE IF EXISTS `bb_attachments_desc`; CREATE TABLE IF NOT EXISTS `bb_attachments_desc` ( - `attach_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `physical_filename` varchar(255) NOT NULL DEFAULT '', - `real_filename` varchar(255) NOT NULL DEFAULT '', - `download_count` mediumint(8) unsigned NOT NULL DEFAULT '0', - `comment` varchar(255) NOT NULL DEFAULT '', - `extension` varchar(100) NOT NULL DEFAULT '', - `mimetype` varchar(100) NOT NULL DEFAULT '', - `filesize` int(20) NOT NULL DEFAULT '0', - `filetime` int(11) NOT NULL DEFAULT '0', - `thumbnail` tinyint(1) NOT NULL DEFAULT '0', - `tracker_status` tinyint(1) NOT NULL DEFAULT '0', + `attach_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `physical_filename` VARCHAR(255) NOT NULL DEFAULT '', + `real_filename` VARCHAR(255) NOT NULL DEFAULT '', + `download_count` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `comment` VARCHAR(255) NOT NULL DEFAULT '', + `extension` VARCHAR(100) NOT NULL DEFAULT '', + `mimetype` VARCHAR(100) NOT NULL DEFAULT '', + `filesize` INT(20) NOT NULL DEFAULT '0', + `filetime` INT(11) NOT NULL DEFAULT '0', + `thumbnail` TINYINT(1) NOT NULL DEFAULT '0', + `tracker_status` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`attach_id`), KEY `filetime` (`filetime`), KEY `filesize` (`filesize`), KEY `physical_filename` (`physical_filename`(10)) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_attachments_desc @@ -104,12 +112,14 @@ CREATE TABLE IF NOT EXISTS `bb_attachments_desc` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_attach_quota`; CREATE TABLE IF NOT EXISTS `bb_attach_quota` ( - `user_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `group_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `quota_type` smallint(2) NOT NULL DEFAULT '0', - `quota_limit_id` mediumint(8) unsigned NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `group_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `quota_type` SMALLINT(2) NOT NULL DEFAULT '0', + `quota_limit_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', KEY `quota_type` (`quota_type`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_attach_quota @@ -120,12 +130,14 @@ CREATE TABLE IF NOT EXISTS `bb_attach_quota` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_auth_access`; CREATE TABLE IF NOT EXISTS `bb_auth_access` ( - `group_id` mediumint(8) NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `forum_perm` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`group_id`,`forum_id`), + `group_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `forum_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `forum_perm` INT(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`group_id`, `forum_id`), KEY `forum_id` (`forum_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_auth_access @@ -136,11 +148,13 @@ CREATE TABLE IF NOT EXISTS `bb_auth_access` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_auth_access_snap`; CREATE TABLE IF NOT EXISTS `bb_auth_access_snap` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `forum_id` smallint(6) NOT NULL DEFAULT '0', - `forum_perm` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`user_id`,`forum_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `forum_id` SMALLINT(6) NOT NULL DEFAULT '0', + `forum_perm` INT(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`user_id`, `forum_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_auth_access_snap @@ -151,13 +165,15 @@ CREATE TABLE IF NOT EXISTS `bb_auth_access_snap` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_banlist`; CREATE TABLE IF NOT EXISTS `bb_banlist` ( - `ban_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `ban_userid` mediumint(8) NOT NULL DEFAULT '0', - `ban_ip` varchar(32) NOT NULL DEFAULT '', - `ban_email` varchar(255) NOT NULL DEFAULT '', + `ban_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `ban_userid` MEDIUMINT(8) NOT NULL DEFAULT '0', + `ban_ip` VARCHAR(32) NOT NULL DEFAULT '', + `ban_email` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`ban_id`), - KEY `ban_ip_user_id` (`ban_ip`,`ban_userid`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + KEY `ban_ip_user_id` (`ban_ip`, `ban_userid`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_banlist @@ -168,13 +184,15 @@ CREATE TABLE IF NOT EXISTS `bb_banlist` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_dlstatus`; CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_status` tinyint(1) NOT NULL DEFAULT '0', - `last_modified_dlstatus` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`user_id`,`topic_id`), + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_status` TINYINT(1) NOT NULL DEFAULT '0', + `last_modified_dlstatus` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`user_id`, `topic_id`), KEY `topic_id` (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_dlstatus @@ -185,11 +203,13 @@ CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_dlstatus_snap`; CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus_snap` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `dl_status` tinyint(4) NOT NULL DEFAULT '0', - `users_count` smallint(5) unsigned NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `dl_status` TINYINT(4) NOT NULL DEFAULT '0', + `users_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', KEY `topic_id` (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_dlstatus_snap @@ -200,17 +220,19 @@ CREATE TABLE IF NOT EXISTS `bb_bt_dlstatus_snap` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_last_torstat`; CREATE TABLE IF NOT EXISTS `bb_bt_last_torstat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `dl_status` tinyint(1) NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `release_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `bonus_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_down` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) USING BTREE -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `dl_status` TINYINT(1) NOT NULL DEFAULT '0', + `up_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `down_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `release_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `bonus_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `speed_up` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `speed_down` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY (`topic_id`, `user_id`) USING BTREE +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_last_torstat @@ -221,15 +243,17 @@ CREATE TABLE IF NOT EXISTS `bb_bt_last_torstat` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_last_userstat`; CREATE TABLE IF NOT EXISTS `bb_bt_last_userstat` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `release_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `bonus_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_down` bigint(20) unsigned NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `up_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `down_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `release_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `bonus_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `speed_up` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `speed_down` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_last_userstat @@ -240,10 +264,12 @@ CREATE TABLE IF NOT EXISTS `bb_bt_last_userstat` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_torhelp`; CREATE TABLE IF NOT EXISTS `bb_bt_torhelp` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id_csv` text NOT NULL, + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `topic_id_csv` TEXT NOT NULL, PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_torhelp @@ -254,23 +280,23 @@ CREATE TABLE IF NOT EXISTS `bb_bt_torhelp` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_torrents`; CREATE TABLE IF NOT EXISTS `bb_bt_torrents` ( - `info_hash` varbinary(20) NOT NULL DEFAULT '', - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `poster_id` mediumint(9) NOT NULL DEFAULT '0', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `size` bigint(20) unsigned NOT NULL DEFAULT '0', - `reg_time` int(11) NOT NULL DEFAULT '0', - `call_seed_time` int(11) NOT NULL DEFAULT '0', - `complete_count` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeder_last_seen` int(11) NOT NULL DEFAULT '0', - `tor_status` tinyint(4) NOT NULL DEFAULT '0', - `checked_user_id` mediumint(8) NOT NULL DEFAULT '0', - `checked_time` int(11) NOT NULL DEFAULT '0', - `tor_type` tinyint(1) NOT NULL DEFAULT '0', - `speed_up` int(11) NOT NULL DEFAULT '0', - `speed_down` int(11) NOT NULL DEFAULT '0', + `info_hash` VARBINARY(20) NOT NULL DEFAULT '', + `post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `poster_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `forum_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `attach_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `size` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `reg_time` INT(11) NOT NULL DEFAULT '0', + `call_seed_time` INT(11) NOT NULL DEFAULT '0', + `complete_count` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `seeder_last_seen` INT(11) NOT NULL DEFAULT '0', + `tor_status` TINYINT(4) NOT NULL DEFAULT '0', + `checked_user_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `checked_time` INT(11) NOT NULL DEFAULT '0', + `tor_type` TINYINT(1) NOT NULL DEFAULT '0', + `speed_up` INT(11) NOT NULL DEFAULT '0', + `speed_down` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`info_hash`), UNIQUE KEY `post_id` (`post_id`), UNIQUE KEY `topic_id` (`topic_id`), @@ -278,7 +304,9 @@ CREATE TABLE IF NOT EXISTS `bb_bt_torrents` ( KEY `reg_time` (`reg_time`), KEY `forum_id` (`forum_id`), KEY `poster_id` (`poster_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_torrents @@ -289,12 +317,14 @@ CREATE TABLE IF NOT EXISTS `bb_bt_torrents` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_torstat`; CREATE TABLE IF NOT EXISTS `bb_bt_torstat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `last_modified_torstat` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `completed` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `last_modified_torstat` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `completed` TINYINT(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`topic_id`, `user_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_torstat @@ -305,14 +335,16 @@ CREATE TABLE IF NOT EXISTS `bb_bt_torstat` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_tor_dl_stat`; CREATE TABLE IF NOT EXISTS `bb_bt_tor_dl_stat` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `attach_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `t_up_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `t_down_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `t_bonus_total` bigint(20) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `attach_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `t_up_total` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `t_down_total` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `t_bonus_total` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY (`topic_id`, `user_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_tor_dl_stat @@ -323,31 +355,37 @@ CREATE TABLE IF NOT EXISTS `bb_bt_tor_dl_stat` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_tracker`; CREATE TABLE IF NOT EXISTS `bb_bt_tracker` ( - `peer_hash` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `peer_id` varchar(20) NOT NULL DEFAULT '0', - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `ip` char(8) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '0', - `ipv6` varchar(32) DEFAULT NULL, - `port` smallint(5) unsigned NOT NULL DEFAULT '0', - `client` varchar(51) NOT NULL DEFAULT 'Unknown', - `seeder` tinyint(1) NOT NULL DEFAULT '0', - `releaser` tinyint(1) NOT NULL DEFAULT '0', - `tor_type` tinyint(1) NOT NULL DEFAULT '0', - `uploaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `downloaded` bigint(20) unsigned NOT NULL DEFAULT '0', - `remain` bigint(20) unsigned NOT NULL DEFAULT '0', - `speed_up` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_down` mediumint(8) unsigned NOT NULL DEFAULT '0', - `up_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_add` bigint(20) unsigned NOT NULL DEFAULT '0', - `update_time` int(11) NOT NULL DEFAULT '0', - `complete_percent` bigint(20) NOT NULL DEFAULT '0', - `complete` int(11) NOT NULL DEFAULT '0', + `peer_hash` VARCHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `peer_id` VARCHAR(20) NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `ip` CHAR(8) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '0', + `ipv6` VARCHAR(32) DEFAULT NULL, + `port` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `client` VARCHAR(51) NOT NULL DEFAULT 'Unknown', + `seeder` TINYINT(1) NOT NULL DEFAULT '0', + `releaser` TINYINT(1) NOT NULL DEFAULT '0', + `tor_type` TINYINT(1) NOT NULL DEFAULT '0', + `uploaded` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `downloaded` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `remain` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `speed_up` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `speed_down` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `up_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `down_add` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `update_time` INT(11) NOT NULL DEFAULT '0', + `complete_percent` BIGINT(20) NOT NULL DEFAULT '0', + `complete` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`peer_hash`), KEY `topic_id` (`topic_id`), KEY `user_id` (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_tracker @@ -358,13 +396,15 @@ CREATE TABLE IF NOT EXISTS `bb_bt_tracker` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_tracker_snap`; CREATE TABLE IF NOT EXISTS `bb_bt_tracker_snap` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeders` mediumint(8) unsigned NOT NULL DEFAULT '0', - `leechers` mediumint(8) unsigned NOT NULL DEFAULT '0', - `speed_up` int(10) unsigned NOT NULL DEFAULT '0', - `speed_down` int(10) unsigned NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `seeders` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `leechers` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `speed_up` INT(10) UNSIGNED NOT NULL DEFAULT '0', + `speed_down` INT(10) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_tracker_snap @@ -375,25 +415,29 @@ CREATE TABLE IF NOT EXISTS `bb_bt_tracker_snap` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_users`; CREATE TABLE IF NOT EXISTS `bb_bt_users` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `auth_key` char(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `u_up_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_down_total` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_up_release` bigint(20) unsigned NOT NULL DEFAULT '0', - `u_up_bonus` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_release_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_bonus_today` bigint(20) unsigned NOT NULL DEFAULT '0', - `points_today` float(16,2) unsigned NOT NULL DEFAULT '0.00', - `up_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `down_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_release_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `up_bonus_yesterday` bigint(20) unsigned NOT NULL DEFAULT '0', - `points_yesterday` float(16,2) unsigned NOT NULL DEFAULT '0.00', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `auth_key` CHAR(10) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `u_up_total` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `u_down_total` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `u_up_release` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `u_up_bonus` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `up_today` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `down_today` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `up_release_today` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `up_bonus_today` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `points_today` FLOAT(16, 2) UNSIGNED NOT NULL DEFAULT '0.00', + `up_yesterday` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `down_yesterday` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `up_release_yesterday` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `up_bonus_yesterday` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `points_yesterday` FLOAT(16, 2) UNSIGNED NOT NULL DEFAULT '0.00', PRIMARY KEY (`user_id`), UNIQUE KEY `auth_key` (`auth_key`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_users @@ -404,11 +448,13 @@ CREATE TABLE IF NOT EXISTS `bb_bt_users` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_bt_user_settings`; CREATE TABLE IF NOT EXISTS `bb_bt_user_settings` ( - `user_id` mediumint(9) NOT NULL DEFAULT '0', - `tor_search_set` text NOT NULL, - `last_modified` int(11) NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `tor_search_set` TEXT NOT NULL, + `last_modified` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_bt_user_settings @@ -419,12 +465,14 @@ CREATE TABLE IF NOT EXISTS `bb_bt_user_settings` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_categories`; CREATE TABLE IF NOT EXISTS `bb_categories` ( - `cat_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cat_title` varchar(100) NOT NULL DEFAULT '', - `cat_order` smallint(5) unsigned NOT NULL DEFAULT '0', + `cat_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, + `cat_title` VARCHAR(100) NOT NULL DEFAULT '', + `cat_order` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`cat_id`), KEY `cat_order` (`cat_order`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_categories @@ -436,10 +484,12 @@ INSERT INTO `bb_categories` VALUES ('1', 'Ваша первая категори -- ---------------------------- DROP TABLE IF EXISTS `bb_config`; CREATE TABLE IF NOT EXISTS `bb_config` ( - `config_name` varchar(255) NOT NULL DEFAULT '', - `config_value` text NOT NULL, + `config_name` VARCHAR(255) NOT NULL DEFAULT '', + `config_value` TEXT NOT NULL, PRIMARY KEY (`config_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_config @@ -536,61 +586,103 @@ INSERT INTO `bb_config` VALUES ('terms', ''); -- ---------------------------- DROP TABLE IF EXISTS `bb_cron`; CREATE TABLE IF NOT EXISTS `bb_cron` ( - `cron_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cron_active` tinyint(4) NOT NULL DEFAULT '1', - `cron_title` char(120) NOT NULL DEFAULT '', - `cron_script` char(120) NOT NULL DEFAULT '', - `schedule` enum('hourly','daily','weekly','monthly','interval') NOT NULL DEFAULT 'daily', - `run_day` enum('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28') DEFAULT NULL, - `run_time` time DEFAULT '04:00:00', - `run_order` tinyint(4) unsigned NOT NULL DEFAULT '0', - `last_run` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `next_run` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `run_interval` time DEFAULT NULL DEFAULT '0', - `log_enabled` tinyint(1) NOT NULL DEFAULT '0', - `log_file` char(120) NOT NULL DEFAULT '', - `log_sql_queries` tinyint(4) NOT NULL DEFAULT '0', - `disable_board` tinyint(1) NOT NULL DEFAULT '0', - `run_counter` bigint(20) unsigned NOT NULL DEFAULT '0', + `cron_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, + `cron_active` TINYINT(4) NOT NULL DEFAULT '1', + `cron_title` CHAR(120) NOT NULL DEFAULT '', + `cron_script` CHAR(120) NOT NULL DEFAULT '', + `schedule` ENUM ('hourly', 'daily', 'weekly', 'monthly', 'interval') NOT NULL DEFAULT 'daily', + `run_day` ENUM ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28') DEFAULT NULL, + `run_time` TIME DEFAULT '04:00:00', + `run_order` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0', + `last_run` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `next_run` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + `run_interval` TIME DEFAULT NULL DEFAULT '0', + `log_enabled` TINYINT(1) NOT NULL DEFAULT '0', + `log_file` CHAR(120) NOT NULL DEFAULT '', + `log_sql_queries` TINYINT(4) NOT NULL DEFAULT '0', + `disable_board` TINYINT(1) NOT NULL DEFAULT '0', + `run_counter` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`cron_id`), UNIQUE KEY `title` (`cron_title`), UNIQUE KEY `script` (`cron_script`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_cron -- ---------------------------- -INSERT INTO `bb_cron` VALUES ('', '1', 'Attach maintenance', 'attach_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Board maintenance', 'board_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune forums', 'prune_forums.php', 'daily', '', '05:00:00', '50', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune topic moved stubs', 'prune_topic_moved.php', 'daily', '', '05:00:00', '60', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Logs cleanup', 'clean_log.php', 'daily', '', '05:00:00', '70', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker maintenance', 'tr_maintenance.php', 'daily', '', '05:00:00', '90', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Clean dlstat', 'clean_dlstat.php', 'daily', '', '05:00:00', '100', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Prune inactive users', 'prune_inactive_users.php', 'daily', '', '05:00:00', '110', '', '', '', '1', '', '0', '1', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Sessions cleanup', 'sessions_cleanup.php', 'interval', '', '', '255', '', '', '00:03:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'DS update cat_forums', 'ds_update_cat_forums.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'DS update stats', 'ds_update_stats.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Flash topic view', 'flash_topic_view.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Clean search results', 'clean_search_results.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker cleanup and dlstat', 'tr_cleanup_and_dlstat.php', 'interval', '', '', '20', '', '', '00:15:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Accrual seedbonus', 'tr_seed_bonus.php', 'interval', '', '', '25', '', '', '00:15:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Make tracker snapshot', 'tr_make_snapshot.php', 'interval', '', '', '10', '', '', '00:10:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Seeder last seen', 'tr_update_seeder_last_seen.php', 'interval', '', '', '255', '', '', '01:00:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker dl-complete count', 'tr_complete_count.php', 'interval', '', '', '255', '', '', '06:00:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Cache garbage collector', 'cache_gc.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Sitemap update', 'sitemap.php', 'daily', '', '06:00:00', '30', '', '', '', '0', '', '0', '0', '0'); -INSERT INTO `bb_cron` VALUES ('', '1', 'Update forums atom', 'update_forums_atom.php', 'interval', '', '', '255', '', '', '00:15:00', '0', '', '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Attach maintenance', 'attach_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', + '1', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Board maintenance', 'board_maintenance.php', 'daily', '', '05:00:00', '40', '', '', '', '1', '', '0', '1', + '0'); +INSERT INTO `bb_cron` +VALUES ('', '1', 'Prune forums', 'prune_forums.php', 'daily', '', '05:00:00', '50', '', '', '', '1', '', '0', '1', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Prune topic moved stubs', 'prune_topic_moved.php', 'daily', '', '05:00:00', '60', '', '', '', '1', '', '0', + '1', '0'); +INSERT INTO `bb_cron` +VALUES ('', '1', 'Logs cleanup', 'clean_log.php', 'daily', '', '05:00:00', '70', '', '', '', '1', '', '0', '1', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Tracker maintenance', 'tr_maintenance.php', 'daily', '', '05:00:00', '90', '', '', '', '1', '', '0', '1', + '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Clean dlstat', 'clean_dlstat.php', 'daily', '', '05:00:00', '100', '', '', '', '1', '', '0', '1', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Prune inactive users', 'prune_inactive_users.php', 'daily', '', '05:00:00', '110', '', '', '', '1', '', + '0', '1', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Sessions cleanup', 'sessions_cleanup.php', 'interval', '', '', '255', '', '', '00:03:00', '0', '', '0', + '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'DS update cat_forums', 'ds_update_cat_forums.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', + '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'DS update stats', 'ds_update_stats.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', '0', + '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Flash topic view', 'flash_topic_view.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', '0', + '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Clean search results', 'clean_search_results.php', 'interval', '', '', '255', '', '', '00:10:00', '0', '', + '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Tracker cleanup and dlstat', 'tr_cleanup_and_dlstat.php', 'interval', '', '', '20', '', '', '00:15:00', + '0', '', '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Accrual seedbonus', 'tr_seed_bonus.php', 'interval', '', '', '25', '', '', '00:15:00', '0', '', '0', '0', + '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Make tracker snapshot', 'tr_make_snapshot.php', 'interval', '', '', '10', '', '', '00:10:00', '0', '', '0', + '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Seeder last seen', 'tr_update_seeder_last_seen.php', 'interval', '', '', '255', '', '', '01:00:00', '0', + '', '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Tracker dl-complete count', 'tr_complete_count.php', 'interval', '', '', '255', '', '', '06:00:00', '0', + '', '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Cache garbage collector', 'cache_gc.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', + '0'); +INSERT INTO `bb_cron` +VALUES ('', '1', 'Sitemap update', 'sitemap.php', 'daily', '', '06:00:00', '30', '', '', '', '0', '', '0', '0', '0'); +INSERT INTO `bb_cron` VALUES + ('', '1', 'Update forums atom', 'update_forums_atom.php', 'interval', '', '', '255', '', '', '00:15:00', '0', '', '0', + '0', '0'); -- ---------------------------- -- Table structure for `bb_disallow` -- ---------------------------- DROP TABLE IF EXISTS `bb_disallow`; CREATE TABLE IF NOT EXISTS `bb_disallow` ( - `disallow_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `disallow_username` varchar(25) NOT NULL DEFAULT '', + `disallow_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `disallow_username` VARCHAR(25) NOT NULL DEFAULT '', PRIMARY KEY (`disallow_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_disallow @@ -601,12 +693,14 @@ CREATE TABLE IF NOT EXISTS `bb_disallow` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_extensions`; CREATE TABLE IF NOT EXISTS `bb_extensions` ( - `ext_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `group_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `extension` varchar(100) NOT NULL DEFAULT '', - `comment` varchar(100) NOT NULL DEFAULT '', + `ext_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `group_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `extension` VARCHAR(100) NOT NULL DEFAULT '', + `comment` VARCHAR(100) NOT NULL DEFAULT '', PRIMARY KEY (`ext_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_extensions @@ -644,16 +738,18 @@ INSERT INTO `bb_extensions` VALUES ('', '6', 'torrent', ''); -- ---------------------------- DROP TABLE IF EXISTS `bb_extension_groups`; CREATE TABLE IF NOT EXISTS `bb_extension_groups` ( - `group_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `group_name` varchar(20) NOT NULL DEFAULT '', - `cat_id` tinyint(2) NOT NULL DEFAULT '0', - `allow_group` tinyint(1) NOT NULL DEFAULT '0', - `download_mode` tinyint(1) unsigned NOT NULL DEFAULT '1', - `upload_icon` varchar(100) NOT NULL DEFAULT '', - `max_filesize` int(20) NOT NULL DEFAULT '0', - `forum_permissions` text NOT NULL, + `group_id` MEDIUMINT(8) NOT NULL AUTO_INCREMENT, + `group_name` VARCHAR(20) NOT NULL DEFAULT '', + `cat_id` TINYINT(2) NOT NULL DEFAULT '0', + `allow_group` TINYINT(1) NOT NULL DEFAULT '0', + `download_mode` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1', + `upload_icon` VARCHAR(100) NOT NULL DEFAULT '', + `max_filesize` INT(20) NOT NULL DEFAULT '0', + `forum_permissions` TEXT NOT NULL, PRIMARY KEY (`group_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_extension_groups @@ -670,67 +766,76 @@ INSERT INTO `bb_extension_groups` VALUES ('', 'Torrent', '0', '1', '1', '', '122 -- ---------------------------- DROP TABLE IF EXISTS `bb_forums`; CREATE TABLE IF NOT EXISTS `bb_forums` ( - `forum_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `cat_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `forum_name` varchar(150) NOT NULL DEFAULT '', - `forum_desc` text NOT NULL, - `forum_status` tinyint(4) NOT NULL DEFAULT '0', - `forum_order` smallint(5) unsigned NOT NULL DEFAULT '1', - `forum_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_topics` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_last_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_tpl_id` smallint(6) NOT NULL DEFAULT '0', - `prune_days` smallint(5) unsigned NOT NULL DEFAULT '0', - `auth_view` tinyint(2) NOT NULL DEFAULT '0', - `auth_read` tinyint(2) NOT NULL DEFAULT '0', - `auth_post` tinyint(2) NOT NULL DEFAULT '0', - `auth_reply` tinyint(2) NOT NULL DEFAULT '0', - `auth_edit` tinyint(2) NOT NULL DEFAULT '0', - `auth_delete` tinyint(2) NOT NULL DEFAULT '0', - `auth_sticky` tinyint(2) NOT NULL DEFAULT '0', - `auth_announce` tinyint(2) NOT NULL DEFAULT '0', - `auth_vote` tinyint(2) NOT NULL DEFAULT '0', - `auth_pollcreate` tinyint(2) NOT NULL DEFAULT '0', - `auth_attachments` tinyint(2) NOT NULL DEFAULT '0', - `auth_download` tinyint(2) NOT NULL DEFAULT '0', - `allow_reg_tracker` tinyint(1) NOT NULL DEFAULT '0', - `allow_porno_topic` tinyint(1) NOT NULL DEFAULT '0', - `self_moderated` tinyint(1) NOT NULL DEFAULT '0', - `forum_parent` smallint(5) unsigned NOT NULL DEFAULT '0', - `show_on_index` tinyint(1) NOT NULL DEFAULT '1', - `forum_display_sort` tinyint(1) NOT NULL DEFAULT '0', - `forum_display_order` tinyint(1) NOT NULL DEFAULT '0', + `forum_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, + `cat_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `forum_name` VARCHAR(150) NOT NULL DEFAULT '', + `forum_desc` TEXT NOT NULL, + `forum_status` TINYINT(4) NOT NULL DEFAULT '0', + `forum_order` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '1', + `forum_posts` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `forum_topics` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `forum_last_post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `forum_tpl_id` SMALLINT(6) NOT NULL DEFAULT '0', + `prune_days` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `auth_view` TINYINT(2) NOT NULL DEFAULT '0', + `auth_read` TINYINT(2) NOT NULL DEFAULT '0', + `auth_post` TINYINT(2) NOT NULL DEFAULT '0', + `auth_reply` TINYINT(2) NOT NULL DEFAULT '0', + `auth_edit` TINYINT(2) NOT NULL DEFAULT '0', + `auth_delete` TINYINT(2) NOT NULL DEFAULT '0', + `auth_sticky` TINYINT(2) NOT NULL DEFAULT '0', + `auth_announce` TINYINT(2) NOT NULL DEFAULT '0', + `auth_vote` TINYINT(2) NOT NULL DEFAULT '0', + `auth_pollcreate` TINYINT(2) NOT NULL DEFAULT '0', + `auth_attachments` TINYINT(2) NOT NULL DEFAULT '0', + `auth_download` TINYINT(2) NOT NULL DEFAULT '0', + `allow_reg_tracker` TINYINT(1) NOT NULL DEFAULT '0', + `allow_porno_topic` TINYINT(1) NOT NULL DEFAULT '0', + `self_moderated` TINYINT(1) NOT NULL DEFAULT '0', + `forum_parent` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `show_on_index` TINYINT(1) NOT NULL DEFAULT '1', + `forum_display_sort` TINYINT(1) NOT NULL DEFAULT '0', + `forum_display_order` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`forum_id`), KEY `forums_order` (`forum_order`), KEY `cat_id` (`cat_id`), KEY `forum_last_post_id` (`forum_last_post_id`), KEY `forum_parent` (`forum_parent`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_forums -- ---------------------------- -INSERT INTO `bb_forums` VALUES ('1', '1', 'Ваш первый форум', 'Описание вашего первого форума.', '0', '10', '1', '1', '1', '0', '0', '0', '0', '1', '1', '1', '1', '3', '3', '1', '1', '1', '1', '0', '0', '0', '0', '1', '0', '0'); +INSERT INTO `bb_forums` VALUES + ('1', '1', 'Ваш первый форум', 'Описание вашего первого форума.', '0', '10', '1', '1', '1', '0', '0', '0', '0', '1', + '1', '1', '1', + '3', '3', '1', + '1', '1', '1', + '0', '0', '0', '0', '1', '0', '0'); -- ---------------------------- -- Table structure for `bb_groups` -- ---------------------------- DROP TABLE IF EXISTS `bb_groups`; CREATE TABLE IF NOT EXISTS `bb_groups` ( - `group_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `avatar_ext_id` int(15) NOT NULL DEFAULT '0', - `group_time` int(11) NOT NULL DEFAULT '0', - `mod_time` int(11) NOT NULL DEFAULT '0', - `group_type` tinyint(4) NOT NULL DEFAULT '1', - `release_group` tinyint(4) NOT NULL DEFAULT '0', - `group_name` varchar(40) NOT NULL DEFAULT '', - `group_description` text NOT NULL, - `group_signature` text NOT NULL, - `group_moderator` mediumint(8) NOT NULL DEFAULT '0', - `group_single_user` tinyint(1) NOT NULL DEFAULT '1', + `group_id` MEDIUMINT(8) NOT NULL AUTO_INCREMENT, + `avatar_ext_id` INT(15) NOT NULL DEFAULT '0', + `group_time` INT(11) NOT NULL DEFAULT '0', + `mod_time` INT(11) NOT NULL DEFAULT '0', + `group_type` TINYINT(4) NOT NULL DEFAULT '1', + `release_group` TINYINT(4) NOT NULL DEFAULT '0', + `group_name` VARCHAR(40) NOT NULL DEFAULT '', + `group_description` TEXT NOT NULL, + `group_signature` TEXT NOT NULL, + `group_moderator` MEDIUMINT(8) NOT NULL DEFAULT '0', + `group_single_user` TINYINT(1) NOT NULL DEFAULT '1', PRIMARY KEY (`group_id`), KEY `group_single_user` (`group_single_user`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_groups @@ -741,21 +846,25 @@ CREATE TABLE IF NOT EXISTS `bb_groups` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_log`; CREATE TABLE IF NOT EXISTS `bb_log` ( - `log_type_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_user_id` mediumint(9) NOT NULL DEFAULT '0', - `log_username` varchar(25) NOT NULL DEFAULT '', - `log_user_ip` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `log_forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `log_forum_id_new` smallint(5) unsigned NOT NULL DEFAULT '0', - `log_topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_topic_id_new` mediumint(8) unsigned NOT NULL DEFAULT '0', - `log_topic_title` varchar(250) NOT NULL DEFAULT '', - `log_topic_title_new` varchar(250) NOT NULL DEFAULT '', - `log_time` int(11) NOT NULL DEFAULT '0', - `log_msg` text NOT NULL, + `log_type_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `log_user_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `log_username` VARCHAR(25) NOT NULL DEFAULT '', + `log_user_ip` VARCHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `log_forum_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `log_forum_id_new` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `log_topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `log_topic_id_new` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `log_topic_title` VARCHAR(250) NOT NULL DEFAULT '', + `log_topic_title_new` VARCHAR(250) NOT NULL DEFAULT '', + `log_time` INT(11) NOT NULL DEFAULT '0', + `log_msg` TEXT NOT NULL, KEY `log_time` (`log_time`), FULLTEXT KEY `log_topic_title` (`log_topic_title`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_log @@ -766,12 +875,14 @@ CREATE TABLE IF NOT EXISTS `bb_log` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_poll_users`; CREATE TABLE IF NOT EXISTS `bb_poll_users` ( - `topic_id` int(10) unsigned NOT NULL, - `user_id` int(11) NOT NULL, - `vote_ip` varchar(32) NOT NULL, - `vote_dt` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`topic_id`,`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `topic_id` INT(10) UNSIGNED NOT NULL, + `user_id` INT(11) NOT NULL, + `vote_ip` VARCHAR(32) NOT NULL, + `vote_dt` INT(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`topic_id`, `user_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_poll_users @@ -782,12 +893,14 @@ CREATE TABLE IF NOT EXISTS `bb_poll_users` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_poll_votes`; CREATE TABLE IF NOT EXISTS `bb_poll_votes` ( - `topic_id` int(10) unsigned NOT NULL, - `vote_id` tinyint(4) unsigned NOT NULL, - `vote_text` varchar(255) NOT NULL, - `vote_result` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`topic_id`,`vote_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `topic_id` INT(10) UNSIGNED NOT NULL, + `vote_id` TINYINT(4) UNSIGNED NOT NULL, + `vote_text` VARCHAR(255) NOT NULL, + `vote_result` MEDIUMINT(8) UNSIGNED NOT NULL, + PRIMARY KEY (`topic_id`, `vote_id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_poll_votes @@ -798,44 +911,51 @@ CREATE TABLE IF NOT EXISTS `bb_poll_votes` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_posts`; CREATE TABLE IF NOT EXISTS `bb_posts` ( - `post_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `forum_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `poster_id` mediumint(8) NOT NULL DEFAULT '0', - `post_time` int(11) NOT NULL DEFAULT '0', - `poster_ip` char(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `poster_rg_id` mediumint(8) NOT NULL DEFAULT '0', - `attach_rg_sig` tinyint(4) NOT NULL DEFAULT '0', - `post_username` varchar(25) NOT NULL DEFAULT '', - `post_edit_time` int(11) NOT NULL DEFAULT '0', - `post_edit_count` smallint(5) unsigned NOT NULL DEFAULT '0', - `post_attachment` tinyint(1) NOT NULL DEFAULT '0', - `user_post` tinyint(1) NOT NULL DEFAULT '1', - `mc_comment` text NOT NULL, - `mc_type` tinyint(1) NOT NULL DEFAULT '0', - `mc_user_id` mediumint(8) NOT NULL DEFAULT '0', + `post_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `forum_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `poster_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `post_time` INT(11) NOT NULL DEFAULT '0', + `poster_ip` CHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `poster_rg_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `attach_rg_sig` TINYINT(4) NOT NULL DEFAULT '0', + `post_username` VARCHAR(25) NOT NULL DEFAULT '', + `post_edit_time` INT(11) NOT NULL DEFAULT '0', + `post_edit_count` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `post_attachment` TINYINT(1) NOT NULL DEFAULT '0', + `user_post` TINYINT(1) NOT NULL DEFAULT '1', + `mc_comment` TEXT NOT NULL, + `mc_type` TINYINT(1) NOT NULL DEFAULT '0', + `mc_user_id` MEDIUMINT(8) NOT NULL DEFAULT '0', PRIMARY KEY (`post_id`), KEY `topic_id` (`topic_id`), KEY `poster_id` (`poster_id`), KEY `post_time` (`post_time`), - KEY `forum_id_post_time` (`forum_id`,`post_time`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + KEY `forum_id_post_time` (`forum_id`, `post_time`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_posts -- ---------------------------- -INSERT INTO `bb_posts` VALUES ('1', '1', '1', '2', UNIX_TIMESTAMP(), '', '0', '0', '', '0', '0', '0', '1', '', '0', '0'); +INSERT INTO `bb_posts` +VALUES ('1', '1', '1', '2', UNIX_TIMESTAMP(), '', '0', '0', '', '0', '0', '0', '1', '', '0', '0'); -- ---------------------------- -- Table structure for `bb_posts_html` -- ---------------------------- DROP TABLE IF EXISTS `bb_posts_html`; CREATE TABLE IF NOT EXISTS `bb_posts_html` ( - `post_id` mediumint(9) NOT NULL DEFAULT '0', - `post_html_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `post_html` mediumtext NOT NULL DEFAULT '', + `post_id` MEDIUMINT(9) NOT NULL DEFAULT '0', + `post_html_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `post_html` MEDIUMTEXT NOT NULL DEFAULT '', PRIMARY KEY (`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_posts_html @@ -846,11 +966,13 @@ CREATE TABLE IF NOT EXISTS `bb_posts_html` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_posts_search`; CREATE TABLE IF NOT EXISTS `bb_posts_search` ( - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `search_words` text NOT NULL, + `post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `search_words` TEXT NOT NULL, PRIMARY KEY (`post_id`), FULLTEXT KEY `search_words` (`search_words`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_posts_search @@ -861,32 +983,39 @@ CREATE TABLE IF NOT EXISTS `bb_posts_search` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_posts_text`; CREATE TABLE IF NOT EXISTS `bb_posts_text` ( - `post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `post_text` text NOT NULL, + `post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `post_text` TEXT NOT NULL, PRIMARY KEY (`post_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_posts_text -- ---------------------------- -INSERT INTO `bb_posts_text` VALUES ('1', 'Благодарим вас за установку новой версии TorrentPier II!\n\nЧто делать дальше? Сперва настройте ваш сайт в администраторском разделе. Измените базовые опции: заголовок сайта, число сообщений на страницу, часовой пояс, язык по-умолчанию, настройки сидбонусов, дней рождения и т.д. Создайте несколько форумов, а также не забудьте переименовать или удалить этот. Обязательно настройте возможность создания релизов в созданных вами разделах и добавьте [url=https://torrentpier.me/threads/25867/]шаблоны оформления раздач[/url] для них. Если у вас возникнут вопросы или потребность в дополнительных модификациях, [url=https://torrentpier.me/]посетите наш форум[/url].\n\nТакже напоминаем, что у проекта TorrentPier II есть несколько сайтов, которые могут оказаться полезны для вас:\n[list]\n[*]Форум: https://torrentpier.me/\n[*]Демо-версия: https://demo.torrentpier.me/\n[*]Инструкция: https://faq.torrentpier.me/\n[*]Центр загрузки: https://get.torrentpier.me/\n[*]Перевод на другие языки: http://translate.torrentpier.me/\n[/list]\nНе забудьте добавить их себе в закладки и регулярно проверять наличие новых версий движка на нашем форуме, для своевременного обновления.\n\nНе сомневаемся, вам под силу создать самый лучший трекер. Удачи!'); +INSERT INTO `bb_posts_text` VALUES ('1', + 'Благодарим вас за установку новой версии TorrentPier II!\n\nЧто делать дальше? Сперва настройте ваш сайт в администраторском разделе. Измените базовые опции: заголовок сайта, число сообщений на страницу, часовой пояс, язык по-умолчанию, настройки сидбонусов, дней рождения и т.д. Создайте несколько форумов, а также не забудьте переименовать или удалить этот. Обязательно настройте возможность создания релизов в созданных вами разделах и добавьте [url=https://torrentpier.me/threads/25867/]шаблоны оформления раздач[/url] для них. Если у вас возникнут вопросы или потребность в дополнительных модификациях, [url=https://torrentpier.me/]посетите наш форум[/url].\n\nТакже напоминаем, что у проекта TorrentPier II есть несколько сайтов, которые могут оказаться полезны для вас:\n[list]\n[*]Форум: https://torrentpier.me/\n[*]Демо-версия: https://demo.torrentpier.me/\n[*]Инструкция: https://faq.torrentpier.me/\n[*]Центр загрузки: https://get.torrentpier.me/\n[*]Перевод на другие языки: http://translate.torrentpier.me/\n[/list]\nНе забудьте добавить их себе в закладки и регулярно проверять наличие новых версий движка на нашем форуме, для своевременного обновления.\n\nНе сомневаемся, вам под силу создать самый лучший трекер. Удачи!'); -- ---------------------------- -- Table structure for `bb_privmsgs` -- ---------------------------- DROP TABLE IF EXISTS `bb_privmsgs`; CREATE TABLE IF NOT EXISTS `bb_privmsgs` ( - `privmsgs_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `privmsgs_type` tinyint(4) NOT NULL DEFAULT '0', - `privmsgs_subject` varchar(255) NOT NULL DEFAULT '0', - `privmsgs_from_userid` mediumint(8) NOT NULL DEFAULT '0', - `privmsgs_to_userid` mediumint(8) NOT NULL DEFAULT '0', - `privmsgs_date` int(11) NOT NULL DEFAULT '0', - `privmsgs_ip` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', + `privmsgs_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `privmsgs_type` TINYINT(4) NOT NULL DEFAULT '0', + `privmsgs_subject` VARCHAR(255) NOT NULL DEFAULT '0', + `privmsgs_from_userid` MEDIUMINT(8) NOT NULL DEFAULT '0', + `privmsgs_to_userid` MEDIUMINT(8) NOT NULL DEFAULT '0', + `privmsgs_date` INT(11) NOT NULL DEFAULT '0', + `privmsgs_ip` VARCHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', PRIMARY KEY (`privmsgs_id`), KEY `privmsgs_from_userid` (`privmsgs_from_userid`), KEY `privmsgs_to_userid` (`privmsgs_to_userid`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_privmsgs @@ -897,10 +1026,12 @@ CREATE TABLE IF NOT EXISTS `bb_privmsgs` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_privmsgs_text`; CREATE TABLE IF NOT EXISTS `bb_privmsgs_text` ( - `privmsgs_text_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `privmsgs_text` text NOT NULL, + `privmsgs_text_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `privmsgs_text` TEXT NOT NULL, PRIMARY KEY (`privmsgs_text_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_privmsgs_text @@ -911,11 +1042,13 @@ CREATE TABLE IF NOT EXISTS `bb_privmsgs_text` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_quota_limits`; CREATE TABLE IF NOT EXISTS `bb_quota_limits` ( - `quota_limit_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `quota_desc` varchar(20) NOT NULL DEFAULT '', - `quota_limit` bigint(20) unsigned NOT NULL DEFAULT '0', + `quota_limit_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `quota_desc` VARCHAR(20) NOT NULL DEFAULT '', + `quota_limit` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`quota_limit_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_quota_limits @@ -929,14 +1062,16 @@ INSERT INTO `bb_quota_limits` VALUES ('3', 'High', '15728640'); -- ---------------------------- DROP TABLE IF EXISTS `bb_ranks`; CREATE TABLE IF NOT EXISTS `bb_ranks` ( - `rank_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `rank_title` varchar(50) NOT NULL DEFAULT '', - `rank_min` mediumint(8) NOT NULL DEFAULT '0', - `rank_special` tinyint(1) NOT NULL DEFAULT '1', - `rank_image` varchar(255) NOT NULL DEFAULT '', - `rank_style` varchar(255) NOT NULL DEFAULT '', + `rank_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, + `rank_title` VARCHAR(50) NOT NULL DEFAULT '', + `rank_min` MEDIUMINT(8) NOT NULL DEFAULT '0', + `rank_special` TINYINT(1) NOT NULL DEFAULT '1', + `rank_image` VARCHAR(255) NOT NULL DEFAULT '', + `rank_style` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`rank_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_ranks @@ -948,19 +1083,21 @@ INSERT INTO `bb_ranks` VALUES ('', 'Администратор', '-1', '1', 'sty -- ---------------------------- DROP TABLE IF EXISTS `bb_search_rebuild`; CREATE TABLE IF NOT EXISTS `bb_search_rebuild` ( - `rebuild_session_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `start_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `end_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `start_time` int(11) NOT NULL DEFAULT '0', - `end_time` int(11) NOT NULL DEFAULT '0', - `last_cycle_time` int(11) NOT NULL DEFAULT '0', - `session_time` int(11) NOT NULL DEFAULT '0', - `session_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `session_cycles` mediumint(8) unsigned NOT NULL DEFAULT '0', - `search_size` int(10) unsigned NOT NULL DEFAULT '0', - `rebuild_session_status` tinyint(1) NOT NULL DEFAULT '0', + `rebuild_session_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `start_post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `end_post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `start_time` INT(11) NOT NULL DEFAULT '0', + `end_time` INT(11) NOT NULL DEFAULT '0', + `last_cycle_time` INT(11) NOT NULL DEFAULT '0', + `session_time` INT(11) NOT NULL DEFAULT '0', + `session_posts` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `session_cycles` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `search_size` INT(10) UNSIGNED NOT NULL DEFAULT '0', + `rebuild_session_status` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`rebuild_session_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_search_rebuild @@ -971,14 +1108,20 @@ CREATE TABLE IF NOT EXISTS `bb_search_rebuild` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_search_results`; CREATE TABLE IF NOT EXISTS `bb_search_results` ( - `session_id` char(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `search_type` tinyint(4) NOT NULL DEFAULT '0', - `search_id` varchar(12) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `search_time` int(11) NOT NULL DEFAULT '0', - `search_settings` text NOT NULL, - `search_array` text NOT NULL, - PRIMARY KEY (`session_id`,`search_type`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; + `session_id` CHAR(20) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `search_type` TINYINT(4) NOT NULL DEFAULT '0', + `search_id` VARCHAR(12) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `search_time` INT(11) NOT NULL DEFAULT '0', + `search_settings` TEXT NOT NULL, + `search_array` TEXT NOT NULL, + PRIMARY KEY (`session_id`, `search_type`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_search_results @@ -989,15 +1132,21 @@ CREATE TABLE IF NOT EXISTS `bb_search_results` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_sessions`; CREATE TABLE IF NOT EXISTS `bb_sessions` ( - `session_id` char(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `session_user_id` mediumint(8) NOT NULL DEFAULT '0', - `session_start` int(11) NOT NULL DEFAULT '0', - `session_time` int(11) NOT NULL DEFAULT '0', - `session_ip` char(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `session_logged_in` tinyint(1) NOT NULL DEFAULT '0', - `session_admin` tinyint(2) NOT NULL DEFAULT '0', + `session_id` CHAR(20) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `session_user_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `session_start` INT(11) NOT NULL DEFAULT '0', + `session_time` INT(11) NOT NULL DEFAULT '0', + `session_ip` CHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `session_logged_in` TINYINT(1) NOT NULL DEFAULT '0', + `session_admin` TINYINT(2) NOT NULL DEFAULT '0', PRIMARY KEY (`session_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_sessions @@ -1008,12 +1157,14 @@ CREATE TABLE IF NOT EXISTS `bb_sessions` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_smilies`; CREATE TABLE IF NOT EXISTS `bb_smilies` ( - `smilies_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `code` varchar(50) NOT NULL DEFAULT '', - `smile_url` varchar(100) NOT NULL DEFAULT '', - `emoticon` varchar(75) NOT NULL DEFAULT '', + `smilies_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, + `code` VARCHAR(50) NOT NULL DEFAULT '', + `smile_url` VARCHAR(100) NOT NULL DEFAULT '', + `emoticon` VARCHAR(75) NOT NULL DEFAULT '', PRIMARY KEY (`smilies_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_smilies @@ -1079,47 +1230,53 @@ INSERT INTO `bb_smilies` VALUES ('', ':cc:', 'cc.gif', 'cc'); -- ---------------------------- DROP TABLE IF EXISTS `bb_topics`; CREATE TABLE IF NOT EXISTS `bb_topics` ( - `topic_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `forum_id` smallint(8) unsigned NOT NULL DEFAULT '0', - `topic_title` varchar(250) NOT NULL DEFAULT '', - `topic_poster` mediumint(8) NOT NULL DEFAULT '0', - `topic_time` int(11) NOT NULL DEFAULT '0', - `topic_views` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_replies` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_status` tinyint(3) NOT NULL DEFAULT '0', - `topic_vote` tinyint(1) NOT NULL DEFAULT '0', - `topic_type` tinyint(3) NOT NULL DEFAULT '0', - `topic_first_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_last_post_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_moved_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_attachment` tinyint(1) NOT NULL DEFAULT '0', - `topic_dl_type` tinyint(1) NOT NULL DEFAULT '0', - `topic_last_post_time` int(11) NOT NULL DEFAULT '0', - `topic_show_first_post` tinyint(1) unsigned NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `forum_id` SMALLINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_title` VARCHAR(250) NOT NULL DEFAULT '', + `topic_poster` MEDIUMINT(8) NOT NULL DEFAULT '0', + `topic_time` INT(11) NOT NULL DEFAULT '0', + `topic_views` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_replies` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_status` TINYINT(3) NOT NULL DEFAULT '0', + `topic_vote` TINYINT(1) NOT NULL DEFAULT '0', + `topic_type` TINYINT(3) NOT NULL DEFAULT '0', + `topic_first_post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_last_post_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_moved_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_attachment` TINYINT(1) NOT NULL DEFAULT '0', + `topic_dl_type` TINYINT(1) NOT NULL DEFAULT '0', + `topic_last_post_time` INT(11) NOT NULL DEFAULT '0', + `topic_show_first_post` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`topic_id`), KEY `forum_id` (`forum_id`), KEY `topic_last_post_id` (`topic_last_post_id`), KEY `topic_last_post_time` (`topic_last_post_time`), FULLTEXT KEY `topic_title` (`topic_title`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_topics -- ---------------------------- -INSERT INTO `bb_topics` VALUES ('1', '1', 'Добро пожаловать в TorrentPier II', '2', UNIX_TIMESTAMP(), '2', '0', '0', '0', '0', '1', '1', '0', '0', '0', '1414658247', '0'); +INSERT INTO `bb_topics` VALUES + ('1', '1', 'Добро пожаловать в TorrentPier II', '2', UNIX_TIMESTAMP(), '2', '0', '0', '0', '0', '1', '1', '0', '0', + '0', '1414658247', '0'); -- ---------------------------- -- Table structure for `bb_topics_watch` -- ---------------------------- DROP TABLE IF EXISTS `bb_topics_watch`; CREATE TABLE IF NOT EXISTS `bb_topics_watch` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_id` mediumint(8) NOT NULL DEFAULT '0', - `notify_status` tinyint(1) NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `notify_status` TINYINT(1) NOT NULL DEFAULT '0', KEY `topic_id` (`topic_id`), KEY `user_id` (`user_id`), KEY `notify_status` (`notify_status`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_topics_watch @@ -1130,18 +1287,20 @@ CREATE TABLE IF NOT EXISTS `bb_topics_watch` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_topic_tpl`; CREATE TABLE IF NOT EXISTS `bb_topic_tpl` ( - `tpl_id` smallint(6) NOT NULL AUTO_INCREMENT, - `tpl_name` varchar(60) NOT NULL DEFAULT '', - `tpl_src_form` text NOT NULL, - `tpl_src_title` text NOT NULL, - `tpl_src_msg` text NOT NULL, - `tpl_comment` text NOT NULL, - `tpl_rules_post_id` int(10) unsigned NOT NULL DEFAULT '0', - `tpl_last_edit_tm` int(11) NOT NULL DEFAULT '0', - `tpl_last_edit_by` int(11) NOT NULL DEFAULT '0', + `tpl_id` SMALLINT(6) NOT NULL AUTO_INCREMENT, + `tpl_name` VARCHAR(60) NOT NULL DEFAULT '', + `tpl_src_form` TEXT NOT NULL, + `tpl_src_title` TEXT NOT NULL, + `tpl_src_msg` TEXT NOT NULL, + `tpl_comment` TEXT NOT NULL, + `tpl_rules_post_id` INT(10) UNSIGNED NOT NULL DEFAULT '0', + `tpl_last_edit_tm` INT(11) NOT NULL DEFAULT '0', + `tpl_last_edit_by` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`tpl_id`), UNIQUE KEY `tpl_name` (`tpl_name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_topic_tpl @@ -1152,67 +1311,93 @@ CREATE TABLE IF NOT EXISTS `bb_topic_tpl` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_users`; CREATE TABLE IF NOT EXISTS `bb_users` ( - `user_id` mediumint(8) NOT NULL AUTO_INCREMENT, - `user_active` tinyint(1) NOT NULL DEFAULT '1', - `username` varchar(25) NOT NULL DEFAULT '', - `user_password` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `user_session_time` int(11) NOT NULL DEFAULT '0', - `user_lastvisit` int(11) NOT NULL DEFAULT '0', - `user_last_ip` char(32) NOT NULL DEFAULT '', - `user_regdate` int(11) NOT NULL DEFAULT '0', - `user_reg_ip` char(32) NOT NULL DEFAULT '', - `user_level` tinyint(4) NOT NULL DEFAULT '0', - `user_posts` mediumint(8) unsigned NOT NULL DEFAULT '0', - `user_timezone` decimal(5,2) NOT NULL DEFAULT '0.00', - `user_lang` varchar(255) NOT NULL DEFAULT 'ru', - `user_new_privmsg` smallint(5) unsigned NOT NULL DEFAULT '0', - `user_unread_privmsg` smallint(5) unsigned NOT NULL DEFAULT '0', - `user_last_privmsg` int(11) NOT NULL DEFAULT '0', - `user_opt` int(11) NOT NULL DEFAULT '0', - `user_rank` int(11) NOT NULL DEFAULT '0', - `avatar_ext_id` tinyint(4) NOT NULL DEFAULT '0', - `user_gender` tinyint(1) NOT NULL DEFAULT '0', - `user_birthday` date NOT NULL DEFAULT '0000-00-00', - `user_email` varchar(255) NOT NULL DEFAULT '', - `user_skype` varchar(32) NOT NULL DEFAULT '', - `user_twitter` varchar(15) NOT NULL DEFAULT '', - `user_icq` varchar(15) NOT NULL DEFAULT '', - `user_website` varchar(100) NOT NULL DEFAULT '', - `user_from` varchar(100) NOT NULL DEFAULT '', - `user_sig` text NOT NULL, - `user_occ` varchar(100) NOT NULL DEFAULT '', - `user_interests` varchar(255) NOT NULL DEFAULT '', - `user_actkey` varchar(32) NOT NULL DEFAULT '', - `user_newpasswd` varchar(32) NOT NULL DEFAULT '', - `autologin_id` varchar(12) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '', - `user_newest_pm_id` mediumint(8) NOT NULL DEFAULT '0', - `user_points` float(16,2) NOT NULL DEFAULT '0.00', - `tpl_name` varchar(255) NOT NULL DEFAULT 'default', + `user_id` MEDIUMINT(8) NOT NULL AUTO_INCREMENT, + `user_active` TINYINT(1) NOT NULL DEFAULT '1', + `username` VARCHAR(25) NOT NULL DEFAULT '', + `user_password` VARCHAR(32) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `user_session_time` INT(11) NOT NULL DEFAULT '0', + `user_lastvisit` INT(11) NOT NULL DEFAULT '0', + `user_last_ip` CHAR(32) NOT NULL DEFAULT '', + `user_regdate` INT(11) NOT NULL DEFAULT '0', + `user_reg_ip` CHAR(32) NOT NULL DEFAULT '', + `user_level` TINYINT(4) NOT NULL DEFAULT '0', + `user_posts` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `user_timezone` DECIMAL(5, 2) NOT NULL DEFAULT '0.00', + `user_lang` VARCHAR(255) NOT NULL DEFAULT 'ru', + `user_new_privmsg` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `user_unread_privmsg` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', + `user_last_privmsg` INT(11) NOT NULL DEFAULT '0', + `user_opt` INT(11) NOT NULL DEFAULT '0', + `user_rank` INT(11) NOT NULL DEFAULT '0', + `avatar_ext_id` TINYINT(4) NOT NULL DEFAULT '0', + `user_gender` TINYINT(1) NOT NULL DEFAULT '0', + `user_birthday` DATE NOT NULL DEFAULT '0000-00-00', + `user_email` VARCHAR(255) NOT NULL DEFAULT '', + `user_skype` VARCHAR(32) NOT NULL DEFAULT '', + `user_twitter` VARCHAR(15) NOT NULL DEFAULT '', + `user_icq` VARCHAR(15) NOT NULL DEFAULT '', + `user_website` VARCHAR(100) NOT NULL DEFAULT '', + `user_from` VARCHAR(100) NOT NULL DEFAULT '', + `user_sig` TEXT NOT NULL, + `user_occ` VARCHAR(100) NOT NULL DEFAULT '', + `user_interests` VARCHAR(255) NOT NULL DEFAULT '', + `user_actkey` VARCHAR(32) NOT NULL DEFAULT '', + `user_newpasswd` VARCHAR(32) NOT NULL DEFAULT '', + `autologin_id` VARCHAR(12) + CHARACTER SET utf8 + COLLATE utf8_bin NOT NULL DEFAULT '', + `user_newest_pm_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `user_points` FLOAT(16, 2) NOT NULL DEFAULT '0.00', + `tpl_name` VARCHAR(255) NOT NULL DEFAULT 'default', PRIMARY KEY (`user_id`), KEY `username` (`username`(10)), KEY `user_email` (`user_email`(10)), KEY `user_level` (`user_level`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_users -- ---------------------------- -INSERT INTO `bb_users` VALUES ('-1', '0', 'Guest', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', '0', '0', '0', '0', '0', '0', '0000-00-00', '', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); -INSERT INTO `bb_users` VALUES ('-746', '0', 'bot', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', '0', '0', '144', '0', '0', '0', '0000-00-00', 'bot@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); -INSERT INTO `bb_users` VALUES ('2', '1', 'admin', 'c3284d0f94606de1fd2af172aba15bf3', '0', '0', '0', UNIX_TIMESTAMP(), '0', '1', '1', '', '', '0', '0', '0', '304', '1', '0', '0', '0000-00-00', 'admin@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); +INSERT INTO `bb_users` VALUES + ('-1', '0', 'Guest', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', + '0', '0', + '0', '0', + '0', '0', + '0000-00-00', + '', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); +INSERT INTO `bb_users` VALUES + ('-746', '0', 'bot', 'd41d8cd98f00b204e9800998ecf8427e', '0', '0', '0', UNIX_TIMESTAMP(), '0', '0', '0', '', '', '0', + '0', '0', + '144', '0', + '0', '0', + '0000-00-00', + 'bot@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); +INSERT INTO `bb_users` VALUES + ('2', '1', 'admin', 'c3284d0f94606de1fd2af172aba15bf3', '0', '0', '0', UNIX_TIMESTAMP(), '0', '1', '1', '', '', '0', + '0', '0', + '304', '1', + '0', '0', + '0000-00-00', + 'admin@torrentpier.me', '', '', '', '', '', '', '', '', '', '', '', '0', '0.00', 'default'); -- ---------------------------- -- Table structure for `bb_user_group` -- ---------------------------- DROP TABLE IF EXISTS `bb_user_group`; CREATE TABLE IF NOT EXISTS `bb_user_group` ( - `group_id` mediumint(8) NOT NULL DEFAULT '0', - `user_id` mediumint(8) NOT NULL DEFAULT '0', - `user_pending` tinyint(1) NOT NULL DEFAULT '0', - `user_time` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`group_id`,`user_id`), + `group_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `user_id` MEDIUMINT(8) NOT NULL DEFAULT '0', + `user_pending` TINYINT(1) NOT NULL DEFAULT '0', + `user_time` INT(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`group_id`, `user_id`), KEY `user_id` (`user_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_user_group @@ -1223,11 +1408,13 @@ CREATE TABLE IF NOT EXISTS `bb_user_group` ( -- ---------------------------- DROP TABLE IF EXISTS `bb_words`; CREATE TABLE IF NOT EXISTS `bb_words` ( - `word_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `word` char(100) NOT NULL DEFAULT '', - `replacement` char(100) NOT NULL DEFAULT '', + `word_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + `word` CHAR(100) NOT NULL DEFAULT '', + `replacement` CHAR(100) NOT NULL DEFAULT '', PRIMARY KEY (`word_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of bb_words @@ -1238,10 +1425,12 @@ CREATE TABLE IF NOT EXISTS `bb_words` ( -- ---------------------------- DROP TABLE IF EXISTS `buf_last_seeder`; CREATE TABLE IF NOT EXISTS `buf_last_seeder` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `seeder_last_seen` int(11) NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `seeder_last_seen` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of buf_last_seeder @@ -1252,10 +1441,12 @@ CREATE TABLE IF NOT EXISTS `buf_last_seeder` ( -- ---------------------------- DROP TABLE IF EXISTS `buf_topic_view`; CREATE TABLE IF NOT EXISTS `buf_topic_view` ( - `topic_id` mediumint(8) unsigned NOT NULL DEFAULT '0', - `topic_views` mediumint(8) unsigned NOT NULL DEFAULT '0', + `topic_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', + `topic_views` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`topic_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8; +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8; -- ---------------------------- -- Records of buf_topic_view diff --git a/install/upgrade/r496-user_birthday.php b/install/upgrade/r496-user_birthday.php index a82c8f2c0..4e451b3e2 100644 --- a/install/upgrade/r496-user_birthday.php +++ b/install/upgrade/r496-user_birthday.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} $confirm = request_var('confirm', ''); if ($confirm) { - DB()->query("ALTER TABLE ". BB_USERS ." CHANGE COLUMN user_birthday user_birthday_old int(11) NOT NULL DEFAULT 0 AFTER user_gender"); - DB()->query("ALTER TABLE ". BB_USERS ." ADD user_birthday date NOT NULL DEFAULT '0000-00-00' AFTER user_gender"); + DB()->query("ALTER TABLE " . BB_USERS . " CHANGE COLUMN user_birthday user_birthday_old int(11) NOT NULL DEFAULT 0 AFTER user_gender"); + DB()->query("ALTER TABLE " . BB_USERS . " ADD user_birthday date NOT NULL DEFAULT '0000-00-00' AFTER user_gender"); - $sql = "SELECT user_id, user_birthday_old FROM ". BB_USERS ." WHERE user_birthday_old != 0 AND user_id NOT IN ('". EXCLUDED_USERS_CSV ."')"; + $sql = "SELECT user_id, user_birthday_old FROM " . BB_USERS . " WHERE user_birthday_old != 0 AND user_id NOT IN ('" . EXCLUDED_USERS_CSV . "')"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $birthday = bb_date($row['user_birthday_old'] * 86400 + 1, 'Y-m-d', 0); - DB()->query("UPDATE ". BB_USERS ." SET user_birthday = '". $birthday ."' WHERE user_id = ". $row['user_id'] .""); - } + foreach (DB()->fetch_rowset($sql) as $row) { + $birthday = bb_date($row['user_birthday_old'] * 86400 + 1, 'Y-m-d', 0); + DB()->query("UPDATE " . BB_USERS . " SET user_birthday = '" . $birthday . "' WHERE user_id = " . $row['user_id'] . ""); + } - DB()->query("ALTER TABLE ". BB_USERS ." DROP user_birthday_old"); + DB()->query("ALTER TABLE " . BB_USERS . " DROP user_birthday_old"); - bb_die('

        База данных обновлена

        '); + bb_die('

        База данных обновлена

        '); } else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; + $msg = '
        '; + $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; + $msg .= ''; + $msg .= '
        '; - bb_die($msg); -} \ No newline at end of file + bb_die($msg); +} diff --git a/install/upgrade/r571-dl_upgrade.php b/install/upgrade/r571-dl_upgrade.php index 90adb63b5..f82a37ba6 100644 --- a/install/upgrade/r571-dl_upgrade.php +++ b/install/upgrade/r571-dl_upgrade.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} $confirm = request_var('confirm', ''); if ($confirm) { - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE tmp_buf_dlstatus ( user_id mediumint(9) NOT NULL default '0', topic_id mediumint(8) unsigned NOT NULL default '0', @@ -21,7 +46,7 @@ if ($confirm) { ) ENGINE = MyISAM "); - DB()->query(" + DB()->query(" INSERT INTO tmp_buf_dlstatus (user_id, topic_id, user_status) SELECT @@ -29,7 +54,7 @@ if ($confirm) { FROM bb_bt_dlstatus_new "); - DB()->query(" + DB()->query(" REPLACE INTO bb_bt_dlstatus_main (user_id, topic_id, user_status) SELECT @@ -37,18 +62,18 @@ if ($confirm) { FROM tmp_buf_dlstatus "); - DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_buf_dlstatus"); - DB()->query("RENAME TABLE bb_bt_dlstatus_main TO bb_bt_dlstatus"); + DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_buf_dlstatus"); + DB()->query("RENAME TABLE bb_bt_dlstatus_main TO bb_bt_dlstatus"); - DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_mrg"); - DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_new"); + DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_mrg"); + DB()->query("DROP TABLE IF EXISTS bb_bt_dlstatus_new"); - bb_die('

        База данных обновлена

        '); + bb_die('

        База данных обновлена

        '); } else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; + $msg = '
        '; + $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; + $msg .= ''; + $msg .= '
        '; - bb_die($msg); -} \ No newline at end of file + bb_die($msg); +} diff --git a/install/upgrade/r575-poll_upgrade.php b/install/upgrade/r575-poll_upgrade.php index 71388bdb4..92b5acbc9 100644 --- a/install/upgrade/r575-poll_upgrade.php +++ b/install/upgrade/r575-poll_upgrade.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} $confirm = request_var('confirm', ''); if ($confirm) { - DB()->query(" + DB()->query(" CREATE TABLE IF NOT EXISTS `bb_poll_users` ( `topic_id` int(10) unsigned NOT NULL, `user_id` int(11) NOT NULL, @@ -22,7 +47,7 @@ if ($confirm) { ) ENGINE=MyISAM DEFAULT CHARSET=utf8 "); - DB()->query(" + DB()->query(" CREATE TABLE IF NOT EXISTS `bb_poll_votes` ( `topic_id` int(10) unsigned NOT NULL, `vote_id` tinyint(4) unsigned NOT NULL, @@ -32,7 +57,7 @@ if ($confirm) { ) ENGINE=MyISAM DEFAULT CHARSET=utf8 "); - DB()->query(" + DB()->query(" INSERT IGNORE INTO bb_poll_votes (topic_id, vote_id, vote_text, vote_result) SELECT @@ -40,7 +65,7 @@ if ($confirm) { FROM bb_vote_desc; "); - DB()->query(" + DB()->query(" INSERT IGNORE INTO bb_poll_votes (topic_id, vote_id, vote_text, vote_result) SELECT @@ -50,7 +75,7 @@ if ($confirm) { d.vote_id = r.vote_id; "); - DB()->query(" + DB()->query(" INSERT IGNORE INTO bb_poll_users (topic_id, user_id, vote_ip) SELECT @@ -61,16 +86,16 @@ if ($confirm) { AND v.vote_user_id > 0; "); - DB()->query("DROP TABLE IF EXISTS bb_vote_desc"); - DB()->query("DROP TABLE IF EXISTS bb_vote_results"); - DB()->query("DROP TABLE IF EXISTS bb_vote_voters"); + DB()->query("DROP TABLE IF EXISTS bb_vote_desc"); + DB()->query("DROP TABLE IF EXISTS bb_vote_results"); + DB()->query("DROP TABLE IF EXISTS bb_vote_voters"); - bb_die('

        База данных обновлена

        '); + bb_die('

        База данных обновлена

        '); } else { - $msg = '
        '; - $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; - $msg .= ''; - $msg .= '
        '; + $msg = '
        '; + $msg .= '

        !!! Перед тем как нажать на кнопку, сделайте бекап базы данных !!!


        '; + $msg .= ''; + $msg .= '
        '; - bb_die($msg); -} \ No newline at end of file + bb_die($msg); +} diff --git a/install/upgrade/r583-convert_avatars.php b/install/upgrade/r583-convert_avatars.php index 20fbe2878..c7b028607 100644 --- a/install/upgrade/r583-convert_avatars.php +++ b/install/upgrade/r583-convert_avatars.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} $confirm = request_var('confirm', ''); if ($confirm) { - DB()->query("ALTER TABLE " . BB_USERS . " ADD `avatar_ext_id` TINYINT( 4 ) NOT NULL AFTER `user_rank`"); + DB()->query("ALTER TABLE " . BB_USERS . " ADD `avatar_ext_id` TINYINT( 4 ) NOT NULL AFTER `user_rank`"); - $rows_per_cycle = 10000; + $rows_per_cycle = 10000; - $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); - $end_id = (int)$row['end_id']; - $start = $avatars_ok = $avatars_err = 0; + $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); + $end_id = (int)$row['end_id']; + $start = $avatars_ok = $avatars_err = 0; - echo "
        \n";
        +    echo "
        \n";
         
        -	while (true) {
        -		set_time_limit(600);
        -		echo "$start [ $avatars_ok / $avatars_err ]\n";
        -		$end = $start + $rows_per_cycle - 1;
        -		$sql = "
        +    while (true) {
        +        set_time_limit(600);
        +        echo "$start [ $avatars_ok / $avatars_err ]\n";
        +        $end = $start + $rows_per_cycle - 1;
        +        $sql = "
         			SELECT user_id, avatar_ext_id, user_avatar
         			FROM " . BB_USERS . "
         			WHERE user_avatar != ''
        @@ -41,44 +66,44 @@ if ($confirm) {
         			ORDER BY NULL
         		";
         
        -		foreach (DB()->fetch_rowset($sql) as $row) {
        -			$FILE = array(
        -				'name' => '',
        -				'type' => '',
        -				'size' => 0,
        -				'tmp_name' => BB_ROOT . $bb_cfg['avatar_path'] . '/' . basename($row['user_avatar']),
        -				'error' => 0,
        -			);
        -			$upload = new upload_common();
        +        foreach (DB()->fetch_rowset($sql) as $row) {
        +            $FILE = array(
        +                'name' => '',
        +                'type' => '',
        +                'size' => 0,
        +                'tmp_name' => BB_ROOT . $bb_cfg['avatar_path'] . '/' . basename($row['user_avatar']),
        +                'error' => 0,
        +            );
        +            $upload = new upload_common();
         
        -			if ($upload->init($bb_cfg['avatars'], $FILE, false) AND $upload->store('avatar', $row)) {
        -				DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = {$upload->file_ext_id} WHERE user_id = {$row['user_id']} LIMIT 1");
        -				$avatars_ok++;
        -			} else {
        -				echo "{$row['user_id']}: ", join("\n{$row['user_id']}: ", $upload->errors), "\n";
        -				$avatars_err++;
        -			}
        -		}
        +            if ($upload->init($bb_cfg['avatars'], $FILE, false) and $upload->store('avatar', $row)) {
        +                DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = {$upload->file_ext_id} WHERE user_id = {$row['user_id']} LIMIT 1");
        +                $avatars_ok++;
        +            } else {
        +                echo "{$row['user_id']}: ", join("\n{$row['user_id']}: ", $upload->errors), "\n";
        +                $avatars_err++;
        +            }
        +        }
         
        -		if ($end > $end_id) {
        -			break;
        -		}
        -		$start += $rows_per_cycle;
        -		sleep(1);
        -	}
        +        if ($end > $end_id) {
        +            break;
        +        }
        +        $start += $rows_per_cycle;
        +        sleep(1);
        +    }
         
        -	echo "---------- База данных успешно обновлена. Аватары указанных выше пользователей перенесены не были. ----------\n";
        +    echo "---------- База данных успешно обновлена. Аватары указанных выше пользователей перенесены не были. ----------\n";
         
        -	DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar`");
        -	DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar_type`");
        +    DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar`");
        +    DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar_type`");
         } else {
        -	$msg = '
        '; - $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация имеющихся аватаров пользователей + $msg = ''; + $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация имеющихся аватаров пользователей по новому алгоритму. Для конвертации аватарка пользователя должна соответствовать текущим значениям из конфига: ширина не более ' . $bb_cfg['avatars']['max_width'] . ' пикселов, высота не более ' . $bb_cfg['avatars']['max_height'] . ' пикселов и объем не более ' . $bb_cfg['avatars']['max_size'] . ' байт. Если эти условия не соблюдены - аватарка пользователя не будет конвертирована и пользователю придется залить ее заново! Если вы хотите поправить указанные значения - ПЕРЕД обновлением базы данных сделайте это в config.php!


        '; - $msg .= ''; - $msg .= '
        '; + $msg .= ''; + $msg .= ''; - bb_die($msg); -} \ No newline at end of file + bb_die($msg); +} diff --git a/install/upgrade/r588-short_lang.php b/install/upgrade/r588-short_lang.php index df2eefdde..0e6bd0c76 100644 --- a/install/upgrade/r588-short_lang.php +++ b/install/upgrade/r588-short_lang.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} $confirm = request_var('confirm', ''); if ($confirm) { - DB()->query("UPDATE " . BB_CONFIG . " SET `config_value` = 'ru' WHERE `config_name` = 'default_lang'"); - DB()->query("ALTER TABLE " . BB_USERS . " ADD `user_twitter` varchar (15) NOT NULL DEFAULT '' AFTER `user_skype`"); + DB()->query("UPDATE " . BB_CONFIG . " SET `config_value` = 'ru' WHERE `config_name` = 'default_lang'"); + DB()->query("ALTER TABLE " . BB_USERS . " ADD `user_twitter` varchar (15) NOT NULL DEFAULT '' AFTER `user_skype`"); - $rows_per_cycle = 10000; + $rows_per_cycle = 10000; - $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); - $end_id = (int)$row['end_id']; - $start = 0; + $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); + $end_id = (int)$row['end_id']; + $start = 0; - while (true) { - set_time_limit(600); - $end = $start + $rows_per_cycle - 1; + while (true) { + set_time_limit(600); + $end = $start + $rows_per_cycle - 1; - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'ru' WHERE user_lang = 'russian'"); - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'en' WHERE user_lang = 'english'"); + DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'ru' WHERE user_lang = 'russian'"); + DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'en' WHERE user_lang = 'english'"); - if ($end > $end_id) { - break; - } - $start += $rows_per_cycle; - sleep(1); - } + if ($end > $end_id) { + break; + } + $start += $rows_per_cycle; + sleep(1); + } - bb_die("База данных успешно обновлена. Можно приступать к обновлению файлов. Не забудьте удалить этот файл."); + bb_die("База данных успешно обновлена. Можно приступать к обновлению файлов. Не забудьте удалить этот файл."); } else { - $msg = '
        '; - $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация текущих языков интерфейса пользователей + $msg = ''; + $msg .= '

        Перед тем как нажать на кнопку, сделайте бекап базы данных! В ходе обновления базы данных, произойдет автоматическая конвертация текущих языков интерфейса пользователей на новое именование, а также будет добавлено поле в базу данных пользователей, для их Twitter-аккаунтов. После этого, вам можно будет приступать к обновлению файлов.


        '; - $msg .= ''; - $msg .= '
        '; + $msg .= ''; + $msg .= ''; - bb_die($msg); -} \ No newline at end of file + bb_die($msg); +} diff --git a/install/upgrade/r600-stable.php b/install/upgrade/r600-stable.php index 75c57424b..91bdd591e 100644 --- a/install/upgrade/r600-stable.php +++ b/install/upgrade/r600-stable.php @@ -1,4 +1,27 @@ session_start(); set_die_append_msg(); -if (!IS_SUPER_ADMIN) bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +if (!IS_SUPER_ADMIN) { + bb_die($lang['ONLY_FOR_SUPER_ADMIN']); +} bb_die('

        Для обновления до стабильной ревизии R600, вам необходимо воспользоваться request['mode']; -$user_id = (int) $this->request['user_id']; +$mode = (string)$this->request['mode']; +$user_id = (int)$this->request['user_id']; -if (!$user_id OR !$u_data = get_userdata($user_id)) -{ - $this->ajax_die('Invalid user_id'); +if (!$user_id or !$u_data = get_userdata($user_id)) { + $this->ajax_die('Invalid user_id'); } -if (!IS_ADMIN && $user_id != $user->id) -{ - $this->ajax_die($lang['NOT_ADMIN']); +if (!IS_ADMIN && $user_id != $user->id) { + $this->ajax_die($lang['NOT_ADMIN']); } -switch ($mode) -{ - case 'delete': - delete_avatar($user_id, $u_data['avatar_ext_id']); - $new_ext_id = 0; - $response = ''. $user_id .''; - break; - default: - $this->ajax_die('Invalid mode'); +switch ($mode) { + case 'delete': + delete_avatar($user_id, $u_data['avatar_ext_id']); + $new_ext_id = 0; + $response = '' . $user_id . ''; + break; + default: + $this->ajax_die('Invalid mode'); } -DB()->query("UPDATE ". BB_USERS ." SET avatar_ext_id = $new_ext_id WHERE user_id = $user_id LIMIT 1"); +DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = $new_ext_id WHERE user_id = $user_id LIMIT 1"); cache_rm_user_sessions($user_id); -$this->response['avatar_html'] = $response; \ No newline at end of file +$this->response['avatar_html'] = $response; diff --git a/library/ajax/change_tor_status.php b/library/ajax/change_tor_status.php index fe7698c1c..2959884c6 100644 --- a/library/ajax/change_tor_status.php +++ b/library/ajax/change_tor_status.php @@ -1,106 +1,138 @@ request['attach_id'])) $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!isset($this->request['attach_id'])) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); +} -$attach_id = (int) $this->request['attach_id']; -$mode = (string) $this->request['mode']; +$attach_id = (int)$this->request['attach_id']; +$mode = (string)$this->request['mode']; -if ($bb_cfg['tor_comment']) -{ - $comment = (string) $this->request['comment']; +if ($bb_cfg['tor_comment']) { + $comment = (string)$this->request['comment']; } $tor = DB()->fetch_row(" SELECT tor.poster_id, tor.forum_id, tor.topic_id, tor.tor_status, tor.checked_time, tor.checked_user_id, f.cat_id, t.topic_title - FROM ". BB_BT_TORRENTS ." tor - INNER JOIN ". BB_FORUMS ." f ON(f.forum_id = tor.forum_id) - INNER JOIN ". BB_TOPICS ." t ON(t.topic_id = tor.topic_id) + FROM " . BB_BT_TORRENTS . " tor + INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = tor.forum_id) + INNER JOIN " . BB_TOPICS . " t ON(t.topic_id = tor.topic_id) WHERE tor.attach_id = $attach_id LIMIT 1 "); -if (!$tor) $this->ajax_die($lang['TORRENT_FAILED']); - -switch ($mode) -{ - case 'status': - $new_status = (int) $this->request['status']; - - // Валидность статуса - if (!isset($lang['TOR_STATUS_NAME'][$new_status])) $this->ajax_die($lang['TOR_STATUS_FAILED']); - if (!isset($this->request['status'])) $this->ajax_die($lang['TOR_DONT_CHANGE']); - if (!IS_AM) $this->ajax_die($lang['NOT_MODERATOR']); - - // Тот же статус - if ($tor['tor_status'] == $new_status) - { - $this->ajax_die($lang['TOR_STATUS_DUB']); - } - - // Запрет на изменение/присвоение CH-статуса модератором - if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) - { - $this->ajax_die($lang['TOR_DONT_CHANGE']); - } - - // Права на изменение статуса - if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) - { - if (!IS_ADMIN) $this->verify_mod_rights($tor['forum_id']); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_status = ". TOPIC_UNLOCKED ." WHERE topic_id = {$tor['topic_id']} LIMIT 1"); - } - else - { - $this->verify_mod_rights($tor['forum_id']); - } - - // Подтверждение изменения статуса, выставленного другим модератором - if ($tor['tor_status'] != TOR_NOT_APPROVED && $tor['checked_user_id'] != $userdata['user_id'] && $tor['checked_time'] + 2*3600 > TIMENOW) - { - if (empty($this->request['confirmed'])) - { - $msg = $lang['TOR_STATUS_OF'] ." {$lang['TOR_STATUS_NAME'][$tor['tor_status']]}\n\n"; - $msg .= ($username = get_username($tor['checked_user_id'])) ? $lang['TOR_STATUS_CHANGED'] . html_entity_decode($username) .", ". delta_time($tor['checked_time']) . $lang['TOR_BACK'] ."\n\n" : ""; - $msg .= $lang['PROCEED'] .'?'; - $this->prompt_for_confirm($msg); - } - } - - change_tor_status($attach_id, $new_status); - - $this->response['status'] = $bb_cfg['tor_icons'][$new_status] .' '. $lang['TOR_STATUS_NAME'][$new_status]. ' · '. profile_url($userdata) .' · '. delta_time(TIMENOW) . $lang['TOR_BACK']. ''; - - if ($bb_cfg['tor_comment'] && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $bb_cfg['tor_reply']))) - { - if ($tor['poster_id'] > 0) - { - $subject = sprintf($lang['TOR_MOD_TITLE'], $tor['topic_title']); - $message = sprintf($lang['TOR_MOD_MSG'], get_username($tor['poster_id']), make_url(TOPIC_URL . $tor['topic_id']), $bb_cfg['tor_icons'][$new_status] .' '.$lang['TOR_STATUS_NAME'][$new_status]); - - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; - - send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']); - cache_rm_user_sessions($tor['poster_id']); - } - } - break; - - case 'status_reply': - if (!$bb_cfg['tor_comment']) $this->ajax_die($lang['MODULE_OFF']); - - $subject = sprintf($lang['TOR_AUTH_TITLE'], $tor['topic_title']); - $message = sprintf($lang['TOR_AUTH_MSG'], get_username($tor['checked_user_id']), make_url(TOPIC_URL . $tor['topic_id']), $tor['topic_title']); - - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; - - send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']); - cache_rm_user_sessions($tor['checked_user_id']); - break; +if (!$tor) { + $this->ajax_die($lang['TORRENT_FAILED']); } -$this->response['attach_id'] = $attach_id; \ No newline at end of file +switch ($mode) { + case 'status': + $new_status = (int)$this->request['status']; + + // Валидность статуса + if (!isset($lang['TOR_STATUS_NAME'][$new_status])) { + $this->ajax_die($lang['TOR_STATUS_FAILED']); + } + if (!isset($this->request['status'])) { + $this->ajax_die($lang['TOR_DONT_CHANGE']); + } + if (!IS_AM) { + $this->ajax_die($lang['NOT_MODERATOR']); + } + + // Тот же статус + if ($tor['tor_status'] == $new_status) { + $this->ajax_die($lang['TOR_STATUS_DUB']); + } + + // Запрет на изменение/присвоение CH-статуса модератором + if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) { + $this->ajax_die($lang['TOR_DONT_CHANGE']); + } + + // Права на изменение статуса + if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) { + if (!IS_ADMIN) { + $this->verify_mod_rights($tor['forum_id']); + } + DB()->query("UPDATE " . BB_TOPICS . " SET topic_status = " . TOPIC_UNLOCKED . " WHERE topic_id = {$tor['topic_id']} LIMIT 1"); + } else { + $this->verify_mod_rights($tor['forum_id']); + } + + // Подтверждение изменения статуса, выставленного другим модератором + if ($tor['tor_status'] != TOR_NOT_APPROVED && $tor['checked_user_id'] != $userdata['user_id'] && $tor['checked_time'] + 2 * 3600 > TIMENOW) { + if (empty($this->request['confirmed'])) { + $msg = $lang['TOR_STATUS_OF'] . " {$lang['TOR_STATUS_NAME'][$tor['tor_status']]}\n\n"; + $msg .= ($username = get_username($tor['checked_user_id'])) ? $lang['TOR_STATUS_CHANGED'] . html_entity_decode($username) . ", " . delta_time($tor['checked_time']) . $lang['TOR_BACK'] . "\n\n" : ""; + $msg .= $lang['PROCEED'] . '?'; + $this->prompt_for_confirm($msg); + } + } + + change_tor_status($attach_id, $new_status); + + $this->response['status'] = $bb_cfg['tor_icons'][$new_status] . ' ' . $lang['TOR_STATUS_NAME'][$new_status] . ' · ' . profile_url($userdata) . ' · ' . delta_time(TIMENOW) . $lang['TOR_BACK'] . ''; + + if ($bb_cfg['tor_comment'] && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $bb_cfg['tor_reply']))) { + if ($tor['poster_id'] > 0) { + $subject = sprintf($lang['TOR_MOD_TITLE'], $tor['topic_title']); + $message = sprintf($lang['TOR_MOD_MSG'], get_username($tor['poster_id']), make_url(TOPIC_URL . $tor['topic_id']), $bb_cfg['tor_icons'][$new_status] . ' ' . $lang['TOR_STATUS_NAME'][$new_status]); + + if ($comment && $comment != $lang['COMMENT']) { + $message .= "\n\n[b]" . $lang['COMMENT'] . '[/b]: ' . $comment; + } + + send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']); + cache_rm_user_sessions($tor['poster_id']); + } + } + break; + + case 'status_reply': + if (!$bb_cfg['tor_comment']) { + $this->ajax_die($lang['MODULE_OFF']); + } + + $subject = sprintf($lang['TOR_AUTH_TITLE'], $tor['topic_title']); + $message = sprintf($lang['TOR_AUTH_MSG'], get_username($tor['checked_user_id']), make_url(TOPIC_URL . $tor['topic_id']), $tor['topic_title']); + + if ($comment && $comment != $lang['COMMENT']) { + $message .= "\n\n[b]" . $lang['COMMENT'] . '[/b]: ' . $comment; + } + + send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']); + cache_rm_user_sessions($tor['checked_user_id']); + break; +} + +$this->response['attach_id'] = $attach_id; diff --git a/library/ajax/change_torrent.php b/library/ajax/change_torrent.php index 6d1445a66..1b1354b19 100644 --- a/library/ajax/change_torrent.php +++ b/library/ajax/change_torrent.php @@ -1,19 +1,42 @@ request['attach_id'])) -{ - $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!isset($this->request['attach_id'])) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); } -if (!isset($this->request['type'])) -{ - $this->ajax_die('type'); +if (!isset($this->request['type'])) { + $this->ajax_die('type'); } -$attach_id = (int) $this->request['attach_id']; -$type = (string) $this->request['type']; +$attach_id = (int)$this->request['attach_id']; +$type = (string)$this->request['type']; $torrent = DB()->fetch_row(" SELECT @@ -22,11 +45,11 @@ $torrent = DB()->fetch_row(" p.poster_id, p.topic_id, p.forum_id, f.allow_reg_tracker FROM - ". BB_ATTACHMENTS ." a, - ". BB_ATTACHMENTS_DESC ." d, - ". BB_POSTS ." p, - ". BB_TOPICS ." t, - ". BB_FORUMS ." f + " . BB_ATTACHMENTS . " a, + " . BB_ATTACHMENTS_DESC . " d, + " . BB_POSTS . " p, + " . BB_TOPICS . " t, + " . BB_FORUMS . " f WHERE a.attach_id = $attach_id AND d.attach_id = $attach_id @@ -36,69 +59,63 @@ $torrent = DB()->fetch_row(" LIMIT 1 "); -if (!$torrent) $this->ajax_die($lang['INVALID_ATTACH_ID']); - -if ($torrent['poster_id'] == $userdata['user_id'] && !IS_AM) -{ - if ($type == 'del_torrent' || $type == 'reg' || $type == 'unreg') - { - true; - } - else - { - $this->ajax_die($lang['ONLY_FOR_MOD']); - } +if (!$torrent) { + $this->ajax_die($lang['INVALID_ATTACH_ID']); } -elseif (!IS_AM) -{ - $this->ajax_die($lang['ONLY_FOR_MOD']); + +if ($torrent['poster_id'] == $userdata['user_id'] && !IS_AM) { + if ($type == 'del_torrent' || $type == 'reg' || $type == 'unreg') { + true; + } else { + $this->ajax_die($lang['ONLY_FOR_MOD']); + } +} elseif (!IS_AM) { + $this->ajax_die($lang['ONLY_FOR_MOD']); } $title = $url = ''; -switch ($type) -{ - case 'set_gold'; - case 'set_silver'; - case 'unset_silver_gold'; - if ($type == 'set_silver') - { - $tor_type = TOR_TYPE_SILVER; - } - elseif ($type == 'set_gold') - { - $tor_type = TOR_TYPE_GOLD; - } - else - { - $tor_type = 0; - } - change_tor_type($attach_id, $tor_type); - $title = $lang['CHANGE_TOR_TYPE']; - $url = make_url(TOPIC_URL . $torrent['topic_id']); - break; +switch ($type) { + case 'set_gold'; + case 'set_silver'; + case 'unset_silver_gold'; + if ($type == 'set_silver') { + $tor_type = TOR_TYPE_SILVER; + } elseif ($type == 'set_gold') { + $tor_type = TOR_TYPE_GOLD; + } else { + $tor_type = 0; + } + change_tor_type($attach_id, $tor_type); + $title = $lang['CHANGE_TOR_TYPE']; + $url = make_url(TOPIC_URL . $torrent['topic_id']); + break; - case 'reg'; - tracker_register($attach_id); - $url = (TOPIC_URL . $torrent['topic_id']); - break; + case 'reg'; + tracker_register($attach_id); + $url = (TOPIC_URL . $torrent['topic_id']); + break; - case 'unreg'; - tracker_unregister($attach_id); - $url = (TOPIC_URL . $torrent['topic_id']); - break; + case 'unreg'; + tracker_unregister($attach_id); + $url = (TOPIC_URL . $torrent['topic_id']); + break; - case 'del_torrent'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_TORRENT']); - delete_torrent($attach_id); - $url = make_url(TOPIC_URL . $torrent['topic_id']); - break; + case 'del_torrent'; + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEL_TORRENT']); + } + delete_torrent($attach_id); + $url = make_url(TOPIC_URL . $torrent['topic_id']); + break; - case 'del_torrent_move_topic'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); - delete_torrent($attach_id); - $url = make_url("modcp.php?t={$torrent['topic_id']}&mode=move&sid={$userdata['session_id']}"); - break; + case 'del_torrent_move_topic'; + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); + } + delete_torrent($attach_id); + $url = make_url("modcp.php?t={$torrent['topic_id']}&mode=move&sid={$userdata['session_id']}"); + break; } -$this->response['url'] = $url; -$this->response['title'] = $title; \ No newline at end of file +$this->response['url'] = $url; +$this->response['title'] = $title; diff --git a/library/ajax/change_user_opt.php b/library/ajax/change_user_opt.php index db9fc94e8..be24948f0 100644 --- a/library/ajax/change_user_opt.php +++ b/library/ajax/change_user_opt.php @@ -1,33 +1,54 @@ request['user_id']; +$user_id = (int)$this->request['user_id']; $new_opt = Zend\Json\Json::decode($this->request['user_opt'], Zend\Json\Json::TYPE_ARRAY); -if (!$user_id OR !$u_data = get_userdata($user_id)) -{ - $this->ajax_die('invalid user_id'); +if (!$user_id or !$u_data = get_userdata($user_id)) { + $this->ajax_die('invalid user_id'); } -if (!is_array($new_opt)) -{ - $this->ajax_die('invalid new_opt'); +if (!is_array($new_opt)) { + $this->ajax_die('invalid new_opt'); } -foreach ($bf['user_opt'] as $opt_name => $opt_bit) -{ - if (isset($new_opt[$opt_name])) - { - setbit($u_data['user_opt'], $opt_bit, !empty($new_opt[$opt_name])); - } +foreach ($bf['user_opt'] as $opt_name => $opt_bit) { + if (isset($new_opt[$opt_name])) { + setbit($u_data['user_opt'], $opt_bit, !empty($new_opt[$opt_name])); + } } -DB()->query("UPDATE ". BB_USERS ." SET user_opt = {$u_data['user_opt']} WHERE user_id = $user_id LIMIT 1"); +DB()->query("UPDATE " . BB_USERS . " SET user_opt = {$u_data['user_opt']} WHERE user_id = $user_id LIMIT 1"); // Удаляем данные из кеша -cache_rm_user_sessions ($user_id); +cache_rm_user_sessions($user_id); -$this->response['resp_html'] = $lang['SAVED']; \ No newline at end of file +$this->response['resp_html'] = $lang['SAVED']; diff --git a/library/ajax/change_user_rank.php b/library/ajax/change_user_rank.php index a6d283aa0..5cfe3aa48 100644 --- a/library/ajax/change_user_rank.php +++ b/library/ajax/change_user_rank.php @@ -1,27 +1,50 @@ get('ranks'); +$ranks = $datastore->get('ranks'); $rank_id = intval($this->request['rank_id']); -if (!$user_id = intval($this->request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!$user_id = intval($this->request['user_id']) or !$profiledata = get_userdata($user_id)) { + $this->ajax_die("invalid user_id: $user_id"); } -if ($rank_id != 0 && !isset($ranks[$rank_id])) -{ - $this->ajax_die("invalid rank_id: $rank_id"); +if ($rank_id != 0 && !isset($ranks[$rank_id])) { + $this->ajax_die("invalid rank_id: $rank_id"); } -DB()->query("UPDATE ". BB_USERS ." SET user_rank = $rank_id WHERE user_id = $user_id LIMIT 1"); +DB()->query("UPDATE " . BB_USERS . " SET user_rank = $rank_id WHERE user_id = $user_id LIMIT 1"); cache_rm_user_sessions($user_id); -$user_rank = ($rank_id) ? ''. $ranks[$rank_id]['rank_title'] .'' : ''; +$user_rank = ($rank_id) ? '' . $ranks[$rank_id]['rank_title'] . '' : ''; $this->response['html'] = ($rank_id) ? $lang['AWARDED_RANK'] . " $user_rank " : $lang['SHOT_RANK']; $this->response['rank_name'] = ($rank_id) ? $user_rank : $lang['USER']; diff --git a/library/ajax/edit_group_profile.php b/library/ajax/edit_group_profile.php index 5c0cc9e54..12778c893 100644 --- a/library/ajax/edit_group_profile.php +++ b/library/ajax/edit_group_profile.php @@ -1,52 +1,73 @@ request['group_id']) OR !$group_info = get_group_data($group_id)) -{ - $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); +if (!$group_id = intval($this->request['group_id']) or !$group_info = get_group_data($group_id)) { + $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); } -if (!$mode = (string) $this->request['mode']) -{ - $this->ajax_die('No mode specified'); +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('No mode specified'); } -$value = $this->request['value'] = (string) (isset($this->request['value'])) ? $this->request['value'] : 0; +$value = $this->request['value'] = (string)(isset($this->request['value'])) ? $this->request['value'] : 0; -if (!IS_ADMIN && $userdata['user_id'] != $group_info['group_moderator']) -{ - $this->ajax_die($lang['ONLY_FOR_MOD']); +if (!IS_ADMIN && $userdata['user_id'] != $group_info['group_moderator']) { + $this->ajax_die($lang['ONLY_FOR_MOD']); } -switch ($mode) -{ - case 'group_name': - case 'group_signature': - case 'group_description': - $value = htmlCHR($value, false, ENT_NOQUOTES); - $this->response['new_value'] = $value; - break; +switch ($mode) { + case 'group_name': + case 'group_signature': + case 'group_description': + $value = htmlCHR($value, false, ENT_NOQUOTES); + $this->response['new_value'] = $value; + break; - case 'group_type': - $this->response['new_value'] = $value; - break; + case 'group_type': + $this->response['new_value'] = $value; + break; - case 'release_group': - $this->response['new_value'] = $value; - break; + case 'release_group': + $this->response['new_value'] = $value; + break; - case 'delete_avatar': - delete_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']); - $value = 0; - $mode = 'avatar_ext_id'; - $this->response['act'] = $value; - break; + case 'delete_avatar': + delete_avatar(GROUP_AVATAR_MASK . $group_id, $group_info['avatar_ext_id']); + $value = 0; + $mode = 'avatar_ext_id'; + $this->response['act'] = $value; + break; - default: - $this->ajax_die('Unknown mode'); + default: + $this->ajax_die('Unknown mode'); } $value_sql = DB()->escape($value, true); -DB()->query("UPDATE ". BB_GROUPS ." SET $mode = $value_sql WHERE group_id = $group_id LIMIT 1"); \ No newline at end of file +DB()->query("UPDATE " . BB_GROUPS . " SET $mode = $value_sql WHERE group_id = $group_id LIMIT 1"); diff --git a/library/ajax/edit_user_profile.php b/library/ajax/edit_user_profile.php index 04e11f890..8477831ec 100644 --- a/library/ajax/edit_user_profile.php +++ b/library/ajax/edit_user_profile.php @@ -1,168 +1,181 @@ request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +if (!$user_id = intval($this->request['user_id']) or !$profiledata = get_userdata($user_id)) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); } -if (!$field = (string) $this->request['field']) -{ - $this->ajax_die('invalid profile field'); +if (!$field = (string)$this->request['field']) { + $this->ajax_die('invalid profile field'); } $table = BB_USERS; -$value = $this->request['value'] = (string) (isset($this->request['value'])) ? $this->request['value'] : 0; +$value = $this->request['value'] = (string)(isset($this->request['value'])) ? $this->request['value'] : 0; -switch ($field) -{ - case 'username': - require_once(INC_DIR .'functions_validate.php'); - $value = clean_username($value); - if ($err = validate_username($value)) - { - $this->ajax_die(strip_tags($err)); - } - $this->response['new_value'] = $this->request['value']; - break; +switch ($field) { + case 'username': + require_once(INC_DIR . 'functions_validate.php'); + $value = clean_username($value); + if ($err = validate_username($value)) { + $this->ajax_die(strip_tags($err)); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_email': - require_once(INC_DIR .'functions_validate.php'); - $value = htmlCHR($value); - if ($err = validate_email($value)) - { - $this->ajax_die($err); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_email': + require_once(INC_DIR . 'functions_validate.php'); + $value = htmlCHR($value); + if ($err = validate_email($value)) { + $this->ajax_die($err); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_website': - if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) - { - $this->response['new_value'] = htmlCHR($value); - } - else $this->ajax_die($lang['WEBSITE_ERROR']); - break; + case 'user_website': + if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) { + $this->response['new_value'] = htmlCHR($value); + } else { + $this->ajax_die($lang['WEBSITE_ERROR']); + } + break; - case 'user_gender': - if (!$bb_cfg['gender']) $this->ajax_die($lang['MODULE_OFF']); - if (!isset($lang['GENDER_SELECT'][$value])) - { - $this->ajax_die($lang['ERROR']); - } - else $this->response['new_value'] = $lang['GENDER_SELECT'][$value]; - break; + case 'user_gender': + if (!$bb_cfg['gender']) { + $this->ajax_die($lang['MODULE_OFF']); + } + if (!isset($lang['GENDER_SELECT'][$value])) { + $this->ajax_die($lang['ERROR']); + } else { + $this->response['new_value'] = $lang['GENDER_SELECT'][$value]; + } + break; - case 'user_birthday': - if (!$bb_cfg['birthday_enabled']) $this->ajax_die($lang['MODULE_OFF']); - $birthday_date = date_parse($value); + case 'user_birthday': + if (!$bb_cfg['birthday_enabled']) { + $this->ajax_die($lang['MODULE_OFF']); + } + $birthday_date = date_parse($value); - if (!empty($birthday_date['year'])) - { - if (strtotime($value) >= TIMENOW) - { - $this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']); - } - elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] > $bb_cfg['birthday_max_age']) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], $bb_cfg['birthday_max_age'])); - } - elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] < $bb_cfg['birthday_min_age']) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $bb_cfg['birthday_min_age'])); - } - } + if (!empty($birthday_date['year'])) { + if (strtotime($value) >= TIMENOW) { + $this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']); + } elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] > $bb_cfg['birthday_max_age']) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], $bb_cfg['birthday_max_age'])); + } elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] < $bb_cfg['birthday_min_age']) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $bb_cfg['birthday_min_age'])); + } + } - $this->response['new_value'] = $this->request['value']; - break; + $this->response['new_value'] = $this->request['value']; + break; - case 'user_icq': - if ($value && !preg_match('#^\d{6,15}$#', $value)) - { - $this->ajax_die($lang['ICQ_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_icq': + if ($value && !preg_match('#^\d{6,15}$#', $value)) { + $this->ajax_die($lang['ICQ_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_skype': - if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) - { - $this->ajax_die($lang['SKYPE_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_skype': + if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) { + $this->ajax_die($lang['SKYPE_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_twitter': - if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) - { - $this->ajax_die($lang['TWITTER_ERROR']); - } - $this->response['new_value'] = $this->request['value']; - break; + case 'user_twitter': + if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) { + $this->ajax_die($lang['TWITTER_ERROR']); + } + $this->response['new_value'] = $this->request['value']; + break; - case 'user_from': - case 'user_occ': - case 'user_interests': - $value = htmlCHR($value); - $this->response['new_value'] = $value; - break; + case 'user_from': + case 'user_occ': + case 'user_interests': + $value = htmlCHR($value); + $this->response['new_value'] = $value; + break; - case 'user_regdate': - case 'user_lastvisit': - $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); - if (($value = strtotime($value, $tz)) < $bb_cfg['board_startdate'] OR $value > TIMENOW) - { - $this->ajax_die($lang['INVALID_DATE'] . $this->request['value']); - } - $this->response['new_value'] = bb_date($value, 'Y-m-d H:i', false); - break; + case 'user_regdate': + case 'user_lastvisit': + $tz = TIMENOW + (3600 * $bb_cfg['board_timezone']); + if (($value = strtotime($value, $tz)) < $bb_cfg['board_startdate'] or $value > TIMENOW) { + $this->ajax_die($lang['INVALID_DATE'] . $this->request['value']); + } + $this->response['new_value'] = bb_date($value, 'Y-m-d H:i', false); + break; - case 'u_up_total': - case 'u_down_total': - case 'u_up_release': - case 'u_up_bonus': - if (!IS_ADMIN) $this->ajax_die($lang['NOT_ADMIN']); + case 'u_up_total': + case 'u_down_total': + case 'u_up_release': + case 'u_up_bonus': + if (!IS_ADMIN) { + $this->ajax_die($lang['NOT_ADMIN']); + } - $table = BB_BT_USERS; - $value = (float) str_replace(',', '.', $this->request['value']); + $table = BB_BT_USERS; + $value = (float)str_replace(',', '.', $this->request['value']); - foreach (array('KB'=>1,'MB'=>2,'GB'=>3,'TB'=>4) as $s => $m) - { - if (strpos($this->request['value'], $s) !== false) - { - $value *= pow(1024, $m); - break; - } - } - $value = sprintf('%.0f', $value); - $this->response['new_value'] = humn_size($value, null, null, ' '); + foreach (array('KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4) as $s => $m) { + if (strpos($this->request['value'], $s) !== false) { + $value *= pow(1024, $m); + break; + } + } + $value = sprintf('%.0f', $value); + $this->response['new_value'] = humn_size($value, null, null, ' '); - if (!$btu = get_bt_userdata($user_id)) - { - require(INC_DIR .'functions_torrent.php'); - generate_passkey($user_id, true); - $btu = get_bt_userdata($user_id); - } - $btu[$field] = $value; - $this->response['update_ids']['u_ratio'] = (string) get_bt_ratio($btu); - break; + if (!$btu = get_bt_userdata($user_id)) { + require(INC_DIR . 'functions_torrent.php'); + generate_passkey($user_id, true); + $btu = get_bt_userdata($user_id); + } + $btu[$field] = $value; + $this->response['update_ids']['u_ratio'] = (string)get_bt_ratio($btu); + break; - case 'user_points': - $value = htmlCHR($value); - $value = (float) str_replace(',', '.', $this->request['value']); - $value = sprintf('%.2f', $value); - $this->response['new_value'] = $value; - break; + case 'user_points': + $value = htmlCHR($value); + $value = (float)str_replace(',', '.', $this->request['value']); + $value = sprintf('%.2f', $value); + $this->response['new_value'] = $value; + break; - default: - $this->ajax_die("invalid profile field: $field"); + default: + $this->ajax_die("invalid profile field: $field"); } $value_sql = DB()->escape($value, true); DB()->query("UPDATE $table SET $field = $value_sql WHERE user_id = $user_id LIMIT 1"); -cache_rm_user_sessions ($user_id); +cache_rm_user_sessions($user_id); -$this->response['edit_id'] = $this->request['edit_id']; \ No newline at end of file +$this->response['edit_id'] = $this->request['edit_id']; diff --git a/library/ajax/gen_passkey.php b/library/ajax/gen_passkey.php index a3d94bb08..2b0a10d29 100644 --- a/library/ajax/gen_passkey.php +++ b/library/ajax/gen_passkey.php @@ -1,25 +1,48 @@ request['user_id']; +$req_uid = (int)$this->request['user_id']; -if ($req_uid == $userdata['user_id'] || IS_ADMIN) -{ - if (empty($this->request['confirmed'])) - { - $this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']); - } +if ($req_uid == $userdata['user_id'] || IS_ADMIN) { + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']); + } - if (!$passkey = generate_passkey($req_uid, IS_ADMIN)) - { - $this->ajax_die('Could not insert passkey'); - } + if (!$passkey = generate_passkey($req_uid, IS_ADMIN)) { + $this->ajax_die('Could not insert passkey'); + } - tracker_rm_user($req_uid); + tracker_rm_user($req_uid); - $this->response['passkey'] = $passkey; + $this->response['passkey'] = $passkey; +} else { + $this->ajax_die($lang['NOT_AUTHORISED']); } -else $this->ajax_die($lang['NOT_AUTHORISED']); \ No newline at end of file diff --git a/library/ajax/group_membership.php b/library/ajax/group_membership.php index 78b9c3071..ed4551dc3 100644 --- a/library/ajax/group_membership.php +++ b/library/ajax/group_membership.php @@ -1,69 +1,82 @@ request['user_id']) OR !$profiledata = get_userdata($user_id)) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!$user_id = intval($this->request['user_id']) or !$profiledata = get_userdata($user_id)) { + $this->ajax_die("invalid user_id: $user_id"); } -if (!$mode = (string) $this->request['mode']) -{ - $this->ajax_die('invalid mode (empty)'); +if (!$mode = (string)$this->request['mode']) { + $this->ajax_die('invalid mode (empty)'); } -switch ($mode) -{ - case 'get_group_list': - $sql = " +switch ($mode) { + case 'get_group_list': + $sql = " SELECT ug.user_pending, g.group_id, g.group_type, g.group_name, g.group_moderator, self.user_id AS can_view - FROM ". BB_USER_GROUP ." ug - INNER JOIN ". BB_GROUPS ." g ON(g.group_id = ug.group_id AND g.group_single_user = 0) - LEFT JOIN ". BB_USER_GROUP ." self ON(self.group_id = g.group_id AND self.user_id = {$user->id} AND self.user_pending = 0) + FROM " . BB_USER_GROUP . " ug + INNER JOIN " . BB_GROUPS . " g ON(g.group_id = ug.group_id AND g.group_single_user = 0) + LEFT JOIN " . BB_USER_GROUP . " self ON(self.group_id = g.group_id AND self.user_id = {$user->id} AND self.user_pending = 0) WHERE ug.user_id = $user_id ORDER BY g.group_name "; - $html = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $class = ($row['user_pending']) ? 'med' : 'med bold'; - $class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : ''; - $href = "group.php?g={$row['group_id']}"; + $html = array(); + foreach (DB()->fetch_rowset($sql) as $row) { + $class = ($row['user_pending']) ? 'med' : 'med bold'; + $class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : ''; + $href = "group.php?g={$row['group_id']}"; - if (IS_ADMIN) - { - $href .= "&u=$user_id"; - $link = ''. htmlCHR($row['group_name']) .''; - $html[] = $link; - } - else - { - // скрытая группа и сам юзер не является ее членом - if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) - { - continue; - } - if ($row['group_moderator'] == $user->id) - { - $class .= ' selfMod'; - $href .= "&u=$user_id"; // сам юзер модератор этой группы - } - $link = ''. htmlCHR($row['group_name']) .''; - $html[] = $link; - } - } - if ($html) - { - $this->response['group_list_html'] = '
        • '. join('
        • ', $html) .'
        '; - } - else - { - $this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN']; - } - break; + if (IS_ADMIN) { + $href .= "&u=$user_id"; + $link = '' . htmlCHR($row['group_name']) . ''; + $html[] = $link; + } else { + // скрытая группа и сам юзер не является ее членом + if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) { + continue; + } + if ($row['group_moderator'] == $user->id) { + $class .= ' selfMod'; + $href .= "&u=$user_id"; // сам юзер модератор этой группы + } + $link = '' . htmlCHR($row['group_name']) . ''; + $html[] = $link; + } + } + if ($html) { + $this->response['group_list_html'] = '
        • ' . join('
        • ', $html) . '
        '; + } else { + $this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN']; + } + break; - default: - $this->ajax_die("invalid mode: $mode"); -} \ No newline at end of file + default: + $this->ajax_die("invalid mode: $mode"); +} diff --git a/library/ajax/index_data.php b/library/ajax/index_data.php index 47447c854..872cac13f 100644 --- a/library/ajax/index_data.php +++ b/library/ajax/index_data.php @@ -1,132 +1,153 @@ request['mode']; +$mode = (string)$this->request['mode']; $html = ''; -switch($mode) -{ - case 'birthday_week': - $stats = $datastore->get('stats'); - $datastore->enqueue(array( - 'stats', - )); +switch ($mode) { + case 'birthday_week': + $stats = $datastore->get('stats'); + $datastore->enqueue(array( + 'stats', + )); - if ($stats['birthday_week_list']) - { - foreach($stats['birthday_week_list'] as $week) - { - $html[] = profile_url($week) .' ('. birthday_age($week['user_birthday']) .')'; - } - $html = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $html)); - } - else $html = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); - break; + if ($stats['birthday_week_list']) { + foreach ($stats['birthday_week_list'] as $week) { + $html[] = profile_url($week) . ' (' . birthday_age($week['user_birthday']) . ')'; + } + $html = sprintf($lang['BIRTHDAY_WEEK'], $bb_cfg['birthday_check_day'], join(', ', $html)); + } else { + $html = sprintf($lang['NOBIRTHDAY_WEEK'], $bb_cfg['birthday_check_day']); + } + break; - case 'birthday_today': - $stats = $datastore->get('stats'); - $datastore->enqueue(array( - 'stats', - )); + case 'birthday_today': + $stats = $datastore->get('stats'); + $datastore->enqueue(array( + 'stats', + )); - if ($stats['birthday_today_list']) - { - foreach($stats['birthday_today_list'] as $today) - { - $html[] = profile_url($today) .' ('. birthday_age($today['user_birthday']) .')'; - } - $html = $lang['BIRTHDAY_TODAY'] . join(', ', $html); - } - else $html = $lang['NOBIRTHDAY_TODAY']; - break; + if ($stats['birthday_today_list']) { + foreach ($stats['birthday_today_list'] as $today) { + $html[] = profile_url($today) . ' (' . birthday_age($today['user_birthday']) . ')'; + } + $html = $lang['BIRTHDAY_TODAY'] . join(', ', $html); + } else { + $html = $lang['NOBIRTHDAY_TODAY']; + } + break; - case 'get_forum_mods': - $forum_id = (int) $this->request['forum_id']; + case 'get_forum_mods': + $forum_id = (int)$this->request['forum_id']; - $datastore->enqueue(array( - 'moderators', - )); + $datastore->enqueue(array( + 'moderators', + )); - $moderators = array(); - $mod = $datastore->get('moderators'); + $moderators = array(); + $mod = $datastore->get('moderators'); - if (isset($mod['mod_users'][$forum_id])) - { - foreach ($mod['mod_users'][$forum_id] as $user_id) - { - $moderators[] = ''. $mod['name_users'][$user_id] .''; - } - } + if (isset($mod['mod_users'][$forum_id])) { + foreach ($mod['mod_users'][$forum_id] as $user_id) { + $moderators[] = '' . $mod['name_users'][$user_id] . ''; + } + } - if (isset($mod['mod_groups'][$forum_id])) - { - foreach ($mod['mod_groups'][$forum_id] as $group_id) - { - $moderators[] = ''. $mod['name_groups'][$group_id] .''; - } - } + if (isset($mod['mod_groups'][$forum_id])) { + foreach ($mod['mod_groups'][$forum_id] as $group_id) { + $moderators[] = '' . $mod['name_groups'][$group_id] . ''; + } + } - $html = ': '; - $html .= ($moderators) ? join(', ', $moderators) : $lang['NONE']; - unset($moderators, $mod); - $datastore->rm('moderators'); - break; + $html = ': '; + $html .= ($moderators) ? join(', ', $moderators) : $lang['NONE']; + unset($moderators, $mod); + $datastore->rm('moderators'); + break; - case 'change_tz': - $tz = (int) $this->request['tz']; - if ($tz < -12) $tz = -12; - if ($tz > 13) $tz = 13; - if ($tz != $bb_cfg['board_timezone']) - { - // Set current user timezone - DB()->query("UPDATE ". BB_USERS ." SET user_timezone = $tz WHERE user_id = ". $userdata['user_id'] ." LIMIT 1"); - $bb_cfg['board_timezone'] = $tz; - cache_rm_user_sessions ($userdata['user_id']); - } - break; + case 'change_tz': + $tz = (int)$this->request['tz']; + if ($tz < -12) { + $tz = -12; + } + if ($tz > 13) { + $tz = 13; + } + if ($tz != $bb_cfg['board_timezone']) { + // Set current user timezone + DB()->query("UPDATE " . BB_USERS . " SET user_timezone = $tz WHERE user_id = " . $userdata['user_id'] . " LIMIT 1"); + $bb_cfg['board_timezone'] = $tz; + cache_rm_user_sessions($userdata['user_id']); + } + break; - case 'get_traf_stats': - $user_id = (int) $this->request['user_id']; - $btu = get_bt_userdata($user_id); - $profiledata = get_userdata($user_id); + case 'get_traf_stats': + $user_id = (int)$this->request['user_id']; + $btu = get_bt_userdata($user_id); + $profiledata = get_userdata($user_id); - $speed_up = ($btu['speed_up']) ? humn_size($btu['speed_up']).'/s' : '0 KB/s'; - $speed_down = ($btu['speed_down']) ? humn_size($btu['speed_down']).'/s' : '0 KB/s'; - $user_ratio = ($btu['u_down_total'] > MIN_DL_FOR_RATIO) ? ''. get_bt_ratio($btu) .'' : $lang['IT_WILL_BE_DOWN'] .' '. humn_size(MIN_DL_FOR_RATIO) .''; + $speed_up = ($btu['speed_up']) ? humn_size($btu['speed_up']) . '/s' : '0 KB/s'; + $speed_down = ($btu['speed_down']) ? humn_size($btu['speed_down']) . '/s' : '0 KB/s'; + $user_ratio = ($btu['u_down_total'] > MIN_DL_FOR_RATIO) ? '' . get_bt_ratio($btu) . '' : $lang['IT_WILL_BE_DOWN'] . ' ' . humn_size(MIN_DL_FOR_RATIO) . ''; - $html = ' + $html = ' - '. $lang['DOWNLOADED'] .' - '. $lang['UPLOADED'] .' - '. $lang['RELEASED'] .' - '. $lang['BONUS'] .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? ''. $lang['SEED_BONUS'] .'' : ''; - $html .= ' + ' . $lang['DOWNLOADED'] . ' + ' . $lang['UPLOADED'] . ' + ' . $lang['RELEASED'] . ' + ' . $lang['BONUS'] . ''; + $html .= ($bb_cfg['seed_bonus_enabled']) ? '' . $lang['SEED_BONUS'] . '' : ''; + $html .= ' - '. $lang['TOTAL_TRAF'] .' - '. humn_size($btu['u_down_total']) .' - ' .humn_size($btu['u_up_total']) .' - '. humn_size($btu['u_up_release']) .' - '. humn_size($btu['u_up_bonus']) .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? ''. $profiledata['user_points'] .'' : ''; - $html .= ' + ' . $lang['TOTAL_TRAF'] . ' + ' . humn_size($btu['u_down_total']) . ' + ' . humn_size($btu['u_up_total']) . ' + ' . humn_size($btu['u_up_release']) . ' + ' . humn_size($btu['u_up_bonus']) . ''; + $html .= ($bb_cfg['seed_bonus_enabled']) ? '' . $profiledata['user_points'] . '' : ''; + $html .= ' - '. $lang['MAX_SPEED'] .' - '. $lang['DL_DL_SPEED'] .': '. $speed_down .' - '. $lang['DL_UL_SPEED'] .': '. $speed_up .''; - $html .= ($bb_cfg['seed_bonus_enabled']) ? '' : ''; - $html .= ''; + ' . $lang['MAX_SPEED'] . ' + ' . $lang['DL_DL_SPEED'] . ': ' . $speed_down . ' + ' . $lang['DL_UL_SPEED'] . ': ' . $speed_up . ''; + $html .= ($bb_cfg['seed_bonus_enabled']) ? '' : ''; + $html .= ''; - $this->response['user_ratio'] = ' - '. $lang['USER_RATIO'] .': - '. $user_ratio .' + $this->response['user_ratio'] = ' + ' . $lang['USER_RATIO'] . ': + ' . $user_ratio . ' '; - break; + break; } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/manage_admin.php b/library/ajax/manage_admin.php index 74311b2ac..bc4a0958a 100644 --- a/library/ajax/manage_admin.php +++ b/library/ajax/manage_admin.php @@ -1,115 +1,133 @@ request['mode']; +$mode = (string)$this->request['mode']; -switch ($mode) -{ - case 'clear_cache': +switch ($mode) { + case 'clear_cache': - foreach ($bb_cfg['cache']['engines'] as $cache_name => $cache_val) - { - if (!in_array('db_sqlite', $cache_val)) - { - CACHE($cache_name)->rm(); - } - } + foreach ($bb_cfg['cache']['engines'] as $cache_name => $cache_val) { + if (!in_array('db_sqlite', $cache_val)) { + CACHE($cache_name)->rm(); + } + } - $this->response['cache_html'] = ''. $lang['ALL_CACHE_CLEARED'] .''; + $this->response['cache_html'] = '' . $lang['ALL_CACHE_CLEARED'] . ''; - break; + break; - case 'clear_datastore': + case 'clear_datastore': - global $datastore; + global $datastore; - $datastore->clean(); + $datastore->clean(); - $this->response['datastore_html'] = ''. $lang['DATASTORE_CLEARED'] .''; + $this->response['datastore_html'] = '' . $lang['DATASTORE_CLEARED'] . ''; - break; + break; - case 'clear_template_cache': + case 'clear_template_cache': - global $template; + global $template; - $match = 'tpl_'; - $match_len = strlen($match); - $dir = $template->cachedir; - $res = @opendir($dir); - while (($file = readdir($res)) !== false) - { - if (substr($file, 0, $match_len) === $match) - { - @unlink($dir . $file); - } - } - closedir($res); + $match = 'tpl_'; + $match_len = strlen($match); + $dir = $template->cachedir; + $res = @opendir($dir); + while (($file = readdir($res)) !== false) { + if (substr($file, 0, $match_len) === $match) { + @unlink($dir . $file); + } + } + closedir($res); - $this->response['template_cache_html'] = ''. $lang['ALL_TEMPLATE_CLEARED'] .''; + $this->response['template_cache_html'] = '' . $lang['ALL_TEMPLATE_CLEARED'] . ''; - break; + break; - case 'indexer': + case 'indexer': - exec("indexer --config {$bb_cfg['sphinx_config_path']} --all --rotate", $result); + exec("indexer --config {$bb_cfg['sphinx_config_path']} --all --rotate", $result); - if (!is_file($bb_cfg['sphinx_config_path'].".log")) - { - file_put_contents($bb_cfg['sphinx_config_path'].".log", "####Logger from dimka3210.####".date("H:i:s", TIMENOW)."##############################\r\n\r\n\r\n\r\n", FILE_APPEND); - } + if (!is_file($bb_cfg['sphinx_config_path'] . ".log")) { + file_put_contents($bb_cfg['sphinx_config_path'] . ".log", "####Logger from dimka3210.####" . date("H:i:s", TIMENOW) . "##############################\r\n\r\n\r\n\r\n", FILE_APPEND); + } - file_put_contents($bb_cfg['sphinx_config_path'].".log", "##############################".date("H:i:s", TIMENOW)."##############################\r\n", FILE_APPEND); + file_put_contents($bb_cfg['sphinx_config_path'] . ".log", "##############################" . date("H:i:s", TIMENOW) . "##############################\r\n", FILE_APPEND); - foreach ($result as $row) - { - file_put_contents($bb_cfg['sphinx_config_path'].".log", $row."\r\n", FILE_APPEND); - } + foreach ($result as $row) { + file_put_contents($bb_cfg['sphinx_config_path'] . ".log", $row . "\r\n", FILE_APPEND); + } - file_put_contents($bb_cfg['sphinx_config_path'].".log", "\r\n", FILE_APPEND); - file_put_contents($bb_cfg['sphinx_config_path'].".log", "\r\n", FILE_APPEND); + file_put_contents($bb_cfg['sphinx_config_path'] . ".log", "\r\n", FILE_APPEND); + file_put_contents($bb_cfg['sphinx_config_path'] . ".log", "\r\n", FILE_APPEND); - $this->response['indexer_html'] = ''. $lang['INDEXER'] .''; + $this->response['indexer_html'] = '' . $lang['INDEXER'] . ''; - break; + break; - case 'update_user_level': + case 'update_user_level': - require(INC_DIR .'functions_group.php'); + require(INC_DIR . 'functions_group.php'); - update_user_level('all'); + update_user_level('all'); - $this->response['update_user_level_html'] = ''. $lang['USER_LEVELS_UPDATED'] .''; + $this->response['update_user_level_html'] = '' . $lang['USER_LEVELS_UPDATED'] . ''; - break; + break; - case 'sync_topics': + case 'sync_topics': - sync('topic', 'all'); - sync_all_forums(); + sync('topic', 'all'); + sync_all_forums(); - $this->response['sync_topics_html'] = ''. $lang['TOPICS_DATA_SYNCHRONIZED'] .''; + $this->response['sync_topics_html'] = '' . $lang['TOPICS_DATA_SYNCHRONIZED'] . ''; - break; + break; - case 'sync_user_posts': + case 'sync_user_posts': - sync('user_posts', 'all'); + sync('user_posts', 'all'); - $this->response['sync_user_posts_html'] = ''. $lang['USER_POSTS_COUNT_SYNCHRONIZED'] .''; + $this->response['sync_user_posts_html'] = '' . $lang['USER_POSTS_COUNT_SYNCHRONIZED'] . ''; - break; + break; - case 'unlock_cron': + case 'unlock_cron': - cron_enable_board(); + cron_enable_board(); - $this->response['unlock_cron_html'] = ''. $lang['ADMIN_UNLOCKED'] .''; + $this->response['unlock_cron_html'] = '' . $lang['ADMIN_UNLOCKED'] . ''; - break; + break; } -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/manage_user.php b/library/ajax/manage_user.php index b1783e083..2ebefb778 100644 --- a/library/ajax/manage_user.php +++ b/library/ajax/manage_user.php @@ -1,84 +1,126 @@ request['mode']; +$mode = (string)$this->request['mode']; $user_id = $this->request['user_id']; -switch ($mode) -{ - case 'delete_profile': +switch ($mode) { + case 'delete_profile': - if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DELETE_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['USER_DELETE_CONFIRM']); + if ($userdata['user_id'] == $user_id) { + $this->ajax_die($lang['USER_DELETE_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['USER_DELETE_CONFIRM']); + } - if ($user_id != BOT_UID) - { - delete_user_sessions($user_id); - user_delete($user_id); + if ($user_id != BOT_UID) { + delete_user_sessions($user_id); + user_delete($user_id); - $this->response['info'] = $lang['USER_DELETED']; - } - else $this->ajax_die($lang['USER_DELETE_CSV']); + $this->response['info'] = $lang['USER_DELETED']; + } else { + $this->ajax_die($lang['USER_DELETE_CSV']); + } - break; + break; - case 'delete_topics': + case 'delete_topics': - if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_ALL_POSTS_CONFIRM']); + if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DELETE_USER_ALL_POSTS_CONFIRM']); + } - if (IS_ADMIN) - { - $user_topics = DB()->fetch_rowset("SELECT topic_id FROM ". BB_TOPICS ." WHERE topic_poster = $user_id", 'topic_id'); - $deleted_topics = topic_delete($user_topics); - $deleted_posts = post_delete('user', $user_id); + if (IS_ADMIN) { + $user_topics = DB()->fetch_rowset("SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_poster = $user_id", 'topic_id'); + $deleted_topics = topic_delete($user_topics); + $deleted_posts = post_delete('user', $user_id); - $this->response['info'] = $lang['USER_DELETED_POSTS']; - } - else $this->ajax_die($lang['NOT_ADMIN']); + $this->response['info'] = $lang['USER_DELETED_POSTS']; + } else { + $this->ajax_die($lang['NOT_ADMIN']); + } - break; + break; - case 'delete_message': + case 'delete_message': - if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_CONFIRM']); + if (empty($this->request['confirmed']) && $userdata['user_id'] == $user_id) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DELETE_USER_POSTS_CONFIRM']); + } - if (IS_ADMIN) - { - post_delete('user', $user_id); + if (IS_ADMIN) { + post_delete('user', $user_id); - $this->response['info'] = $lang['USER_DELETED_POSTS']; - } - else $this->ajax_die($lang['NOT_ADMIN']); + $this->response['info'] = $lang['USER_DELETED_POSTS']; + } else { + $this->ajax_die($lang['NOT_ADMIN']); + } - break; + break; - case 'user_activate': + case 'user_activate': - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEACTIVATE_CONFIRM']); + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['DEACTIVATE_CONFIRM']); + } - DB()->query("UPDATE ". BB_USERS ." SET user_active = '1' WHERE user_id = ". $user_id); + DB()->query("UPDATE " . BB_USERS . " SET user_active = '1' WHERE user_id = " . $user_id); - $this->response['info'] = $lang['USER_ACTIVATE_ON']; + $this->response['info'] = $lang['USER_ACTIVATE_ON']; - break; + break; - case 'user_deactivate': + case 'user_deactivate': - if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DEACTIVATE_ME']); - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['ACTIVATE_CONFIRM']); + if ($userdata['user_id'] == $user_id) { + $this->ajax_die($lang['USER_DEACTIVATE_ME']); + } + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['ACTIVATE_CONFIRM']); + } - DB()->query("UPDATE ". BB_USERS ." SET user_active = '0' WHERE user_id = ". $user_id); - delete_user_sessions($user_id); + DB()->query("UPDATE " . BB_USERS . " SET user_active = '0' WHERE user_id = " . $user_id); + delete_user_sessions($user_id); - $this->response['info'] = $lang['USER_ACTIVATE_OFF']; + $this->response['info'] = $lang['USER_ACTIVATE_OFF']; - break; + break; } $this->response['mode'] = $mode; -$this->response['url'] = html_entity_decode(make_url('/') . PROFILE_URL . $user_id); \ No newline at end of file +$this->response['url'] = html_entity_decode(make_url('/') . PROFILE_URL . $user_id); diff --git a/library/ajax/mod_action.php b/library/ajax/mod_action.php index 80153be06..c78e40dc8 100644 --- a/library/ajax/mod_action.php +++ b/library/ajax/mod_action.php @@ -1,130 +1,152 @@ request['mode']; +$mode = (string)$this->request['mode']; -switch ($mode) -{ - case 'tor_status': - $topics = (string) $this->request['topic_ids']; - $status = (int) $this->request['status']; +switch ($mode) { + case 'tor_status': + $topics = (string)$this->request['topic_ids']; + $status = (int)$this->request['status']; - // Валидность статуса - if (!isset($lang['TOR_STATUS_NAME'][$status])) - { - $this->ajax_die($lang['STATUS_DOES_EXIST'] . $new_status); - } + // Валидность статуса + if (!isset($lang['TOR_STATUS_NAME'][$status])) { + $this->ajax_die($lang['STATUS_DOES_EXIST'] . $new_status); + } - $topic_ids = DB()->fetch_rowset("SELECT attach_id FROM ". BB_BT_TORRENTS ." WHERE topic_id IN($topics)", 'attach_id'); + $topic_ids = DB()->fetch_rowset("SELECT attach_id FROM " . BB_BT_TORRENTS . " WHERE topic_id IN($topics)", 'attach_id'); - foreach($topic_ids as $attach_id) - { - change_tor_status($attach_id, $status); - } - $this->response['status'] = $bb_cfg['tor_icons'][$status]; - $this->response['topics'] = explode(',', $topics); - break; + foreach ($topic_ids as $attach_id) { + change_tor_status($attach_id, $status); + } + $this->response['status'] = $bb_cfg['tor_icons'][$status]; + $this->response['topics'] = explode(',', $topics); + break; - case 'edit_topic_title': - $topic_id = (int) $this->request['topic_id']; - $topic_title = (string) $this->request['topic_title']; - $new_title = clean_title($topic_title); + case 'edit_topic_title': + $topic_id = (int)$this->request['topic_id']; + $topic_title = (string)$this->request['topic_title']; + $new_title = clean_title($topic_title); - if (!$topic_id) $this->ajax_die($lang['INVALID_TOPIC_ID']); - if ($new_title == '') $this->ajax_die($lang['DONT_MESSAGE_TITLE']); + if (!$topic_id) { + $this->ajax_die($lang['INVALID_TOPIC_ID']); + } + if ($new_title == '') { + $this->ajax_die($lang['DONT_MESSAGE_TITLE']); + } - if (!$t_data = DB()->fetch_row("SELECT forum_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1")) - { - $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); - } - $this->verify_mod_rights($t_data['forum_id']); + if (!$t_data = DB()->fetch_row("SELECT forum_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1")) { + $this->ajax_die($lang['INVALID_TOPIC_ID_DB']); + } + $this->verify_mod_rights($t_data['forum_id']); - $topic_title_sql = DB()->escape($new_title); + $topic_title_sql = DB()->escape($new_title); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_title = '$topic_title_sql' WHERE topic_id = $topic_id LIMIT 1"); + DB()->query("UPDATE " . BB_TOPICS . " SET topic_title = '$topic_title_sql' WHERE topic_id = $topic_id LIMIT 1"); - // Обновление кеша новостей на главной - $news_forums = array_flip(explode(',', $bb_cfg['latest_news_forum_id'])); - if (isset($news_forums[$t_data['forum_id']]) && $bb_cfg['show_latest_news']) - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } + // Обновление кеша новостей на главной + $news_forums = array_flip(explode(',', $bb_cfg['latest_news_forum_id'])); + if (isset($news_forums[$t_data['forum_id']]) && $bb_cfg['show_latest_news']) { + $datastore->enqueue('latest_news'); + $datastore->update('latest_news'); + } - $net_forums = array_flip(explode(',', $bb_cfg['network_news_forum_id'])); - if (isset($net_forums[$t_data['forum_id']]) && $bb_cfg['show_network_news']) - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } + $net_forums = array_flip(explode(',', $bb_cfg['network_news_forum_id'])); + if (isset($net_forums[$t_data['forum_id']]) && $bb_cfg['show_network_news']) { + $datastore->enqueue('network_news'); + $datastore->update('network_news'); + } - $this->response['topic_id'] = $topic_id; - $this->response['topic_title'] = $new_title; - break; + $this->response['topic_id'] = $topic_id; + $this->response['topic_title'] = $new_title; + break; - case 'profile_ip': - $user_id = (int) $this->request['user_id']; - $profiledata = get_userdata($user_id); + case 'profile_ip': + $user_id = (int)$this->request['user_id']; + $profiledata = get_userdata($user_id); - if (!$user_id) $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); + if (!$user_id) { + $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); + } - $reg_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM ". BB_USERS ." + $reg_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " . BB_USERS . " WHERE user_reg_ip = '{$profiledata['user_reg_ip']}' AND user_reg_ip != '' AND user_id != {$profiledata['user_id']} ORDER BY username ASC"); - $last_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " .BB_USERS ." + $last_ip = DB()->fetch_rowset("SELECT username, user_id, user_rank FROM " . BB_USERS . " WHERE user_last_ip = '{$profiledata['user_last_ip']}' AND user_last_ip != '' AND user_id != {$profiledata['user_id']}"); - $link_reg_ip = $link_last_ip = ''; + $link_reg_ip = $link_last_ip = ''; - if (!empty($reg_ip)) - { - $link_reg_ip .= $lang['OTHER_IP'] .' '; - foreach ($reg_ip as $row) - { - $link_reg_ip .= profile_url($row) .' '; - } - } + if (!empty($reg_ip)) { + $link_reg_ip .= $lang['OTHER_IP'] . ' '; + foreach ($reg_ip as $row) { + $link_reg_ip .= profile_url($row) . ' '; + } + } - if (!empty($last_ip)) - { - $link_last_ip .= $lang['OTHER_IP'] .' '; - foreach ($last_ip as $row) - { - $link_last_ip .= profile_url($row) .' '; - } - } + if (!empty($last_ip)) { + $link_last_ip .= $lang['OTHER_IP'] . ' '; + foreach ($last_ip as $row) { + $link_last_ip .= profile_url($row) . ' '; + } + } - if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) $reg_ip = $last_ip = $lang['HIDDEN']; - elseif ($profiledata['user_level'] == MOD && IS_MOD) $reg_ip = $last_ip = $lang['HIDDEN']; - else - { - $user_reg_ip = decode_ip($profiledata['user_reg_ip']); - $user_last_ip = decode_ip($profiledata['user_last_ip']); - $reg_ip = ''. $user_reg_ip .''; - $last_ip = ''. $user_last_ip .''; - } + if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) { + $reg_ip = $last_ip = $lang['HIDDEN']; + } elseif ($profiledata['user_level'] == MOD && IS_MOD) { + $reg_ip = $last_ip = $lang['HIDDEN']; + } else { + $user_reg_ip = decode_ip($profiledata['user_reg_ip']); + $user_last_ip = decode_ip($profiledata['user_last_ip']); + $reg_ip = '' . $user_reg_ip . ''; + $last_ip = '' . $user_last_ip . ''; + } - $this->response['ip_list_html'] = ' + $this->response['ip_list_html'] = '
        - - - + + + - - - + + +
        '. $lang['REG_IP'] .''. $reg_ip .'
        '. $link_reg_ip .'
        ' . $lang['REG_IP'] . '' . $reg_ip . '
        ' . $link_reg_ip . '
        '. $lang['LAST_IP'] .''. $last_ip .'
        '. $link_last_ip .'
        ' . $lang['LAST_IP'] . '' . $last_ip . '
        ' . $link_last_ip . '

        '; - break; -} \ No newline at end of file + break; +} diff --git a/library/ajax/post_mod_comment.php b/library/ajax/post_mod_comment.php index 3cc5e0f5a..384ceefce 100644 --- a/library/ajax/post_mod_comment.php +++ b/library/ajax/post_mod_comment.php @@ -1,60 +1,87 @@ request['post_id']; -$mc_type = (int) $this->request['mc_type']; -$mc_text = (string) $this->request['mc_text']; -if (!$mc_text = prepare_message($mc_text)) $this->ajax_die($lang['EMPTY_MESSAGE']); +$post_id = (int)$this->request['post_id']; +$mc_type = (int)$this->request['mc_type']; +$mc_text = (string)$this->request['mc_text']; +if (!$mc_text = prepare_message($mc_text)) { + $this->ajax_die($lang['EMPTY_MESSAGE']); +} $post = DB()->fetch_row(" SELECT p.post_id, p.poster_id - FROM ". BB_POSTS ." p + FROM " . BB_POSTS . " p WHERE p.post_id = $post_id "); -if (!$post) $this->ajax_die('not post'); +if (!$post) { + $this->ajax_die('not post'); +} $data = array( - 'mc_comment' => ($mc_type) ? $mc_text : '', - 'mc_type' => $mc_type, - 'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0, + 'mc_comment' => ($mc_type) ? $mc_text : '', + 'mc_type' => $mc_type, + 'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0, ); $sql_args = DB()->build_array('UPDATE', $data); -DB()->query("UPDATE ". BB_POSTS ." SET $sql_args WHERE post_id = $post_id"); +DB()->query("UPDATE " . BB_POSTS . " SET $sql_args WHERE post_id = $post_id"); -if ($mc_type && $post['poster_id'] != $userdata['user_id']) -{ - $subject = sprintf($lang['MC_COMMENT_PM_SUBJECT'], $lang['MC_COMMENT'][$mc_type]['type']); - $message = sprintf($lang['MC_COMMENT_PM_MSG'], get_username($post['poster_id']), make_url(POST_URL ."$post_id#$post_id"), $lang['MC_COMMENT'][$mc_type]['type'], $mc_text); +if ($mc_type && $post['poster_id'] != $userdata['user_id']) { + $subject = sprintf($lang['MC_COMMENT_PM_SUBJECT'], $lang['MC_COMMENT'][$mc_type]['type']); + $message = sprintf($lang['MC_COMMENT_PM_MSG'], get_username($post['poster_id']), make_url(POST_URL . "$post_id#$post_id"), $lang['MC_COMMENT'][$mc_type]['type'], $mc_text); - send_pm($post['poster_id'], $subject, $message); - cache_rm_user_sessions($post['poster_id']); + send_pm($post['poster_id'], $subject, $message); + cache_rm_user_sessions($post['poster_id']); } -switch($mc_type) -{ - case 1: // Комментарий - $mc_class = 'success'; - break; - case 2: // Информация - $mc_class = 'info'; - break; - case 3: // Предупреждение - $mc_class = 'warning'; - break; - case 4: // Нарушение - $mc_class = 'danger'; - break; - default: - $mc_class = ''; - break; +switch ($mc_type) { + case 1: // Комментарий + $mc_class = 'success'; + break; + case 2: // Информация + $mc_class = 'info'; + break; + case 3: // Предупреждение + $mc_class = 'warning'; + break; + case 4: // Нарушение + $mc_class = 'danger'; + break; + default: + $mc_class = ''; + break; } -$this->response['mc_type'] = $mc_type; -$this->response['post_id'] = $post_id; +$this->response['mc_type'] = $mc_type; +$this->response['post_id'] = $post_id; $this->response['mc_title'] = sprintf($lang['MC_COMMENT'][$mc_type]['title'], profile_url($userdata)); -$this->response['mc_text'] = bbcode2html($mc_text); -$this->response['mc_class'] = $mc_class; \ No newline at end of file +$this->response['mc_text'] = bbcode2html($mc_text); +$this->response['mc_class'] = $mc_class; diff --git a/library/ajax/posts.php b/library/ajax/posts.php index ccfe534a5..1029bb0c2 100644 --- a/library/ajax/posts.php +++ b/library/ajax/posts.php @@ -1,212 +1,212 @@ request['type'])) -{ - $this->ajax_die('empty type'); +if (!isset($this->request['type'])) { + $this->ajax_die('empty type'); } -if (isset($this->request['post_id'])) -{ - $post_id = (int) $this->request['post_id']; - $post = DB()->fetch_row("SELECT t.*, f.*, p.*, pt.post_text - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f, ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt +if (isset($this->request['post_id'])) { + $post_id = (int)$this->request['post_id']; + $post = DB()->fetch_row("SELECT t.*, f.*, p.*, pt.post_text + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f, " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt WHERE p.post_id = $post_id AND t.topic_id = p.topic_id AND f.forum_id = t.forum_id AND p.post_id = pt.post_id LIMIT 1"); - if(!$post) $this->ajax_die('not post'); + if (!$post) { + $this->ajax_die('not post'); + } - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } -} -elseif (isset($this->request['topic_id'])) -{ - $topic_id = (int) $this->request['topic_id']; - $post = DB()->fetch_row("SELECT t.*, f.* - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } +} elseif (isset($this->request['topic_id'])) { + $topic_id = (int)$this->request['topic_id']; + $post = DB()->fetch_row("SELECT t.*, f.* + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f WHERE t.topic_id = $topic_id AND f.forum_id = t.forum_id LIMIT 1"); - if(!$post) $this->ajax_die('not post'); + if (!$post) { + $this->ajax_die('not post'); + } - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); } -if (!defined('WORD_LIST_OBTAINED')) -{ - $orig_word = array(); - $replace_word = array(); - obtain_word_list($orig_word, $replace_word); - define('WORD_LIST_OBTAINED', true); +if (!defined('WORD_LIST_OBTAINED')) { + $orig_word = array(); + $replace_word = array(); + obtain_word_list($orig_word, $replace_word); + define('WORD_LIST_OBTAINED', true); } -switch($this->request['type']) -{ - case 'delete'; - if ($post['post_id'] != $post['topic_first_post_id'] && $is_auth['auth_delete'] && ($is_auth['auth_mod'] || ($userdata['user_id'] == $post['poster_id'] && $post['topic_last_post_id'] == $post['post_id'] && $post['post_time'] + 3600*3 > TIMENOW))) - { - if (empty($this->request['confirmed'])) - { - $this->prompt_for_confirm($lang['CONFIRM_DELETE']); - } - post_delete($post_id); +switch ($this->request['type']) { + case 'delete'; + if ($post['post_id'] != $post['topic_first_post_id'] && $is_auth['auth_delete'] && ($is_auth['auth_mod'] || ($userdata['user_id'] == $post['poster_id'] && $post['topic_last_post_id'] == $post['post_id'] && $post['post_time'] + 3600 * 3 > TIMENOW))) { + if (empty($this->request['confirmed'])) { + $this->prompt_for_confirm($lang['CONFIRM_DELETE']); + } + post_delete($post_id); - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - $this->response['hide'] = true; - $this->response['post_id'] = $post_id; - } - else - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type']))); - } - break; + $this->response['hide'] = true; + $this->response['post_id'] = $post_id; + } else { + $this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type']))); + } + break; - case 'reply'; - if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) - { - $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); - } - elseif(!$is_auth['auth_reply']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); - } + case 'reply'; + if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) { + $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); + } elseif (!$is_auth['auth_reply']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); + } - $quote_username = ($post['post_username'] != '') ? $post['post_username'] : get_username($post['poster_id']); - $message = "[quote=\"". $quote_username ."\"][qpost=". $post['post_id'] ."]". $post['post_text'] ."[/quote]\r"; + $quote_username = ($post['post_username'] != '') ? $post['post_username'] : get_username($post['poster_id']); + $message = "[quote=\"" . $quote_username . "\"][qpost=" . $post['post_id'] . "]" . $post['post_text'] . "[/quote]\r"; - // hide user passkey - $message = preg_replace('#(?<=\?uk=)[a-zA-Z0-9]{10}(?=&)#', 'passkey', $message); - // hide sid - $message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]{12}#', 'sid', $message); + // hide user passkey + $message = preg_replace('#(?<=\?uk=)[a-zA-Z0-9]{10}(?=&)#', 'passkey', $message); + // hide sid + $message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]{12}#', 'sid', $message); - if (!empty($orig_word)) - { - $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; - } + if (!empty($orig_word)) { + $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; + } - if ($post['post_id'] == $post['topic_first_post_id']) - { - $message = "[quote]". $post['topic_title'] ."[/quote]\r"; - } - if (mb_strlen($message, 'UTF-8') > 1000) - { - $this->response['redirect'] = make_url(POSTING_URL.'?mode=quote&p='. $post_id); - } + if ($post['post_id'] == $post['topic_first_post_id']) { + $message = "[quote]" . $post['topic_title'] . "[/quote]\r"; + } + if (mb_strlen($message, 'UTF-8') > 1000) { + $this->response['redirect'] = make_url(POSTING_URL . '?mode=quote&p=' . $post_id); + } - $this->response['quote'] = true; - $this->response['message'] = $message; - break; + $this->response['quote'] = true; + $this->response['message'] = $message; + break; - case 'view_message': - $message = (string) $this->request['message']; - if(!trim($message)) $this->ajax_die($lang['EMPTY_MESSAGE']); - $message = htmlCHR($message, false, ENT_NOQUOTES); + case 'view_message': + $message = (string)$this->request['message']; + if (!trim($message)) { + $this->ajax_die($lang['EMPTY_MESSAGE']); + } + $message = htmlCHR($message, false, ENT_NOQUOTES); - $this->response['message_html'] = bbcode2html($message); - $this->response['res_id'] = @$this->request['res_id']; - break; + $this->response['message_html'] = bbcode2html($message); + $this->response['res_id'] = @$this->request['res_id']; + break; - case 'edit': - case 'editor': - if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) - { - $this->ajax_die($lang['POST_EDIT_CANNOT']); - } - if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['EDIT_OWN_POSTS']); - } - if ((mb_strlen($post['post_text'], 'UTF-8') > 1000) || $post['post_attachment'] || ($post['topic_first_post_id'] == $post_id)) - { - $this->response['redirect'] = make_url(POSTING_URL.'?mode=editpost&p='. $post_id); - } - elseif ($this->request['type'] == 'editor') - { - $text = (string) $this->request['text']; - $text = prepare_message($text); + case 'edit': + case 'editor': + if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) { + $this->ajax_die($lang['POST_EDIT_CANNOT']); + } + if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) { + $this->ajax_die($lang['EDIT_OWN_POSTS']); + } + if ((mb_strlen($post['post_text'], 'UTF-8') > 1000) || $post['post_attachment'] || ($post['topic_first_post_id'] == $post_id)) { + $this->response['redirect'] = make_url(POSTING_URL . '?mode=editpost&p=' . $post_id); + } elseif ($this->request['type'] == 'editor') { + $text = (string)$this->request['text']; + $text = prepare_message($text); - if (mb_strlen($text) > 2) - { - if ($text != $post['post_text']) - { - if ($bb_cfg['max_smilies']) - { - $count_smilies = substr_count(bbcode2html($text), 'query("UPDATE ". BB_POSTS ." SET post_edit_time = '". TIMENOW ."', post_edit_count = post_edit_count + 1 WHERE post_id = $post_id LIMIT 1"); - } - $s_text = str_replace('\n', "\n", $text); - $s_topic_title = str_replace('\n', "\n", $post['topic_title']); - add_search_words($post_id, stripslashes($s_text), stripslashes($s_topic_title)); - update_post_html(array( - 'post_id' => $post_id, - 'post_text' => $text, - )); - } - } - else $this->ajax_die($lang['EMPTY_MESSAGE']); + if (mb_strlen($text) > 2) { + if ($text != $post['post_text']) { + if ($bb_cfg['max_smilies']) { + $count_smilies = substr_count(bbcode2html($text), 'query("UPDATE " . BB_POSTS . " SET post_edit_time = '" . TIMENOW . "', post_edit_count = post_edit_count + 1 WHERE post_id = $post_id LIMIT 1"); + } + $s_text = str_replace('\n', "\n", $text); + $s_topic_title = str_replace('\n', "\n", $post['topic_title']); + add_search_words($post_id, stripslashes($s_text), stripslashes($s_topic_title)); + update_post_html(array( + 'post_id' => $post_id, + 'post_text' => $text, + )); + } + } else { + $this->ajax_die($lang['EMPTY_MESSAGE']); + } - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - $this->response['html'] = bbcode2html($text); - } - else - { - $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } - elseif (!$is_auth['auth_edit']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_EDIT'], strip_tags($is_auth['auth_edit_type']))); - } + $this->response['html'] = bbcode2html($text); + } else { + $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } elseif (!$is_auth['auth_edit']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_EDIT'], strip_tags($is_auth['auth_edit_type']))); + } - $hidden_form = ''; - $hidden_form .= ''; - $hidden_form .= ''; + $hidden_form = ''; + $hidden_form .= ''; + $hidden_form .= ''; - $this->response['text'] = ' -
        - '. $hidden_form .' + $this->response['text'] = ' + + ' . $hidden_form . '
        - - - -    - - -   - - -   -   + + + +    + + +   + + +   +  
        - +
        - - - + + +

        '; - } - $this->response['post_id'] = $post_id; - break; + } + $this->response['post_id'] = $post_id; + break; - case 'add': - if (!isset($this->request['topic_id'])) - { - $this->ajax_die('empty topic_id'); - } + case 'add': + if (!isset($this->request['topic_id'])) { + $this->ajax_die('empty topic_id'); + } - if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) - { - $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); - } - elseif (!$is_auth['auth_reply']) - { - $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); - } - if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - $this->ajax_die($lang['TOPIC_LOCKED']); - } + if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) { + $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); + } elseif (!$is_auth['auth_reply']) { + $this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); + } + if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + $this->ajax_die($lang['TOPIC_LOCKED']); + } - $message = (string) $this->request['message']; - $message = prepare_message($message); + $message = (string)$this->request['message']; + $message = prepare_message($message); - // Flood control - $where_sql = (IS_GUEST) ? "p.poster_ip = '". USER_IP ."'" : "p.poster_id = {$userdata['user_id']}"; + // Flood control + $where_sql = (IS_GUEST) ? "p.poster_ip = '" . USER_IP . "'" : "p.poster_id = {$userdata['user_id']}"; - $sql = "SELECT MAX(p.post_time) AS last_post_time FROM ". BB_POSTS ." p WHERE $where_sql"; - if ($row = DB()->fetch_row($sql) AND $row['last_post_time']) - { - if ($userdata['user_level'] == USER) - { - if (TIMENOW - $row['last_post_time'] < $bb_cfg['flood_interval']) - { - $this->ajax_die($lang['FLOOD_ERROR']); - } - } - } + $sql = "SELECT MAX(p.post_time) AS last_post_time FROM " . BB_POSTS . " p WHERE $where_sql"; + if ($row = DB()->fetch_row($sql) and $row['last_post_time']) { + if ($userdata['user_level'] == USER) { + if (TIMENOW - $row['last_post_time'] < $bb_cfg['flood_interval']) { + $this->ajax_die($lang['FLOOD_ERROR']); + } + } + } - // Double Post Control - if (!empty($row['last_post_time']) && !IS_AM) - { - $sql = " + // Double Post Control + if (!empty($row['last_post_time']) && !IS_AM) { + $sql = " SELECT pt.post_text - FROM ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt + FROM " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt WHERE $where_sql - AND p.post_time = ". (int) $row['last_post_time'] ." + AND p.post_time = " . (int)$row['last_post_time'] . " AND pt.post_id = p.post_id LIMIT 1 "; - if ($row = DB()->fetch_row($sql)) - { - $last_msg = DB()->escape($row['post_text']); + if ($row = DB()->fetch_row($sql)) { + $last_msg = DB()->escape($row['post_text']); - if ($last_msg == $message) - { - $this->ajax_die($lang['DOUBLE_POST_ERROR']); - } - } - } + if ($last_msg == $message) { + $this->ajax_die($lang['DOUBLE_POST_ERROR']); + } + } + } - if ($bb_cfg['max_smilies']) - { - $count_smilies = substr_count(bbcode2html($message), 'sql_nextid(); - DB()->sql_query("INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '". DB()->escape($message) ."')"); + DB()->sql_query("INSERT INTO " . BB_POSTS . " (topic_id, forum_id, poster_id, post_time, poster_ip) VALUES ($topic_id, " . $post['forum_id'] . ", " . $userdata['user_id'] . ", '" . TIMENOW . "', '" . USER_IP . "')"); + $post_id = DB()->sql_nextid(); + DB()->sql_query("INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '" . DB()->escape($message) . "')"); - update_post_stats('reply', $post, $post['forum_id'], $topic_id, $post_id, $userdata['user_id']); + update_post_stats('reply', $post, $post['forum_id'], $topic_id, $post_id, $userdata['user_id']); - $s_message = str_replace('\n', "\n", $message); - $s_topic_title = str_replace('\n', "\n", $post['topic_title']); - add_search_words($post_id, stripslashes($s_message), stripslashes($s_topic_title)); - update_post_html(array( - 'post_id' => $post_id, - 'post_text' => $message, - )); + $s_message = str_replace('\n', "\n", $message); + $s_topic_title = str_replace('\n', "\n", $post['topic_title']); + add_search_words($post_id, stripslashes($s_message), stripslashes($s_topic_title)); + update_post_html(array( + 'post_id' => $post_id, + 'post_text' => $message, + )); - if ($bb_cfg['topic_notify_enabled']) - { - $notify = !empty($this->request['notify']); - user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); - } + if ($bb_cfg['topic_notify_enabled']) { + $notify = !empty($this->request['notify']); + user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); + } - // Update atom feed - update_atom('topic', (int) $this->request['topic_id']); + // Update atom feed + update_atom('topic', (int)$this->request['topic_id']); - $this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id"); - break; + $this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id"); + break; - default: - $this->ajax_die('empty type'); - break; -} \ No newline at end of file + default: + $this->ajax_die('empty type'); + break; +} diff --git a/library/ajax/sitemap.php b/library/ajax/sitemap.php index 45decf5f7..c03932242 100644 --- a/library/ajax/sitemap.php +++ b/library/ajax/sitemap.php @@ -1,55 +1,80 @@ request['mode']; -$map = new sitemap(); +$mode = (string)$this->request['mode']; +$map = new sitemap(); $html = ''; -switch ($mode) -{ - case 'create': - $map->create(); - if (@file_exists(SITEMAP_DIR. 'sitemap.xml')) - { - $html .= $lang['SITEMAP_CREATED'].': '.bb_date(TIMENOW, $bb_cfg['post_date_format']).' '.$lang['SITEMAP_AVAILABLE'].': '.make_url('sitemap.xml').''; - } else { - $html .= $lang['SITEMAP_NOT_CREATED']; - } - break; +switch ($mode) { + case 'create': + $map->create(); + if (@file_exists(SITEMAP_DIR . 'sitemap.xml')) { + $html .= $lang['SITEMAP_CREATED'] . ': ' . bb_date(TIMENOW, $bb_cfg['post_date_format']) . ' ' . $lang['SITEMAP_AVAILABLE'] . ': ' . make_url('sitemap.xml') . ''; + } else { + $html .= $lang['SITEMAP_NOT_CREATED']; + } + break; - case 'search_update': - if (!@file_exists(SITEMAP_DIR. 'sitemap.xml')) $map->create(); + case 'search_update': + if (!@file_exists(SITEMAP_DIR . 'sitemap.xml')) { + $map->create(); + } - $map_link = make_url(SITEMAP_DIR. 'sitemap.xml'); + $map_link = make_url(SITEMAP_DIR . 'sitemap.xml'); - if (strpos($map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link), "successfully added") !== false) { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: '.$lang['SITEMAP_ERROR'].' URL: http://google.com/webmasters/sitemaps/ping?sitemap='.$map_link.''; - } + if (strpos($map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link), "successfully added") !== false) { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Google: ' . $lang['SITEMAP_SENT'] . ''; + } else { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Google: ' . $lang['SITEMAP_ERROR'] . ' URL: http://google.com/webmasters/sitemaps/ping?sitemap=' . $map_link . ''; + } - if (strpos($map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link), "OK") !== false) { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: '.$lang['SITEMAP_ERROR'].' URL: http://ping.blogs.yandex.ru/ping?sitemap='.$map_link.''; - } + if (strpos($map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link), "OK") !== false) { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Yandex: ' . $lang['SITEMAP_SENT'] . ''; + } else { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Yandex: ' . $lang['SITEMAP_ERROR'] . ' URL: http://ping.blogs.yandex.ru/ping?sitemap=' . $map_link . ''; + } - if ($map->send_url("http://www.bing.com/ping?sitemap=", $map_link)) { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: '.$lang['SITEMAP_ERROR'].' URL: http://www.bing.com/ping?sitemap='.$map_link.''; - } + if ($map->send_url("http://www.bing.com/ping?sitemap=", $map_link)) { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Bing: ' . $lang['SITEMAP_SENT'] . ''; + } else { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Bing: ' . $lang['SITEMAP_ERROR'] . ' URL: http://www.bing.com/ping?sitemap=' . $map_link . ''; + } - if (strpos($map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link), "Thanks for the ping") !== false) { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: '.$lang['SITEMAP_SENT'].''; - } else { - $html .= '
        '.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: '.$lang['SITEMAP_ERROR'].' URL: http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url='.$map_link.''; - } - break; + if (strpos($map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link), "Thanks for the ping") !== false) { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Weblogs: ' . $lang['SITEMAP_SENT'] . ''; + } else { + $html .= '
        ' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Weblogs: ' . $lang['SITEMAP_ERROR'] . ' URL: http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=' . $map_link . ''; + } + break; } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/topic_tpl.php b/library/ajax/topic_tpl.php index fdc366349..f355dce10 100644 --- a/library/ajax/topic_tpl.php +++ b/library/ajax/topic_tpl.php @@ -1,172 +1,180 @@ ajax_die('not auth'); +if (!IS_SUPER_ADMIN) { + $this->ajax_die('not auth'); +} array_deep($this->request, 'trim'); -$mode = (string) $this->request['mode']; +$mode = (string)$this->request['mode']; $sql_error = false; // установка / начальная валидация значений -switch ($mode) -{ - case 'load': - case 'save': - if (!$tpl_id = (int) $this->request['tpl_id']) - { - $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); - } - if (!$tpl_data = DB()->fetch_row("SELECT * FROM ". BB_TOPIC_TPL ." WHERE tpl_id = $tpl_id LIMIT 1")) - { - $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); - } - break; +switch ($mode) { + case 'load': + case 'save': + if (!$tpl_id = (int)$this->request['tpl_id']) { + $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); + } + if (!$tpl_data = DB()->fetch_row("SELECT * FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1")) { + $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); + } + break; } -switch ($mode) -{ - case 'save': - case 'new': - if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) - { - $this->ajax_die('не заполнено название шаблона'); - } - $tpl_name = substr($tpl_name, 0, 60); +switch ($mode) { + case 'save': + case 'new': + if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) { + $this->ajax_die('не заполнено название шаблона'); + } + $tpl_name = substr($tpl_name, 0, 60); - if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) - { - $this->ajax_die('не заполнен скрипт формы шаблона'); - } - if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) - { - $this->ajax_die('не заполнен формат названия темы'); - } - $tpl_src_title = str_compact($tpl_src_title); + if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) { + $this->ajax_die('не заполнен скрипт формы шаблона'); + } + if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) { + $this->ajax_die('не заполнен формат названия темы'); + } + $tpl_src_title = str_compact($tpl_src_title); - if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) - { - $this->ajax_die('не заполнен формат создания сообщения'); - } + if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) { + $this->ajax_die('не заполнен формат создания сообщения'); + } - $tpl_comment = htmlCHR($this->request['tpl_comment']); + $tpl_comment = htmlCHR($this->request['tpl_comment']); - preg_match('#\d+#', (string) $this->request['tpl_rules'], $m); - $tpl_rules_post_id = isset($m[0]) ? (int) $m[0] : 0; + preg_match('#\d+#', (string)$this->request['tpl_rules'], $m); + $tpl_rules_post_id = isset($m[0]) ? (int)$m[0] : 0; - $sql_args = array( - 'tpl_name' => (string) $tpl_name, - 'tpl_src_form' => (string) $tpl_src_form, - 'tpl_src_title' => (string) $tpl_src_title, - 'tpl_src_msg' => (string) $tpl_src_msg, - 'tpl_comment' => (string) $tpl_comment, - 'tpl_rules_post_id' => (int) $tpl_rules_post_id, - 'tpl_last_edit_tm' => (int) TIMENOW, - 'tpl_last_edit_by' => (int) $userdata['user_id'], - ); - break; + $sql_args = array( + 'tpl_name' => (string)$tpl_name, + 'tpl_src_form' => (string)$tpl_src_form, + 'tpl_src_title' => (string)$tpl_src_title, + 'tpl_src_msg' => (string)$tpl_src_msg, + 'tpl_comment' => (string)$tpl_comment, + 'tpl_rules_post_id' => (int)$tpl_rules_post_id, + 'tpl_last_edit_tm' => (int)TIMENOW, + 'tpl_last_edit_by' => (int)$userdata['user_id'], + ); + break; } // выполнение -switch ($mode) -{ - // загрузка шаблона - case 'load': - $this->response['val']['tpl-name-save'] = $tpl_data['tpl_name']; - $this->response['val']['tpl-src-form'] = $tpl_data['tpl_src_form']; - $this->response['val']['tpl-src-title'] = $tpl_data['tpl_src_title']; - $this->response['val']['tpl-src-msg'] = $tpl_data['tpl_src_msg']; - $this->response['val']['tpl-comment-save'] = $tpl_data['tpl_comment']; - $this->response['val']['tpl-rules-save'] = $tpl_data['tpl_rules_post_id']; - array_deep($this->response['val'], 'html_ent_decode'); +switch ($mode) { + // загрузка шаблона + case 'load': + $this->response['val']['tpl-name-save'] = $tpl_data['tpl_name']; + $this->response['val']['tpl-src-form'] = $tpl_data['tpl_src_form']; + $this->response['val']['tpl-src-title'] = $tpl_data['tpl_src_title']; + $this->response['val']['tpl-src-msg'] = $tpl_data['tpl_src_msg']; + $this->response['val']['tpl-comment-save'] = $tpl_data['tpl_comment']; + $this->response['val']['tpl-rules-save'] = $tpl_data['tpl_rules_post_id']; + array_deep($this->response['val'], 'html_ent_decode'); - $this->response['val']['tpl-id-save'] = $tpl_id; - $this->response['val']['tpl-last-edit-tst'] = $tpl_data['tpl_last_edit_tm']; - $this->response['html']['tpl-name-old-save'] = $tpl_data['tpl_name']; - $this->response['html']['tpl-last-edit-time'] = bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'); - $this->response['html']['tpl-last-edit-by'] = get_username(intval($tpl_data['tpl_last_edit_by'])); + $this->response['val']['tpl-id-save'] = $tpl_id; + $this->response['val']['tpl-last-edit-tst'] = $tpl_data['tpl_last_edit_tm']; + $this->response['html']['tpl-name-old-save'] = $tpl_data['tpl_name']; + $this->response['html']['tpl-last-edit-time'] = bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'); + $this->response['html']['tpl-last-edit-by'] = get_username(intval($tpl_data['tpl_last_edit_by'])); - $this->response['tpl_rules_href'] = POST_URL . $tpl_data['tpl_rules_post_id'] .'#'. $tpl_data['tpl_rules_post_id']; - break; + $this->response['tpl_rules_href'] = POST_URL . $tpl_data['tpl_rules_post_id'] . '#' . $tpl_data['tpl_rules_post_id']; + break; - // включение / отключение шаблона в форуме - case 'assign': - if (!$tpl_id = (int) $this->request['tpl_id']) - { - $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); - } - if (!$forum_id = (int) $this->request['forum_id']) - { - $this->ajax_die('empty forum_id'); - } - if (!forum_exists($forum_id)) - { - $this->ajax_die("нет такого форума [id: $forum_id]"); - } - // отключение - if ($tpl_id == -1) - { - $new_tpl_id = 0; - $this->response['msg'] = 'Шаблоны в этом форуме отключены'; - } - // включение - else - { - if (!$tpl_name = DB()->fetch_row("SELECT tpl_name FROM ". BB_TOPIC_TPL ." WHERE tpl_id = $tpl_id LIMIT 1", 'tpl_name')) - { - $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); - } - $new_tpl_id = $tpl_id; - $this->response['msg'] = "Включен шаблон $tpl_name"; - } - DB()->query("UPDATE ". BB_FORUMS ." SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1"); - break; + // включение / отключение шаблона в форуме + case 'assign': + if (!$tpl_id = (int)$this->request['tpl_id']) { + $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); + } + if (!$forum_id = (int)$this->request['forum_id']) { + $this->ajax_die('empty forum_id'); + } + if (!forum_exists($forum_id)) { + $this->ajax_die("нет такого форума [id: $forum_id]"); + } + // отключение + if ($tpl_id == -1) { + $new_tpl_id = 0; + $this->response['msg'] = 'Шаблоны в этом форуме отключены'; + } // включение + else { + if (!$tpl_name = DB()->fetch_row("SELECT tpl_name FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1", 'tpl_name')) { + $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); + } + $new_tpl_id = $tpl_id; + $this->response['msg'] = "Включен шаблон $tpl_name"; + } + DB()->query("UPDATE " . BB_FORUMS . " SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1"); + break; - // сохранение изменений - case 'save': - if ($tpl_data['tpl_last_edit_tm'] > $this->request['tpl_l_ed_tst'] && $tpl_data['tpl_last_edit_by'] != $userdata['user_id']) - { - $last_edit_by_username = get_username(intval($tpl_data['tpl_last_edit_by'])); - $msg = "Изменения не были сохранены!\n\n"; - $msg .= 'Шаблон был отредактирован: '. html_entity_decode($last_edit_by_username) .', '. delta_time($tpl_data['tpl_last_edit_tm']) ." назад\n\n"; - $this->ajax_die($msg); - } - $sql = "UPDATE ". BB_TOPIC_TPL ." SET ". DB()->build_array('UPDATE', $sql_args) ." WHERE tpl_id = $tpl_id LIMIT 1"; - if (!@DB()->query($sql)) - { - $sql_error = DB()->sql_error(); - } - $this->response['tpl_id'] = $tpl_id; - $this->response['tpl_name'] = $tpl_name; - $this->response['html']['tpl-last-edit-time'] = bb_date(TIMENOW, 'd-M-y H:i'); - $this->response['html']['tpl-last-edit-by'] = $userdata['username']; - break; + // сохранение изменений + case 'save': + if ($tpl_data['tpl_last_edit_tm'] > $this->request['tpl_l_ed_tst'] && $tpl_data['tpl_last_edit_by'] != $userdata['user_id']) { + $last_edit_by_username = get_username(intval($tpl_data['tpl_last_edit_by'])); + $msg = "Изменения не были сохранены!\n\n"; + $msg .= 'Шаблон был отредактирован: ' . html_entity_decode($last_edit_by_username) . ', ' . delta_time($tpl_data['tpl_last_edit_tm']) . " назад\n\n"; + $this->ajax_die($msg); + } + $sql = "UPDATE " . BB_TOPIC_TPL . " SET " . DB()->build_array('UPDATE', $sql_args) . " WHERE tpl_id = $tpl_id LIMIT 1"; + if (!@DB()->query($sql)) { + $sql_error = DB()->sql_error(); + } + $this->response['tpl_id'] = $tpl_id; + $this->response['tpl_name'] = $tpl_name; + $this->response['html']['tpl-last-edit-time'] = bb_date(TIMENOW, 'd-M-y H:i'); + $this->response['html']['tpl-last-edit-by'] = $userdata['username']; + break; - // создание нового шаблона - case 'new': - $sql = "INSERT INTO ". BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args); - if (!@DB()->query($sql)) - { - $sql_error = DB()->sql_error(); - } - break; + // создание нового шаблона + case 'new': + $sql = "INSERT INTO " . BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args); + if (!@DB()->query($sql)) { + $sql_error = DB()->sql_error(); + } + break; - // ошибочный $mode - default: - $this->ajax_die("invalid mode: $mode"); + // ошибочный $mode + default: + $this->ajax_die("invalid mode: $mode"); } // возможный дубль названия шаблона -if ($sql_error) -{ - if ($sql_error['code'] == 1062) // Duplicate entry - { - $this->ajax_die('Шаблон с таким названием уже существует, выберите другое название'); - } - $this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}"); +if ($sql_error) { + if ($sql_error['code'] == 1062) { + // Duplicate entry + + $this->ajax_die('Шаблон с таким названием уже существует, выберите другое название'); + } + $this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}"); } // выход -$this->response['mode'] = $mode; -$this->response['timestamp'] = TIMENOW; \ No newline at end of file +$this->response['mode'] = $mode; +$this->response['timestamp'] = TIMENOW; diff --git a/library/ajax/user_register.php b/library/ajax/user_register.php index 818b95c28..817464d8c 100644 --- a/library/ajax/user_register.php +++ b/library/ajax/user_register.php @@ -1,72 +1,79 @@ request['mode']; +$mode = (string)$this->request['mode']; $html = ''; -switch($mode) -{ - case 'check_name': - $username = clean_username($this->request['username']); +switch ($mode) { + case 'check_name': + $username = clean_username($this->request['username']); - if (empty($username)) - { - $html = ' '. $lang['CHOOSE_A_NAME'] .''; - } - elseif($err = validate_username($username)) - { - $html = ' '. $err .''; - } - break; + if (empty($username)) { + $html = ' ' . $lang['CHOOSE_A_NAME'] . ''; + } elseif ($err = validate_username($username)) { + $html = ' ' . $err . ''; + } + break; - case 'check_email': - $email = (string) $this->request['email']; + case 'check_email': + $email = (string)$this->request['email']; - if (empty($email)) - { - $html = ' '. $lang['CHOOSE_E_MAIL'] .''; - } - elseif($err = validate_email($email)) - { - $html = ' '. $err .''; - } - break; + if (empty($email)) { + $html = ' ' . $lang['CHOOSE_E_MAIL'] . ''; + } elseif ($err = validate_email($email)) { + $html = ' ' . $err . ''; + } + break; - case 'check_pass': - $pass = (string) $this->request['pass']; - $pass_confirm = (string) $this->request['pass_confirm']; - if (empty($pass) || empty($pass_confirm)) - { - $html = ' '. $lang['CHOOSE_PASS'] .''; - } - else - { - if ($pass != $pass_confirm) - { - $html = ' '. $lang['CHOOSE_PASS_ERR'] .''; - } - else - { - if (mb_strlen($pass, 'UTF-8') > 20) - { - $html = ' '. sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) .''; - } - elseif (mb_strlen($pass, 'UTF-8') < 5) - { - $html = ' '. sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) .''; - } - else - { - $text = (IS_GUEST) ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK']; - $html = ' '. $text .''; - } - } - } - break; + case 'check_pass': + $pass = (string)$this->request['pass']; + $pass_confirm = (string)$this->request['pass_confirm']; + if (empty($pass) || empty($pass_confirm)) { + $html = ' ' . $lang['CHOOSE_PASS'] . ''; + } else { + if ($pass != $pass_confirm) { + $html = ' ' . $lang['CHOOSE_PASS_ERR'] . ''; + } else { + if (mb_strlen($pass, 'UTF-8') > 20) { + $html = ' ' . sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) . ''; + } elseif (mb_strlen($pass, 'UTF-8') < 5) { + $html = ' ' . sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) . ''; + } else { + $text = (IS_GUEST) ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK']; + $html = ' ' . $text . ''; + } + } + } + break; } $this->response['html'] = $html; -$this->response['mode'] = $mode; \ No newline at end of file +$this->response['mode'] = $mode; diff --git a/library/ajax/view_post.php b/library/ajax/view_post.php index 2f0415b7a..bc263f815 100644 --- a/library/ajax/view_post.php +++ b/library/ajax/view_post.php @@ -1,15 +1,39 @@ request['post_id']; -$topic_id = (int) @$this->request['topic_id']; +$post_id = (int)@$this->request['post_id']; +$topic_id = (int)@$this->request['topic_id']; -if (!$post_id) -{ - $post_id = DB()->fetch_row("SELECT topic_first_post_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id", 'topic_first_post_id'); +if (!$post_id) { + $post_id = DB()->fetch_row("SELECT topic_first_post_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id", 'topic_first_post_id'); } $sql = " @@ -17,37 +41,31 @@ $sql = " p.*, h.post_html, IF(h.post_html IS NULL, pt.post_text, NULL) AS post_text, f.auth_read - FROM ". BB_POSTS ." p - INNER JOIN ". BB_POSTS_TEXT ." pt ON(pt.post_id = p.post_id) - LEFT JOIN ". BB_POSTS_HTML ." h ON(h.post_id = pt.post_id) - INNER JOIN ". BB_FORUMS ." f ON(f.forum_id = p.forum_id) + FROM " . BB_POSTS . " p + INNER JOIN " . BB_POSTS_TEXT . " pt ON(pt.post_id = p.post_id) + LEFT JOIN " . BB_POSTS_HTML . " h ON(h.post_id = pt.post_id) + INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = p.forum_id) WHERE p.post_id = $post_id LIMIT 1 "; -if (!$post_data = DB()->fetch_row($sql)) -{ - $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); +if (!$post_data = DB()->fetch_row($sql)) { + $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); } // Auth check -if ($post_data['auth_read'] == AUTH_REG) -{ - if (IS_GUEST) - { - $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); - } -} -elseif ($post_data['auth_read'] != AUTH_ALL) -{ - $is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data); - if (!$is_auth['auth_read']) - { - $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); - } +if ($post_data['auth_read'] == AUTH_REG) { + if (IS_GUEST) { + $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); + } +} elseif ($post_data['auth_read'] != AUTH_ALL) { + $is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data); + if (!$is_auth['auth_read']) { + $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); + } } -$this->response['post_id'] = $post_id; -$this->response['topic_id'] = $topic_id; -$this->response['post_html'] = get_parsed_post($post_data); \ No newline at end of file +$this->response['post_id'] = $post_id; +$this->response['topic_id'] = $topic_id; +$this->response['post_html'] = get_parsed_post($post_data); diff --git a/library/ajax/view_torrent.php b/library/ajax/view_torrent.php index 8100dfb41..30a0d72e2 100644 --- a/library/ajax/view_torrent.php +++ b/library/ajax/view_torrent.php @@ -1,186 +1,190 @@ request['attach_id'])) -{ - $this->ajax_die($lang['EMPTY_ATTACH_ID']); +if (!isset($this->request['attach_id'])) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); } -$attach_id = (int) $this->request['attach_id']; +$attach_id = (int)$this->request['attach_id']; global $bnc_error; $bnc_error = 0; -$torrent = DB()->fetch_row("SELECT at.attach_id, at.physical_filename FROM ". BB_ATTACHMENTS_DESC ." at WHERE at.attach_id = $attach_id LIMIT 1"); -if (!$torrent) $this->ajax_die($lang['EMPTY_ATTACH_ID']); -$filename = get_attachments_dir() .'/'. $torrent['physical_filename']; +$torrent = DB()->fetch_row("SELECT at.attach_id, at.physical_filename FROM " . BB_ATTACHMENTS_DESC . " at WHERE at.attach_id = $attach_id LIMIT 1"); +if (!$torrent) { + $this->ajax_die($lang['EMPTY_ATTACH_ID']); +} +$filename = get_attachments_dir() . '/' . $torrent['physical_filename']; -if (($file_contents = @file_get_contents($filename)) === false) -{ - if (IS_AM) - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] ."\n\n". htmlCHR($filename)); - } - else - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT']); - } +if (($file_contents = @file_get_contents($filename)) === false) { + if (IS_AM) { + $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] . "\n\n" . htmlCHR($filename)); + } else { + $this->ajax_die($lang['ERROR_NO_ATTACHMENT']); + } } // Построение списка $tor_filelist = build_tor_filelist($file_contents); -function build_tor_filelist ($file_contents) +function build_tor_filelist($file_contents) { - global $lang; + global $lang; - if (!$tor = bdecode($file_contents)) - { - return $lang['TORFILE_INVALID']; - } + if (!$tor = bdecode($file_contents)) { + return $lang['TORFILE_INVALID']; + } - $torrent = new torrent($tor); + $torrent = new torrent($tor); - return $torrent->get_filelist(); + return $torrent->get_filelist(); } class torrent { - public $tor_decoded = array(); - public $files_ary = array('/' => ''); - public $multiple = null; - public $root_dir = ''; - public $files_html = ''; + public $tor_decoded = array(); + public $files_ary = array('/' => ''); + public $multiple = null; + public $root_dir = ''; + public $files_html = ''; - public function __construct ($decoded_file_contents) - { - $this->tor_decoded = $decoded_file_contents; - } + public function __construct($decoded_file_contents) + { + $this->tor_decoded = $decoded_file_contents; + } - public function get_filelist () - { - $this->build_filelist_array(); + public function get_filelist() + { + $this->build_filelist_array(); - if ($this->multiple) - { - if ($this->files_ary['/'] !== '') - { - $this->files_ary = array_merge($this->files_ary, $this->files_ary['/']); - unset($this->files_ary['/']); - } - $filelist = $this->build_filelist_html(); - return "
        {$this->root_dir}
        $filelist"; - } - else - { - return join('', $this->files_ary['/']); - } - } + if ($this->multiple) { + if ($this->files_ary['/'] !== '') { + $this->files_ary = array_merge($this->files_ary, $this->files_ary['/']); + unset($this->files_ary['/']); + } + $filelist = $this->build_filelist_html(); + return "
        {$this->root_dir}
        $filelist"; + } else { + return join('', $this->files_ary['/']); + } + } - public function build_filelist_array () - { - $info = $this->tor_decoded['info']; + public function build_filelist_array() + { + $info = $this->tor_decoded['info']; - if (isset($info['name.utf-8'])) - { - $info['name'] =& $info['name.utf-8']; - } + if (isset($info['name.utf-8'])) { + $info['name'] =& $info['name.utf-8']; + } - if (isset($info['files']) && is_array($info['files'])) - { - $this->root_dir = isset($info['name']) ? '../'. clean_tor_dirname($info['name']) : '...'; - $this->multiple = true; + if (isset($info['files']) && is_array($info['files'])) { + $this->root_dir = isset($info['name']) ? '../' . clean_tor_dirname($info['name']) : '...'; + $this->multiple = true; - foreach ($info['files'] as $f) - { - if (isset($f['path.utf-8'])) - { - $f['path'] =& $f['path.utf-8']; - } - if (!isset($f['path']) || !is_array($f['path'])) - { - continue; - } - array_deep($f['path'], 'clean_tor_dirname'); + foreach ($info['files'] as $f) { + if (isset($f['path.utf-8'])) { + $f['path'] =& $f['path.utf-8']; + } + if (!isset($f['path']) || !is_array($f['path'])) { + continue; + } + array_deep($f['path'], 'clean_tor_dirname'); - $length = isset($f['length']) ? (float) $f['length'] : 0; - $subdir_count = count($f['path']) - 1; + $length = isset($f['length']) ? (float)$f['length'] : 0; + $subdir_count = count($f['path']) - 1; - if ($subdir_count > 0) - { - $name = array_pop($f['path']); - $cur_files_ary =& $this->files_ary; + if ($subdir_count > 0) { + $name = array_pop($f['path']); + $cur_files_ary =& $this->files_ary; - for ($i=0,$j=1; $i < $subdir_count; $i++,$j++) - { - $subdir = $f['path'][$i]; + for ($i = 0, $j = 1; $i < $subdir_count; $i++, $j++) { + $subdir = $f['path'][$i]; - if (!isset($cur_files_ary[$subdir])) - { - $cur_files_ary[$subdir] = array(); - } - $cur_files_ary =& $cur_files_ary[$subdir]; + if (!isset($cur_files_ary[$subdir])) { + $cur_files_ary[$subdir] = array(); + } + $cur_files_ary =& $cur_files_ary[$subdir]; - if ($j == $subdir_count) - { - if (is_string($cur_files_ary)) - { - $GLOBALS['bnc_error'] = 1; - break(1); - } - $cur_files_ary[] = $this->build_file_item($name, $length); - } - } - @natsort($cur_files_ary); - } - else - { - $name = $f['path'][0]; - $this->files_ary['/'][] = $this->build_file_item($name, $length); - natsort($this->files_ary['/']); - } - } - } - else - { - $this->multiple = false; - $name = isset($info['name']) ? clean_tor_dirname($info['name']) : ''; - $length = isset($info['length']) ? (float) $info['length'] : 0; + if ($j == $subdir_count) { + if (is_string($cur_files_ary)) { + $GLOBALS['bnc_error'] = 1; + break(1); + } + $cur_files_ary[] = $this->build_file_item($name, $length); + } + } + @natsort($cur_files_ary); + } else { + $name = $f['path'][0]; + $this->files_ary['/'][] = $this->build_file_item($name, $length); + natsort($this->files_ary['/']); + } + } + } else { + $this->multiple = false; + $name = isset($info['name']) ? clean_tor_dirname($info['name']) : ''; + $length = isset($info['length']) ? (float)$info['length'] : 0; - $this->files_ary['/'][] = $this->build_file_item($name, $length); - natsort($this->files_ary['/']); - } - } + $this->files_ary['/'][] = $this->build_file_item($name, $length); + natsort($this->files_ary['/']); + } + } - public function build_file_item ($name, $length) - { - global $bb_cfg, $images, $lang; + public function build_file_item($name, $length) + { + global $bb_cfg, $images, $lang; - $magnet_name = $magnet_ext = ''; + $magnet_name = $magnet_ext = ''; - if ($bb_cfg['magnet_links_enabled']) - { - $magnet_name = ''; - $magnet_ext = ''; - } + if ($bb_cfg['magnet_links_enabled']) { + $magnet_name = ''; + $magnet_ext = ''; + } - return "$name $length $magnet_name $magnet_ext"; - } + return "$name $length $magnet_name $magnet_ext"; + } - public function build_filelist_html () - { - global $html; - return $html->array2html($this->files_ary); - } + public function build_filelist_html() + { + global $html; + return $html->array2html($this->files_ary); + } } -function clean_tor_dirname ($dirname) +function clean_tor_dirname($dirname) { - return str_replace(array('[', ']', '<', '>', "'"), array('[', ']', '<', '>', '''), $dirname); + return str_replace(array('[', ']', '<', '>', "'"), array('[', ']', '<', '>', '''), $dirname); } -if ($bnc_error) $tor_filelist = ''.$lang['ERROR_BUILD'].'

        '.$tor_filelist; +if ($bnc_error) { + $tor_filelist = '' . $lang['ERROR_BUILD'] . '

        ' . $tor_filelist; +} $this->response['html'] = $tor_filelist; diff --git a/library/attach_mod/attachment_mod.php b/library/attach_mod/attachment_mod.php index c6f3eac02..c0ed60289 100644 --- a/library/attach_mod/attachment_mod.php +++ b/library/attach_mod/attachment_mod.php @@ -1,82 +1,97 @@ sql_query($sql))) - { - bb_die('Could not query attachment information'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachment information'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $attach_config[$row['config_name']] = trim($row['config_value']); - } + while ($row = DB()->sql_fetchrow($result)) { + $attach_config[$row['config_name']] = trim($row['config_value']); + } - // We assign the original default board language here, because it gets overwritten later with the users default language - $attach_config['board_lang'] = trim($bb_cfg['default_lang']); + // We assign the original default board language here, because it gets overwritten later with the users default language + $attach_config['board_lang'] = trim($bb_cfg['default_lang']); - return $attach_config; + return $attach_config; } // Get Attachment Config $attach_config = array(); -if (!$attach_config = CACHE('bb_cache')->get('attach_config')) -{ - $attach_config = get_config(); - CACHE('bb_cache')->set('attach_config', $attach_config, 86400); +if (!$attach_config = CACHE('bb_cache')->get('attach_config')) { + $attach_config = get_config(); + CACHE('bb_cache')->set('attach_config', $attach_config, 86400); } -include(ATTACH_DIR .'displaying.php'); -include(ATTACH_DIR .'posting_attachments.php'); +include(ATTACH_DIR . 'displaying.php'); +include(ATTACH_DIR . 'posting_attachments.php'); -$upload_dir = $attach_config['upload_dir']; \ No newline at end of file +$upload_dir = $attach_config['upload_dir']; diff --git a/library/attach_mod/displaying.php b/library/attach_mod/displaying.php index d1c6e3e6e..d4c4fec03 100644 --- a/library/attach_mod/displaying.php +++ b/library/attach_mod/displaying.php @@ -1,6 +1,31 @@ update('attach_extensions'); //get_extension_informations() - $extension_informations = get_extension_informations(); - } - $allowed_extensions = array(); + if (!$extension_informations = get_extension_informations()) { + $extension_informations = $GLOBALS['datastore']->update('attach_extensions'); //get_extension_informations() + $extension_informations = get_extension_informations(); + } + $allowed_extensions = array(); - for ($i = 0, $size = sizeof($extension_informations); $i < $size; $i++) - { - $extension = strtolower(trim($extension_informations[$i]['extension'])); - $allowed_extensions[] = $extension; - $display_categories[$extension] = intval($extension_informations[$i]['cat_id']); - $download_modes[$extension] = intval($extension_informations[$i]['download_mode']); - $upload_icons[$extension] = trim($extension_informations[$i]['upload_icon']); - } + for ($i = 0, $size = sizeof($extension_informations); $i < $size; $i++) { + $extension = strtolower(trim($extension_informations[$i]['extension'])); + $allowed_extensions[] = $extension; + $display_categories[$extension] = intval($extension_informations[$i]['cat_id']); + $download_modes[$extension] = intval($extension_informations[$i]['download_mode']); + $upload_icons[$extension] = trim($extension_informations[$i]['upload_icon']); + } } /** -* Writing Data into plain Template Vars -*/ + * Writing Data into plain Template Vars + */ function init_display_template($template_var, $replacement, $filename = 'viewtopic_attach.tpl') { - global $template; + global $template; - // This function is adapted from the old template class - // I wish i had the functions from the 3.x one. :D (This class rocks, can't await to use it in Mods) + // This function is adapted from the old template class + // I wish i had the functions from the 3.x one. :D (This class rocks, can't await to use it in Mods) - // Handle Attachment Informations - if (!isset($template->uncompiled_code[$template_var]) && empty($template->uncompiled_code[$template_var])) - { - // If we don't have a file assigned to this handle, die. - if (!isset($template->files[$template_var])) - { - die("Template->loadfile(): No file specified for handle $template_var"); - } + // Handle Attachment Informations + if (!isset($template->uncompiled_code[$template_var]) && empty($template->uncompiled_code[$template_var])) { + // If we don't have a file assigned to this handle, die. + if (!isset($template->files[$template_var])) { + die("Template->loadfile(): No file specified for handle $template_var"); + } - $filename_2 = $template->files[$template_var]; + $filename_2 = $template->files[$template_var]; - $str = implode('', @file($filename_2)); - if (empty($str)) - { - die("Template->loadfile(): File $filename_2 for handle $template_var is empty"); - } + $str = implode('', @file($filename_2)); + if (empty($str)) { + die("Template->loadfile(): File $filename_2 for handle $template_var is empty"); + } - $template->uncompiled_code[$template_var] = $str; - } + $template->uncompiled_code[$template_var] = $str; + } - $complete_filename = $filename; - if (substr($complete_filename, 0, 1) != '/') - { - $complete_filename = $template->root . '/' . $complete_filename; - } + $complete_filename = $filename; + if (substr($complete_filename, 0, 1) != '/') { + $complete_filename = $template->root . '/' . $complete_filename; + } - if (!file_exists($complete_filename)) - { - die("Template->make_filename(): Error - file $complete_filename does not exist"); - } + if (!file_exists($complete_filename)) { + die("Template->make_filename(): Error - file $complete_filename does not exist"); + } - $content = implode('', file($complete_filename)); - if (empty($content)) - { - die('Template->loadfile(): File ' . $complete_filename . ' is empty'); - } + $content = implode('', file($complete_filename)); + if (empty($content)) { + die('Template->loadfile(): File ' . $complete_filename . ' is empty'); + } - // replace $replacement with uncompiled code in $filename - $template->uncompiled_code[$template_var] = str_replace($replacement, $content, $template->uncompiled_code[$template_var]); + // replace $replacement with uncompiled code in $filename + $template->uncompiled_code[$template_var] = str_replace($replacement, $content, $template->uncompiled_code[$template_var]); } /** -* Display Attachments in Posts -*/ + * Display Attachments in Posts + */ function display_post_attachments($post_id, $switch_attachment) { - global $attach_config, $is_auth; + global $attach_config, $is_auth; - if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod'])) - { - return; - } + if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod'])) { + return; + } - if ($is_auth['auth_download'] && $is_auth['auth_view']) - { - display_attachments($post_id); - } + if ($is_auth['auth_download'] && $is_auth['auth_view']) { + display_attachments($post_id); + } } /** -* Initializes some templating variables for displaying Attachments in Posts -*/ + * Initializes some templating variables for displaying Attachments in Posts + */ function init_display_post_attachments($switch_attachment) { - global $attach_config, $is_auth, $template, $lang, $postrow, $total_posts, $attachments, $forum_row, $t_data; + global $attach_config, $is_auth, $template, $lang, $postrow, $total_posts, $attachments, $forum_row, $t_data; - if (empty($t_data) && !empty($forum_row)) - { - $switch_attachment = $forum_row['topic_attachment']; - } + if (empty($t_data) && !empty($forum_row)) { + $switch_attachment = $forum_row['topic_attachment']; + } - if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod']) || (!($is_auth['auth_download'] && $is_auth['auth_view']))) - { - init_display_template('body', '{postrow.ATTACHMENTS}', 'viewtopic_attach_guest.tpl'); - return; - } + if (intval($switch_attachment) == 0 || intval($attach_config['disable_mod']) || (!($is_auth['auth_download'] && $is_auth['auth_view']))) { + init_display_template('body', '{postrow.ATTACHMENTS}', 'viewtopic_attach_guest.tpl'); + return; + } - $post_id_array = array(); + $post_id_array = array(); - for ($i = 0; $i < $total_posts; $i++) - { - if ($postrow[$i]['post_attachment'] == 1) - { - $post_id_array[] = (int) $postrow[$i]['post_id']; - } - } + for ($i = 0; $i < $total_posts; $i++) { + if ($postrow[$i]['post_attachment'] == 1) { + $post_id_array[] = (int)$postrow[$i]['post_id']; + } + } - if (sizeof($post_id_array) == 0) - { - return; - } + if (sizeof($post_id_array) == 0) { + return; + } - $rows = get_attachments_from_post($post_id_array); - $num_rows = sizeof($rows); + $rows = get_attachments_from_post($post_id_array); + $num_rows = sizeof($rows); - if ($num_rows == 0) - { - return; - } + if ($num_rows == 0) { + return; + } - @reset($attachments); + @reset($attachments); - for ($i = 0; $i < $num_rows; $i++) - { - $attachments['_' . $rows[$i]['post_id']][] = $rows[$i]; - //bt - if ($rows[$i]['tracker_status']) - { - if (defined('TORRENT_POST')) - { - bb_die('Multiple registered torrents in one topic

        first torrent found in post_id = '. TORRENT_POST .'
        current post_id = '. $rows[$i]['post_id'] .'

        attachments info:
        '. print_r($rows, TRUE) .'
        '); - } - define('TORRENT_POST', $rows[$i]['post_id']); - } - //bt end - } + for ($i = 0; $i < $num_rows; $i++) { + $attachments['_' . $rows[$i]['post_id']][] = $rows[$i]; + //bt + if ($rows[$i]['tracker_status']) { + if (defined('TORRENT_POST')) { + bb_die('Multiple registered torrents in one topic

        first torrent found in post_id = ' . TORRENT_POST . '
        current post_id = ' . $rows[$i]['post_id'] . '

        attachments info:
        ' . print_r($rows, true) . '
        '); + } + define('TORRENT_POST', $rows[$i]['post_id']); + } + //bt end + } - init_display_template('body', '{postrow.ATTACHMENTS}'); + init_display_template('body', '{postrow.ATTACHMENTS}'); - init_complete_extensions_data(); + init_complete_extensions_data(); } /** -* END ATTACHMENT DISPLAY IN POSTS -*/ + * END ATTACHMENT DISPLAY IN POSTS + */ /** -* Assign Variables and Definitions based on the fetched Attachments - internal -* used by all displaying functions, the Data was collected before, it's only dependend on the template used. :) -* before this function is usable, init_display_attachments have to be called for specific pages (pm, posting, review etc...) -*/ + * Assign Variables and Definitions based on the fetched Attachments - internal + * used by all displaying functions, the Data was collected before, it's only dependend on the template used. :) + * before this function is usable, init_display_attachments have to be called for specific pages (pm, posting, review etc...) + */ function display_attachments($post_id) { - global $template, $upload_dir, $userdata, $allowed_extensions, $display_categories, $download_modes, $lang, $attachments, $upload_icons, $attach_config; + global $template, $upload_dir, $userdata, $allowed_extensions, $display_categories, $download_modes, $lang, $attachments, $upload_icons, $attach_config; - $num_attachments = @sizeof($attachments['_' . $post_id]); + $num_attachments = @sizeof($attachments['_' . $post_id]); - if ($num_attachments == 0) - { - return; - } + if ($num_attachments == 0) { + return; + } - $template->assign_block_vars('postrow.attach', array()); + $template->assign_block_vars('postrow.attach', array()); - for ($i = 0; $i < $num_attachments; $i++) - { - // Some basic things... - $filename = $upload_dir . '/' . basename($attachments['_' . $post_id][$i]['physical_filename']); - $thumbnail_filename = $upload_dir . '/' . THUMB_DIR . '/t_' . basename($attachments['_' . $post_id][$i]['physical_filename']); + for ($i = 0; $i < $num_attachments; $i++) { + // Some basic things... + $filename = $upload_dir . '/' . basename($attachments['_' . $post_id][$i]['physical_filename']); + $thumbnail_filename = $upload_dir . '/' . THUMB_DIR . '/t_' . basename($attachments['_' . $post_id][$i]['physical_filename']); - $upload_image = ''; + $upload_image = ''; - if ($attach_config['upload_img'] && empty($upload_icons[$attachments['_' . $post_id][$i]['extension']])) - { - $upload_image = ''; - } - else if (trim($upload_icons[$attachments['_' . $post_id][$i]['extension']]) != '') - { - $upload_image = ''; - } + if ($attach_config['upload_img'] && empty($upload_icons[$attachments['_' . $post_id][$i]['extension']])) { + $upload_image = ''; + } elseif (trim($upload_icons[$attachments['_' . $post_id][$i]['extension']]) != '') { + $upload_image = ''; + } - $filesize = humn_size($attachments['_' . $post_id][$i]['filesize']); + $filesize = humn_size($attachments['_' . $post_id][$i]['filesize']); - $display_name = htmlspecialchars($attachments['_' . $post_id][$i]['real_filename']); - $comment = htmlspecialchars($attachments['_' . $post_id][$i]['comment']); - $comment = str_replace("\n", '
        ', $comment); + $display_name = htmlspecialchars($attachments['_' . $post_id][$i]['real_filename']); + $comment = htmlspecialchars($attachments['_' . $post_id][$i]['comment']); + $comment = str_replace("\n", '
        ', $comment); - $denied = false; + $denied = false; - // Admin is allowed to view forbidden Attachments, but the error-message is displayed too to inform the Admin - if (!in_array($attachments['_' . $post_id][$i]['extension'], $allowed_extensions)) - { - $denied = true; + // Admin is allowed to view forbidden Attachments, but the error-message is displayed too to inform the Admin + if (!in_array($attachments['_' . $post_id][$i]['extension'], $allowed_extensions)) { + $denied = true; - $template->assign_block_vars('postrow.attach.denyrow', array( - 'L_DENIED' => sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachments['_' . $post_id][$i]['extension'])) - ); - } + $template->assign_block_vars('postrow.attach.denyrow', array( + 'L_DENIED' => sprintf($lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachments['_' . $post_id][$i]['extension'])) + ); + } - if (!$denied || IS_ADMIN) - { - // define category - $image = FALSE; - $thumbnail = FALSE; - $link = FALSE; + if (!$denied || IS_ADMIN) { + // define category + $image = false; + $thumbnail = false; + $link = false; - if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && intval($attach_config['img_display_inlined'])) - { - if (intval($attach_config['img_link_width']) != 0 || intval($attach_config['img_link_height']) != 0) - { - list($width, $height) = image_getdimension($filename); + if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && intval($attach_config['img_display_inlined'])) { + if (intval($attach_config['img_link_width']) != 0 || intval($attach_config['img_link_height']) != 0) { + list($width, $height) = image_getdimension($filename); - if ($width == 0 && $height == 0) - { - $image = TRUE; - } - else - { - if ($width <= intval($attach_config['img_link_width']) && $height <= intval($attach_config['img_link_height'])) - { - $image = TRUE; - } - } - } - else - { - $image = TRUE; - } - } + if ($width == 0 && $height == 0) { + $image = true; + } else { + if ($width <= intval($attach_config['img_link_width']) && $height <= intval($attach_config['img_link_height'])) { + $image = true; + } + } + } else { + $image = true; + } + } - if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && $attachments['_' . $post_id][$i]['thumbnail'] == 1) - { - $thumbnail = TRUE; - $image = FALSE; - } + if (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT && $attachments['_' . $post_id][$i]['thumbnail'] == 1) { + $thumbnail = true; + $image = false; + } - if (!$image && !$thumbnail) - { - $link = TRUE; - } + if (!$image && !$thumbnail) { + $link = true; + } - if ($image) - { - // Images - if ($attach_config['upload_dir'][0] == '/' || ( $attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $img_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id']; - $download_link = TRUE; - } - else - { - $img_source = $filename; - $download_link = FALSE; - } + if ($image) { + // Images + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $img_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id']; + $download_link = true; + } else { + $img_source = $filename; + $download_link = false; + } - $template->assign_block_vars('postrow.attach.cat_images', array( - 'DOWNLOAD_NAME' => $display_name, - 'S_UPLOAD_IMAGE' => $upload_image, - 'IMG_SRC' => $img_source, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - )); + $template->assign_block_vars('postrow.attach.cat_images', array( + 'DOWNLOAD_NAME' => $display_name, + 'S_UPLOAD_IMAGE' => $upload_image, + 'IMG_SRC' => $img_source, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment, + )); - // Directly Viewed Image ... update the download count - if (!$download_link) - { - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' + // Directly Viewed Image ... update the download count + if (!$download_link) { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET download_count = download_count + 1 - WHERE attach_id = ' . (int) $attachments['_' . $post_id][$i]['attach_id']; + WHERE attach_id = ' . (int)$attachments['_' . $post_id][$i]['attach_id']; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not update attachment download count'); - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not update attachment download count'); + } + } + } - if ($thumbnail) - { - // Images, but display Thumbnail - if ($attach_config['upload_dir'][0] == '/' || ( $attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $thumb_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'] . '&thumb=1'; - } - else - { - $thumb_source = $thumbnail_filename; - } + if ($thumbnail) { + // Images, but display Thumbnail + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $thumb_source = BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'] . '&thumb=1'; + } else { + $thumb_source = $thumbnail_filename; + } - $template->assign_block_vars('postrow.attach.cat_thumb_images', array( - 'DOWNLOAD_NAME' => $display_name, - 'S_UPLOAD_IMAGE' => $upload_image, - 'IMG_SRC' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], - 'IMG_THUMB_SRC' => $thumb_source, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - )); - } + $template->assign_block_vars('postrow.attach.cat_thumb_images', array( + 'DOWNLOAD_NAME' => $display_name, + 'S_UPLOAD_IMAGE' => $upload_image, + 'IMG_SRC' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], + 'IMG_THUMB_SRC' => $thumb_source, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment, + )); + } - // bt - if ($link && ($attachments['_'. $post_id][$i]['extension'] === TORRENT_EXT)) - { - include(ATTACH_DIR .'displaying_torrent.php'); - } - else if ($link) - { - $target_blank = ( (@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT) ) ? 'target="_blank"' : ''; + // bt + if ($link && ($attachments['_' . $post_id][$i]['extension'] === TORRENT_EXT)) { + include(ATTACH_DIR . 'displaying_torrent.php'); + } elseif ($link) { + $target_blank = ((@intval($display_categories[$attachments['_' . $post_id][$i]['extension']]) == IMAGE_CAT)) ? 'target="_blank"' : ''; - // display attachment - $template->assign_block_vars('postrow.attach.attachrow', array( - 'U_DOWNLOAD_LINK' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], - 'S_UPLOAD_IMAGE' => $upload_image, - 'DOWNLOAD_NAME' => $display_name, - 'FILESIZE' => $filesize, - 'COMMENT' => $comment, - 'TARGET_BLANK' => $target_blank, - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $attachments['_' . $post_id][$i]['download_count']), - )); - } - } - } -} \ No newline at end of file + // display attachment + $template->assign_block_vars('postrow.attach.attachrow', array( + 'U_DOWNLOAD_LINK' => BB_ROOT . DOWNLOAD_URL . $attachments['_' . $post_id][$i]['attach_id'], + 'S_UPLOAD_IMAGE' => $upload_image, + 'DOWNLOAD_NAME' => $display_name, + 'FILESIZE' => $filesize, + 'COMMENT' => $comment, + 'TARGET_BLANK' => $target_blank, + 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $attachments['_' . $post_id][$i]['download_count']), + )); + } + } + } +} diff --git a/library/attach_mod/displaying_torrent.php b/library/attach_mod/displaying_torrent.php index 4373939a7..2acd53104 100644 --- a/library/attach_mod/displaying_torrent.php +++ b/library/attach_mod/displaying_torrent.php @@ -1,32 +1,57 @@ '; +$peers_div_style_normal = 'padding: 3px;'; +$peers_div_style_overflow = "padding: 6px; height: $peers_overflow_div_height; overflow: auto; border: 1px inset;"; +$s_last_seed_date_format = 'Y-m-d'; +$upload_image = '' . $lang['DL_TORRENT'] . ''; $peers_cnt = $seed_count = 0; $seeders = $leechers = ''; $tor_info = array(); $template->assign_vars(array( - 'SEED_COUNT' => false, - 'LEECH_COUNT' => false, - 'TOR_SPEED_UP' => false, - 'TOR_SPEED_DOWN' => false, - 'SHOW_RATIO_WARN' => false, + 'SEED_COUNT' => false, + 'LEECH_COUNT' => false, + 'TOR_SPEED_UP' => false, + 'TOR_SPEED_DOWN' => false, + 'SHOW_RATIO_WARN' => false, )); // Define show peers mode (count only || user names with complete % || full details) @@ -35,37 +60,30 @@ $get_sp_mode = (isset($_GET['spmode'])) ? $_GET['spmode'] : ''; $s_mode = 'count'; -if ($cfg_sp_mode == SHOW_PEERS_NAMES) -{ - $s_mode = 'names'; -} -else if ($cfg_sp_mode == SHOW_PEERS_FULL) -{ - $s_mode = 'full'; +if ($cfg_sp_mode == SHOW_PEERS_NAMES) { + $s_mode = 'names'; +} elseif ($cfg_sp_mode == SHOW_PEERS_FULL) { + $s_mode = 'full'; } -if ($bb_cfg['bt_allow_spmode_change']) -{ - if ($get_sp_mode == 'names') - { - $s_mode = 'names'; - } - else if ($get_sp_mode == 'full') - { - $s_mode = 'full'; - } +if ($bb_cfg['bt_allow_spmode_change']) { + if ($get_sp_mode == 'names') { + $s_mode = 'names'; + } elseif ($get_sp_mode == 'full') { + $s_mode = 'full'; + } } -$bt_topic_id = $t_data['topic_id']; -$bt_user_id = $userdata['user_id']; -$attach_id = $attachments['_'. $post_id][$i]['attach_id']; -$tracker_status = $attachments['_'. $post_id][$i]['tracker_status']; -$download_count = $attachments['_'. $post_id][$i]['download_count']; -$tor_file_size = humn_size($attachments['_'. $post_id][$i]['filesize']); -$tor_file_time = bb_date($attachments['_'. $post_id][$i]['filetime']); +$bt_topic_id = $t_data['topic_id']; +$bt_user_id = $userdata['user_id']; +$attach_id = $attachments['_' . $post_id][$i]['attach_id']; +$tracker_status = $attachments['_' . $post_id][$i]['tracker_status']; +$download_count = $attachments['_' . $post_id][$i]['download_count']; +$tor_file_size = humn_size($attachments['_' . $post_id][$i]['filesize']); +$tor_file_time = bb_date($attachments['_' . $post_id][$i]['filetime']); -$tor_reged = (bool) $tracker_status; -$show_peers = (bool) $bb_cfg['bt_show_peers']; +$tor_reged = (bool)$tracker_status; +$show_peers = (bool)$bb_cfg['bt_show_peers']; $locked = ($t_data['forum_status'] == FORUM_LOCKED || $t_data['topic_status'] == TOPIC_LOCKED); $tor_auth = ($bt_user_id != GUEST_UID && (($bt_user_id == $poster_id && !$locked) || $is_auth['auth_mod'])); @@ -73,532 +91,462 @@ $tor_auth = ($bt_user_id != GUEST_UID && (($bt_user_id == $poster_id && !$locked $tor_auth_reg = ($tor_auth && $t_data['allow_reg_tracker'] && $post_id == $t_data['topic_first_post_id']); $tor_auth_del = ($tor_auth && $tor_reged); -$tracker_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; +$tracker_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; $download_link = DOWNLOAD_URL . $attach_id; -$description = ($comment) ? $comment : preg_replace("#.torrent$#i", '', $display_name); +$description = ($comment) ? $comment : preg_replace("#.torrent$#i", '', $display_name); -if ($tor_auth_reg || $tor_auth_del) -{ - $reg_tor_url = ''. $lang['BT_REG_ON_TRACKER'] .''; - $unreg_tor_url = ''. $lang['BT_UNREG_FROM_TRACKER'] .''; +if ($tor_auth_reg || $tor_auth_del) { + $reg_tor_url = '' . $lang['BT_REG_ON_TRACKER'] . ''; + $unreg_tor_url = '' . $lang['BT_UNREG_FROM_TRACKER'] . ''; - $tracker_link = ($tor_reged) ? $unreg_tor_url : $reg_tor_url; + $tracker_link = ($tor_reged) ? $unreg_tor_url : $reg_tor_url; } -if ($bb_cfg['torrent_name_style']) -{ - $display_name = '['.$bb_cfg['server_name'].'].t' . $bt_topic_id . '.torrent'; +if ($bb_cfg['torrent_name_style']) { + $display_name = '[' . $bb_cfg['server_name'] . '].t' . $bt_topic_id . '.torrent'; } -if (!$tor_reged) -{ - $template->assign_block_vars('postrow.attach.tor_not_reged', array( - 'DOWNLOAD_NAME' => $display_name, - 'TRACKER_LINK' => $tracker_link, - 'ATTACH_ID' => $attach_id, +if (!$tor_reged) { + $template->assign_block_vars('postrow.attach.tor_not_reged', array( + 'DOWNLOAD_NAME' => $display_name, + 'TRACKER_LINK' => $tracker_link, + 'ATTACH_ID' => $attach_id, - 'S_UPLOAD_IMAGE' => $upload_image, - 'U_DOWNLOAD_LINK' => $download_link, - 'FILESIZE' => $tor_file_size, + 'S_UPLOAD_IMAGE' => $upload_image, + 'U_DOWNLOAD_LINK' => $download_link, + 'FILESIZE' => $tor_file_size, - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), - 'POSTED_TIME' => $tor_file_time, - )); + 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), + 'POSTED_TIME' => $tor_file_time, + )); - if ($comment) - { - $template->assign_block_vars('postrow.attach.tor_not_reged.comment', array('COMMENT' => $comment)); - } -} -else -{ - $sql = "SELECT bt.*, u.user_id, u.username, u.user_rank - FROM ". BB_BT_TORRENTS ." bt - LEFT JOIN ". BB_USERS ." u ON(bt.checked_user_id = u.user_id) + if ($comment) { + $template->assign_block_vars('postrow.attach.tor_not_reged.comment', array('COMMENT' => $comment)); + } +} else { + $sql = "SELECT bt.*, u.user_id, u.username, u.user_rank + FROM " . BB_BT_TORRENTS . " bt + LEFT JOIN " . BB_USERS . " u ON(bt.checked_user_id = u.user_id) WHERE bt.attach_id = $attach_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain torrent information'); - } - $tor_info = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain torrent information'); + } + $tor_info = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); } -if ($tor_reged && !$tor_info) -{ - DB()->query("UPDATE ". BB_ATTACHMENTS_DESC ." SET tracker_status = 0 WHERE attach_id = $attach_id"); +if ($tor_reged && !$tor_info) { + DB()->query("UPDATE " . BB_ATTACHMENTS_DESC . " SET tracker_status = 0 WHERE attach_id = $attach_id"); - bb_die('Torrent status fixed'); + bb_die('Torrent status fixed'); } -if ($tor_auth) -{ - $template->assign_vars(array( - 'TOR_CONTROLS' => true, - 'TOR_ATTACH_ID' => $attach_id, - )); +if ($tor_auth) { + $template->assign_vars(array( + 'TOR_CONTROLS' => true, + 'TOR_ATTACH_ID' => $attach_id, + )); - if ($t_data['self_moderated'] || $is_auth['auth_mod']) - { - $template->assign_vars(array('AUTH_MOVE' => true)); - } + if ($t_data['self_moderated'] || $is_auth['auth_mod']) { + $template->assign_vars(array('AUTH_MOVE' => true)); + } } -if ($tor_reged && $tor_info) -{ - $tor_size = ($tor_info['size']) ? $tor_info['size'] : 0; - $tor_id = $tor_info['topic_id']; - $tor_type = $tor_info['tor_type']; +if ($tor_reged && $tor_info) { + $tor_size = ($tor_info['size']) ? $tor_info['size'] : 0; + $tor_id = $tor_info['topic_id']; + $tor_type = $tor_info['tor_type']; - // Magnet link - $passkey = DB()->fetch_row("SELECT auth_key FROM ". BB_BT_USERS ." WHERE user_id = ". (int) $bt_user_id ." LIMIT 1"); - $tor_magnet = create_magnet($tor_info['info_hash'], $passkey['auth_key'], $userdata['session_logged_in']); + // Magnet link + $passkey = DB()->fetch_row("SELECT auth_key FROM " . BB_BT_USERS . " WHERE user_id = " . (int)$bt_user_id . " LIMIT 1"); + $tor_magnet = create_magnet($tor_info['info_hash'], $passkey['auth_key'], $userdata['session_logged_in']); - // ratio limits - $min_ratio_dl = $bb_cfg['bt_min_ratio_allow_dl_tor']; - $min_ratio_warn = $bb_cfg['bt_min_ratio_warning']; - $dl_allowed = true; - $user_ratio = 0; + // ratio limits + $min_ratio_dl = $bb_cfg['bt_min_ratio_allow_dl_tor']; + $min_ratio_warn = $bb_cfg['bt_min_ratio_warning']; + $dl_allowed = true; + $user_ratio = 0; - if (($min_ratio_dl || $min_ratio_warn) && $bt_user_id != $poster_id) - { - $sql = "SELECT u.*, dl.user_status - FROM ". BB_BT_USERS ." u - LEFT JOIN ". BB_BT_DLSTATUS ." dl ON dl.user_id = $bt_user_id AND dl.topic_id = $bt_topic_id + if (($min_ratio_dl || $min_ratio_warn) && $bt_user_id != $poster_id) { + $sql = "SELECT u.*, dl.user_status + FROM " . BB_BT_USERS . " u + LEFT JOIN " . BB_BT_DLSTATUS . " dl ON dl.user_id = $bt_user_id AND dl.topic_id = $bt_topic_id WHERE u.user_id = $bt_user_id LIMIT 1"; - } - else - { - $sql = "SELECT user_status - FROM ". BB_BT_DLSTATUS ." + } else { + $sql = "SELECT user_status + FROM " . BB_BT_DLSTATUS . " WHERE user_id = $bt_user_id AND topic_id = $bt_topic_id LIMIT 1"; - } + } - $bt_userdata = DB()->fetch_row($sql); + $bt_userdata = DB()->fetch_row($sql); - $user_status = isset($bt_userdata['user_status']) ? $bt_userdata['user_status'] : null; + $user_status = isset($bt_userdata['user_status']) ? $bt_userdata['user_status'] : null; - if (($min_ratio_dl || $min_ratio_warn) && $user_status != DL_STATUS_COMPLETE && $bt_user_id != $poster_id && $tor_type != TOR_TYPE_GOLD) - { - if (($user_ratio = get_bt_ratio($bt_userdata)) !== null) - { - $dl_allowed = ($user_ratio > $min_ratio_dl); - } + if (($min_ratio_dl || $min_ratio_warn) && $user_status != DL_STATUS_COMPLETE && $bt_user_id != $poster_id && $tor_type != TOR_TYPE_GOLD) { + if (($user_ratio = get_bt_ratio($bt_userdata)) !== null) { + $dl_allowed = ($user_ratio > $min_ratio_dl); + } - if ((isset($user_ratio) && isset($min_ratio_warn) && $user_ratio < $min_ratio_warn && TR_RATING_LIMITS) || ($bt_userdata['u_down_total'] < MIN_DL_FOR_RATIO)) - { - $template->assign_vars(array( - 'SHOW_RATIO_WARN' => true, - 'RATIO_WARN_MSG' => sprintf($lang['BT_RATIO_WARNING_MSG'], $min_ratio_dl, $bb_cfg['ratio_url_help']), - )); - } - } + if ((isset($user_ratio) && isset($min_ratio_warn) && $user_ratio < $min_ratio_warn && TR_RATING_LIMITS) || ($bt_userdata['u_down_total'] < MIN_DL_FOR_RATIO)) { + $template->assign_vars(array( + 'SHOW_RATIO_WARN' => true, + 'RATIO_WARN_MSG' => sprintf($lang['BT_RATIO_WARNING_MSG'], $min_ratio_dl, $bb_cfg['ratio_url_help']), + )); + } + } - if (!$dl_allowed) - { - $template->assign_block_vars('postrow.attach.tor_reged', array()); - $template->assign_vars(array( - 'TOR_BLOCKED' => true, - 'TOR_BLOCKED_MSG' => sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$bt_user_id&dlc=1"), - )); - } - else - { - $template->assign_block_vars('postrow.attach.tor_reged', array( - 'DOWNLOAD_NAME' => $display_name, - 'TRACKER_LINK' => $tracker_link, - 'ATTACH_ID' => $attach_id, - 'TOR_SILVER_GOLD' => $tor_type, + if (!$dl_allowed) { + $template->assign_block_vars('postrow.attach.tor_reged', array()); + $template->assign_vars(array( + 'TOR_BLOCKED' => true, + 'TOR_BLOCKED_MSG' => sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$bt_user_id&dlc=1"), + )); + } else { + $template->assign_block_vars('postrow.attach.tor_reged', array( + 'DOWNLOAD_NAME' => $display_name, + 'TRACKER_LINK' => $tracker_link, + 'ATTACH_ID' => $attach_id, + 'TOR_SILVER_GOLD' => $tor_type, - // torrent status mod - 'TOR_FROZEN' => (!IS_AM) ? (isset($bb_cfg['tor_frozen'][$tor_info['tor_status']]) && !(isset($bb_cfg['tor_frozen_author_download'][$tor_info['tor_status']]) && $userdata['user_id'] == $tor_info['poster_id'])) ? true : '' : '', - 'TOR_STATUS_TEXT' => $lang['TOR_STATUS_NAME'][$tor_info['tor_status']], - 'TOR_STATUS_ICON' => $bb_cfg['tor_icons'][$tor_info['tor_status']], - 'TOR_STATUS_BY' => ($tor_info['checked_user_id'] && $is_auth['auth_mod']) ? (' · '. profile_url($tor_info) .' · '. delta_time($tor_info['checked_time']) . $lang['TOR_BACK'] .'') : '', - 'TOR_STATUS_SELECT' => build_select('sel_status', array_flip($lang['TOR_STATUS_NAME']), TOR_APPROVED), - 'TOR_STATUS_REPLY' => $bb_cfg['tor_comment'] && !IS_GUEST && in_array($tor_info['tor_status'], $bb_cfg['tor_reply']) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, - //end torrent status mod + // torrent status mod + 'TOR_FROZEN' => (!IS_AM) ? (isset($bb_cfg['tor_frozen'][$tor_info['tor_status']]) && !(isset($bb_cfg['tor_frozen_author_download'][$tor_info['tor_status']]) && $userdata['user_id'] == $tor_info['poster_id'])) ? true : '' : '', + 'TOR_STATUS_TEXT' => $lang['TOR_STATUS_NAME'][$tor_info['tor_status']], + 'TOR_STATUS_ICON' => $bb_cfg['tor_icons'][$tor_info['tor_status']], + 'TOR_STATUS_BY' => ($tor_info['checked_user_id'] && $is_auth['auth_mod']) ? (' · ' . profile_url($tor_info) . ' · ' . delta_time($tor_info['checked_time']) . $lang['TOR_BACK'] . '') : '', + 'TOR_STATUS_SELECT' => build_select('sel_status', array_flip($lang['TOR_STATUS_NAME']), TOR_APPROVED), + 'TOR_STATUS_REPLY' => $bb_cfg['tor_comment'] && !IS_GUEST && in_array($tor_info['tor_status'], $bb_cfg['tor_reply']) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, + //end torrent status mod - 'S_UPLOAD_IMAGE' => $upload_image, - 'U_DOWNLOAD_LINK' => $download_link, - 'DL_LINK_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_link_css[$bt_userdata['user_status']] : 'genmed', - 'DL_TITLE_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_status_css[$bt_userdata['user_status']] : 'gen', - 'FILESIZE' => $tor_file_size, - 'MAGNET' => $tor_magnet, - 'HASH' => strtoupper(bin2hex($tor_info['info_hash'])), - 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), - 'REGED_TIME' => bb_date($tor_info['reg_time']), - 'REGED_DELTA' => delta_time($tor_info['reg_time']), - 'TORRENT_SIZE' => humn_size($tor_size), - 'COMPLETED' => sprintf($lang['DOWNLOAD_NUMBER'], $tor_info['complete_count']), - )); + 'S_UPLOAD_IMAGE' => $upload_image, + 'U_DOWNLOAD_LINK' => $download_link, + 'DL_LINK_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_link_css[$bt_userdata['user_status']] : 'genmed', + 'DL_TITLE_CLASS' => (isset($bt_userdata['user_status'])) ? $dl_status_css[$bt_userdata['user_status']] : 'gen', + 'FILESIZE' => $tor_file_size, + 'MAGNET' => $tor_magnet, + 'HASH' => strtoupper(bin2hex($tor_info['info_hash'])), + 'DOWNLOAD_COUNT' => sprintf($lang['DOWNLOAD_NUMBER'], $download_count), + 'REGED_TIME' => bb_date($tor_info['reg_time']), + 'REGED_DELTA' => delta_time($tor_info['reg_time']), + 'TORRENT_SIZE' => humn_size($tor_size), + 'COMPLETED' => sprintf($lang['DOWNLOAD_NUMBER'], $tor_info['complete_count']), + )); - if ($comment) - { - $template->assign_block_vars('postrow.attach.tor_reged.comment', array('COMMENT' => $comment)); - } - } + if ($comment) { + $template->assign_block_vars('postrow.attach.tor_reged.comment', array('COMMENT' => $comment)); + } + } - if ($bb_cfg['show_tor_info_in_dl_list']) - { - $template->assign_vars(array( - 'SHOW_DL_LIST' => true, - 'SHOW_DL_LIST_TOR_INFO' => true, + if ($bb_cfg['show_tor_info_in_dl_list']) { + $template->assign_vars(array( + 'SHOW_DL_LIST' => true, + 'SHOW_DL_LIST_TOR_INFO' => true, - 'TOR_SIZE' => humn_size($tor_size), - 'TOR_LONGEVITY' => delta_time($tor_info['reg_time']), - 'TOR_COMPLETED' => declension($tor_info['complete_count'], 'times'), - )); - } + 'TOR_SIZE' => humn_size($tor_size), + 'TOR_LONGEVITY' => delta_time($tor_info['reg_time']), + 'TOR_COMPLETED' => declension($tor_info['complete_count'], 'times'), + )); + } - // Show peers - if ($show_peers) - { - // Sorting order in full mode - if ($s_mode == 'full') - { - $full_mode_order = 'tr.remain'; - $full_mode_sort_dir = 'ASC'; + // Show peers + if ($show_peers) { + // Sorting order in full mode + if ($s_mode == 'full') { + $full_mode_order = 'tr.remain'; + $full_mode_sort_dir = 'ASC'; - if (isset($_REQUEST['psortasc'])) - { - $full_mode_sort_dir = 'ASC'; - } - else if (isset($_REQUEST['psortdesc'])) - { - $full_mode_sort_dir = 'DESC'; - } + if (isset($_REQUEST['psortasc'])) { + $full_mode_sort_dir = 'ASC'; + } elseif (isset($_REQUEST['psortdesc'])) { + $full_mode_sort_dir = 'DESC'; + } - if (isset($_REQUEST['porder'])) - { - $peer_orders = array( - 'name' => 'u.username', - 'ip' => 'tr.ip', - 'port' => 'tr.port', - 'compl' => 'tr.remain', - 'cup' => 'tr.uploaded', - 'cdown' => 'tr.downloaded', - 'sup' => 'tr.speed_up', - 'sdown' => 'tr.speed_down', - 'time' => 'tr.update_time', - ); + if (isset($_REQUEST['porder'])) { + $peer_orders = array( + 'name' => 'u.username', + 'ip' => 'tr.ip', + 'port' => 'tr.port', + 'compl' => 'tr.remain', + 'cup' => 'tr.uploaded', + 'cdown' => 'tr.downloaded', + 'sup' => 'tr.speed_up', + 'sdown' => 'tr.speed_down', + 'time' => 'tr.update_time', + ); - foreach ($peer_orders as $get_key => $order_by_value) - { - if ($_REQUEST['porder'] == $get_key) - { - $full_mode_order = $order_by_value; - break; - } - } - } - } - // SQL for each mode - if ($s_mode == 'count') - { - $sql = "SELECT seeders, leechers, speed_up, speed_down - FROM ". BB_BT_TRACKER_SNAP ." + foreach ($peer_orders as $get_key => $order_by_value) { + if ($_REQUEST['porder'] == $get_key) { + $full_mode_order = $order_by_value; + break; + } + } + } + } + // SQL for each mode + if ($s_mode == 'count') { + $sql = "SELECT seeders, leechers, speed_up, speed_down + FROM " . BB_BT_TRACKER_SNAP . " WHERE topic_id = $tor_id LIMIT 1"; - } - else if ($s_mode == 'names') - { - $sql = "SELECT tr.user_id, tr.ip, tr.port, tr.remain, tr.seeder, u.username, u.user_rank - FROM ". BB_BT_TRACKER ." tr, ". BB_USERS ." u + } elseif ($s_mode == 'names') { + $sql = "SELECT tr.user_id, tr.ip, tr.port, tr.remain, tr.seeder, u.username, u.user_rank + FROM " . BB_BT_TRACKER . " tr, " . BB_USERS . " u WHERE tr.topic_id = $tor_id AND u.user_id = tr.user_id GROUP BY tr.ip, tr.user_id, tr.port, tr.seeder ORDER BY u.username LIMIT $show_peers_limit"; - } - else - { - $sql = "SELECT + } else { + $sql = "SELECT tr.user_id, tr.ip, tr.port, tr.uploaded, tr.downloaded, tr.remain, tr.seeder, tr.releaser, tr.speed_up, tr.speed_down, tr.update_time, tr.complete_percent, u.username, u.user_rank - FROM ". BB_BT_TRACKER ." tr - LEFT JOIN ". BB_USERS ." u ON u.user_id = tr.user_id + FROM " . BB_BT_TRACKER . " tr + LEFT JOIN " . BB_USERS . " u ON u.user_id = tr.user_id WHERE tr.topic_id = $tor_id GROUP BY tr.ip, tr.user_id, tr.port, tr.seeder ORDER BY $full_mode_order $full_mode_sort_dir LIMIT $show_peers_limit"; - } + } - // Build peers table - if ($peers = DB()->fetch_rowset($sql)) - { - $peers_cnt = count($peers); + // Build peers table + if ($peers = DB()->fetch_rowset($sql)) { + $peers_cnt = count($peers); - $cnt = $tr = $sp_up = $sp_down = $sp_up_tot = $sp_down_tot = array(); - $cnt['s'] = $tr['s'] = $sp_up['s'] = $sp_down['s'] = $sp_up_tot['s'] = $sp_down_tot['s'] = 0; - $cnt['l'] = $tr['l'] = $sp_up['l'] = $sp_down['l'] = $sp_up_tot['l'] = $sp_down_tot['l'] = 0; + $cnt = $tr = $sp_up = $sp_down = $sp_up_tot = $sp_down_tot = array(); + $cnt['s'] = $tr['s'] = $sp_up['s'] = $sp_down['s'] = $sp_up_tot['s'] = $sp_down_tot['s'] = 0; + $cnt['l'] = $tr['l'] = $sp_up['l'] = $sp_down['l'] = $sp_up_tot['l'] = $sp_down_tot['l'] = 0; - $max_up = $max_down = $max_sp_up = $max_sp_down = array(); - $max_up['s'] = $max_down['s'] = $max_sp_up['s'] = $max_sp_down['s'] = 0; - $max_up['l'] = $max_down['l'] = $max_sp_up['l'] = $max_sp_down['l'] = 0; - $max_up_id['s'] = $max_down_id['s'] = $max_sp_up_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); - $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); + $max_up = $max_down = $max_sp_up = $max_sp_down = array(); + $max_up['s'] = $max_down['s'] = $max_sp_up['s'] = $max_sp_down['s'] = 0; + $max_up['l'] = $max_down['l'] = $max_sp_up['l'] = $max_sp_down['l'] = 0; + $max_up_id['s'] = $max_down_id['s'] = $max_sp_up_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); + $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); - if ($s_mode == 'full') - { - foreach ($peers as $pid => $peer) - { - $x = ($peer['seeder']) ? 's' : 'l'; - $cnt[$x]++; - $sp_up_tot[$x] += $peer['speed_up']; - $sp_down_tot[$x] += $peer['speed_down']; + if ($s_mode == 'full') { + foreach ($peers as $pid => $peer) { + $x = ($peer['seeder']) ? 's' : 'l'; + $cnt[$x]++; + $sp_up_tot[$x] += $peer['speed_up']; + $sp_down_tot[$x] += $peer['speed_down']; - $guest = ($peer['user_id'] == GUEST_UID || is_null($peer['username'])); - $p_max_up = $peer['uploaded']; - $p_max_down = $peer['downloaded']; + $guest = ($peer['user_id'] == GUEST_UID || is_null($peer['username'])); + $p_max_up = $peer['uploaded']; + $p_max_down = $peer['downloaded']; - if ($p_max_up > $max_up[$x]) - { - $max_up[$x] = $p_max_up; - $max_up_id[$x] = $pid; - } - if ($peer['speed_up'] > $max_sp_up[$x]) - { - $max_sp_up[$x] = $peer['speed_up']; - $max_sp_up_id[$x] = $pid; - } - if ($p_max_down > $max_down[$x]) - { - $max_down[$x] = $p_max_down; - $max_down_id[$x] = $pid; - } - if ($peer['speed_down'] > $max_sp_down[$x]) - { - $max_sp_down[$x] = $peer['speed_down']; - $max_sp_down_id[$x] = $pid; - } - } - $max_down_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); + if ($p_max_up > $max_up[$x]) { + $max_up[$x] = $p_max_up; + $max_up_id[$x] = $pid; + } + if ($peer['speed_up'] > $max_sp_up[$x]) { + $max_sp_up[$x] = $peer['speed_up']; + $max_sp_up_id[$x] = $pid; + } + if ($p_max_down > $max_down[$x]) { + $max_down[$x] = $p_max_down; + $max_down_id[$x] = $pid; + } + if ($peer['speed_down'] > $max_sp_down[$x]) { + $max_sp_down[$x] = $peer['speed_down']; + $max_sp_down_id[$x] = $pid; + } + } + $max_down_id['s'] = $max_sp_down_id['s'] = ($peers_cnt + 1); - if ($cnt['s'] == 1) - { - $max_up_id['s'] = $max_sp_up_id['s'] = ($peers_cnt + 1); - } - if ($cnt['l'] == 1) - { - $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); - } - } + if ($cnt['s'] == 1) { + $max_up_id['s'] = $max_sp_up_id['s'] = ($peers_cnt + 1); + } + if ($cnt['l'] == 1) { + $max_up_id['l'] = $max_down_id['l'] = $max_sp_up_id['l'] = $max_sp_down_id['l'] = ($peers_cnt + 1); + } + } - if ($s_mode == 'count') - { - $tmp = array(); - $tmp[0]['seeder'] = $tmp[0]['username'] = $tmp[1]['username'] = 0; - $tmp[1]['seeder'] = 1; - $tmp[0]['username'] = (int) @$peers[0]['leechers']; - $tmp[1]['username'] = (int) @$peers[0]['seeders']; - $tor_speed_up = (int) @$peers[0]['speed_up']; - $tor_speed_down = (int) @$peers[0]['speed_down']; - $peers = $tmp; + if ($s_mode == 'count') { + $tmp = array(); + $tmp[0]['seeder'] = $tmp[0]['username'] = $tmp[1]['username'] = 0; + $tmp[1]['seeder'] = 1; + $tmp[0]['username'] = (int)@$peers[0]['leechers']; + $tmp[1]['username'] = (int)@$peers[0]['seeders']; + $tor_speed_up = (int)@$peers[0]['speed_up']; + $tor_speed_down = (int)@$peers[0]['speed_down']; + $peers = $tmp; - $template->assign_vars(array( - 'TOR_SPEED_UP' => ($tor_speed_up) ? humn_size($tor_speed_up, 0, 'KB') .'/s' : '0 KB/s', - 'TOR_SPEED_DOWN' => ($tor_speed_down) ? humn_size($tor_speed_down, 0, 'KB') .'/s' : '0 KB/s', - )); - } + $template->assign_vars(array( + 'TOR_SPEED_UP' => ($tor_speed_up) ? humn_size($tor_speed_up, 0, 'KB') . '/s' : '0 KB/s', + 'TOR_SPEED_DOWN' => ($tor_speed_down) ? humn_size($tor_speed_down, 0, 'KB') . '/s' : '0 KB/s', + )); + } - foreach ($peers as $pid => $peer) - { - $u_prof_href = ($s_mode == 'count') ? '#' : "profile.php?mode=viewprofile&u=". $peer['user_id'] ."#torrent"; + foreach ($peers as $pid => $peer) { + $u_prof_href = ($s_mode == 'count') ? '#' : "profile.php?mode=viewprofile&u=" . $peer['user_id'] . "#torrent"; - // Full details mode - if ($s_mode == 'full') - { - $ip = bt_show_ip($peer['ip']); - $port = bt_show_port($peer['port']); + // Full details mode + if ($s_mode == 'full') { + $ip = bt_show_ip($peer['ip']); + $port = bt_show_port($peer['port']); - // peer max/current up/down - $p_max_up = $peer['uploaded']; - $p_max_down = $peer['downloaded']; - $p_cur_up = $peer['uploaded']; - $p_cur_down = $peer['downloaded']; + // peer max/current up/down + $p_max_up = $peer['uploaded']; + $p_max_down = $peer['downloaded']; + $p_cur_up = $peer['uploaded']; + $p_cur_down = $peer['downloaded']; - if ($peer['seeder']) - { - $x = 's'; - $x_row = 'srow'; - $x_full = 'sfull'; + if ($peer['seeder']) { + $x = 's'; + $x_row = 'srow'; + $x_full = 'sfull'; - if (!defined('SEEDER_EXIST')) - { - define('SEEDER_EXIST', true); - $seed_order_action = "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#seeders"; + if (!defined('SEEDER_EXIST')) { + define('SEEDER_EXIST', true); + $seed_order_action = "viewtopic.php?" . POST_TOPIC_URL . "=$bt_topic_id&spmode=full#seeders"; - $template->assign_block_vars("$x_full", array( - 'SEED_ORD_ACT' => $seed_order_action, - 'SEEDERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') .'/s' - )); + $template->assign_block_vars("$x_full", array( + 'SEED_ORD_ACT' => $seed_order_action, + 'SEEDERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') . '/s' + )); - if ($ip) - { - $template->assign_block_vars("$x_full.iphead", array()); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.porthead", array()); - } - } - $compl_perc = ($tor_size) ? round(($p_max_up / $tor_size), 1) : 0; - } - else - { - $x = 'l'; - $x_row = 'lrow'; - $x_full = 'lfull'; + if ($ip) { + $template->assign_block_vars("$x_full.iphead", array()); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.porthead", array()); + } + } + $compl_perc = ($tor_size) ? round(($p_max_up / $tor_size), 1) : 0; + } else { + $x = 'l'; + $x_row = 'lrow'; + $x_full = 'lfull'; - if (!defined('LEECHER_EXIST')) - { - define('LEECHER_EXIST', true); - $leech_order_action = "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#leechers"; + if (!defined('LEECHER_EXIST')) { + define('LEECHER_EXIST', true); + $leech_order_action = "viewtopic.php?" . POST_TOPIC_URL . "=$bt_topic_id&spmode=full#leechers"; - $template->assign_block_vars("$x_full", array( - 'LEECH_ORD_ACT' => $leech_order_action, - 'LEECHERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') .'/s', - 'LEECHERS_DOWN_TOT' => humn_size($sp_down_tot[$x], 0, 'KB') .'/s' - )); + $template->assign_block_vars("$x_full", array( + 'LEECH_ORD_ACT' => $leech_order_action, + 'LEECHERS_UP_TOT' => humn_size($sp_up_tot[$x], 0, 'KB') . '/s', + 'LEECHERS_DOWN_TOT' => humn_size($sp_down_tot[$x], 0, 'KB') . '/s' + )); - if ($ip) - { - $template->assign_block_vars("$x_full.iphead", array()); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.porthead", array()); - } - } - $compl_size = ($peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; - $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; - } + if ($ip) { + $template->assign_block_vars("$x_full.iphead", array()); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.porthead", array()); + } + } + $compl_size = ($peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; + $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; + } - $rel_sign = (!$guest && $peer['releaser']) ? ' ®' : ''; - $name = profile_url($peer). $rel_sign; - $up_tot = ($p_max_up) ? humn_size($p_max_up) : '-'; - $down_tot = ($p_max_down) ? humn_size($p_max_down) : '-'; - $up_ratio = ($p_max_down) ? round(($p_max_up / $p_max_down), 2) : ''; - $sp_up = ($peer['speed_up']) ? humn_size($peer['speed_up'], 0, 'KB') .'/s' : '-'; - $sp_down = ($peer['speed_down']) ? humn_size($peer['speed_down'], 0, 'KB') .'/s' : '-'; + $rel_sign = (!$guest && $peer['releaser']) ? ' ®' : ''; + $name = profile_url($peer) . $rel_sign; + $up_tot = ($p_max_up) ? humn_size($p_max_up) : '-'; + $down_tot = ($p_max_down) ? humn_size($p_max_down) : '-'; + $up_ratio = ($p_max_down) ? round(($p_max_up / $p_max_down), 2) : ''; + $sp_up = ($peer['speed_up']) ? humn_size($peer['speed_up'], 0, 'KB') . '/s' : '-'; + $sp_down = ($peer['speed_down']) ? humn_size($peer['speed_down'], 0, 'KB') . '/s' : '-'; - $bgr_class = (!($tr[$x] % 2)) ? $bgr_class_1 : $bgr_class_2; - $row_bgr = ($change_peers_bgr_over) ? " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\"" : ''; - $tr[$x]++; + $bgr_class = (!($tr[$x] % 2)) ? $bgr_class_1 : $bgr_class_2; + $row_bgr = ($change_peers_bgr_over) ? " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\"" : ''; + $tr[$x]++; - $template->assign_block_vars("$x_full.$x_row", array( - 'ROW_BGR' => $row_bgr, - 'NAME' => ($peer['update_time']) ? $name : "$name", - 'COMPL_PRC' => $compl_perc, - 'UP_TOTAL' => ($max_up_id[$x] == $pid) ? "$up_tot" : $up_tot, - 'DOWN_TOTAL' => ($max_down_id[$x] == $pid) ? "$down_tot" : $down_tot, - 'SPEED_UP' => ($max_sp_up_id[$x] == $pid) ? "$sp_up" : $sp_up, - 'SPEED_DOWN' => ($max_sp_down_id[$x] == $pid) ? "$sp_down" : $sp_down, - 'UP_TOTAL_RAW' => $peer['uploaded'], - 'DOWN_TOTAL_RAW' => $peer['downloaded'], - 'SPEED_UP_RAW' => $peer['speed_up'], - 'SPEED_DOWN_RAW' => $peer['speed_down'], - 'UPD_EXP_TIME' => ($peer['update_time']) ? $lang['DL_UPD'] . bb_date($peer['update_time'], 'd-M-y H:i') .' · '. delta_time($peer['update_time']) . $lang['TOR_BACK'] : $lang['DL_STOPPED'], - 'TOR_RATIO' => ($up_ratio) ? $lang['USER_RATIO'] . "UL/DL: $up_ratio" : '', - )); + $template->assign_block_vars("$x_full.$x_row", array( + 'ROW_BGR' => $row_bgr, + 'NAME' => ($peer['update_time']) ? $name : "$name", + 'COMPL_PRC' => $compl_perc, + 'UP_TOTAL' => ($max_up_id[$x] == $pid) ? "$up_tot" : $up_tot, + 'DOWN_TOTAL' => ($max_down_id[$x] == $pid) ? "$down_tot" : $down_tot, + 'SPEED_UP' => ($max_sp_up_id[$x] == $pid) ? "$sp_up" : $sp_up, + 'SPEED_DOWN' => ($max_sp_down_id[$x] == $pid) ? "$sp_down" : $sp_down, + 'UP_TOTAL_RAW' => $peer['uploaded'], + 'DOWN_TOTAL_RAW' => $peer['downloaded'], + 'SPEED_UP_RAW' => $peer['speed_up'], + 'SPEED_DOWN_RAW' => $peer['speed_down'], + 'UPD_EXP_TIME' => ($peer['update_time']) ? $lang['DL_UPD'] . bb_date($peer['update_time'], 'd-M-y H:i') . ' · ' . delta_time($peer['update_time']) . $lang['TOR_BACK'] : $lang['DL_STOPPED'], + 'TOR_RATIO' => ($up_ratio) ? $lang['USER_RATIO'] . "UL/DL: $up_ratio" : '', + )); - if ($ip) - { - $template->assign_block_vars("$x_full.$x_row.ip", array('IP' => $ip)); - } - if ($port !== false) - { - $template->assign_block_vars("$x_full.$x_row.port", array('PORT' => $port)); - } - } - // Count only & only names modes - else - { - if ($peer['seeder']) - { - $seeders .= ''. $peer['username'] .', '; - $seed_count = $peer['username']; - } - else - { - $compl_size = (@$peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; - $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; + if ($ip) { + $template->assign_block_vars("$x_full.$x_row.ip", array('IP' => $ip)); + } + if ($port !== false) { + $template->assign_block_vars("$x_full.$x_row.port", array('PORT' => $port)); + } + } // Count only & only names modes + else { + if ($peer['seeder']) { + $seeders .= '' . $peer['username'] . ', '; + $seed_count = $peer['username']; + } else { + $compl_size = (@$peer['remain'] && $tor_size && $tor_size > $peer['remain']) ? ($tor_size - $peer['remain']) : 0; + $compl_perc = ($compl_size) ? floor($compl_size * 100 / $tor_size) : 0; - $leechers .= ''. $peer['username'] .''; - $leechers .= ($s_mode == 'names') ? ' ['. $compl_perc .'%]' : ''; - $leechers .= ', '; - $leech_count = $peer['username']; - } - } - } + $leechers .= '' . $peer['username'] . ''; + $leechers .= ($s_mode == 'names') ? ' [' . $compl_perc . '%]' : ''; + $leechers .= ', '; + $leech_count = $peer['username']; + } + } + } - if ($s_mode != 'full' && $seeders) - { - $seeders[strlen($seeders)-9] = ' '; - $template->assign_vars(array( - 'SEED_LIST' => $seeders, - 'SEED_COUNT' => ($seed_count) ? $seed_count : 0, - )); - } - if ($s_mode != 'full' && $leechers) - { - $leechers[strlen($leechers)-9] = ' '; - $template->assign_vars(array( - 'LEECH_LIST' => $leechers, - 'LEECH_COUNT' => ($leech_count) ? $leech_count : 0, - )); - } - } - unset($peers); + if ($s_mode != 'full' && $seeders) { + $seeders[strlen($seeders) - 9] = ' '; + $template->assign_vars(array( + 'SEED_LIST' => $seeders, + 'SEED_COUNT' => ($seed_count) ? $seed_count : 0, + )); + } + if ($s_mode != 'full' && $leechers) { + $leechers[strlen($leechers) - 9] = ' '; + $template->assign_vars(array( + 'LEECH_LIST' => $leechers, + 'LEECH_COUNT' => ($leech_count) ? $leech_count : 0, + )); + } + } + unset($peers); - // Show "seeder last seen info" - if (($s_mode == 'count' && !$seed_count) || (!$seeders && !defined('SEEDER_EXIST'))) - { - $last_seen_time = ($tor_info['seeder_last_seen']) ? delta_time($tor_info['seeder_last_seen']) : $lang['NEVER']; + // Show "seeder last seen info" + if (($s_mode == 'count' && !$seed_count) || (!$seeders && !defined('SEEDER_EXIST'))) { + $last_seen_time = ($tor_info['seeder_last_seen']) ? delta_time($tor_info['seeder_last_seen']) : $lang['NEVER']; - $template->assign_vars(array( - 'SEEDER_LAST_SEEN' => sprintf($lang['SEEDER_LAST_SEEN'], $last_seen_time), - )); - } - } + $template->assign_vars(array( + 'SEEDER_LAST_SEEN' => sprintf($lang['SEEDER_LAST_SEEN'], $last_seen_time), + )); + } + } - $template->assign_block_vars('tor_title', array('U_DOWNLOAD_LINK' => $download_link)); + $template->assign_block_vars('tor_title', array('U_DOWNLOAD_LINK' => $download_link)); - if ($peers_cnt > $max_peers_before_overflow && $s_mode == 'full') - { - $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_overflow)); - $template->assign_vars(array('PEERS_OVERFLOW' => true)); - } - else - { - $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_normal)); - } + if ($peers_cnt > $max_peers_before_overflow && $s_mode == 'full') { + $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_overflow)); + $template->assign_vars(array('PEERS_OVERFLOW' => true)); + } else { + $template->assign_vars(array('PEERS_DIV_STYLE' => $peers_div_style_normal)); + } } -if ($bb_cfg['bt_allow_spmode_change'] && $s_mode != 'full') -{ - $template->assign_vars(array( - 'PEERS_FULL_LINK' => true, - 'SPMODE_FULL_HREF' => "viewtopic.php?". POST_TOPIC_URL ."=$bt_topic_id&spmode=full#seeders", - )); +if ($bb_cfg['bt_allow_spmode_change'] && $s_mode != 'full') { + $template->assign_vars(array( + 'PEERS_FULL_LINK' => true, + 'SPMODE_FULL_HREF' => "viewtopic.php?" . POST_TOPIC_URL . "=$bt_topic_id&spmode=full#seeders", + )); } $template->assign_vars(array( - 'SHOW_DL_LIST_LINK' => (($bb_cfg['bt_show_dl_list'] || $bb_cfg['allow_dl_list_names_mode']) && $t_data['topic_dl_type'] == TOPIC_DL_TYPE_DL), - 'SHOW_TOR_ACT' => ($tor_reged && $show_peers && (!isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) || IS_AM)), - 'S_MODE_COUNT' => ($s_mode == 'count'), - 'S_MODE_NAMES' => ($s_mode == 'names'), - 'S_MODE_FULL' => ($s_mode == 'full'), - 'PEER_EXIST' => ($seeders || $leechers || defined('SEEDER_EXIST') || defined('LEECHER_EXIST')), - 'SEED_EXIST' => ($seeders || defined('SEEDER_EXIST')), - 'LEECH_EXIST' => ($leechers || defined('LEECHER_EXIST')), - 'TOR_HELP_LINKS' => $bb_cfg['tor_help_links'], - 'CALL_SEED' => ($bb_cfg['callseed'] && $tor_reged && !isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) && $seed_count < 3 && $tor_info['call_seed_time'] < (TIMENOW - 86400)), -)); \ No newline at end of file + 'SHOW_DL_LIST_LINK' => (($bb_cfg['bt_show_dl_list'] || $bb_cfg['allow_dl_list_names_mode']) && $t_data['topic_dl_type'] == TOPIC_DL_TYPE_DL), + 'SHOW_TOR_ACT' => ($tor_reged && $show_peers && (!isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) || IS_AM)), + 'S_MODE_COUNT' => ($s_mode == 'count'), + 'S_MODE_NAMES' => ($s_mode == 'names'), + 'S_MODE_FULL' => ($s_mode == 'full'), + 'PEER_EXIST' => ($seeders || $leechers || defined('SEEDER_EXIST') || defined('LEECHER_EXIST')), + 'SEED_EXIST' => ($seeders || defined('SEEDER_EXIST')), + 'LEECH_EXIST' => ($leechers || defined('LEECHER_EXIST')), + 'TOR_HELP_LINKS' => $bb_cfg['tor_help_links'], + 'CALL_SEED' => ($bb_cfg['callseed'] && $tor_reged && !isset($bb_cfg['tor_no_tor_act'][$tor_info['tor_status']]) && $seed_count < 3 && $tor_info['call_seed_time'] < (TIMENOW - 86400)), +)); diff --git a/library/attach_mod/includes/functions_admin.php b/library/attach_mod/includes/functions_admin.php index 2f0b0a4c3..782adbd53 100644 --- a/library/attach_mod/includes/functions_admin.php +++ b/library/attach_mod/includes/functions_admin.php @@ -1,191 +1,177 @@ sql_query($sql)) ) - { - bb_die('Could not get entry #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get entry #1'); + } - if (DB()->num_rows($result) == 0) - { - $sql_ary = array( - 'user_id' => (int) $id, - 'group_id' => 0, - 'quota_type' => (int) $quota_type, - 'quota_limit_id'=> (int) $quota_limit_id - ); + if (DB()->num_rows($result) == 0) { + $sql_ary = array( + 'user_id' => (int)$id, + 'group_id' => 0, + 'quota_type' => (int)$quota_type, + 'quota_limit_id' => (int)$quota_limit_id + ); - $sql = 'INSERT INTO ' . BB_QUOTA . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - } - else - { - $sql = 'UPDATE ' . BB_QUOTA . " + $sql = 'INSERT INTO ' . BB_QUOTA . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + } else { + $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id WHERE user_id = $id AND quota_type = $quota_type"; - } - DB()->sql_freeresult($result); - } + } + DB()->sql_freeresult($result); + } - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to update quota settings'); - } - - } - else if ($mode == 'group') - { - if (!$quota_limit_id) - { - $sql = 'DELETE FROM ' . BB_QUOTA . " + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to update quota settings'); + } + } elseif ($mode == 'group') { + if (!$quota_limit_id) { + $sql = 'DELETE FROM ' . BB_QUOTA . " WHERE group_id = $id AND quota_type = $quota_type"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to delete quota settings'); - } - } - else - { - // Check if user is already entered - $sql = 'SELECT group_id + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to delete quota settings'); + } + } else { + // Check if user is already entered + $sql = 'SELECT group_id FROM ' . BB_QUOTA . " WHERE group_id = $id AND quota_type = $quota_type"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get entry #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get entry #2'); + } - if (DB()->num_rows($result) == 0) - { - $sql = 'INSERT INTO ' . BB_QUOTA . " (user_id, group_id, quota_type, quota_limit_id) + if (DB()->num_rows($result) == 0) { + $sql = 'INSERT INTO ' . BB_QUOTA . " (user_id, group_id, quota_type, quota_limit_id) VALUES (0, $id, $quota_type, $quota_limit_id)"; - } - else - { - $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id + } else { + $sql = 'UPDATE ' . BB_QUOTA . " SET quota_limit_id = $quota_limit_id WHERE group_id = $id AND quota_type = $quota_type"; - } + } - if (!DB()->sql_query($sql)) - { - bb_die('Unable to update quota settings'); - } - } - } + if (!DB()->sql_query($sql)) { + bb_die('Unable to update quota settings'); + } + } + } } /** -* sort multi-dimensional Array -*/ -function sort_multi_array ($sort_array, $key, $sort_order, $pre_string_sort = 0) + * sort multi-dimensional Array + */ +function sort_multi_array($sort_array, $key, $sort_order, $pre_string_sort = 0) { - $last_element = sizeof($sort_array) - 1; + $last_element = sizeof($sort_array) - 1; - if (!$pre_string_sort) - { - $string_sort = (!is_numeric(@$sort_array[$last_element-1][$key]) ) ? true : false; - } - else - { - $string_sort = $pre_string_sort; - } + if (!$pre_string_sort) { + $string_sort = (!is_numeric(@$sort_array[$last_element - 1][$key])) ? true : false; + } else { + $string_sort = $pre_string_sort; + } - for ($i = 0; $i < $last_element; $i++) - { - $num_iterations = $last_element - $i; + for ($i = 0; $i < $last_element; $i++) { + $num_iterations = $last_element - $i; - for ($j = 0; $j < $num_iterations; $j++) - { - $next = 0; + for ($j = 0; $j < $num_iterations; $j++) { + $next = 0; - // do checks based on key - $switch = false; - if (!$string_sort) - { - if (($sort_order == 'DESC' && intval(@$sort_array[$j][$key]) < intval(@$sort_array[$j + 1][$key])) || ($sort_order == 'ASC' && intval(@$sort_array[$j][$key]) > intval(@$sort_array[$j + 1][$key]))) - { - $switch = true; - } - } - else - { - if (($sort_order == 'DESC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) < 0) || ($sort_order == 'ASC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) > 0)) - { - $switch = true; - } - } + // do checks based on key + $switch = false; + if (!$string_sort) { + if (($sort_order == 'DESC' && intval(@$sort_array[$j][$key]) < intval(@$sort_array[$j + 1][$key])) || ($sort_order == 'ASC' && intval(@$sort_array[$j][$key]) > intval(@$sort_array[$j + 1][$key]))) { + $switch = true; + } + } else { + if (($sort_order == 'DESC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) < 0) || ($sort_order == 'ASC' && strcasecmp(@$sort_array[$j][$key], @$sort_array[$j + 1][$key]) > 0)) { + $switch = true; + } + } - if ($switch) - { - $temp = $sort_array[$j]; - $sort_array[$j] = $sort_array[$j + 1]; - $sort_array[$j + 1] = $temp; - } - } - } + if ($switch) { + $temp = $sort_array[$j]; + $sort_array[$j] = $sort_array[$j + 1]; + $sort_array[$j + 1] = $temp; + } + } + } - return $sort_array; + return $sort_array; } /** -* Returns the filesize of the upload directory in human readable format -*/ + * Returns the filesize of the upload directory in human readable format + */ function get_formatted_dirsize() { - global $attach_config, $upload_dir, $lang; + global $attach_config, $upload_dir, $lang; - $upload_dir_size = 0; + $upload_dir_size = 0; - if ($dirname = @opendir($upload_dir)) - { - while ($file = @readdir($dirname)) - { - if ($file != 'index.php' && $file != '.htaccess' && !is_dir($upload_dir . '/' . $file) && !is_link($upload_dir . '/' . $file)) - { - $upload_dir_size += @filesize($upload_dir . '/' . $file); - } - } - @closedir($dirname); - } - else - { - $upload_dir_size = $lang['NOT_AVAILABLE']; - return $upload_dir_size; - } + if ($dirname = @opendir($upload_dir)) { + while ($file = @readdir($dirname)) { + if ($file != 'index.php' && $file != '.htaccess' && !is_dir($upload_dir . '/' . $file) && !is_link($upload_dir . '/' . $file)) { + $upload_dir_size += @filesize($upload_dir . '/' . $file); + } + } + @closedir($dirname); + } else { + $upload_dir_size = $lang['NOT_AVAILABLE']; + return $upload_dir_size; + } - return humn_size($upload_dir_size); + return humn_size($upload_dir_size); } /* @@ -193,161 +179,136 @@ function get_formatted_dirsize() */ function search_attachments($order_by, &$total_rows) { - global $lang; + global $lang; - $where_sql = array(); + $where_sql = array(); - // Get submitted Vars - $search_vars = array('search_keyword_fname', 'search_keyword_comment', 'search_author', 'search_size_smaller', 'search_size_greater', 'search_count_smaller', 'search_count_greater', 'search_days_greater', 'search_forum', 'search_cat'); + // Get submitted Vars + $search_vars = array('search_keyword_fname', 'search_keyword_comment', 'search_author', 'search_size_smaller', 'search_size_greater', 'search_count_smaller', 'search_count_greater', 'search_days_greater', 'search_forum', 'search_cat'); - for ($i = 0; $i < sizeof($search_vars); $i++) - { - $$search_vars[$i] = get_var($search_vars[$i], ''); - } + for ($i = 0; $i < sizeof($search_vars); $i++) { + $$search_vars[$i] = get_var($search_vars[$i], ''); + } - // Author name search - if ($search_author != '') - { - // Bring in line with 2.0.x expected username - $search_author = addslashes(html_entity_decode($search_author)); - $search_author = stripslashes(clean_username($search_author)); + // Author name search + if ($search_author != '') { + // Bring in line with 2.0.x expected username + $search_author = addslashes(html_entity_decode($search_author)); + $search_author = stripslashes(clean_username($search_author)); - // Prepare for directly going into sql query - $search_author = str_replace('*', '%', attach_mod_sql_escape($search_author)); + // Prepare for directly going into sql query + $search_author = str_replace('*', '%', attach_mod_sql_escape($search_author)); - // We need the post_id's, because we want to query the Attachment Table - $sql = 'SELECT user_id FROM ' . BB_USERS . " WHERE username LIKE '$search_author'"; + // We need the post_id's, because we want to query the Attachment Table + $sql = 'SELECT user_id FROM ' . BB_USERS . " WHERE username LIKE '$search_author'"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not obtain list of matching users (searching for: ' . $search_author . ')'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain list of matching users (searching for: ' . $search_author . ')'); + } - $matching_userids = ''; - if ( $row = DB()->sql_fetchrow($result) ) - { - do - { - $matching_userids .= (($matching_userids != '') ? ', ' : '') . intval($row['user_id']); - } - while ($row = DB()->sql_fetchrow($result)); + $matching_userids = ''; + if ($row = DB()->sql_fetchrow($result)) { + do { + $matching_userids .= (($matching_userids != '') ? ', ' : '') . intval($row['user_id']); + } while ($row = DB()->sql_fetchrow($result)); - DB()->sql_freeresult($result); - } - else - { - bb_die($lang['NO_ATTACH_SEARCH_MATCH']); - } + DB()->sql_freeresult($result); + } else { + bb_die($lang['NO_ATTACH_SEARCH_MATCH']); + } - $where_sql[] = ' (t.user_id_1 IN (' . $matching_userids . ')) '; - } + $where_sql[] = ' (t.user_id_1 IN (' . $matching_userids . ')) '; + } - // Search Keyword - if ($search_keyword_fname != '') - { - $match_word = str_replace('*', '%', $search_keyword_fname); - $where_sql[] = " (a.real_filename LIKE '" . attach_mod_sql_escape($match_word) . "') "; - } + // Search Keyword + if ($search_keyword_fname != '') { + $match_word = str_replace('*', '%', $search_keyword_fname); + $where_sql[] = " (a.real_filename LIKE '" . attach_mod_sql_escape($match_word) . "') "; + } - if ($search_keyword_comment != '') - { - $match_word = str_replace('*', '%', $search_keyword_comment); - $where_sql[] = " (a.comment LIKE '" . attach_mod_sql_escape($match_word) . "') "; - } + if ($search_keyword_comment != '') { + $match_word = str_replace('*', '%', $search_keyword_comment); + $where_sql[] = " (a.comment LIKE '" . attach_mod_sql_escape($match_word) . "') "; + } - // Search Download Count - if ($search_count_smaller != '' || $search_count_greater != '') - { - if ($search_count_smaller != '') - { - $where_sql[] = ' (a.download_count < ' . (int) $search_count_smaller . ') '; - } - else if ($search_count_greater != '') - { - $where_sql[] = ' (a.download_count > ' . (int) $search_count_greater . ') '; - } - } + // Search Download Count + if ($search_count_smaller != '' || $search_count_greater != '') { + if ($search_count_smaller != '') { + $where_sql[] = ' (a.download_count < ' . (int)$search_count_smaller . ') '; + } elseif ($search_count_greater != '') { + $where_sql[] = ' (a.download_count > ' . (int)$search_count_greater . ') '; + } + } - // Search Filesize - if ($search_size_smaller != '' || $search_size_greater != '') - { - if ($search_size_smaller != '') - { - $where_sql[] = ' (a.filesize < ' . (int) $search_size_smaller . ') '; - } - else if ($search_size_greater != '') - { - $where_sql[] = ' (a.filesize > ' . (int) $search_size_greater . ') '; - } - } + // Search Filesize + if ($search_size_smaller != '' || $search_size_greater != '') { + if ($search_size_smaller != '') { + $where_sql[] = ' (a.filesize < ' . (int)$search_size_smaller . ') '; + } elseif ($search_size_greater != '') { + $where_sql[] = ' (a.filesize > ' . (int)$search_size_greater . ') '; + } + } - // Search Attachment Time - if ($search_days_greater != '') - { - $where_sql[] = ' (a.filetime < ' . ( TIMENOW - ((int) $search_days_greater * 86400)) . ') '; - } + // Search Attachment Time + if ($search_days_greater != '') { + $where_sql[] = ' (a.filetime < ' . (TIMENOW - ((int)$search_days_greater * 86400)) . ') '; + } - // Search Forum - if ($search_forum) - { - $where_sql[] = ' (p.forum_id = ' . intval($search_forum) . ') '; - } + // Search Forum + if ($search_forum) { + $where_sql[] = ' (p.forum_id = ' . intval($search_forum) . ') '; + } - // Search Cat... nope... sorry :( + // Search Cat... nope... sorry :( - $sql = 'SELECT a.*, t.post_id, p.post_time, p.topic_id + $sql = 'SELECT a.*, t.post_id, p.post_time, p.topic_id FROM ' . BB_ATTACHMENTS . ' t, ' . BB_ATTACHMENTS_DESC . ' a, ' . BB_POSTS . ' p WHERE '; - if (sizeof($where_sql) > 0) - { - $sql .= implode('AND', $where_sql) . ' AND '; - } + if (sizeof($where_sql) > 0) { + $sql .= implode('AND', $where_sql) . ' AND '; + } - $sql .= 't.post_id = p.post_id AND a.attach_id = t.attach_id '; + $sql .= 't.post_id = p.post_id AND a.attach_id = t.attach_id '; - $total_rows_sql = $sql; + $total_rows_sql = $sql; - $sql .= $order_by; + $sql .= $order_by; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments #1'); + } - $attachments = DB()->sql_fetchrowset($result); - $num_attach = DB()->num_rows($result); - DB()->sql_freeresult($result); + $attachments = DB()->sql_fetchrowset($result); + $num_attach = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_attach == 0) - { - bb_die($lang['NO_ATTACH_SEARCH_MATCH']); - } + if ($num_attach == 0) { + bb_die($lang['NO_ATTACH_SEARCH_MATCH']); + } - if (!($result = DB()->sql_query($total_rows_sql))) - { - bb_die('Could not query attachments #2'); - } + if (!($result = DB()->sql_query($total_rows_sql))) { + bb_die('Could not query attachments #2'); + } - $total_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $total_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - return $attachments; + return $attachments; } /** -* perform LIMIT statement on arrays -*/ + * perform LIMIT statement on arrays + */ function limit_array($array, $start, $pagelimit) { - // array from start - start+pagelimit - $limit = (sizeof($array) < ($start + $pagelimit)) ? sizeof($array) : $start + $pagelimit; + // array from start - start+pagelimit + $limit = (sizeof($array) < ($start + $pagelimit)) ? sizeof($array) : $start + $pagelimit; - $limit_array = array(); + $limit_array = array(); - for ($i = $start; $i < $limit; $i++) - { - $limit_array[] = $array[$i]; - } + for ($i = $start; $i < $limit; $i++) { + $limit_array[] = $array[$i]; + } - return $limit_array; -} \ No newline at end of file + return $limit_array; +} diff --git a/library/attach_mod/includes/functions_attach.php b/library/attach_mod/includes/functions_attach.php index 4746283c7..eda3c8ece 100644 --- a/library/attach_mod/includes/functions_attach.php +++ b/library/attach_mod/includes/functions_attach.php @@ -1,475 +1,445 @@ 4096) - { - return; - } - else if ($number < $base) - { - return $chars[$number]; - } + if ($number > 4096) { + return; + } elseif ($number < $base) { + return $chars[$number]; + } - $hexval = ''; + $hexval = ''; - while ($number > 0) - { - $remainder = $number%$base; + while ($number > 0) { + $remainder = $number % $base; - if ($remainder < $base) - { - $hexval = $chars[$remainder] . $hexval; - } + if ($remainder < $base) { + $hexval = $chars[$remainder] . $hexval; + } - $number = floor($number/$base); - } + $number = floor($number / $base); + } - return $hexval; + return $hexval; } /** -* base64todec function -*/ + * base64todec function + */ function base64_unpack($string) { - $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-'; - $base = strlen($chars); + $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-'; + $base = strlen($chars); - $length = strlen($string); - $number = 0; + $length = strlen($string); + $number = 0; - for($i = 1; $i <= $length; $i++) - { - $pos = $length - $i; - $operand = strpos($chars, substr($string,$pos,1)); - $exponent = pow($base, $i-1); - $decValue = $operand * $exponent; - $number += $decValue; - } + for ($i = 1; $i <= $length; $i++) { + $pos = $length - $i; + $operand = strpos($chars, substr($string, $pos, 1)); + $exponent = pow($base, $i - 1); + $decValue = $operand * $exponent; + $number += $decValue; + } - return $number; + return $number; } /** -* Per Forum based Extension Group Permissions (Encode Number) -> Theoretically up to 158 Forums saveable. :) -* We are using a base of 64, but splitting it to one-char and two-char numbers. :) -*/ + * Per Forum based Extension Group Permissions (Encode Number) -> Theoretically up to 158 Forums saveable. :) + * We are using a base of 64, but splitting it to one-char and two-char numbers. :) + */ function auth_pack($auth_array) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; - $one_char = $two_char = false; - $auth_cache = ''; + $one_char_encoding = '#'; + $two_char_encoding = '.'; + $one_char = $two_char = false; + $auth_cache = ''; - for ($i = 0; $i < sizeof($auth_array); $i++) - { - $val = base64_pack(intval($auth_array[$i])); - if (strlen($val) == 1 && !$one_char) - { - $auth_cache .= $one_char_encoding; - $one_char = true; - } - else if (strlen($val) == 2 && !$two_char) - { - $auth_cache .= $two_char_encoding; - $two_char = true; - } + for ($i = 0; $i < sizeof($auth_array); $i++) { + $val = base64_pack(intval($auth_array[$i])); + if (strlen($val) == 1 && !$one_char) { + $auth_cache .= $one_char_encoding; + $one_char = true; + } elseif (strlen($val) == 2 && !$two_char) { + $auth_cache .= $two_char_encoding; + $two_char = true; + } - $auth_cache .= $val; - } + $auth_cache .= $val; + } - return $auth_cache; + return $auth_cache; } /** -* Reverse the auth_pack process -*/ + * Reverse the auth_pack process + */ function auth_unpack($auth_cache) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; + $one_char_encoding = '#'; + $two_char_encoding = '.'; - $auth = array(); - $auth_len = 1; + $auth = array(); + $auth_len = 1; - for ($pos = 0; $pos < strlen($auth_cache); $pos += $auth_len) - { - $forum_auth = substr($auth_cache, $pos, 1); - if ($forum_auth == $one_char_encoding) - { - $auth_len = 1; - continue; - } - else if ($forum_auth == $two_char_encoding) - { - $auth_len = 2; - $pos--; - continue; - } + for ($pos = 0; $pos < strlen($auth_cache); $pos += $auth_len) { + $forum_auth = substr($auth_cache, $pos, 1); + if ($forum_auth == $one_char_encoding) { + $auth_len = 1; + continue; + } elseif ($forum_auth == $two_char_encoding) { + $auth_len = 2; + $pos--; + continue; + } - $forum_auth = substr($auth_cache, $pos, $auth_len); - $forum_id = base64_unpack($forum_auth); - $auth[] = intval($forum_id); - } - return $auth; + $forum_auth = substr($auth_cache, $pos, $auth_len); + $forum_id = base64_unpack($forum_auth); + $auth[] = intval($forum_id); + } + return $auth; } /** -* Used for determining if Forum ID is authed, please use this Function on all Posting Screens -*/ + * Used for determining if Forum ID is authed, please use this Function on all Posting Screens + */ function is_forum_authed($auth_cache, $check_forum_id) { - $one_char_encoding = '#'; - $two_char_encoding = '.'; + $one_char_encoding = '#'; + $two_char_encoding = '.'; - if (trim($auth_cache) == '') - { - return true; - } + if (trim($auth_cache) == '') { + return true; + } - $auth = array(); - $auth_len = 1; + $auth = array(); + $auth_len = 1; - for ($pos = 0; $pos < strlen($auth_cache); $pos+=$auth_len) - { - $forum_auth = substr($auth_cache, $pos, 1); - if ($forum_auth == $one_char_encoding) - { - $auth_len = 1; - continue; - } - else if ($forum_auth == $two_char_encoding) - { - $auth_len = 2; - $pos--; - continue; - } + for ($pos = 0; $pos < strlen($auth_cache); $pos += $auth_len) { + $forum_auth = substr($auth_cache, $pos, 1); + if ($forum_auth == $one_char_encoding) { + $auth_len = 1; + continue; + } elseif ($forum_auth == $two_char_encoding) { + $auth_len = 2; + $pos--; + continue; + } - $forum_auth = substr($auth_cache, $pos, $auth_len); - $forum_id = (int) base64_unpack($forum_auth); - if ($forum_id == $check_forum_id) - { - return true; - } - } - return false; + $forum_auth = substr($auth_cache, $pos, $auth_len); + $forum_id = (int)base64_unpack($forum_auth); + if ($forum_id == $check_forum_id) { + return true; + } + } + return false; } /** -* Deletes an Attachment -*/ + * Deletes an Attachment + */ function unlink_attach($filename, $mode = false) { - global $upload_dir, $attach_config; + global $upload_dir, $attach_config; - $filename = basename($filename); + $filename = basename($filename); - if ($mode == MODE_THUMBNAIL) - { - $filename = $upload_dir . '/' . THUMB_DIR . '/t_' . $filename; - } - else - { - $filename = $upload_dir . '/' . $filename; - } + if ($mode == MODE_THUMBNAIL) { + $filename = $upload_dir . '/' . THUMB_DIR . '/t_' . $filename; + } else { + $filename = $upload_dir . '/' . $filename; + } - $deleted = @unlink($filename); + $deleted = @unlink($filename); - return $deleted; + return $deleted; } /** -* Check if Attachment exist -*/ + * Check if Attachment exist + */ function attachment_exists($filename) { - global $upload_dir, $attach_config; + global $upload_dir, $attach_config; - $filename = basename($filename); + $filename = basename($filename); - if (!@file_exists(@amod_realpath($upload_dir . '/' . $filename))) - { - return false; - } - else - { - return true; - } + if (!@file_exists(@amod_realpath($upload_dir . '/' . $filename))) { + return false; + } else { + return true; + } } /** -* Check if Thumbnail exist -*/ + * Check if Thumbnail exist + */ function thumbnail_exists($filename) { - global $upload_dir, $attach_config; + global $upload_dir, $attach_config; - $filename = basename($filename); + $filename = basename($filename); - if (!@file_exists(@amod_realpath($upload_dir . '/' . THUMB_DIR . '/t_' . $filename))) - { - return false; - } - else - { - return true; - } + if (!@file_exists(@amod_realpath($upload_dir . '/' . THUMB_DIR . '/t_' . $filename))) { + return false; + } else { + return true; + } } /** -* Physical Filename stored already ? -*/ + * Physical Filename stored already ? + */ function physical_filename_already_stored($filename) { - if ($filename == '') - { - return false; - } + if ($filename == '') { + return false; + } - $filename = basename($filename); + $filename = basename($filename); - $sql = 'SELECT attach_id + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS_DESC . " WHERE physical_filename = '" . attach_mod_sql_escape($filename) . "' LIMIT 1"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment information for filename: ' . htmlspecialchars($filename)); - } - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment information for filename: ' . htmlspecialchars($filename)); + } + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - return ($num_rows == 0) ? false : true; + return ($num_rows == 0) ? false : true; } /** -* get all attachments from a post (could be an post array too) -*/ + * get all attachments from a post (could be an post array too) + */ function get_attachments_from_post($post_id_array) { - global $attach_config; + global $attach_config; - $attachments = array(); + $attachments = array(); - if (!is_array($post_id_array)) - { - if (empty($post_id_array)) - { - return $attachments; - } + if (!is_array($post_id_array)) { + if (empty($post_id_array)) { + return $attachments; + } - $post_id = intval($post_id_array); + $post_id = intval($post_id_array); - $post_id_array = array(); - $post_id_array[] = $post_id; - } + $post_id_array = array(); + $post_id_array[] = $post_id; + } - $post_id_array = implode(', ', array_map('intval', $post_id_array)); + $post_id_array = implode(', ', array_map('intval', $post_id_array)); - if ($post_id_array == '') - { - return $attachments; - } + if ($post_id_array == '') { + return $attachments; + } - $display_order = (intval($attach_config['display_order']) == 0) ? 'DESC' : 'ASC'; + $display_order = (intval($attach_config['display_order']) == 0) ? 'DESC' : 'ASC'; - $sql = 'SELECT a.post_id, d.* + $sql = 'SELECT a.post_id, d.* FROM ' . BB_ATTACHMENTS . ' a, ' . BB_ATTACHMENTS_DESC . " d WHERE a.post_id IN ($post_id_array) AND a.attach_id = d.attach_id ORDER BY d.filetime $display_order"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get attachment informations for post number ' . $post_id_array); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get attachment informations for post number ' . $post_id_array); + } - $num_rows = DB()->num_rows($result); - $attachments = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + $attachments = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - if ($num_rows == 0) - { - return array(); - } + if ($num_rows == 0) { + return array(); + } - return $attachments; + return $attachments; } /** -* Count Filesize of Attachments in Database based on the attachment id -*/ + * Count Filesize of Attachments in Database based on the attachment id + */ function get_total_attach_filesize($attach_ids) { - if (!is_array($attach_ids) || !sizeof($attach_ids)) - { - return 0; - } + if (!is_array($attach_ids) || !sizeof($attach_ids)) { + return 0; + } - $attach_ids = implode(', ', array_map('intval', $attach_ids)); + $attach_ids = implode(', ', array_map('intval', $attach_ids)); - if (!$attach_ids) - { - return 0; - } + if (!$attach_ids) { + return 0; + } - $sql = 'SELECT filesize FROM ' . BB_ATTACHMENTS_DESC . " WHERE attach_id IN ($attach_ids)"; + $sql = 'SELECT filesize FROM ' . BB_ATTACHMENTS_DESC . " WHERE attach_id IN ($attach_ids)"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query total filesize'); + } - $total_filesize = 0; + $total_filesize = 0; - while ($row = DB()->sql_fetchrow($result)) - { - $total_filesize += (int) $row['filesize']; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $total_filesize += (int)$row['filesize']; + } + DB()->sql_freeresult($result); - return $total_filesize; + return $total_filesize; } /** -* Get allowed Extensions and their respective Values -*/ + * Get allowed Extensions and their respective Values + */ function get_extension_informations() { - return $GLOBALS['datastore']->get('attach_extensions'); + return $GLOBALS['datastore']->get('attach_extensions'); } // // Sync Topic // -function attachment_sync_topic ($topics) +function attachment_sync_topic($topics) { - if (is_array($topics)) - { - $topics = join(',', $topics); - } - $posts_without_attach = $topics_without_attach = array(); + if (is_array($topics)) { + $topics = join(',', $topics); + } + $posts_without_attach = $topics_without_attach = array(); - // Check orphan post_attachment markers - $sql = "SELECT p.post_id - FROM ". BB_POSTS ." p - LEFT JOIN ". BB_ATTACHMENTS ." a USING(post_id) + // Check orphan post_attachment markers + $sql = "SELECT p.post_id + FROM " . BB_POSTS . " p + LEFT JOIN " . BB_ATTACHMENTS . " a USING(post_id) WHERE p.topic_id IN($topics) AND p.post_attachment = 1 AND a.post_id IS NULL"; - if ($rowset = DB()->fetch_rowset($sql)) - { - foreach ($rowset as $row) - { - $posts_without_attach[] = $row['post_id']; - } - if ($posts_sql = join(',', $posts_without_attach)) - { - DB()->query("UPDATE ". BB_POSTS ." SET post_attachment = 0 WHERE post_id IN($posts_sql)"); - } - } + if ($rowset = DB()->fetch_rowset($sql)) { + foreach ($rowset as $row) { + $posts_without_attach[] = $row['post_id']; + } + if ($posts_sql = join(',', $posts_without_attach)) { + DB()->query("UPDATE " . BB_POSTS . " SET post_attachment = 0 WHERE post_id IN($posts_sql)"); + } + } - // Update missing topic_attachment markers - DB()->query(" - UPDATE ". BB_TOPICS ." t, ". BB_POSTS ." p SET + // Update missing topic_attachment markers + DB()->query(" + UPDATE " . BB_TOPICS . " t, " . BB_POSTS . " p SET t.topic_attachment = 1 WHERE p.topic_id IN($topics) AND p.post_attachment = 1 AND p.topic_id = t.topic_id "); - // Fix orphan topic_attachment markers - $sql = "SELECT t.topic_id - FROM ". BB_POSTS ." p, ". BB_TOPICS ." t + // Fix orphan topic_attachment markers + $sql = "SELECT t.topic_id + FROM " . BB_POSTS . " p, " . BB_TOPICS . " t WHERE t.topic_id = p.topic_id AND t.topic_id IN($topics) AND t.topic_attachment = 1 GROUP BY p.topic_id HAVING SUM(p.post_attachment) = 0"; - if ($rowset = DB()->fetch_rowset($sql)) - { - foreach ($rowset as $row) - { - $topics_without_attach[] = $row['topic_id']; - } - if ($topics_sql = join(',', $topics_without_attach)) - { - DB()->query("UPDATE ". BB_TOPICS ." SET topic_attachment = 0 WHERE topic_id IN($topics_sql)"); - } - } + if ($rowset = DB()->fetch_rowset($sql)) { + foreach ($rowset as $row) { + $topics_without_attach[] = $row['topic_id']; + } + if ($topics_sql = join(',', $topics_without_attach)) { + DB()->query("UPDATE " . BB_TOPICS . " SET topic_attachment = 0 WHERE topic_id IN($topics_sql)"); + } + } } /** -* Get Extension -*/ + * Get Extension + */ function get_extension($filename) { - if (!stristr($filename, '.')) - { - return ''; - } - $extension = strrchr(strtolower($filename), '.'); - $extension[0] = ' '; - $extension = strtolower(trim($extension)); - if (is_array($extension)) - { - return ''; - } - else - { - return $extension; - } + if (!stristr($filename, '.')) { + return ''; + } + $extension = strrchr(strtolower($filename), '.'); + $extension[0] = ' '; + $extension = strtolower(trim($extension)); + if (is_array($extension)) { + return ''; + } else { + return $extension; + } } /** -* Delete Extension -*/ + * Delete Extension + */ function delete_extension($filename) { - return substr($filename, 0, strrpos(strtolower(trim($filename)), '.')); + return substr($filename, 0, strrpos(strtolower(trim($filename)), '.')); } /** -* Check if a user is within Group -*/ + * Check if a user is within Group + */ function user_in_group($user_id, $group_id) { - $user_id = (int) $user_id; - $group_id = (int) $group_id; + $user_id = (int)$user_id; + $group_id = (int)$group_id; - if (!$user_id || !$group_id) - { - return false; - } + if (!$user_id || !$group_id) { + return false; + } - $sql = 'SELECT u.group_id + $sql = 'SELECT u.group_id FROM ' . BB_USER_GROUP . ' u, ' . BB_GROUPS . " g WHERE g.group_single_user = 0 AND u.group_id = g.group_id @@ -477,214 +447,168 @@ function user_in_group($user_id, $group_id) AND g.group_id = $group_id LIMIT 1"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user group'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get user group'); + } - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows == 0) - { - return false; - } + if ($num_rows == 0) { + return false; + } - return true; + return true; } /** -* Realpath replacement for attachment mod -*/ + * Realpath replacement for attachment mod + */ function amod_realpath($path) { - return (function_exists('realpath')) ? realpath($path) : $path; + return (function_exists('realpath')) ? realpath($path) : $path; } /** -* _set_var -* -* Set variable, used by {@link get_var the get_var function} -* -* @private -*/ + * _set_var + * + * Set variable, used by {@link get_var the get_var function} + * + * @private + */ function _set_var(&$result, $var, $type, $multibyte = false) { - settype($var, $type); - $result = $var; + settype($var, $type); + $result = $var; - if ($type == 'string') - { - $result = trim(str_replace(array("\r\n", "\r", '\xFF'), array("\n", "\n", ' '), $result)); - // 2.0.x is doing addslashes on all variables - $result = stripslashes($result); - if ($multibyte) - { - $result = preg_replace('#&(\#[0-9]+;)#', '&\1', $result); - } - } + if ($type == 'string') { + $result = trim(str_replace(array("\r\n", "\r", '\xFF'), array("\n", "\n", ' '), $result)); + // 2.0.x is doing addslashes on all variables + $result = stripslashes($result); + if ($multibyte) { + $result = preg_replace('#&(\#[0-9]+;)#', '&\1', $result); + } + } } /** -* get_var -* -* Used to get passed variable -*/ + * get_var + * + * Used to get passed variable + */ function get_var($var_name, $default, $multibyte = false) { - $request_var = (isset($_POST[$var_name])) ? $_POST : $_GET; + $request_var = (isset($_POST[$var_name])) ? $_POST : $_GET; - if (!isset($request_var[$var_name]) || (is_array($request_var[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($request_var[$var_name]))) - { - return (is_array($default)) ? array() : $default; - } + if (!isset($request_var[$var_name]) || (is_array($request_var[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($request_var[$var_name]))) { + return (is_array($default)) ? array() : $default; + } - $var = $request_var[$var_name]; + $var = $request_var[$var_name]; - if (!is_array($default)) - { - $type = gettype($default); - } - else - { - list($key_type, $type) = each($default); - $type = gettype($type); - $key_type = gettype($key_type); - } + if (!is_array($default)) { + $type = gettype($default); + } else { + list($key_type, $type) = each($default); + $type = gettype($type); + $key_type = gettype($key_type); + } - if (is_array($var)) - { - $_var = $var; - $var = array(); + if (is_array($var)) { + $_var = $var; + $var = array(); - foreach ($_var as $k => $v) - { - if (is_array($v)) - { - foreach ($v as $_k => $_v) - { - _set_var($k, $k, $key_type); - _set_var($_k, $_k, $key_type); - _set_var($var[$k][$_k], $_v, $type, $multibyte); - } - } - else - { - _set_var($k, $k, $key_type); - _set_var($var[$k], $v, $type, $multibyte); - } - } - } - else - { - _set_var($var, $var, $type, $multibyte); - } + foreach ($_var as $k => $v) { + if (is_array($v)) { + foreach ($v as $_k => $_v) { + _set_var($k, $k, $key_type); + _set_var($_k, $_k, $key_type); + _set_var($var[$k][$_k], $_v, $type, $multibyte); + } + } else { + _set_var($k, $k, $key_type); + _set_var($var[$k], $v, $type, $multibyte); + } + } + } else { + _set_var($var, $var, $type, $multibyte); + } - return $var; + return $var; } /** -* Escaping SQL -*/ + * Escaping SQL + */ function attach_mod_sql_escape($text) { - if (function_exists('mysqli_real_escape_string')) - { - return DB()->escape_string($text); - } - else - { - return str_replace("'", "''", str_replace('\\', '\\\\', $text)); - } + if (function_exists('mysqli_real_escape_string')) { + return DB()->escape_string($text); + } else { + return str_replace("'", "''", str_replace('\\', '\\\\', $text)); + } } /** -* Build sql statement from array for insert/update/select statements -* -* Idea for this from Ikonboard -* Possible query values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT -*/ + * Build sql statement from array for insert/update/select statements + * + * Idea for this from Ikonboard + * Possible query values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT + */ function attach_mod_sql_build_array($query, $assoc_ary = false) { - if (!is_array($assoc_ary)) - { - return false; - } + if (!is_array($assoc_ary)) { + return false; + } - $fields = array(); - $values = array(); - if ($query == 'INSERT' || $query == 'INSERT_SELECT') - { - foreach ($assoc_ary as $key => $var) - { - $fields[] = $key; + $fields = array(); + $values = array(); + if ($query == 'INSERT' || $query == 'INSERT_SELECT') { + foreach ($assoc_ary as $key => $var) { + $fields[] = $key; - if (is_null($var)) - { - $values[] = 'NULL'; - } - else if (is_string($var)) - { - $values[] = "'" . attach_mod_sql_escape($var) . "'"; - } - else if (is_array($var) && is_string($var[0])) - { - $values[] = $var[0]; - } - else - { - $values[] = (is_bool($var)) ? intval($var) : $var; - } - } + if (is_null($var)) { + $values[] = 'NULL'; + } elseif (is_string($var)) { + $values[] = "'" . attach_mod_sql_escape($var) . "'"; + } elseif (is_array($var) && is_string($var[0])) { + $values[] = $var[0]; + } else { + $values[] = (is_bool($var)) ? intval($var) : $var; + } + } - $query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' '; - } - else if ($query == 'MULTI_INSERT') - { - $ary = array(); - foreach ($assoc_ary as $id => $sql_ary) - { - $values = array(); - foreach ($sql_ary as $key => $var) - { - if (is_null($var)) - { - $values[] = 'NULL'; - } - elseif (is_string($var)) - { - $values[] = "'" . attach_mod_sql_escape($var) . "'"; - } - else - { - $values[] = (is_bool($var)) ? intval($var) : $var; - } - } - $ary[] = '(' . implode(', ', $values) . ')'; - } + $query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' '; + } elseif ($query == 'MULTI_INSERT') { + $ary = array(); + foreach ($assoc_ary as $id => $sql_ary) { + $values = array(); + foreach ($sql_ary as $key => $var) { + if (is_null($var)) { + $values[] = 'NULL'; + } elseif (is_string($var)) { + $values[] = "'" . attach_mod_sql_escape($var) . "'"; + } else { + $values[] = (is_bool($var)) ? intval($var) : $var; + } + } + $ary[] = '(' . implode(', ', $values) . ')'; + } - $query = ' (' . implode(', ', array_keys($assoc_ary[0])) . ') VALUES ' . implode(', ', $ary); - } - else if ($query == 'UPDATE' || $query == 'SELECT') - { - $values = array(); - foreach ($assoc_ary as $key => $var) - { - if (is_null($var)) - { - $values[] = "$key = NULL"; - } - elseif (is_string($var)) - { - $values[] = "$key = '" . attach_mod_sql_escape($var) . "'"; - } - else - { - $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var"; - } - } - $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values); - } + $query = ' (' . implode(', ', array_keys($assoc_ary[0])) . ') VALUES ' . implode(', ', $ary); + } elseif ($query == 'UPDATE' || $query == 'SELECT') { + $values = array(); + foreach ($assoc_ary as $key => $var) { + if (is_null($var)) { + $values[] = "$key = NULL"; + } elseif (is_string($var)) { + $values[] = "$key = '" . attach_mod_sql_escape($var) . "'"; + } else { + $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var"; + } + } + $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values); + } - return $query; + return $query; } diff --git a/library/attach_mod/includes/functions_delete.php b/library/attach_mod/includes/functions_delete.php index 8cf7f7598..c7a2185a3 100644 --- a/library/attach_mod/includes/functions_delete.php +++ b/library/attach_mod/includes/functions_delete.php @@ -1,284 +1,256 @@ sql_query($sql))) - { - bb_die('Could not select ids'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select ids'); + } - $num_post_list = DB()->num_rows($result); + $num_post_list = DB()->num_rows($result); - if ($num_post_list == 0) - { - DB()->sql_freeresult($result); - return; - } + if ($num_post_list == 0) { + DB()->sql_freeresult($result); + return; + } - while ($row = DB()->sql_fetchrow($result)) - { - $post_id_array[] = intval($row[$p_id]); - } - DB()->sql_freeresult($result); - } + while ($row = DB()->sql_fetchrow($result)) { + $post_id_array[] = intval($row[$p_id]); + } + DB()->sql_freeresult($result); + } - if (!is_array($post_id_array)) - { - if (trim($post_id_array) == '') - { - return; - } + if (!is_array($post_id_array)) { + if (trim($post_id_array) == '') { + return; + } - if (strstr($post_id_array, ', ')) - { - $post_id_array = explode(', ', $post_id_array); - } - else if (strstr($post_id_array, ',')) - { - $post_id_array = explode(',', $post_id_array); - } - else - { - $post_id = intval($post_id_array); + if (strstr($post_id_array, ', ')) { + $post_id_array = explode(', ', $post_id_array); + } elseif (strstr($post_id_array, ',')) { + $post_id_array = explode(',', $post_id_array); + } else { + $post_id = intval($post_id_array); - $post_id_array = array(); - $post_id_array[] = $post_id; - } - } + $post_id_array = array(); + $post_id_array[] = $post_id; + } + } - if (!sizeof($post_id_array)) - { - return; - } + if (!sizeof($post_id_array)) { + return; + } - // First of all, determine the post id and attach_id - if ($attach_id_array === 0) - { - $attach_id_array = array(); + // First of all, determine the post id and attach_id + if ($attach_id_array === 0) { + $attach_id_array = array(); - // Get the attach_ids to fill the array - $whereclause = 'WHERE post_id IN (' . implode(', ', $post_id_array) . ')'; + // Get the attach_ids to fill the array + $whereclause = 'WHERE post_id IN (' . implode(', ', $post_id_array) . ')'; - $sql = 'SELECT attach_id + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS . " $whereclause GROUP BY attach_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select attachment id #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select attachment id #1'); + } - $num_attach_list = DB()->num_rows($result); + $num_attach_list = DB()->num_rows($result); - if ($num_attach_list == 0) - { - DB()->sql_freeresult($result); - return; - } + if ($num_attach_list == 0) { + DB()->sql_freeresult($result); + return; + } - while ($row = DB()->sql_fetchrow($result)) - { - $attach_id_array[] = (int) $row['attach_id']; - } - DB()->sql_freeresult($result); - } + while ($row = DB()->sql_fetchrow($result)) { + $attach_id_array[] = (int)$row['attach_id']; + } + DB()->sql_freeresult($result); + } - if (!is_array($attach_id_array)) - { - if (strstr($attach_id_array, ', ')) - { - $attach_id_array = explode(', ', $attach_id_array); - } - else if (strstr($attach_id_array, ',')) - { - $attach_id_array = explode(',', $attach_id_array); - } - else - { - $attach_id = intval($attach_id_array); + if (!is_array($attach_id_array)) { + if (strstr($attach_id_array, ', ')) { + $attach_id_array = explode(', ', $attach_id_array); + } elseif (strstr($attach_id_array, ',')) { + $attach_id_array = explode(',', $attach_id_array); + } else { + $attach_id = intval($attach_id_array); - $attach_id_array = array(); - $attach_id_array[] = $attach_id; - } - } + $attach_id_array = array(); + $attach_id_array[] = $attach_id; + } + } - if (!sizeof($attach_id_array)) - { - return; - } + if (!sizeof($attach_id_array)) { + return; + } - $sql_id = 'post_id'; + $sql_id = 'post_id'; - if (sizeof($post_id_array) && sizeof($attach_id_array)) - { - $sql = 'DELETE FROM ' . BB_ATTACHMENTS . ' + if (sizeof($post_id_array) && sizeof($attach_id_array)) { + $sql = 'DELETE FROM ' . BB_ATTACHMENTS . ' WHERE attach_id IN (' . implode(', ', $attach_id_array) . ") AND $sql_id IN (" . implode(', ', $post_id_array) . ')'; - if (!(DB()->sql_query($sql))) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } + if (!(DB()->sql_query($sql))) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } - //bt - if ($sql_id == 'post_id') - { - $sql = "SELECT topic_id FROM ". BB_BT_TORRENTS ." WHERE attach_id IN(". implode(',', $attach_id_array) .")"; + //bt + if ($sql_id == 'post_id') { + $sql = "SELECT topic_id FROM " . BB_BT_TORRENTS . " WHERE attach_id IN(" . implode(',', $attach_id_array) . ")"; - if (!$result = DB()->sql_query($sql)) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } + if (!$result = DB()->sql_query($sql)) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } - $torrents_sql = array(); + $torrents_sql = array(); - while ($row = DB()->sql_fetchrow($result)) - { - $torrents_sql[] = $row['topic_id']; - } + while ($row = DB()->sql_fetchrow($result)) { + $torrents_sql[] = $row['topic_id']; + } - if ($torrents_sql = implode(',', $torrents_sql)) - { - // Remove peers from tracker - $sql = "DELETE FROM ". BB_BT_TRACKER ." + if ($torrents_sql = implode(',', $torrents_sql)) { + // Remove peers from tracker + $sql = "DELETE FROM " . BB_BT_TRACKER . " WHERE topic_id IN($torrents_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not delete peers'); - } - } - // Delete torrents - $sql = "DELETE FROM ". BB_BT_TORRENTS ." - WHERE attach_id IN(". implode(',', $attach_id_array) .")"; + if (!DB()->sql_query($sql)) { + bb_die('Could not delete peers'); + } + } + // Delete torrents + $sql = "DELETE FROM " . BB_BT_TORRENTS . " + WHERE attach_id IN(" . implode(',', $attach_id_array) . ")"; - if (!DB()->sql_query($sql)) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } - } - //bt end + if (!DB()->sql_query($sql)) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } + } + //bt end - for ($i = 0; $i < sizeof($attach_id_array); $i++) - { - $sql = 'SELECT attach_id + for ($i = 0; $i < sizeof($attach_id_array); $i++) { + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS . ' - WHERE attach_id = ' . (int) $attach_id_array[$i]; + WHERE attach_id = ' . (int)$attach_id_array[$i]; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select Attachment id #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select Attachment id #2'); + } - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows == 0) - { - $sql = 'SELECT attach_id, physical_filename, thumbnail + if ($num_rows == 0) { + $sql = 'SELECT attach_id, physical_filename, thumbnail FROM ' . BB_ATTACHMENTS_DESC . ' - WHERE attach_id = ' . (int) $attach_id_array[$i]; + WHERE attach_id = ' . (int)$attach_id_array[$i]; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attach description table'); - } - $num_rows = DB()->num_rows($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attach description table'); + } + $num_rows = DB()->num_rows($result); - if ($num_rows != 0) - { - $num_attach = $num_rows; - $attachments = DB()->sql_fetchrowset($result); - DB()->sql_freeresult($result); + if ($num_rows != 0) { + $num_attach = $num_rows; + $attachments = DB()->sql_fetchrowset($result); + DB()->sql_freeresult($result); - // delete attachments - for ($j = 0; $j < $num_attach; $j++) - { - unlink_attach($attachments[$j]['physical_filename']); + // delete attachments + for ($j = 0; $j < $num_attach; $j++) { + unlink_attach($attachments[$j]['physical_filename']); - if (intval($attachments[$j]['thumbnail']) == 1) - { - unlink_attach($attachments[$j]['physical_filename'], MODE_THUMBNAIL); - } + if (intval($attachments[$j]['thumbnail']) == 1) { + unlink_attach($attachments[$j]['physical_filename'], MODE_THUMBNAIL); + } - $sql = 'DELETE FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int) $attachments[$j]['attach_id']; + $sql = 'DELETE FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id = ' . (int)$attachments[$j]['attach_id']; - if (!(DB()->sql_query($sql))) - { - bb_die($lang['ERROR_DELETED_ATTACHMENTS']); - } - } - } - else - { - DB()->sql_freeresult($result); - } - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die($lang['ERROR_DELETED_ATTACHMENTS']); + } + } + } else { + DB()->sql_freeresult($result); + } + } + } + } - // Now Sync the Topic/PM - if (sizeof($post_id_array)) - { - $sql = 'SELECT topic_id + // Now Sync the Topic/PM + if (sizeof($post_id_array)) { + $sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id IN (' . implode(', ', $post_id_array) . ') GROUP BY topic_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select topic id'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select topic id'); + } - while ($row = DB()->sql_fetchrow($result)) - { - attachment_sync_topic($row['topic_id']); - } - DB()->sql_freeresult($result); - } -} \ No newline at end of file + while ($row = DB()->sql_fetchrow($result)) { + attachment_sync_topic($row['topic_id']); + } + DB()->sql_freeresult($result); + } +} diff --git a/library/attach_mod/includes/functions_filetypes.php b/library/attach_mod/includes/functions_filetypes.php index 928f05b4c..7d3ac79d6 100644 --- a/library/attach_mod/includes/functions_filetypes.php +++ b/library/attach_mod/includes/functions_filetypes.php @@ -1,293 +1,274 @@ = 4294967294) - { - $value -= 4294967296; - } + $value = ord($data[0]) + (ord($data[1]) << 8) + (ord($data[2]) << 16) + (ord($data[3]) << 24); + if ($value >= 4294967294) { + $value -= 4294967296; + } - return $value; + return $value; } /** -* Read Word (2 Bytes) from File - Note: It's an Intel Word -*/ + * Read Word (2 Bytes) from File - Note: It's an Intel Word + */ function read_word($fp) { - $data = fread($fp, 2); + $data = fread($fp, 2); - $value = ord($data[1]) * 256 + ord($data[0]); + $value = ord($data[1]) * 256 + ord($data[0]); - return $value; + return $value; } /** -* Read Byte -*/ + * Read Byte + */ function read_byte($fp) { - $data = fread($fp, 1); + $data = fread($fp, 1); - $value = ord($data); + $value = ord($data); - return $value; + return $value; } /** -* Get Image Dimensions -*/ + * Get Image Dimensions + */ function image_getdimension($file) { + $size = @getimagesize($file); - $size = @getimagesize($file); + if ($size[0] != 0 || $size[1] != 0) { + return $size; + } - if ($size[0] != 0 || $size[1] != 0) - { - return $size; - } + // Try to get the Dimension manually, depending on the mimetype + $fp = @fopen($file, 'rb'); + if (!$fp) { + return $size; + } - // Try to get the Dimension manually, depending on the mimetype - $fp = @fopen($file, 'rb'); - if (!$fp) - { - return $size; - } + $error = false; - $error = FALSE; + // BMP - IMAGE - // BMP - IMAGE + $tmp_str = fread($fp, 2); + if ($tmp_str == 'BM') { + $length = read_longint($fp); - $tmp_str = fread($fp, 2); - if ($tmp_str == 'BM') - { - $length = read_longint($fp); + if ($length <= 6) { + $error = true; + } - if ($length <= 6) - { - $error = true; - } + if (!$error) { + $i = read_longint($fp); + if ($i != 0) { + $error = true; + } + } - if (!$error) - { - $i = read_longint($fp); - if ( $i != 0) - { - $error = true; - } - } + if (!$error) { + $i = read_longint($fp); - if (!$error) - { - $i = read_longint($fp); + if ($i != 0x3E && $i != 0x76 && $i != 0x436 && $i != 0x36) { + $error = true; + } + } - if ($i != 0x3E && $i != 0x76 && $i != 0x436 && $i != 0x36) - { - $error = true; - } - } + if (!$error) { + $tmp_str = fread($fp, 4); + $width = read_longint($fp); + $height = read_longint($fp); - if (!$error) - { - $tmp_str = fread($fp, 4); - $width = read_longint($fp); - $height = read_longint($fp); + if ($width > 3000 || $height > 3000) { + $error = true; + } + } + } else { + $error = true; + } - if ($width > 3000 || $height > 3000) - { - $error = true; - } - } - } - else - { - $error = true; - } + if (!$error) { + fclose($fp); + return array( + $width, + $height, + 6 + ); + } - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 6 - ); - } + $error = false; + fclose($fp); - $error = false; - fclose($fp); + // GIF - IMAGE - // GIF - IMAGE + $fp = @fopen($file, 'rb'); - $fp = @fopen($file, 'rb'); + $tmp_str = fread($fp, 3); - $tmp_str = fread($fp, 3); + if ($tmp_str == 'GIF') { + $tmp_str = fread($fp, 3); + $width = read_word($fp); + $height = read_word($fp); - if ($tmp_str == 'GIF') - { - $tmp_str = fread($fp, 3); - $width = read_word($fp); - $height = read_word($fp); + $info_byte = fread($fp, 1); + $info_byte = ord($info_byte); + if (($info_byte & 0x80) != 0x80 && ($info_byte & 0x80) != 0) { + $error = true; + } - $info_byte = fread($fp, 1); - $info_byte = ord($info_byte); - if (($info_byte & 0x80) != 0x80 && ($info_byte & 0x80) != 0) - { - $error = true; - } + if (!$error) { + if (($info_byte & 8) != 0) { + $error = true; + } + } + } else { + $error = true; + } - if (!$error) - { - if (($info_byte & 8) != 0) - { - $error = true; - } + if (!$error) { + fclose($fp); + return array( + $width, + $height, + 1 + ); + } - } - } - else - { - $error = true; - } + $error = false; + fclose($fp); - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 1 - ); - } + // JPG - IMAGE + $fp = @fopen($file, 'rb'); - $error = false; - fclose($fp); + $tmp_str = fread($fp, 4); + $w1 = read_word($fp); - // JPG - IMAGE - $fp = @fopen($file, 'rb'); + if (intval($w1) < 16) { + $error = true; + } - $tmp_str = fread($fp, 4); - $w1 = read_word($fp); + if (!$error) { + $tmp_str = fread($fp, 4); + if ($tmp_str == 'JFIF') { + $o_byte = fread($fp, 1); + if (intval($o_byte) != 0) { + $error = true; + } - if (intval($w1) < 16) - { - $error = true; - } + if (!$error) { + $str = fread($fp, 2); + $b = read_byte($fp); - if (!$error) - { - $tmp_str = fread($fp, 4); - if ($tmp_str == 'JFIF') - { - $o_byte = fread($fp, 1); - if (intval($o_byte) != 0) - { - $error = true; - } + if ($b != 0 && $b != 1 && $b != 2) { + $error = true; + } + } - if (!$error) - { - $str = fread($fp, 2); - $b = read_byte($fp); + if (!$error) { + $width = read_word($fp); + $height = read_word($fp); - if ($b != 0 && $b != 1 && $b != 2) - { - $error = true; - } - } + if ($width <= 0 || $height <= 0) { + $error = true; + } + } + } + } else { + $error = true; + } - if (!$error) - { - $width = read_word($fp); - $height = read_word($fp); + if (!$error) { + fclose($fp); + return array( + $width, + $height, + 2 + ); + } - if ($width <= 0 || $height <= 0) - { - $error = true; - } - } - } - } - else - { - $error = true; - } + $error = false; + fclose($fp); - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 2 - ); - } + // PCX - IMAGE - $error = false; - fclose($fp); + $fp = @fopen($file, 'rb'); - // PCX - IMAGE + $tmp_str = fread($fp, 3); - $fp = @fopen($file, 'rb'); + if ((ord($tmp_str[0]) == 10) && (ord($tmp_str[1]) == 0 || ord($tmp_str[1]) == 2 || ord($tmp_str[1]) == 3 || ord($tmp_str[1]) == 4 || ord($tmp_str[1]) == 5) && (ord($tmp_str[2]) == 1)) { + $b = fread($fp, 1); - $tmp_str = fread($fp, 3); + if (ord($b) != 1 && ord($b) != 2 && ord($b) != 4 && ord($b) != 8 && ord($b) != 24) { + $error = true; + } - if ((ord($tmp_str[0]) == 10) && (ord($tmp_str[1]) == 0 || ord($tmp_str[1]) == 2 || ord($tmp_str[1]) == 3 || ord($tmp_str[1]) == 4 || ord($tmp_str[1]) == 5) && (ord($tmp_str[2]) == 1)) - { - $b = fread($fp, 1); + if (!$error) { + $xmin = read_word($fp); + $ymin = read_word($fp); + $xmax = read_word($fp); + $ymax = read_word($fp); + $tmp_str = fread($fp, 52); - if (ord($b) != 1 && ord($b) != 2 && ord($b) != 4 && ord($b) != 8 && ord($b) != 24) - { - $error = true; - } + $b = fread($fp, 1); + if ($b != 0) { + $error = true; + } + } - if (!$error) - { - $xmin = read_word($fp); - $ymin = read_word($fp); - $xmax = read_word($fp); - $ymax = read_word($fp); - $tmp_str = fread($fp, 52); + if (!$error) { + $width = $xmax - $xmin + 1; + $height = $ymax - $ymin + 1; + } + } else { + $error = true; + } - $b = fread($fp, 1); - if ($b != 0) - { - $error = true; - } - } + if (!$error) { + fclose($fp); + return array( + $width, + $height, + 7 + ); + } - if (!$error) - { - $width = $xmax - $xmin + 1; - $height = $ymax - $ymin + 1; - } - } - else - { - $error = true; - } + fclose($fp); - if (!$error) - { - fclose($fp); - return array( - $width, - $height, - 7 - ); - } - - fclose($fp); - - return $size; -} \ No newline at end of file + return $size; +} diff --git a/library/attach_mod/includes/functions_includes.php b/library/attach_mod/includes/functions_includes.php index a4e8708ad..d4e7ed501 100644 --- a/library/attach_mod/includes/functions_includes.php +++ b/library/attach_mod/includes/functions_includes.php @@ -1,204 +1,187 @@ '; - $s_auth_can .= (($is_auth['auth_download']) ? $lang['RULES_DOWNLOAD_CAN'] : $lang['RULES_DOWNLOAD_CANNOT'] ) . '
        '; + // If you want to have the rules window link within the forum view too, comment out the two lines, and comment the third line + $s_auth_can .= (($is_auth['auth_attachments']) ? $lang['RULES_ATTACH_CAN'] : $lang['RULES_ATTACH_CANNOT']) . '
        '; + $s_auth_can .= (($is_auth['auth_download']) ? $lang['RULES_DOWNLOAD_CAN'] : $lang['RULES_DOWNLOAD_CANNOT']) . '
        '; } /** -* Called from admin_users.php and admin_groups.php in order to process Quota Settings (admin/admin_users.php:admin/admin_groups.php) -*/ + * Called from admin_users.php and admin_groups.php in order to process Quota Settings (admin/admin_users.php:admin/admin_groups.php) + */ function attachment_quota_settings($admin_mode, $submit = false, $mode) { - global $template, $lang, $attach_config; + global $template, $lang, $attach_config; - if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) - { - $upload_dir = $attach_config['upload_dir']; - } - else - { - $upload_dir = BB_ROOT . $attach_config['upload_dir']; - } + if ($attach_config['upload_dir'][0] == '/' || ($attach_config['upload_dir'][0] != '/' && $attach_config['upload_dir'][1] == ':')) { + $upload_dir = $attach_config['upload_dir']; + } else { + $upload_dir = BB_ROOT . $attach_config['upload_dir']; + } - include(ATTACH_DIR .'includes/functions_selects.php'); - if (!function_exists("process_quota_settings")) - include(ATTACH_DIR . 'includes/functions_admin.php'); + include(ATTACH_DIR . 'includes/functions_selects.php'); + if (!function_exists("process_quota_settings")) { + include(ATTACH_DIR . 'includes/functions_admin.php'); + } - $user_id = 0; + $user_id = 0; - if ($admin_mode == 'user') - { - // We overwrite submit here... to be sure - $submit = (isset($_POST['submit'])) ? true : false; + if ($admin_mode == 'user') { + // We overwrite submit here... to be sure + $submit = (isset($_POST['submit'])) ? true : false; - if (!$submit && $mode != 'save') - { - $user_id = get_var(POST_USERS_URL, 0); - $u_name = get_var('username', ''); + if (!$submit && $mode != 'save') { + $user_id = get_var(POST_USERS_URL, 0); + $u_name = get_var('username', ''); - if (!$user_id && !$u_name) - { - bb_die($lang['NO_USER_ID_SPECIFIED'] ); - } + if (!$user_id && !$u_name) { + bb_die($lang['NO_USER_ID_SPECIFIED']); + } - if ($user_id) - { - $this_userdata['user_id'] = $user_id; - } - else - { - // Get userdata is handling the sanitizing of username - $this_userdata = get_userdata($_POST['username'], true); - } + if ($user_id) { + $this_userdata['user_id'] = $user_id; + } else { + // Get userdata is handling the sanitizing of username + $this_userdata = get_userdata($_POST['username'], true); + } - $user_id = (int) $this_userdata['user_id']; - } - else - { - $user_id = get_var('id', 0); + $user_id = (int)$this_userdata['user_id']; + } else { + $user_id = get_var('id', 0); - if (!$user_id) - { - bb_die($lang['NO_USER_ID_SPECIFIED'] ); - } - } - } + if (!$user_id) { + bb_die($lang['NO_USER_ID_SPECIFIED']); + } + } + } - if ($admin_mode == 'user' && !$submit && $mode != 'save') - { - // Show the contents - $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE user_id = ' . (int) $user_id; + if ($admin_mode == 'user' && !$submit && $mode != 'save') { + // Show the contents + $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE user_id = ' . (int)$user_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to get quota settings #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to get quota settings #1'); + } - $pm_quota = $upload_quota = 0; + $pm_quota = $upload_quota = 0; - if ($row = DB()->sql_fetchrow($result)) - { - do - { - if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $upload_quota = $row['quota_limit_id']; - } - else if ($row['quota_type'] == QUOTA_PM_LIMIT) - { - $pm_quota = $row['quota_limit_id']; - } - } - while ($row = DB()->sql_fetchrow($result)); - } - else - { - // Set Default Quota Limit - $upload_quota = $attach_config['default_upload_quota']; - $pm_quota = $attach_config['default_pm_quota']; + if ($row = DB()->sql_fetchrow($result)) { + do { + if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $upload_quota = $row['quota_limit_id']; + } elseif ($row['quota_type'] == QUOTA_PM_LIMIT) { + $pm_quota = $row['quota_limit_id']; + } + } while ($row = DB()->sql_fetchrow($result)); + } else { + // Set Default Quota Limit + $upload_quota = $attach_config['default_upload_quota']; + $pm_quota = $attach_config['default_pm_quota']; + } + DB()->sql_freeresult($result); - } - DB()->sql_freeresult($result); + $template->assign_vars(array( + 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('user_upload_quota', $upload_quota), + 'S_SELECT_PM_QUOTA' => quota_limit_select('user_pm_quota', $pm_quota), + )); + } - $template->assign_vars(array( - 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('user_upload_quota', $upload_quota), - 'S_SELECT_PM_QUOTA' => quota_limit_select('user_pm_quota', $pm_quota), - )); - } + if ($admin_mode == 'user' && $submit && @$_POST['delete_user']) { + process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, 0); + process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, 0); + } elseif ($admin_mode == 'user' && $submit && $mode == 'save') { + // Get the contents + $upload_quota = get_var('user_upload_quota', 0); + $pm_quota = get_var('user_pm_quota', 0); - if ($admin_mode == 'user' && $submit && @$_POST['delete_user']) - { - process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, 0); - process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, 0); - } - else if ($admin_mode == 'user' && $submit && $mode == 'save') - { - // Get the contents - $upload_quota = get_var('user_upload_quota', 0); - $pm_quota = get_var('user_pm_quota', 0); + process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, $upload_quota); + process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, $pm_quota); + } - process_quota_settings($admin_mode, $user_id, QUOTA_UPLOAD_LIMIT, $upload_quota); - process_quota_settings($admin_mode, $user_id, QUOTA_PM_LIMIT, $pm_quota); - } + if ($admin_mode == 'group' && $mode == 'newgroup') { + return; + } - if ($admin_mode == 'group' && $mode == 'newgroup') - { - return; - } + if ($admin_mode == 'group' && !$submit && isset($_POST['edit'])) { + // Get group id again + $group_id = get_var(POST_GROUPS_URL, 0); - if ($admin_mode == 'group' && !$submit && isset($_POST['edit'])) - { - // Get group id again - $group_id = get_var(POST_GROUPS_URL, 0); + // Show the contents + $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE group_id = ' . (int)$group_id; - // Show the contents - $sql = 'SELECT quota_limit_id, quota_type FROM ' . BB_QUOTA . ' WHERE group_id = ' . (int) $group_id; + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to get quota settings #2'); + } - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to get quota settings #2'); - } + $pm_quota = $upload_quota = 0; - $pm_quota = $upload_quota = 0; + if ($row = DB()->sql_fetchrow($result)) { + do { + if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) { + $upload_quota = $row['quota_limit_id']; + } elseif ($row['quota_type'] == QUOTA_PM_LIMIT) { + $pm_quota = $row['quota_limit_id']; + } + } while ($row = DB()->sql_fetchrow($result)); + } else { + // Set Default Quota Limit + $upload_quota = $attach_config['default_upload_quota']; + $pm_quota = $attach_config['default_pm_quota']; + } + DB()->sql_freeresult($result); - if ($row = DB()->sql_fetchrow($result)) - { - do - { - if ($row['quota_type'] == QUOTA_UPLOAD_LIMIT) - { - $upload_quota = $row['quota_limit_id']; - } - else if ($row['quota_type'] == QUOTA_PM_LIMIT) - { - $pm_quota = $row['quota_limit_id']; - } - } - while ($row = DB()->sql_fetchrow($result)); - } - else - { - // Set Default Quota Limit - $upload_quota = $attach_config['default_upload_quota']; - $pm_quota = $attach_config['default_pm_quota']; - } - DB()->sql_freeresult($result); + $template->assign_vars(array( + 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('group_upload_quota', $upload_quota), + 'S_SELECT_PM_QUOTA' => quota_limit_select('group_pm_quota', $pm_quota), + )); + } - $template->assign_vars(array( - 'S_SELECT_UPLOAD_QUOTA' => quota_limit_select('group_upload_quota', $upload_quota), - 'S_SELECT_PM_QUOTA' => quota_limit_select('group_pm_quota', $pm_quota), - )); - } + if ($admin_mode == 'group' && $submit && isset($_POST['group_delete'])) { + $group_id = get_var(POST_GROUPS_URL, 0); - if ($admin_mode == 'group' && $submit && isset($_POST['group_delete'])) - { - $group_id = get_var(POST_GROUPS_URL, 0); + process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, 0); + process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, 0); + } elseif ($admin_mode == 'group' && $submit) { + $group_id = get_var(POST_GROUPS_URL, 0); - process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, 0); - process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, 0); - } - else if ($admin_mode == 'group' && $submit) - { - $group_id = get_var(POST_GROUPS_URL, 0); + // Get the contents + $upload_quota = get_var('group_upload_quota', 0); + $pm_quota = get_var('group_pm_quota', 0); - // Get the contents - $upload_quota = get_var('group_upload_quota', 0); - $pm_quota = get_var('group_pm_quota', 0); - - process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, $upload_quota); - process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, $pm_quota); - } -} \ No newline at end of file + process_quota_settings($admin_mode, $group_id, QUOTA_UPLOAD_LIMIT, $upload_quota); + process_quota_settings($admin_mode, $group_id, QUOTA_PM_LIMIT, $pm_quota); + } +} diff --git a/library/attach_mod/includes/functions_selects.php b/library/attach_mod/includes/functions_selects.php index be709e94c..1a771aa8a 100644 --- a/library/attach_mod/includes/functions_selects.php +++ b/library/attach_mod/includes/functions_selects.php @@ -1,251 +1,245 @@ sql_query($sql))) - { - bb_die('Could not query extension groups table #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table #1'); + } - $group_select = ''; - $group_name = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $group_name = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - $group_name[$num_rows]['group_id'] = 0; - $group_name[$num_rows]['group_name'] = $lang['NOT_ASSIGNED']; + if ($num_rows > 0) { + $group_name[$num_rows]['group_id'] = 0; + $group_name[$num_rows]['group_name'] = $lang['NOT_ASSIGNED']; - for ($i = 0; $i < sizeof($group_name); $i++) - { - if (!$default_group) - { - $selected = ($i == 0) ? ' selected="selected"' : ''; - } - else - { - $selected = ($group_name[$i]['group_id'] == $default_group) ? ' selected="selected"' : ''; - } + for ($i = 0; $i < sizeof($group_name); $i++) { + if (!$default_group) { + $selected = ($i == 0) ? ' selected="selected"' : ''; + } else { + $selected = ($group_name[$i]['group_id'] == $default_group) ? ' selected="selected"' : ''; + } - $group_select .= ''; - } - } + $group_select .= ''; + } + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* select download mode -*/ + * select download mode + */ function download_select($select_name, $group_id = 0) { - global $types_download, $modes_download; + global $types_download, $modes_download; - if ($group_id) - { - $sql = 'SELECT download_mode + if ($group_id) { + $sql = 'SELECT download_mode FROM ' . BB_EXTENSION_GROUPS . ' - WHERE group_id = ' . (int) $group_id; + WHERE group_id = ' . (int)$group_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extension groups table #2'); - } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extension groups table #2'); + } + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - if (!isset($row['download_mode'])) - { - return ''; - } + if (!isset($row['download_mode'])) { + return ''; + } - $download_mode = $row['download_mode']; - } + $download_mode = $row['download_mode']; + } - $group_select = ''; - for ($i = 0; $i < sizeof($types_download); $i++) - { - if (!$group_id) - { - $selected = ($types_download[$i] == INLINE_LINK) ? ' selected="selected"' : ''; - } - else - { - $selected = ($row['download_mode'] == $types_download[$i]) ? ' selected="selected"' : ''; - } + for ($i = 0; $i < sizeof($types_download); $i++) { + if (!$group_id) { + $selected = ($types_download[$i] == INLINE_LINK) ? ' selected="selected"' : ''; + } else { + $selected = ($row['download_mode'] == $types_download[$i]) ? ' selected="selected"' : ''; + } - $group_select .= ''; - } + $group_select .= ''; + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* select category types -*/ + * select category types + */ function category_select($select_name, $group_id = 0) { - global $types_category, $modes_category; + global $types_category, $modes_category; - $sql = 'SELECT group_id, cat_id FROM ' . BB_EXTENSION_GROUPS; + $sql = 'SELECT group_id, cat_id FROM ' . BB_EXTENSION_GROUPS; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not select category'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select category'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - $type_category = 0; + $type_category = 0; - if ($num_rows > 0) - { - for ($i = 0; $i < $num_rows; $i++) - { - if ($group_id == $rows[$i]['group_id']) - { - $category_type = $rows[$i]['cat_id']; - } - } - } + if ($num_rows > 0) { + for ($i = 0; $i < $num_rows; $i++) { + if ($group_id == $rows[$i]['group_id']) { + $category_type = $rows[$i]['cat_id']; + } + } + } - $types = array(NONE_CAT); - $modes = array('none'); + $types = array(NONE_CAT); + $modes = array('none'); - for ($i = 0; $i < sizeof($types_category); $i++) - { - $types[] = $types_category[$i]; - $modes[] = $modes_category[$i]; - } + for ($i = 0; $i < sizeof($types_category); $i++) { + $types[] = $types_category[$i]; + $modes[] = $modes_category[$i]; + } - $group_select = ''; - for ($i = 0; $i < sizeof($types); $i++) - { - if (!$group_id) - { - $selected = ($types[$i] == NONE_CAT) ? ' selected="selected"' : ''; - } - else - { - $selected = ($types[$i] == $category_type) ? ' selected="selected"' : ''; - } + for ($i = 0; $i < sizeof($types); $i++) { + if (!$group_id) { + $selected = ($types[$i] == NONE_CAT) ? ' selected="selected"' : ''; + } else { + $selected = ($types[$i] == $category_type) ? ' selected="selected"' : ''; + } - $group_select .= ''; - } + $group_select .= ''; + } - $group_select .= ''; + $group_select .= ''; - return $group_select; + return $group_select; } /** -* Select size mode -*/ + * Select size mode + */ function size_select($select_name, $size_compare) { - global $lang; + global $lang; - $size_types_text = array($lang['BYTES'], $lang['KB'], $lang['MB']); - $size_types = array('b', 'kb', 'mb'); + $size_types_text = array($lang['BYTES'], $lang['KB'], $lang['MB']); + $size_types = array('b', 'kb', 'mb'); - $select_field = ''; - for ($i = 0; $i < sizeof($size_types_text); $i++) - { - $selected = ($size_compare == $size_types[$i]) ? ' selected="selected"' : ''; - $select_field .= ''; - } + for ($i = 0; $i < sizeof($size_types_text); $i++) { + $selected = ($size_compare == $size_types[$i]) ? ' selected="selected"' : ''; + $select_field .= ''; + } - $select_field .= ''; + $select_field .= ''; - return $select_field; + return $select_field; } /** -* select quota limit -*/ + * select quota limit + */ function quota_limit_select($select_name, $default_quota = 0) { - global $lang; + global $lang; - $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; + $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table #1'); + } - $quota_select = ''; + $quota_name[0]['quota_limit_id'] = 0; + $quota_name[0]['quota_desc'] = $lang['NOT_ASSIGNED']; - while ($row = DB()->sql_fetchrow($result)) - { - $quota_name[] = $row; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $quota_name[] = $row; + } + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($quota_name); $i++) - { - $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected="selected"' : ''; - $quota_select .= ''; - } - $quota_select .= ''; + for ($i = 0; $i < sizeof($quota_name); $i++) { + $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected="selected"' : ''; + $quota_select .= ''; + } + $quota_select .= ''; - return $quota_select; + return $quota_select; } /** -* select default quota limit -*/ + * select default quota limit + */ function default_quota_limit_select($select_name, $default_quota = 0) { - global $lang; + global $lang; - $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; + $sql = 'SELECT quota_limit_id, quota_desc FROM ' . BB_QUOTA_LIMITS . ' ORDER BY quota_limit ASC'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query quota limits table #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query quota limits table #2'); + } - $quota_select = ''; + $quota_name[0]['quota_limit_id'] = 0; + $quota_name[0]['quota_desc'] = $lang['NO_QUOTA_LIMIT']; - while ($row = DB()->sql_fetchrow($result)) - { - $quota_name[] = $row; - } - DB()->sql_freeresult($result); + while ($row = DB()->sql_fetchrow($result)) { + $quota_name[] = $row; + } + DB()->sql_freeresult($result); - for ($i = 0; $i < sizeof($quota_name); $i++) - { - $selected = ( $quota_name[$i]['quota_limit_id'] == $default_quota ) ? ' selected="selected"' : ''; - $quota_select .= ''; - } - $quota_select .= ''; + for ($i = 0; $i < sizeof($quota_name); $i++) { + $selected = ($quota_name[$i]['quota_limit_id'] == $default_quota) ? ' selected="selected"' : ''; + $quota_select .= ''; + } + $quota_select .= ''; - return $quota_select; -} \ No newline at end of file + return $quota_select; +} diff --git a/library/attach_mod/includes/functions_thumbs.php b/library/attach_mod/includes/functions_thumbs.php index 54b9035d2..d09031618 100644 --- a/library/attach_mod/includes/functions_thumbs.php +++ b/library/attach_mod/includes/functions_thumbs.php @@ -1,189 +1,194 @@ $height) - { - return array( - round($width * ($max_width / $width)), - round($height * ($max_width / $width)) - ); - } - else - { - return array( - round($width * ($max_width / $height)), - round($height * ($max_width / $height)) - ); - } + if ($width > $height) { + return array( + round($width * ($max_width / $width)), + round($height * ($max_width / $width)) + ); + } else { + return array( + round($width * ($max_width / $height)), + round($height * ($max_width / $height)) + ); + } } /** -* Check if imagick is present -*/ + * Check if imagick is present + */ function is_imagick() { - global $imagick, $attach_config; + global $imagick, $attach_config; - if ($attach_config['img_imagick'] != '') - { - $imagick = $attach_config['img_imagick']; - return true; - } - else - { - return false; - } + if ($attach_config['img_imagick'] != '') { + $imagick = $attach_config['img_imagick']; + return true; + } else { + return false; + } } /** -* Get supported image types -*/ + * Get supported image types + */ function get_supported_image_types($type) { - if (@extension_loaded('gd')) - { - $format = imagetypes(); - $new_type = 0; + if (@extension_loaded('gd')) { + $format = imagetypes(); + $new_type = 0; - switch ($type) - { - case 1: - $new_type = ($format & IMG_GIF) ? IMG_GIF : 0; - break; - case 2: - case 9: - case 10: - case 11: - case 12: - $new_type = ($format & IMG_JPG) ? IMG_JPG : 0; - break; - case 3: - $new_type = ($format & IMG_PNG) ? IMG_PNG : 0; - break; - case 6: - case 15: - $new_type = ($format & IMG_WBMP) ? IMG_WBMP : 0; - break; - } + switch ($type) { + case 1: + $new_type = ($format & IMG_GIF) ? IMG_GIF : 0; + break; + case 2: + case 9: + case 10: + case 11: + case 12: + $new_type = ($format & IMG_JPG) ? IMG_JPG : 0; + break; + case 3: + $new_type = ($format & IMG_PNG) ? IMG_PNG : 0; + break; + case 6: + case 15: + $new_type = ($format & IMG_WBMP) ? IMG_WBMP : 0; + break; + } - return array( - 'gd' => ($new_type) ? true : false, - 'format' => $new_type, - 'version' => (function_exists('imagecreatetruecolor')) ? 2 : 1 - ); - } + return array( + 'gd' => ($new_type) ? true : false, + 'format' => $new_type, + 'version' => (function_exists('imagecreatetruecolor')) ? 2 : 1 + ); + } - return array('gd' => false); + return array('gd' => false); } /** -* Create thumbnail -*/ + * Create thumbnail + */ function create_thumbnail($source, $new_file, $mimetype) { - global $attach_config, $imagick; + global $attach_config, $imagick; - $source = amod_realpath($source); - $min_filesize = (int) $attach_config['img_min_thumb_filesize']; - $img_filesize = (@file_exists($source)) ? @filesize($source) : false; + $source = amod_realpath($source); + $min_filesize = (int)$attach_config['img_min_thumb_filesize']; + $img_filesize = (@file_exists($source)) ? @filesize($source) : false; - if (!$img_filesize || $img_filesize <= $min_filesize) - { - return false; - } + if (!$img_filesize || $img_filesize <= $min_filesize) { + return false; + } - list($width, $height, $type, ) = getimagesize($source); + list($width, $height, $type,) = getimagesize($source); - if (!$width || !$height) - { - return false; - } + if (!$width || !$height) { + return false; + } - list($new_width, $new_height) = get_img_size_format($width, $height); + list($new_width, $new_height) = get_img_size_format($width, $height); - $tmp_path = $old_file = ''; + $tmp_path = $old_file = ''; - $used_imagick = false; + $used_imagick = false; - if (is_imagick()) - { - passthru($imagick . ' -quality 85 -antialias -sample ' . $new_width . 'x' . $new_height . ' "' . str_replace('\\', '/', $source) . '" +profile "*" "' . str_replace('\\', '/', $new_file) . '"'); - if (@file_exists($new_file)) - { - $used_imagick = true; - } - } + if (is_imagick()) { + passthru($imagick . ' -quality 85 -antialias -sample ' . $new_width . 'x' . $new_height . ' "' . str_replace('\\', '/', $source) . '" +profile "*" "' . str_replace('\\', '/', $new_file) . '"'); + if (@file_exists($new_file)) { + $used_imagick = true; + } + } - if (!$used_imagick) - { - $type = get_supported_image_types($type); + if (!$used_imagick) { + $type = get_supported_image_types($type); - if ($type['gd']) - { - switch ($type['format']) - { - case IMG_GIF: - $image = imagecreatefromgif($source); - break; - case IMG_JPG: - $image = imagecreatefromjpeg($source); - break; - case IMG_PNG: - $image = imagecreatefrompng($source); - break; - case IMG_WBMP: - $image = imagecreatefromwbmp($source); - break; - } + if ($type['gd']) { + switch ($type['format']) { + case IMG_GIF: + $image = imagecreatefromgif($source); + break; + case IMG_JPG: + $image = imagecreatefromjpeg($source); + break; + case IMG_PNG: + $image = imagecreatefrompng($source); + break; + case IMG_WBMP: + $image = imagecreatefromwbmp($source); + break; + } - if ($type['version'] == 1 || !$attach_config['use_gd2']) - { - $new_image = imagecreate($new_width, $new_height); - imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); - } - else - { - $new_image = imagecreatetruecolor($new_width, $new_height); - imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); - } + if ($type['version'] == 1 || !$attach_config['use_gd2']) { + $new_image = imagecreate($new_width, $new_height); + imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + } else { + $new_image = imagecreatetruecolor($new_width, $new_height); + imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + } - switch ($type['format']) - { - case IMG_GIF: - imagegif($new_image, $new_file); - break; - case IMG_JPG: - imagejpeg($new_image, $new_file, 90); - break; - case IMG_PNG: - imagepng($new_image, $new_file); - break; - case IMG_WBMP: - imagewbmp($new_image, $new_file); - break; - } + switch ($type['format']) { + case IMG_GIF: + imagegif($new_image, $new_file); + break; + case IMG_JPG: + imagejpeg($new_image, $new_file, 90); + break; + case IMG_PNG: + imagepng($new_image, $new_file); + break; + case IMG_WBMP: + imagewbmp($new_image, $new_file); + break; + } - imagedestroy($new_image); - } - } + imagedestroy($new_image); + } + } - if (!@file_exists($new_file)) - { - return false; - } + if (!@file_exists($new_file)) { + return false; + } - @chmod($new_file, 0664); + @chmod($new_file, 0664); - return true; -} \ No newline at end of file + return true; +} diff --git a/library/attach_mod/posting_attachments.php b/library/attach_mod/posting_attachments.php index 7a75027a0..7c9419de1 100644 --- a/library/attach_mod/posting_attachments.php +++ b/library/attach_mod/posting_attachments.php @@ -1,114 +1,132 @@ add_attachment_body = get_var('add_attachment_body', 0); - $this->posted_attachments_body = get_var('posted_attachments_body', 0); + /** + * Constructor + */ + public function __construct() + { + $this->add_attachment_body = get_var('add_attachment_body', 0); + $this->posted_attachments_body = get_var('posted_attachments_body', 0); - $this->file_comment = get_var('filecomment', ''); - $this->attachment_id_list = get_var('attach_id_list', array(0)); - $this->attachment_comment_list = get_var('comment_list', array('')); - $this->attachment_filesize_list = get_var('filesize_list', array(0)); - $this->attachment_filetime_list = get_var('filetime_list', array(0)); - $this->attachment_filename_list = get_var('filename_list', array('')); - $this->attachment_extension_list = get_var('extension_list', array('')); - $this->attachment_mimetype_list = get_var('mimetype_list', array('')); + $this->file_comment = get_var('filecomment', ''); + $this->attachment_id_list = get_var('attach_id_list', array(0)); + $this->attachment_comment_list = get_var('comment_list', array('')); + $this->attachment_filesize_list = get_var('filesize_list', array(0)); + $this->attachment_filetime_list = get_var('filetime_list', array(0)); + $this->attachment_filename_list = get_var('filename_list', array('')); + $this->attachment_extension_list = get_var('extension_list', array('')); + $this->attachment_mimetype_list = get_var('mimetype_list', array('')); - $this->filename = (isset($_FILES['fileupload']) && isset($_FILES['fileupload']['name']) && $_FILES['fileupload']['name'] != 'none') ? trim(stripslashes($_FILES['fileupload']['name'])) : ''; + $this->filename = (isset($_FILES['fileupload']) && isset($_FILES['fileupload']['name']) && $_FILES['fileupload']['name'] != 'none') ? trim(stripslashes($_FILES['fileupload']['name'])) : ''; - $this->attachment_list = get_var('attachment_list', array('')); - $this->attachment_thumbnail_list = get_var('attach_thumbnail_list', array(0)); - } + $this->attachment_list = get_var('attachment_list', array('')); + $this->attachment_thumbnail_list = get_var('attach_thumbnail_list', array(0)); + } - /** - * Get Quota Limits - */ - public function get_quota_limits($userdata_quota, $user_id = 0) - { - global $attach_config; + /** + * Get Quota Limits + */ + public function get_quota_limits($userdata_quota, $user_id = 0) + { + global $attach_config; // $priority = 'group;user'; - $priority = 'user;group'; + $priority = 'user;group'; - if (IS_ADMIN) - { - $attach_config['pm_filesize_limit'] = 0; // Unlimited - $attach_config['upload_filesize_limit'] = 0; // Unlimited - return; - } + if (IS_ADMIN) { + $attach_config['pm_filesize_limit'] = 0; // Unlimited + $attach_config['upload_filesize_limit'] = 0; // Unlimited + return; + } - $quota_type = QUOTA_UPLOAD_LIMIT; - $limit_type = 'upload_filesize_limit'; - $default = 'attachment_quota'; + $quota_type = QUOTA_UPLOAD_LIMIT; + $limit_type = 'upload_filesize_limit'; + $default = 'attachment_quota'; - if (!$user_id) - { - $user_id = intval($userdata_quota['user_id']); - } + if (!$user_id) { + $user_id = intval($userdata_quota['user_id']); + } - $priority = explode(';', $priority); - $found = false; + $priority = explode(';', $priority); + $found = false; - for ($i = 0; $i < sizeof($priority); $i++) - { - if (($priority[$i] == 'group') && (!$found)) - { - // Get Group Quota, if we find one, we have our quota - $sql = 'SELECT u.group_id + for ($i = 0; $i < sizeof($priority); $i++) { + if (($priority[$i] == 'group') && (!$found)) { + // Get Group Quota, if we find one, we have our quota + $sql = 'SELECT u.group_id FROM ' . BB_USER_GROUP . ' u, ' . BB_GROUPS . ' g WHERE g.group_single_user = 0 AND u.user_pending = 0 AND u.group_id = g.group_id AND u.user_id = ' . $user_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user group'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get user group'); + } - $rows = DB()->sql_fetchrowset($result); - $num_rows = DB()->num_rows($result); - DB()->sql_freeresult($result); + $rows = DB()->sql_fetchrowset($result); + $num_rows = DB()->num_rows($result); + DB()->sql_freeresult($result); - if ($num_rows > 0) - { - $group_id = array(); + if ($num_rows > 0) { + $group_id = array(); - for ($j = 0; $j < $num_rows; $j++) - { - $group_id[] = (int) $rows[$j]['group_id']; - } + for ($j = 0; $j < $num_rows; $j++) { + $group_id[] = (int)$rows[$j]['group_id']; + } - $sql = 'SELECT l.quota_limit + $sql = 'SELECT l.quota_limit FROM ' . BB_QUOTA . ' q, ' . BB_QUOTA_LIMITS . ' l WHERE q.group_id IN (' . implode(', ', $group_id) . ') AND q.group_id <> 0 @@ -117,25 +135,22 @@ class attach_parent ORDER BY l.quota_limit DESC LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get group quota'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get group quota'); + } - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - $found = TRUE; - } - DB()->sql_freeresult($result); - } - } + if (DB()->num_rows($result) > 0) { + $row = DB()->sql_fetchrow($result); + $attach_config[$limit_type] = $row['quota_limit']; + $found = true; + } + DB()->sql_freeresult($result); + } + } - if ($priority[$i] == 'user' && !$found) - { - // Get User Quota, if the user is not in a group or the group has no quotas - $sql = 'SELECT l.quota_limit + if ($priority[$i] == 'user' && !$found) { + // Get User Quota, if the user is not in a group or the group has no quotas + $sql = 'SELECT l.quota_limit FROM ' . BB_QUOTA . ' q, ' . BB_QUOTA_LIMITS . ' l WHERE q.user_id = ' . $user_id . ' AND q.user_id <> 0 @@ -143,1216 +158,1036 @@ class attach_parent AND q.quota_limit_id = l.quota_limit_id LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get user quota'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get user quota'); + } - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - $found = TRUE; - } - DB()->sql_freeresult($result); - } - } + if (DB()->num_rows($result) > 0) { + $row = DB()->sql_fetchrow($result); + $attach_config[$limit_type] = $row['quota_limit']; + $found = true; + } + DB()->sql_freeresult($result); + } + } - if (!$found) - { - // Set Default Quota Limit - $quota_id = ($quota_type == QUOTA_UPLOAD_LIMIT) ? $attach_config['default_upload_quota'] : $attach_config['default_pm_quota']; + if (!$found) { + // Set Default Quota Limit + $quota_id = ($quota_type == QUOTA_UPLOAD_LIMIT) ? $attach_config['default_upload_quota'] : $attach_config['default_pm_quota']; - if ($quota_id == 0) - { - $attach_config[$limit_type] = $attach_config[$default]; - } - else - { - $sql = 'SELECT quota_limit + if ($quota_id == 0) { + $attach_config[$limit_type] = $attach_config[$default]; + } else { + $sql = 'SELECT quota_limit FROM ' . BB_QUOTA_LIMITS . ' - WHERE quota_limit_id = ' . (int) $quota_id . ' + WHERE quota_limit_id = ' . (int)$quota_id . ' LIMIT 1'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get default quota limit'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get default quota limit'); + } - if (DB()->num_rows($result) > 0) - { - $row = DB()->sql_fetchrow($result); - $attach_config[$limit_type] = $row['quota_limit']; - } - else - { - $attach_config[$limit_type] = $attach_config[$default]; - } - DB()->sql_freeresult($result); - } - } + if (DB()->num_rows($result) > 0) { + $row = DB()->sql_fetchrow($result); + $attach_config[$limit_type] = $row['quota_limit']; + } else { + $attach_config[$limit_type] = $attach_config[$default]; + } + DB()->sql_freeresult($result); + } + } - // Never exceed the complete Attachment Upload Quota - if ($quota_type == QUOTA_UPLOAD_LIMIT) - { - if ($attach_config[$limit_type] > $attach_config[$default]) - { - $attach_config[$limit_type] = $attach_config[$default]; - } - } - } + // Never exceed the complete Attachment Upload Quota + if ($quota_type == QUOTA_UPLOAD_LIMIT) { + if ($attach_config[$limit_type] > $attach_config[$default]) { + $attach_config[$limit_type] = $attach_config[$default]; + } + } + } - /** - * Handle all modes... (intern) - * @private - */ - public function handle_attachments($mode) - { - global $is_auth, $attach_config, $refresh, $post_id, $submit, $preview, $error, $error_msg, $lang; + /** + * Handle all modes... (intern) + * @private + */ + public function handle_attachments($mode) + { + global $is_auth, $attach_config, $refresh, $post_id, $submit, $preview, $error, $error_msg, $lang; - // - // ok, what shall we do ;) - // + // + // ok, what shall we do ;) + // - if (IS_ADMIN) - { - $max_attachments = ADMIN_MAX_ATTACHMENTS; - } - else - { - $max_attachments = intval($attach_config['max_attachments']); - } + if (IS_ADMIN) { + $max_attachments = ADMIN_MAX_ATTACHMENTS; + } else { + $max_attachments = intval($attach_config['max_attachments']); + } - $sql_id = 'post_id'; + $sql_id = 'post_id'; - // nothing, if the user is not authorized or attachment mod disabled - if (intval($attach_config['disable_mod']) || !$is_auth['auth_attachments']) - { - return false; - } + // nothing, if the user is not authorized or attachment mod disabled + if (intval($attach_config['disable_mod']) || !$is_auth['auth_attachments']) { + return false; + } - // Init Vars - $attachments = array(); + // Init Vars + $attachments = array(); - if (!$refresh) - { - $add = (isset($_POST['add_attachment'])) ? TRUE : FALSE; - $delete = (isset($_POST['del_attachment'])) ? TRUE : FALSE; - $edit = ( isset($_POST['edit_comment']) ) ? TRUE : FALSE; - $update_attachment = ( isset($_POST['update_attachment']) ) ? TRUE : FALSE; - $del_thumbnail = ( isset($_POST['del_thumbnail']) ) ? TRUE : FALSE; + if (!$refresh) { + $add = (isset($_POST['add_attachment'])) ? true : false; + $delete = (isset($_POST['del_attachment'])) ? true : false; + $edit = (isset($_POST['edit_comment'])) ? true : false; + $update_attachment = (isset($_POST['update_attachment'])) ? true : false; + $del_thumbnail = (isset($_POST['del_thumbnail'])) ? true : false; - $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? TRUE : FALSE; - $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? TRUE : FALSE; + $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? true : false; + $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? true : false; - $refresh = $add || $delete || $edit || $del_thumbnail || $update_attachment || $add_attachment_box || $posted_attachments_box; - } + $refresh = $add || $delete || $edit || $del_thumbnail || $update_attachment || $add_attachment_box || $posted_attachments_box; + } - // Get Attachments - $attachments = get_attachments_from_post($post_id); + // Get Attachments + $attachments = get_attachments_from_post($post_id); - $auth = ($is_auth['auth_edit'] || $is_auth['auth_mod']) ? TRUE : FALSE; + $auth = ($is_auth['auth_edit'] || $is_auth['auth_mod']) ? true : false; - if (!$submit && $mode == 'editpost' && $auth) - { - if (!$refresh && !$preview && !$error) - { - for ($i = 0; $i < sizeof($attachments); $i++) - { - $this->attachment_list[] = $attachments[$i]['physical_filename']; - $this->attachment_comment_list[] = $attachments[$i]['comment']; - $this->attachment_filename_list[] = $attachments[$i]['real_filename']; - $this->attachment_extension_list[] = $attachments[$i]['extension']; - $this->attachment_mimetype_list[] = $attachments[$i]['mimetype']; - $this->attachment_filesize_list[] = $attachments[$i]['filesize']; - $this->attachment_filetime_list[] = $attachments[$i]['filetime']; - $this->attachment_id_list[] = $attachments[$i]['attach_id']; - $this->attachment_thumbnail_list[] = $attachments[$i]['thumbnail']; - } - } - } + if (!$submit && $mode == 'editpost' && $auth) { + if (!$refresh && !$preview && !$error) { + for ($i = 0; $i < sizeof($attachments); $i++) { + $this->attachment_list[] = $attachments[$i]['physical_filename']; + $this->attachment_comment_list[] = $attachments[$i]['comment']; + $this->attachment_filename_list[] = $attachments[$i]['real_filename']; + $this->attachment_extension_list[] = $attachments[$i]['extension']; + $this->attachment_mimetype_list[] = $attachments[$i]['mimetype']; + $this->attachment_filesize_list[] = $attachments[$i]['filesize']; + $this->attachment_filetime_list[] = $attachments[$i]['filetime']; + $this->attachment_id_list[] = $attachments[$i]['attach_id']; + $this->attachment_thumbnail_list[] = $attachments[$i]['thumbnail']; + } + } + } - $this->num_attachments = sizeof($this->attachment_list); + $this->num_attachments = sizeof($this->attachment_list); - if ($submit) - { - if ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') - { - if ($this->filename != '') - { - if ($this->num_attachments < intval($max_attachments)) - { - $this->upload_attachment($this->page); + if ($submit) { + if ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') { + if ($this->filename != '') { + if ($this->num_attachments < intval($max_attachments)) { + $this->upload_attachment($this->page); - if (!$error && $this->post_attach) - { - array_unshift($this->attachment_list, $this->attach_filename); - array_unshift($this->attachment_comment_list, $this->file_comment); - array_unshift($this->attachment_filename_list, $this->filename); - array_unshift($this->attachment_extension_list, $this->extension); - array_unshift($this->attachment_mimetype_list, $this->type); - array_unshift($this->attachment_filesize_list, $this->filesize); - array_unshift($this->attachment_filetime_list, $this->filetime); - array_unshift($this->attachment_id_list, '0'); - array_unshift($this->attachment_thumbnail_list, $this->thumbnail); + if (!$error && $this->post_attach) { + array_unshift($this->attachment_list, $this->attach_filename); + array_unshift($this->attachment_comment_list, $this->file_comment); + array_unshift($this->attachment_filename_list, $this->filename); + array_unshift($this->attachment_extension_list, $this->extension); + array_unshift($this->attachment_mimetype_list, $this->type); + array_unshift($this->attachment_filesize_list, $this->filesize); + array_unshift($this->attachment_filetime_list, $this->filetime); + array_unshift($this->attachment_id_list, '0'); + array_unshift($this->attachment_thumbnail_list, $this->thumbnail); - $this->file_comment = ''; - $this->post_attach = FALSE; - } - } - else - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); - } - } - } - } + $this->file_comment = ''; + $this->post_attach = false; + } + } else { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); + } + } + } + } - if ($preview || $refresh || $error) - { - $delete_attachment = ( isset($_POST['del_attachment']) ) ? TRUE : FALSE; - $delete_thumbnail = (isset($_POST['del_thumbnail'])) ? TRUE : FALSE; + if ($preview || $refresh || $error) { + $delete_attachment = (isset($_POST['del_attachment'])) ? true : false; + $delete_thumbnail = (isset($_POST['del_thumbnail'])) ? true : false; - $add_attachment = (isset($_POST['add_attachment'])) ? TRUE : FALSE; - $edit_attachment = (isset($_POST['edit_comment'])) ? TRUE : FALSE; - $update_attachment = (isset($_POST['update_attachment']) ) ? TRUE : FALSE; + $add_attachment = (isset($_POST['add_attachment'])) ? true : false; + $edit_attachment = (isset($_POST['edit_comment'])) ? true : false; + $update_attachment = (isset($_POST['update_attachment'])) ? true : false; - // Perform actions on temporary attachments - if ($delete_attachment || $delete_thumbnail) - { - // store old values - $actual_id_list = get_var('attach_id_list', array(0)); - $actual_comment_list = get_var('comment_list', array('')); - $actual_filename_list = get_var('filename_list', array('')); - $actual_extension_list = get_var('extension_list', array('')); - $actual_mimetype_list = get_var('mimetype_list', array('')); - $actual_filesize_list = get_var('filesize_list', array(0)); - $actual_filetime_list = get_var('filetime_list', array(0)); + // Perform actions on temporary attachments + if ($delete_attachment || $delete_thumbnail) { + // store old values + $actual_id_list = get_var('attach_id_list', array(0)); + $actual_comment_list = get_var('comment_list', array('')); + $actual_filename_list = get_var('filename_list', array('')); + $actual_extension_list = get_var('extension_list', array('')); + $actual_mimetype_list = get_var('mimetype_list', array('')); + $actual_filesize_list = get_var('filesize_list', array(0)); + $actual_filetime_list = get_var('filetime_list', array(0)); - $actual_list = get_var('attachment_list', array('')); - $actual_thumbnail_list = get_var('attach_thumbnail_list', array(0)); + $actual_list = get_var('attachment_list', array('')); + $actual_thumbnail_list = get_var('attach_thumbnail_list', array(0)); - // clean values - $this->attachment_list = array(); - $this->attachment_comment_list = array(); - $this->attachment_filename_list = array(); - $this->attachment_extension_list = array(); - $this->attachment_mimetype_list = array(); - $this->attachment_filesize_list = array(); - $this->attachment_filetime_list = array(); - $this->attachment_id_list = array(); - $this->attachment_thumbnail_list = array(); + // clean values + $this->attachment_list = array(); + $this->attachment_comment_list = array(); + $this->attachment_filename_list = array(); + $this->attachment_extension_list = array(); + $this->attachment_mimetype_list = array(); + $this->attachment_filesize_list = array(); + $this->attachment_filetime_list = array(); + $this->attachment_id_list = array(); + $this->attachment_thumbnail_list = array(); - // restore values :) - if (isset($_POST['attachment_list'])) - { - for ($i = 0; $i < sizeof($actual_list); $i++) - { - $restore = FALSE; - $del_thumb = FALSE; + // restore values :) + if (isset($_POST['attachment_list'])) { + for ($i = 0; $i < sizeof($actual_list); $i++) { + $restore = false; + $del_thumb = false; - if ($delete_thumbnail) - { - if ( !isset($_POST['del_thumbnail'][$actual_list[$i]]) ) - { - $restore = TRUE; - } - else - { - $del_thumb = TRUE; - } - } - if ( $delete_attachment ) - { - if ( !isset($_POST['del_attachment'][$actual_list[$i]]) ) - { - $restore = TRUE; - } - } + if ($delete_thumbnail) { + if (!isset($_POST['del_thumbnail'][$actual_list[$i]])) { + $restore = true; + } else { + $del_thumb = true; + } + } + if ($delete_attachment) { + if (!isset($_POST['del_attachment'][$actual_list[$i]])) { + $restore = true; + } + } - if ( $restore ) - { - $this->attachment_list[] = $actual_list[$i]; - $this->attachment_comment_list[] = $actual_comment_list[$i]; - $this->attachment_filename_list[] = $actual_filename_list[$i]; - $this->attachment_extension_list[] = $actual_extension_list[$i]; - $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; - $this->attachment_filesize_list[] = $actual_filesize_list[$i]; - $this->attachment_filetime_list[] = $actual_filetime_list[$i]; - $this->attachment_id_list[] = $actual_id_list[$i]; - $this->attachment_thumbnail_list[] = $actual_thumbnail_list[$i]; - } - else if (!$del_thumb) - { - // delete selected attachment - if ($actual_id_list[$i] == '0' ) - { - unlink_attach($actual_list[$i]); + if ($restore) { + $this->attachment_list[] = $actual_list[$i]; + $this->attachment_comment_list[] = $actual_comment_list[$i]; + $this->attachment_filename_list[] = $actual_filename_list[$i]; + $this->attachment_extension_list[] = $actual_extension_list[$i]; + $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; + $this->attachment_filesize_list[] = $actual_filesize_list[$i]; + $this->attachment_filetime_list[] = $actual_filetime_list[$i]; + $this->attachment_id_list[] = $actual_id_list[$i]; + $this->attachment_thumbnail_list[] = $actual_thumbnail_list[$i]; + } elseif (!$del_thumb) { + // delete selected attachment + if ($actual_id_list[$i] == '0') { + unlink_attach($actual_list[$i]); - if ($actual_thumbnail_list[$i] == 1) - { - unlink_attach($actual_list[$i], MODE_THUMBNAIL); - } - } - else - { - delete_attachment($post_id, $actual_id_list[$i], $this->page); - } - } - else if ($del_thumb) - { - // delete selected thumbnail - $this->attachment_list[] = $actual_list[$i]; - $this->attachment_comment_list[] = $actual_comment_list[$i]; - $this->attachment_filename_list[] = $actual_filename_list[$i]; - $this->attachment_extension_list[] = $actual_extension_list[$i]; - $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; - $this->attachment_filesize_list[] = $actual_filesize_list[$i]; - $this->attachment_filetime_list[] = $actual_filetime_list[$i]; - $this->attachment_id_list[] = $actual_id_list[$i]; - $this->attachment_thumbnail_list[] = 0; + if ($actual_thumbnail_list[$i] == 1) { + unlink_attach($actual_list[$i], MODE_THUMBNAIL); + } + } else { + delete_attachment($post_id, $actual_id_list[$i], $this->page); + } + } elseif ($del_thumb) { + // delete selected thumbnail + $this->attachment_list[] = $actual_list[$i]; + $this->attachment_comment_list[] = $actual_comment_list[$i]; + $this->attachment_filename_list[] = $actual_filename_list[$i]; + $this->attachment_extension_list[] = $actual_extension_list[$i]; + $this->attachment_mimetype_list[] = $actual_mimetype_list[$i]; + $this->attachment_filesize_list[] = $actual_filesize_list[$i]; + $this->attachment_filetime_list[] = $actual_filetime_list[$i]; + $this->attachment_id_list[] = $actual_id_list[$i]; + $this->attachment_thumbnail_list[] = 0; - if ($actual_id_list[$i] == 0) - { - unlink_attach($actual_list[$i], MODE_THUMBNAIL); - } - else - { - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET thumbnail = 0 WHERE attach_id = ' . (int) $actual_id_list[$i]; + if ($actual_id_list[$i] == 0) { + unlink_attach($actual_list[$i], MODE_THUMBNAIL); + } else { + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET thumbnail = 0 WHERE attach_id = ' . (int)$actual_id_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update ' . BB_ATTACHMENTS_DESC); - } - } - } - } - } - } - else if ($edit_attachment || $update_attachment || $add_attachment || $preview) - { - if ($edit_attachment) - { - $actual_comment_list = get_var('comment_list', array('')); + if (!(DB()->sql_query($sql))) { + bb_die('Unable to update ' . BB_ATTACHMENTS_DESC); + } + } + } + } + } + } elseif ($edit_attachment || $update_attachment || $add_attachment || $preview) { + if ($edit_attachment) { + $actual_comment_list = get_var('comment_list', array('')); - $this->attachment_comment_list = array(); + $this->attachment_comment_list = array(); - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - $this->attachment_comment_list[$i] = $actual_comment_list[$i]; - } - } + for ($i = 0; $i < sizeof($this->attachment_list); $i++) { + $this->attachment_comment_list[$i] = $actual_comment_list[$i]; + } + } - if ($update_attachment) - { - if ($this->filename == '') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= $lang['ERROR_EMPTY_ADD_ATTACHBOX']; - } + if ($update_attachment) { + if ($this->filename == '') { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= $lang['ERROR_EMPTY_ADD_ATTACHBOX']; + } - $this->upload_attachment($this->page); + $this->upload_attachment($this->page); - if (!$error) - { - $actual_list = get_var('attachment_list', array('')); - $actual_id_list = get_var('attach_id_list', array(0)); + if (!$error) { + $actual_list = get_var('attachment_list', array('')); + $actual_id_list = get_var('attach_id_list', array(0)); - $attachment_id = 0; - $actual_element = 0; + $attachment_id = 0; + $actual_element = 0; - for ($i = 0; $i < sizeof($actual_id_list); $i++) - { - if (isset($_POST['update_attachment'][$actual_id_list[$i]])) - { - $attachment_id = intval($actual_id_list[$i]); - $actual_element = $i; - } - } + for ($i = 0; $i < sizeof($actual_id_list); $i++) { + if (isset($_POST['update_attachment'][$actual_id_list[$i]])) { + $attachment_id = intval($actual_id_list[$i]); + $actual_element = $i; + } + } - // Get current informations to delete the Old Attachment - $sql = 'SELECT physical_filename, comment, thumbnail + // Get current informations to delete the Old Attachment + $sql = 'SELECT physical_filename, comment, thumbnail FROM ' . BB_ATTACHMENTS_DESC . ' - WHERE attach_id = ' . (int) $attachment_id; + WHERE attach_id = ' . (int)$attachment_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to select old attachment entry'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to select old attachment entry'); + } - if (DB()->num_rows($result) != 1) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= $lang['ERROR_MISSING_OLD_ENTRY']; - } + if (DB()->num_rows($result) != 1) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= $lang['ERROR_MISSING_OLD_ENTRY']; + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $comment = (trim($this->file_comment) == '') ? trim($row['comment']) : trim($this->file_comment); + $comment = (trim($this->file_comment) == '') ? trim($row['comment']) : trim($this->file_comment); - // Update Entry - $sql_ary = array( - 'physical_filename' => (string) basename($this->attach_filename), - 'real_filename' => (string) basename($this->filename), - 'comment' => (string) $comment, - 'extension' => (string) strtolower($this->extension), - 'mimetype' => (string) strtolower($this->type), - 'filesize' => (int) $this->filesize, - 'filetime' => (int) $this->filetime, - 'thumbnail' => (int) $this->thumbnail - ); + // Update Entry + $sql_ary = array( + 'physical_filename' => (string)basename($this->attach_filename), + 'real_filename' => (string)basename($this->filename), + 'comment' => (string)$comment, + 'extension' => (string)strtolower($this->extension), + 'mimetype' => (string)strtolower($this->type), + 'filesize' => (int)$this->filesize, + 'filetime' => (int)$this->filetime, + 'thumbnail' => (int)$this->thumbnail + ); - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' - WHERE attach_id = ' . (int) $attachment_id; + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . ' SET ' . attach_mod_sql_build_array('UPDATE', $sql_ary) . ' + WHERE attach_id = ' . (int)$attachment_id; - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update the attachment'); - } + if (!(DB()->sql_query($sql))) { + bb_die('Unable to update the attachment'); + } - // Delete the Old Attachment - unlink_attach($row['physical_filename']); + // Delete the Old Attachment + unlink_attach($row['physical_filename']); - if (intval($row['thumbnail']) == 1) - { - unlink_attach($row['physical_filename'], MODE_THUMBNAIL); - } + if (intval($row['thumbnail']) == 1) { + unlink_attach($row['physical_filename'], MODE_THUMBNAIL); + } - //bt - if ($this->attachment_extension_list[$actual_element] === TORRENT_EXT && $attachments[$actual_element]['tracker_status']) - { - include(INC_DIR .'functions_torrent.php'); - tracker_unregister($attachment_id); - } - //bt end + //bt + if ($this->attachment_extension_list[$actual_element] === TORRENT_EXT && $attachments[$actual_element]['tracker_status']) { + include(INC_DIR . 'functions_torrent.php'); + tracker_unregister($attachment_id); + } + //bt end - // Make sure it is displayed - $this->attachment_list[$actual_element] = $this->attach_filename; - $this->attachment_comment_list[$actual_element] = $comment; - $this->attachment_filename_list[$actual_element] = $this->filename; - $this->attachment_extension_list[$actual_element] = $this->extension; - $this->attachment_mimetype_list[$actual_element] = $this->type; - $this->attachment_filesize_list[$actual_element] = $this->filesize; - $this->attachment_filetime_list[$actual_element] = $this->filetime; - $this->attachment_id_list[$actual_element] = $actual_id_list[$actual_element]; - $this->attachment_thumbnail_list[$actual_element] = $this->thumbnail; - $this->file_comment = ''; - } - } + // Make sure it is displayed + $this->attachment_list[$actual_element] = $this->attach_filename; + $this->attachment_comment_list[$actual_element] = $comment; + $this->attachment_filename_list[$actual_element] = $this->filename; + $this->attachment_extension_list[$actual_element] = $this->extension; + $this->attachment_mimetype_list[$actual_element] = $this->type; + $this->attachment_filesize_list[$actual_element] = $this->filesize; + $this->attachment_filetime_list[$actual_element] = $this->filetime; + $this->attachment_id_list[$actual_element] = $actual_id_list[$actual_element]; + $this->attachment_thumbnail_list[$actual_element] = $this->thumbnail; + $this->file_comment = ''; + } + } - if (($add_attachment || $preview) && $this->filename != '') - { - if ($this->num_attachments < intval($max_attachments)) - { - $this->upload_attachment($this->page); + if (($add_attachment || $preview) && $this->filename != '') { + if ($this->num_attachments < intval($max_attachments)) { + $this->upload_attachment($this->page); - if (!$error) - { - array_unshift($this->attachment_list, $this->attach_filename); - array_unshift($this->attachment_comment_list, $this->file_comment); - array_unshift($this->attachment_filename_list, $this->filename); - array_unshift($this->attachment_extension_list, $this->extension); - array_unshift($this->attachment_mimetype_list, $this->type); - array_unshift($this->attachment_filesize_list, $this->filesize); - array_unshift($this->attachment_filetime_list, $this->filetime); - array_unshift($this->attachment_id_list, '0'); - array_unshift($this->attachment_thumbnail_list, $this->thumbnail); + if (!$error) { + array_unshift($this->attachment_list, $this->attach_filename); + array_unshift($this->attachment_comment_list, $this->file_comment); + array_unshift($this->attachment_filename_list, $this->filename); + array_unshift($this->attachment_extension_list, $this->extension); + array_unshift($this->attachment_mimetype_list, $this->type); + array_unshift($this->attachment_filesize_list, $this->filesize); + array_unshift($this->attachment_filetime_list, $this->filetime); + array_unshift($this->attachment_id_list, '0'); + array_unshift($this->attachment_thumbnail_list, $this->thumbnail); - $this->file_comment = ''; - } - } - else - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); - } - } - } - } + $this->file_comment = ''; + } + } else { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['TOO_MANY_ATTACHMENTS'], intval($max_attachments)); + } + } + } + } - return TRUE; - } + return true; + } - /** - * Basic Insert Attachment Handling for all Message Types - */ - public function do_insert_attachment($mode, $message_type, $message_id) - { - global $upload_dir; + /** + * Basic Insert Attachment Handling for all Message Types + */ + public function do_insert_attachment($mode, $message_type, $message_id) + { + global $upload_dir; - if (intval($message_id) < 0) - { - return FALSE; - } + if (intval($message_id) < 0) { + return false; + } - global $post_info, $userdata; + global $post_info, $userdata; - $post_id = (int) $message_id; - $user_id_1 = (isset($post_info['poster_id'])) ? (int) $post_info['poster_id'] : 0; + $post_id = (int)$message_id; + $user_id_1 = (isset($post_info['poster_id'])) ? (int)$post_info['poster_id'] : 0; - if (!$user_id_1) - { - $user_id_1 = (int) $userdata['user_id']; - } + if (!$user_id_1) { + $user_id_1 = (int)$userdata['user_id']; + } - if ($mode == 'attach_list') - { - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - if ($this->attachment_id_list[$i]) - { - //bt - if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) - { - define('TORRENT_ATTACH_ID', $this->attachment_id_list[$i]); - } - //bt end + if ($mode == 'attach_list') { + for ($i = 0; $i < sizeof($this->attachment_list); $i++) { + if ($this->attachment_id_list[$i]) { + //bt + if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) { + define('TORRENT_ATTACH_ID', $this->attachment_id_list[$i]); + } + //bt end - // update entry in db if attachment already stored in db and filespace - $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . " + // update entry in db if attachment already stored in db and filespace + $sql = 'UPDATE ' . BB_ATTACHMENTS_DESC . " SET comment = '" . @attach_mod_sql_escape($this->attachment_comment_list[$i]) . "' WHERE attach_id = " . $this->attachment_id_list[$i]; - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update the file comment'); - } - } - else - { - if (empty($this->attachment_mimetype_list[$i]) && $this->attachment_extension_list[$i] === TORRENT_EXT) - { - $this->attachment_mimetype_list[$i] = 'application/x-bittorrent'; - } + if (!(DB()->sql_query($sql))) { + bb_die('Unable to update the file comment'); + } + } else { + if (empty($this->attachment_mimetype_list[$i]) && $this->attachment_extension_list[$i] === TORRENT_EXT) { + $this->attachment_mimetype_list[$i] = 'application/x-bittorrent'; + } - // insert attachment into db - $sql_ary = array( - 'physical_filename' => (string) basename($this->attachment_list[$i]), - 'real_filename' => (string) basename($this->attachment_filename_list[$i]), - 'comment' => (string) @$this->attachment_comment_list[$i], - 'extension' => (string) strtolower($this->attachment_extension_list[$i]), - 'mimetype' => (string) strtolower($this->attachment_mimetype_list[$i]), - 'filesize' => (int) $this->attachment_filesize_list[$i], - 'filetime' => (int) $this->attachment_filetime_list[$i], - 'thumbnail' => (int) $this->attachment_thumbnail_list[$i] - ); + // insert attachment into db + $sql_ary = array( + 'physical_filename' => (string)basename($this->attachment_list[$i]), + 'real_filename' => (string)basename($this->attachment_filename_list[$i]), + 'comment' => (string)@$this->attachment_comment_list[$i], + 'extension' => (string)strtolower($this->attachment_extension_list[$i]), + 'mimetype' => (string)strtolower($this->attachment_mimetype_list[$i]), + 'filesize' => (int)$this->attachment_filesize_list[$i], + 'filetime' => (int)$this->attachment_filetime_list[$i], + 'thumbnail' => (int)$this->attachment_thumbnail_list[$i] + ); - $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
        Your '. $message_type .' has been stored'); - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not store Attachment.
        Your ' . $message_type . ' has been stored'); + } - $attach_id = DB()->sql_nextid(); + $attach_id = DB()->sql_nextid(); - //bt - if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) - { - define('TORRENT_ATTACH_ID', $attach_id); - } - //bt end + //bt + if ($this->attachment_extension_list[$i] === TORRENT_EXT && !defined('TORRENT_ATTACH_ID')) { + define('TORRENT_ATTACH_ID', $attach_id); + } + //bt end - $sql_ary = array( - 'attach_id' => (int) $attach_id, - 'post_id' => (int) $post_id, - 'user_id_1' => (int) $user_id_1, - ); + $sql_ary = array( + 'attach_id' => (int)$attach_id, + 'post_id' => (int)$post_id, + 'user_id_1' => (int)$user_id_1, + ); - $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
        Your '. $message_type .' has been stored'); - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not store Attachment.
        Your ' . $message_type . ' has been stored'); + } + } + } - return TRUE; - } + return true; + } - if ($mode == 'last_attachment') - { - if ($this->post_attach && !isset($_POST['update_attachment'])) - { - // insert attachment into db, here the user submited it directly - $sql_ary = array( - 'physical_filename' => (string) basename($this->attach_filename), - 'real_filename' => (string) basename($this->filename), - 'comment' => (string) $this->file_comment, - 'extension' => (string) strtolower($this->extension), - 'mimetype' => (string) strtolower($this->type), - 'filesize' => (int) $this->filesize, - 'filetime' => (int) $this->filetime, - 'thumbnail' => (int) $this->thumbnail - ); + if ($mode == 'last_attachment') { + if ($this->post_attach && !isset($_POST['update_attachment'])) { + // insert attachment into db, here the user submited it directly + $sql_ary = array( + 'physical_filename' => (string)basename($this->attach_filename), + 'real_filename' => (string)basename($this->filename), + 'comment' => (string)$this->file_comment, + 'extension' => (string)strtolower($this->extension), + 'mimetype' => (string)strtolower($this->type), + 'filesize' => (int)$this->filesize, + 'filetime' => (int)$this->filetime, + 'thumbnail' => (int)$this->thumbnail + ); - $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_ATTACHMENTS_DESC . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - // Inform the user that his post has been created, but nothing is attached - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
        Your '. $message_type .' has been stored'); - } + // Inform the user that his post has been created, but nothing is attached + if (!(DB()->sql_query($sql))) { + bb_die('Could not store Attachment.
        Your ' . $message_type . ' has been stored'); + } - $attach_id = DB()->sql_nextid(); + $attach_id = DB()->sql_nextid(); - $sql_ary = array( - 'attach_id' => (int) $attach_id, - 'post_id' => (int) $post_id, - 'user_id_1' => (int) $user_id_1, - ); + $sql_ary = array( + 'attach_id' => (int)$attach_id, + 'post_id' => (int)$post_id, + 'user_id_1' => (int)$user_id_1, + ); - $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); + $sql = 'INSERT INTO ' . BB_ATTACHMENTS . ' ' . attach_mod_sql_build_array('INSERT', $sql_ary); - if (!(DB()->sql_query($sql))) - { - bb_die('Could not store Attachment.
        Your '. $message_type .' has been stored'); - } - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not store Attachment.
        Your ' . $message_type . ' has been stored'); + } + } + } + } - /** - * Attachment Mod entry switch/output (intern) - * @private - */ - public function display_attachment_bodies() - { - global $attach_config, $is_auth, $lang, $template, $upload_dir, $forum_id; + /** + * Attachment Mod entry switch/output (intern) + * @private + */ + public function display_attachment_bodies() + { + global $attach_config, $is_auth, $lang, $template, $upload_dir, $forum_id; - // Choose what to display - $value_add = $value_posted = 0; + // Choose what to display + $value_add = $value_posted = 0; - $this->add_attachment_body = 1; - $this->posted_attachments_body = 1; + $this->add_attachment_body = 1; + $this->posted_attachments_body = 1; - $s_hidden = ''; - $s_hidden .= ''; + $s_hidden = ''; + $s_hidden .= ''; - $template->assign_vars(array( - 'ADD_ATTACH_HIDDEN_FIELDS' => $s_hidden, - )); + $template->assign_vars(array( + 'ADD_ATTACH_HIDDEN_FIELDS' => $s_hidden, + )); - $attachments = array(); + $attachments = array(); - if (sizeof($this->attachment_list) > 0) - { - $hidden = ''; - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; - $hidden .= ''; + if (sizeof($this->attachment_list) > 0) { + $hidden = ''; + for ($i = 0; $i < sizeof($this->attachment_list); $i++) { + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; + $hidden .= ''; - if (!$this->posted_attachments_body || sizeof($this->attachment_list) == 0) - { - $hidden .= ''; - } - } - $template->assign_var('POSTED_ATTACHMENTS_HIDDEN_FIELDS', $hidden); - } + if (!$this->posted_attachments_body || sizeof($this->attachment_list) == 0) { + $hidden .= ''; + } + } + $template->assign_var('POSTED_ATTACHMENTS_HIDDEN_FIELDS', $hidden); + } - if ($this->add_attachment_body) - { - $template->assign_vars(array( - 'TPL_ADD_ATTACHMENT' => true, - 'FILE_COMMENT' => htmlspecialchars($this->file_comment), - 'FILESIZE' => $attach_config['max_filesize'], - 'FILENAME' => htmlspecialchars($this->filename), - 'S_FORM_ENCTYPE' => 'enctype="multipart/form-data"', - )); - } + if ($this->add_attachment_body) { + $template->assign_vars(array( + 'TPL_ADD_ATTACHMENT' => true, + 'FILE_COMMENT' => htmlspecialchars($this->file_comment), + 'FILESIZE' => $attach_config['max_filesize'], + 'FILENAME' => htmlspecialchars($this->filename), + 'S_FORM_ENCTYPE' => 'enctype="multipart/form-data"', + )); + } - if ($this->posted_attachments_body && sizeof($this->attachment_list) > 0) - { - $template->assign_vars(array( - 'TPL_POSTED_ATTACHMENTS' => true, - )); + if ($this->posted_attachments_body && sizeof($this->attachment_list) > 0) { + $template->assign_vars(array( + 'TPL_POSTED_ATTACHMENTS' => true, + )); - for ($i = 0; $i < sizeof($this->attachment_list); $i++) - { - if (@$this->attachment_id_list[$i] == 0) - { - $download_link = $upload_dir . '/' . basename($this->attachment_list[$i]); - } - else - { - $download_link = BB_ROOT . DOWNLOAD_URL . $this->attachment_id_list[$i]; - } + for ($i = 0; $i < sizeof($this->attachment_list); $i++) { + if (@$this->attachment_id_list[$i] == 0) { + $download_link = $upload_dir . '/' . basename($this->attachment_list[$i]); + } else { + $download_link = BB_ROOT . DOWNLOAD_URL . $this->attachment_id_list[$i]; + } - $template->assign_block_vars('attach_row', array( - 'FILE_NAME' => @htmlspecialchars($this->attachment_filename_list[$i]), - 'ATTACH_FILENAME' => @$this->attachment_list[$i], - 'FILE_COMMENT' => @htmlspecialchars($this->attachment_comment_list[$i]), - 'ATTACH_ID' => @$this->attachment_id_list[$i], - 'U_VIEW_ATTACHMENT' => $download_link, - )); + $template->assign_block_vars('attach_row', array( + 'FILE_NAME' => @htmlspecialchars($this->attachment_filename_list[$i]), + 'ATTACH_FILENAME' => @$this->attachment_list[$i], + 'FILE_COMMENT' => @htmlspecialchars($this->attachment_comment_list[$i]), + 'ATTACH_ID' => @$this->attachment_id_list[$i], + 'U_VIEW_ATTACHMENT' => $download_link, + )); - // Thumbnail there ? And is the User Admin or Mod ? Then present the 'Delete Thumbnail' Button - if (@intval($this->attachment_thumbnail_list[$i]) == 1 && ((isset($is_auth['auth_mod']) && $is_auth['auth_mod']) || IS_ADMIN)) - { - $template->assign_block_vars('attach_row.switch_thumbnail', array()); - } + // Thumbnail there ? And is the User Admin or Mod ? Then present the 'Delete Thumbnail' Button + if (@intval($this->attachment_thumbnail_list[$i]) == 1 && ((isset($is_auth['auth_mod']) && $is_auth['auth_mod']) || IS_ADMIN)) { + $template->assign_block_vars('attach_row.switch_thumbnail', array()); + } - if (@$this->attachment_id_list[$i]) - { - $template->assign_block_vars('attach_row.switch_update_attachment', array()); - } - } - } + if (@$this->attachment_id_list[$i]) { + $template->assign_block_vars('attach_row.switch_update_attachment', array()); + } + } + } - $template->assign_var('ATTACHBOX'); - } + $template->assign_var('ATTACHBOX'); + } - /** - * Upload an Attachment to Filespace (intern) - */ - public function upload_attachment() - { - global $error, $error_msg, $lang, $attach_config, $userdata, $upload_dir, $forum_id; + /** + * Upload an Attachment to Filespace (intern) + */ + public function upload_attachment() + { + global $error, $error_msg, $lang, $attach_config, $userdata, $upload_dir, $forum_id; - $this->post_attach = ($this->filename != '') ? TRUE : FALSE; + $this->post_attach = ($this->filename != '') ? true : false; - if ($this->post_attach) - { - $r_file = trim(basename($this->filename)); - $file = $_FILES['fileupload']['tmp_name']; - $this->type = $_FILES['fileupload']['type']; + if ($this->post_attach) { + $r_file = trim(basename($this->filename)); + $file = $_FILES['fileupload']['tmp_name']; + $this->type = $_FILES['fileupload']['type']; - if (isset($_FILES['fileupload']['size']) && $_FILES['fileupload']['size'] == 0) - { - bb_die('Tried to upload empty file'); - } + if (isset($_FILES['fileupload']['size']) && $_FILES['fileupload']['size'] == 0) { + bb_die('Tried to upload empty file'); + } - $this->type = strtolower($this->type); - $this->extension = strtolower(get_extension($this->filename)); + $this->type = strtolower($this->type); + $this->extension = strtolower(get_extension($this->filename)); - $this->filesize = @filesize($file); - $this->filesize = intval($this->filesize); + $this->filesize = @filesize($file); + $this->filesize = intval($this->filesize); - $sql = 'SELECT g.allow_group, g.max_filesize, g.cat_id, g.forum_permissions + $sql = 'SELECT g.allow_group, g.max_filesize, g.cat_id, g.forum_permissions FROM ' . BB_EXTENSION_GROUPS . ' g, ' . BB_EXTENSIONS . " e WHERE g.group_id = e.group_id AND e.extension = '" . attach_mod_sql_escape($this->extension) . "' LIMIT 1"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query extensions'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query extensions'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $allowed_filesize = ($row['max_filesize']) ? $row['max_filesize'] : $attach_config['max_filesize']; - $cat_id = intval($row['cat_id']); - $auth_cache = trim($row['forum_permissions']); + $allowed_filesize = ($row['max_filesize']) ? $row['max_filesize'] : $attach_config['max_filesize']; + $cat_id = intval($row['cat_id']); + $auth_cache = trim($row['forum_permissions']); - // check Filename - if (preg_match("#[\\/:*?\"<>|]#i", $this->filename)) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['INVALID_FILENAME'], htmlspecialchars($this->filename)); - } + // check Filename + if (preg_match("#[\\/:*?\"<>|]#i", $this->filename)) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['INVALID_FILENAME'], htmlspecialchars($this->filename)); + } - // check php upload-size - if (!$error && $file == 'none') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $ini_val = 'ini_get'; + // check php upload-size + if (!$error && $file == 'none') { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $ini_val = 'ini_get'; - $max_size = @$ini_val('upload_max_filesize'); + $max_size = @$ini_val('upload_max_filesize'); - if ($max_size == '') - { - $error_msg .= $lang['ATTACHMENT_PHP_SIZE_NA']; - } - else - { - $error_msg .= sprintf($lang['ATTACHMENT_PHP_SIZE_OVERRUN'], $max_size); - } - } + if ($max_size == '') { + $error_msg .= $lang['ATTACHMENT_PHP_SIZE_NA']; + } else { + $error_msg .= sprintf($lang['ATTACHMENT_PHP_SIZE_OVERRUN'], $max_size); + } + } - // Check Extension - if (!$error && intval($row['allow_group']) == 0) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['DISALLOWED_EXTENSION'], htmlspecialchars($this->extension)); - } + // Check Extension + if (!$error && intval($row['allow_group']) == 0) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['DISALLOWED_EXTENSION'], htmlspecialchars($this->extension)); + } - // Check Forum Permissions - if (!$error && !IS_ADMIN && !is_forum_authed($auth_cache, $forum_id) && trim($auth_cache) != '') - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['DISALLOWED_EXTENSION_WITHIN_FORUM'], htmlspecialchars($this->extension)); - } + // Check Forum Permissions + if (!$error && !IS_ADMIN && !is_forum_authed($auth_cache, $forum_id) && trim($auth_cache) != '') { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['DISALLOWED_EXTENSION_WITHIN_FORUM'], htmlspecialchars($this->extension)); + } - //bt - // Check if user can post torrent - global $post_data; + //bt + // Check if user can post torrent + global $post_data; - if (!$error && $this->extension === TORRENT_EXT && !$post_data['first_post']) - { - $error = TRUE; - if (!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= $lang['ALLOWED_ONLY_1ST_POST_ATTACH']; - } - //bt end + if (!$error && $this->extension === TORRENT_EXT && !$post_data['first_post']) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= $lang['ALLOWED_ONLY_1ST_POST_ATTACH']; + } + //bt end - // Upload File + // Upload File - $this->thumbnail = 0; + $this->thumbnail = 0; - if (!$error) - { - // - // Prepare Values - $this->filetime = TIMENOW; + if (!$error) { + // + // Prepare Values + $this->filetime = TIMENOW; - $this->filename = $r_file; + $this->filename = $r_file; - // physical filename - //$this->attach_filename = strtolower($this->filename); - $this->attach_filename = $this->filename; + // physical filename + //$this->attach_filename = strtolower($this->filename); + $this->attach_filename = $this->filename; - //bt - if (FILENAME_CRYPTIC) - { - $this->attach_filename = make_rand_str(FILENAME_CRYPTIC_LENGTH); - } - else - { // original - $this->attach_filename = html_entity_decode(trim(stripslashes($this->attach_filename))); - $this->attach_filename = delete_extension($this->attach_filename); - $this->attach_filename = str_replace(array(' ','-'), array('_','_'), $this->attach_filename); - $this->attach_filename = str_replace('__', '_', $this->attach_filename); - $this->attach_filename = str_replace(array(',', '.', '!', '?', 'ь', 'Ь', 'ц', 'Ц', 'д', 'Д', ';', ':', '@', "'", '"', '&'), array('', '', '', '', 'ue', 'ue', 'oe', 'oe', 'ae', 'ae', '', '', '', '', '', 'and'), $this->attach_filename); - $this->attach_filename = str_replace(array('$', 'Я', '>','<','§','%','=','/','(',')','#','*','+',"\\",'{','}','[',']'), array('dollar', 'ss','greater','lower','paragraph','percent','equal','','','','','','','','','','',''), $this->attach_filename); - // Remove non-latin characters - $this->attach_filename = preg_replace('#([\xC2\xC3])([\x80-\xBF])#', 'chr(ord(\'$1\')<<6&0xC0|ord(\'$2\')&0x3F)', $this->attach_filename); - $this->attach_filename = rawurlencode($this->attach_filename); - $this->attach_filename = preg_replace("/(%[0-9A-F]{1,2})/i", '', $this->attach_filename); - $this->attach_filename = trim($this->attach_filename); - } - $this->attach_filename = str_replace(array('&','&',' '), '_', $this->attach_filename); - $this->attach_filename = str_replace('php', '_php_', $this->attach_filename); - $this->attach_filename = substr(trim($this->attach_filename), 0, FILENAME_MAX_LENGTH); + //bt + if (FILENAME_CRYPTIC) { + $this->attach_filename = make_rand_str(FILENAME_CRYPTIC_LENGTH); + } else { // original + $this->attach_filename = html_entity_decode(trim(stripslashes($this->attach_filename))); + $this->attach_filename = delete_extension($this->attach_filename); + $this->attach_filename = str_replace(array(' ', '-'), array('_', '_'), $this->attach_filename); + $this->attach_filename = str_replace('__', '_', $this->attach_filename); + $this->attach_filename = str_replace(array(',', '.', '!', '?', 'ь', 'Ь', 'ц', 'Ц', 'д', 'Д', ';', ':', '@', "'", '"', '&'), array('', '', '', '', 'ue', 'ue', 'oe', 'oe', 'ae', 'ae', '', '', '', '', '', 'and'), $this->attach_filename); + $this->attach_filename = str_replace(array('$', 'Я', '>', '<', '§', '%', '=', '/', '(', ')', '#', '*', '+', "\\", '{', '}', '[', ']'), array('dollar', 'ss', 'greater', 'lower', 'paragraph', 'percent', 'equal', '', '', '', '', '', '', '', '', '', '', ''), $this->attach_filename); + // Remove non-latin characters + $this->attach_filename = preg_replace('#([\xC2\xC3])([\x80-\xBF])#', 'chr(ord(\'$1\')<<6&0xC0|ord(\'$2\')&0x3F)', $this->attach_filename); + $this->attach_filename = rawurlencode($this->attach_filename); + $this->attach_filename = preg_replace("/(%[0-9A-F]{1,2})/i", '', $this->attach_filename); + $this->attach_filename = trim($this->attach_filename); + } + $this->attach_filename = str_replace(array('&', '&', ' '), '_', $this->attach_filename); + $this->attach_filename = str_replace('php', '_php_', $this->attach_filename); + $this->attach_filename = substr(trim($this->attach_filename), 0, FILENAME_MAX_LENGTH); - for ($i=0, $max_try=5; $i <= $max_try; $i++) - { - $fn_prefix = make_rand_str(FILENAME_PREFIX_LENGTH) .'_'; - $new_physical_filename = clean_filename($fn_prefix . $this->attach_filename); + for ($i = 0, $max_try = 5; $i <= $max_try; $i++) { + $fn_prefix = make_rand_str(FILENAME_PREFIX_LENGTH) . '_'; + $new_physical_filename = clean_filename($fn_prefix . $this->attach_filename); - if (!physical_filename_already_stored($new_physical_filename)) - { - break; - } - if ($i == $max_try) - { - bb_die('Could not create filename for attachment'); - } - } - $this->attach_filename = $new_physical_filename; + if (!physical_filename_already_stored($new_physical_filename)) { + break; + } + if ($i == $max_try) { + bb_die('Could not create filename for attachment'); + } + } + $this->attach_filename = $new_physical_filename; - // Do we have to create a thumbnail ? - if ($cat_id == IMAGE_CAT && intval($attach_config['img_create_thumbnail'])) - { - $this->thumbnail = 1; - } - } + // Do we have to create a thumbnail ? + if ($cat_id == IMAGE_CAT && intval($attach_config['img_create_thumbnail'])) { + $this->thumbnail = 1; + } + } - if ($error) - { - $this->post_attach = FALSE; - return; - } + if ($error) { + $this->post_attach = false; + return; + } - // Upload Attachment - if (!$error) - { - // Descide the Upload method - $ini_val = 'ini_get'; + // Upload Attachment + if (!$error) { + // Descide the Upload method + $ini_val = 'ini_get'; - $safe_mode = @$ini_val('safe_mode'); + $safe_mode = @$ini_val('safe_mode'); - if (@$ini_val('open_basedir')) - { - $upload_mode = 'move'; - } - else if ( @$ini_val('safe_mode') ) - { - $upload_mode = 'move'; - } - else - { - $upload_mode = 'copy'; - } + if (@$ini_val('open_basedir')) { + $upload_mode = 'move'; + } elseif (@$ini_val('safe_mode')) { + $upload_mode = 'move'; + } else { + $upload_mode = 'copy'; + } - // Ok, upload the Attachment - if (!$error) - { - $this->move_uploaded_attachment($upload_mode, $file); - } - } + // Ok, upload the Attachment + if (!$error) { + $this->move_uploaded_attachment($upload_mode, $file); + } + } - // Now, check filesize parameters - if (!$error) - { - if (!$this->filesize) - { - $this->filesize = intval(@filesize($upload_dir . '/' . $this->attach_filename)); - } - } + // Now, check filesize parameters + if (!$error) { + if (!$this->filesize) { + $this->filesize = intval(@filesize($upload_dir . '/' . $this->attach_filename)); + } + } - // Check Image Size, if it's an image - if (!$error && !IS_ADMIN && $cat_id == IMAGE_CAT) - { - list($width, $height) = image_getdimension($upload_dir . '/' . $this->attach_filename); + // Check Image Size, if it's an image + if (!$error && !IS_ADMIN && $cat_id == IMAGE_CAT) { + list($width, $height) = image_getdimension($upload_dir . '/' . $this->attach_filename); - if ($width != 0 && $height != 0 && intval($attach_config['img_max_width']) != 0 && intval($attach_config['img_max_height']) != 0) - { - if ($width > intval($attach_config['img_max_width']) || $height > intval($attach_config['img_max_height'])) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['ERROR_IMAGESIZE'], intval($attach_config['img_max_width']), intval($attach_config['img_max_height'])); - } - } - } + if ($width != 0 && $height != 0 && intval($attach_config['img_max_width']) != 0 && intval($attach_config['img_max_height']) != 0) { + if ($width > intval($attach_config['img_max_width']) || $height > intval($attach_config['img_max_height'])) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['ERROR_IMAGESIZE'], intval($attach_config['img_max_width']), intval($attach_config['img_max_height'])); + } + } + } - // check Filesize - if (!$error && $allowed_filesize != 0 && $this->filesize > $allowed_filesize && !(IS_ADMIN || IS_MOD || IS_GROUP_MEMBER)) - { - $allowed_filesize = humn_size($allowed_filesize); + // check Filesize + if (!$error && $allowed_filesize != 0 && $this->filesize > $allowed_filesize && !(IS_ADMIN || IS_MOD || IS_GROUP_MEMBER)) { + $allowed_filesize = humn_size($allowed_filesize); - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['ATTACHMENT_TOO_BIG'], $allowed_filesize); - } + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['ATTACHMENT_TOO_BIG'], $allowed_filesize); + } - // Check our complete quota - if ($attach_config['attachment_quota']) - { - $sql = 'SELECT sum(filesize) as total FROM ' . BB_ATTACHMENTS_DESC; + // Check our complete quota + if ($attach_config['attachment_quota']) { + $sql = 'SELECT sum(filesize) as total FROM ' . BB_ATTACHMENTS_DESC; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query total filesize #1'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $total_filesize = $row['total']; + $total_filesize = $row['total']; - if (($total_filesize + $this->filesize) > $attach_config['attachment_quota']) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= $lang['ATTACH_QUOTA_REACHED']; - } + if (($total_filesize + $this->filesize) > $attach_config['attachment_quota']) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= $lang['ATTACH_QUOTA_REACHED']; + } + } - } + $this->get_quota_limits($userdata); - $this->get_quota_limits($userdata); - - // Check our user quota - if ($attach_config['upload_filesize_limit']) - { - $sql = 'SELECT attach_id + // Check our user quota + if ($attach_config['upload_filesize_limit']) { + $sql = 'SELECT attach_id FROM ' . BB_ATTACHMENTS . ' - WHERE user_id_1 = ' . (int) $userdata['user_id'] . ' + WHERE user_id_1 = ' . (int)$userdata['user_id'] . ' GROUP BY attach_id'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query attachments'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query attachments'); + } - $attach_ids = DB()->sql_fetchrowset($result); - $num_attach_ids = DB()->num_rows($result); - DB()->sql_freeresult($result); + $attach_ids = DB()->sql_fetchrowset($result); + $num_attach_ids = DB()->num_rows($result); + DB()->sql_freeresult($result); - $attach_id = array(); + $attach_id = array(); - for ($i = 0; $i < $num_attach_ids; $i++) - { - $attach_id[] = intval($attach_ids[$i]['attach_id']); - } + for ($i = 0; $i < $num_attach_ids; $i++) { + $attach_id[] = intval($attach_ids[$i]['attach_id']); + } - if ($num_attach_ids > 0) - { - // Now get the total filesize - $sql = 'SELECT sum(filesize) as total + if ($num_attach_ids > 0) { + // Now get the total filesize + $sql = 'SELECT sum(filesize) as total FROM ' . BB_ATTACHMENTS_DESC . ' WHERE attach_id IN (' . implode(', ', $attach_id) . ')'; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not query total filesize #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not query total filesize #2'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); - $total_filesize = $row['total']; - } - else - { - $total_filesize = 0; - } + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); + $total_filesize = $row['total']; + } else { + $total_filesize = 0; + } - if (($total_filesize + $this->filesize) > $attach_config['upload_filesize_limit']) - { - $upload_filesize_limit = $attach_config['upload_filesize_limit']; - $size_lang = ($upload_filesize_limit >= 1048576) ? $lang['MB'] : ( ($upload_filesize_limit >= 1024) ? $lang['KB'] : $lang['BYTES'] ); + if (($total_filesize + $this->filesize) > $attach_config['upload_filesize_limit']) { + $upload_filesize_limit = $attach_config['upload_filesize_limit']; + $size_lang = ($upload_filesize_limit >= 1048576) ? $lang['MB'] : (($upload_filesize_limit >= 1024) ? $lang['KB'] : $lang['BYTES']); - if ($upload_filesize_limit >= 1048576) - { - $upload_filesize_limit = round($upload_filesize_limit / 1048576 * 100) / 100; - } - else if($upload_filesize_limit >= 1024) - { - $upload_filesize_limit = round($upload_filesize_limit / 1024 * 100) / 100; - } + if ($upload_filesize_limit >= 1048576) { + $upload_filesize_limit = round($upload_filesize_limit / 1048576 * 100) / 100; + } elseif ($upload_filesize_limit >= 1024) { + $upload_filesize_limit = round($upload_filesize_limit / 1024 * 100) / 100; + } - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['USER_UPLOAD_QUOTA_REACHED'], $upload_filesize_limit, $size_lang); - } - } + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['USER_UPLOAD_QUOTA_REACHED'], $upload_filesize_limit, $size_lang); + } + } - if ($error) - { - unlink_attach($this->attach_filename); - unlink_attach($this->attach_filename, MODE_THUMBNAIL); - $this->post_attach = FALSE; - } - } - } + if ($error) { + unlink_attach($this->attach_filename); + unlink_attach($this->attach_filename, MODE_THUMBNAIL); + $this->post_attach = false; + } + } + } - // Copy the temporary attachment to the right location (copy, move_uploaded_file) - public function move_uploaded_attachment($upload_mode, $file) - { - global $error, $error_msg, $lang, $upload_dir; + // Copy the temporary attachment to the right location (copy, move_uploaded_file) + public function move_uploaded_attachment($upload_mode, $file) + { + global $error, $error_msg, $lang, $upload_dir; - if (!is_uploaded_file($file)) - { - bb_die('Unable to upload file. The given source has not been uploaded'); - } + if (!is_uploaded_file($file)) { + bb_die('Unable to upload file. The given source has not been uploaded'); + } - switch ($upload_mode) - { - case 'copy': + switch ($upload_mode) { + case 'copy': - if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) - { - if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); - return; - } - } - @chmod($upload_dir . '/' . basename($this->attach_filename), 0666); + if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) { + if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); + return; + } + } + @chmod($upload_dir . '/' . basename($this->attach_filename), 0666); - break; + break; - case 'move': + case 'move': - if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) - { - if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) - { - $error = TRUE; - if(!empty($error_msg)) - { - $error_msg .= '
        '; - } - $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); - return; - } - } - @chmod($upload_dir . '/' . $this->attach_filename, 0666); + if (!@move_uploaded_file($file, $upload_dir . '/' . basename($this->attach_filename))) { + if (!@copy($file, $upload_dir . '/' . basename($this->attach_filename))) { + $error = true; + if (!empty($error_msg)) { + $error_msg .= '
        '; + } + $error_msg .= sprintf($lang['GENERAL_UPLOAD_ERROR'], './' . $upload_dir . '/' . $this->attach_filename); + return; + } + } + @chmod($upload_dir . '/' . $this->attach_filename, 0666); - break; - } + break; + } - if (!$error && $this->thumbnail == 1) - { - $source = $upload_dir . '/' . basename($this->attach_filename); - $dest_file = amod_realpath($upload_dir); - $dest_file .= '/' . THUMB_DIR . '/t_' . basename($this->attach_filename); + if (!$error && $this->thumbnail == 1) { + $source = $upload_dir . '/' . basename($this->attach_filename); + $dest_file = amod_realpath($upload_dir); + $dest_file .= '/' . THUMB_DIR . '/t_' . basename($this->attach_filename); - if (!create_thumbnail($source, $dest_file, $this->type)) - { - if (!$file || !create_thumbnail($file, $dest_file, $this->type)) - { - $this->thumbnail = 0; - } - } - } - } + if (!create_thumbnail($source, $dest_file, $this->type)) { + if (!$file || !create_thumbnail($file, $dest_file, $this->type)) { + $this->thumbnail = 0; + } + } + } + } } /** -* @package attachment_mod -* Attachment posting -*/ + * @package attachment_mod + * Attachment posting + */ class attach_posting extends attach_parent { - /** - * Constructor - */ - public function __construct() - { - $this->attach_parent(); - $this->page = 0; - } + /** + * Constructor + */ + public function __construct() + { + $this->attach_parent(); + $this->page = 0; + } - /** - * Insert an Attachment into a Post (this is the second function called from posting.php) - */ - public function insert_attachment($post_id) - { - global $is_auth, $mode; + /** + * Insert an Attachment into a Post (this is the second function called from posting.php) + */ + public function insert_attachment($post_id) + { + global $is_auth, $mode; - // Insert Attachment ? - if (!empty($post_id) && ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') && $is_auth['auth_attachments']) - { - $this->do_insert_attachment('attach_list', 'post', $post_id); - $this->do_insert_attachment('last_attachment', 'post', $post_id); + // Insert Attachment ? + if (!empty($post_id) && ($mode == 'newtopic' || $mode == 'reply' || $mode == 'editpost') && $is_auth['auth_attachments']) { + $this->do_insert_attachment('attach_list', 'post', $post_id); + $this->do_insert_attachment('last_attachment', 'post', $post_id); - if ((sizeof($this->attachment_list) > 0 || $this->post_attach) && !isset($_POST['update_attachment'])) - { - $sql = 'UPDATE ' . BB_POSTS . ' SET post_attachment = 1 WHERE post_id = ' . (int) $post_id; + if ((sizeof($this->attachment_list) > 0 || $this->post_attach) && !isset($_POST['update_attachment'])) { + $sql = 'UPDATE ' . BB_POSTS . ' SET post_attachment = 1 WHERE post_id = ' . (int)$post_id; - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update posts table'); - } + if (!(DB()->sql_query($sql))) { + bb_die('Unable to update posts table'); + } - $sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int) $post_id; + $sql = 'SELECT topic_id FROM ' . BB_POSTS . ' WHERE post_id = ' . (int)$post_id; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Unable to select posts table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Unable to select posts table'); + } - $row = DB()->sql_fetchrow($result); - DB()->sql_freeresult($result); + $row = DB()->sql_fetchrow($result); + DB()->sql_freeresult($result); - $sql = 'UPDATE ' . BB_TOPICS . ' SET topic_attachment = 1 WHERE topic_id = ' . (int) $row['topic_id']; + $sql = 'UPDATE ' . BB_TOPICS . ' SET topic_attachment = 1 WHERE topic_id = ' . (int)$row['topic_id']; - if (!(DB()->sql_query($sql))) - { - bb_die('Unable to update topics table'); - } - } - } - } + if (!(DB()->sql_query($sql))) { + bb_die('Unable to update topics table'); + } + } + } + } - /** - * Handle Attachments (Add/Delete/Edit/Show) - This is the first function called from every message handler - */ - public function posting_attachment_mod() - { - global $mode, $confirm, $is_auth, $post_id, $delete, $refresh; + /** + * Handle Attachments (Add/Delete/Edit/Show) - This is the first function called from every message handler + */ + public function posting_attachment_mod() + { + global $mode, $confirm, $is_auth, $post_id, $delete, $refresh; - if (!$refresh) - { - $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? TRUE : FALSE; - $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? TRUE : FALSE; + if (!$refresh) { + $add_attachment_box = (!empty($_POST['add_attachment_box'])) ? true : false; + $posted_attachments_box = (!empty($_POST['posted_attachments_box'])) ? true : false; - $refresh = $add_attachment_box || $posted_attachments_box; - } + $refresh = $add_attachment_box || $posted_attachments_box; + } - // Choose what to display - $result = $this->handle_attachments($mode); + // Choose what to display + $result = $this->handle_attachments($mode); - if ($result === false) - { - return; - } + if ($result === false) { + return; + } - if ($confirm && ($delete || $mode == 'delete' || $mode == 'editpost') && ($is_auth['auth_delete'] || $is_auth['auth_mod'])) - { - if ($post_id) - { - delete_attachment($post_id); - } - } - - $this->display_attachment_bodies(); - } + if ($confirm && ($delete || $mode == 'delete' || $mode == 'editpost') && ($is_auth['auth_delete'] || $is_auth['auth_mod'])) { + if ($post_id) { + delete_attachment($post_id); + } + } + $this->display_attachment_bodies(); + } } /** -* Entry Point -*/ + * Entry Point + */ function execute_posting_attachment_handling() { - global $attachment_mod; + global $attachment_mod; - $attachment_mod['posting'] = new attach_posting(); - $attachment_mod['posting']->posting_attachment_mod(); + $attachment_mod['posting'] = new attach_posting(); + $attachment_mod['posting']->posting_attachment_mod(); } diff --git a/library/config.php b/library/config.php index d2b3aff23..5efccdb02 100644 --- a/library/config.php +++ b/library/config.php @@ -1,28 +1,51 @@ (array) srv_cfg; // порядок параметров srv_cfg (хост, название базы, пользователь, пароль, charset, pconnect); $bb_cfg['db'] = array( - 'db1' => array('localhost', 'tp_215', 'user', 'pass', $charset, $pconnect), - //'db2' => array('localhost2', 'dbase2', 'user2', 'pass2', $charset, $pconnect), - //'db3' => array('localhost3', 'dbase3', 'user2', 'pass3', $charset, $pconnect), + 'db1' => array('localhost', 'tp_215', 'user', 'pass', $charset, $pconnect), + //'db2' => array('localhost2', 'dbase2', 'user2', 'pass2', $charset, $pconnect), + //'db3' => array('localhost3', 'dbase3', 'user2', 'pass3', $charset, $pconnect), ); $bb_cfg['db_alias'] = array( // 'alias' => 'srv_name' # db1 - 'log' => 'db1', // BB_LOG - 'search' => 'db1', // BB_TOPIC_SEARCH - 'sres' => 'db1', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS - 'u_ses' => 'db1', // BB_USER_SES, BB_USER_LASTVISIT + 'log' => 'db1', // BB_LOG + 'search' => 'db1', // BB_TOPIC_SEARCH + 'sres' => 'db1', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS + 'u_ses' => 'db1', // BB_USER_SES, BB_USER_LASTVISIT # db2 - 'dls' => 'db1', // BB_BT_DLS_* - 'ip' => 'db1', // BB_POSTS_IP - 'ut' => 'db1', // BB_TOPICS_USER_POSTED + 'dls' => 'db1', // BB_BT_DLS_* + 'ip' => 'db1', // BB_POSTS_IP + 'ut' => 'db1', // BB_TOPICS_USER_POSTED # db3 - 'pm' => 'db1', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT - 'pt' => 'db1', // BB_POSTS_TEXT + 'pm' => 'db1', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT + 'pt' => 'db1', // BB_POSTS_TEXT ); // Cache $bb_cfg['cache']['pconnect'] = true; -$bb_cfg['cache']['db_dir'] = realpath(BB_ROOT) .'/internal_data/cache/filecache/'; -$bb_cfg['cache']['prefix'] = 'tp_'; // Префикс кеша ('tp_') +$bb_cfg['cache']['db_dir'] = realpath(BB_ROOT) . '/internal_data/cache/filecache/'; +$bb_cfg['cache']['prefix'] = 'tp_'; // Префикс кеша ('tp_') $bb_cfg['cache']['memcache'] = array( - 'host' => '127.0.0.1', - 'port' => 11211, - 'pconnect' => true, - 'con_required' => true, + 'host' => '127.0.0.1', + 'port' => 11211, + 'pconnect' => true, + 'con_required' => true, ); -$bb_cfg['cache']['redis'] = array( - 'host' => '127.0.0.1', - 'port' => 6379, - 'con_required' => true, +$bb_cfg['cache']['redis'] = array( + 'host' => '127.0.0.1', + 'port' => 6379, + 'con_required' => true, ); // Available cache types: memcache, sqlite, redis, apc, xcache (default of filecache) # name => array( (string) type, (array) cfg ) $bb_cfg['cache']['engines'] = array( - 'bb_cache' => array('filecache', array()), - 'bb_config' => array('filecache', array()), - 'tr_cache' => array('filecache', array()), - 'session_cache' => array('filecache', array()), - 'bb_cap_sid' => array('filecache', array()), - 'bb_login_err' => array('filecache', array()), - 'bb_poll_data' => array('filecache', array()), + 'bb_cache' => array('filecache', array()), + 'bb_config' => array('filecache', array()), + 'tr_cache' => array('filecache', array()), + 'session_cache' => array('filecache', array()), + 'bb_cap_sid' => array('filecache', array()), + 'bb_login_err' => array('filecache', array()), + 'bb_poll_data' => array('filecache', array()), ); // Datastore // Available datastore types: memcache, sqlite, redis, apc, xcache (default filecache) @@ -142,76 +167,75 @@ $bb_cfg['server_port'] = (!empty($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PO $bb_cfg['script_path'] = '/'; // The path where FORUM is located relative to the domain name // Cloudflare -if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) -{ - $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP']; +if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) { + $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP']; } // GZip -$bb_cfg['gzip_compress'] = true; // compress output +$bb_cfg['gzip_compress'] = true; // compress output // Tracker -$bb_cfg['announce_interval'] = 2400; // Announce interval (default: 1800) -$bb_cfg['passkey_key'] = 'uk'; // Passkey key name in GET request +$bb_cfg['announce_interval'] = 2400; // Announce interval (default: 1800) +$bb_cfg['passkey_key'] = 'uk'; // Passkey key name in GET request $bb_cfg['ignore_reported_ip'] = false; // Ignore IP reported by client $bb_cfg['verify_reported_ip'] = true; // Verify IP reported by client against $_SERVER['HTTP_X_FORWARDED_FOR'] -$bb_cfg['allow_internal_ip'] = false; // Allow internal IP (10.xx.. etc.) +$bb_cfg['allow_internal_ip'] = false; // Allow internal IP (10.xx.. etc.) // Ocelot $bb_cfg['ocelot'] = array( - 'enabled' => false, - 'host' => $domain_name, - 'port' => 34000, - 'url' => "http://$domain_name:34000/", // with '/' - 'secret' => 'some_10_chars', // 10 chars - 'stats' => 'some_10_chars', // 10 chars + 'enabled' => false, + 'host' => $domain_name, + 'port' => 34000, + 'url' => "http://$domain_name:34000/", // with '/' + 'secret' => 'some_10_chars', // 10 chars + 'stats' => 'some_10_chars', // 10 chars ); // FAQ url help link -$bb_cfg['how_to_download_url_help'] = 'viewtopic.php?t=1'; // Как скачивать? -$bb_cfg['what_is_torrent_url_help'] = 'viewtopic.php?t=2'; // Что такое торрент? -$bb_cfg['ratio_url_help'] = 'viewtopic.php?t=3'; // Рейтинг и ограничения -$bb_cfg['search_help_url'] = 'viewtopic.php?t=4'; // Помощь по поиску +$bb_cfg['how_to_download_url_help'] = 'viewtopic.php?t=1'; // Как скачивать? +$bb_cfg['what_is_torrent_url_help'] = 'viewtopic.php?t=2'; // Что такое торрент? +$bb_cfg['ratio_url_help'] = 'viewtopic.php?t=3'; // Рейтинг и ограничения +$bb_cfg['search_help_url'] = 'viewtopic.php?t=4'; // Помощь по поиску // Torrents $bb_cfg['bt_min_ratio_allow_dl_tor'] = 0.3; // 0 - disable -$bb_cfg['bt_min_ratio_warning'] = 0.6; // 0 - disable +$bb_cfg['bt_min_ratio_warning'] = 0.6; // 0 - disable $tr_cfg = array( - 'autoclean' => true, - 'off' => false, - 'off_reason' => 'temporarily disabled', - 'numwant' => 50, - 'update_dlstat' => true, - 'expire_factor' => 2.5, - 'compact_mode' => true, - 'upd_user_up_down_stat' => true, - 'browser_redirect_url' => '', - 'scrape' => true, - 'limit_active_tor' => true, - 'limit_seed_count' => 0, - 'limit_leech_count' => 8, - 'leech_expire_factor' => 60, - 'limit_concurrent_ips' => false, - 'limit_seed_ips' => 0, - 'limit_leech_ips' => 0, - 'tor_topic_up' => true, - 'gold_silver_enabled' => true, - 'retracker' => true, - 'retracker_host' => 'http://retracker.local/announce', + 'autoclean' => true, + 'off' => false, + 'off_reason' => 'temporarily disabled', + 'numwant' => 50, + 'update_dlstat' => true, + 'expire_factor' => 2.5, + 'compact_mode' => true, + 'upd_user_up_down_stat' => true, + 'browser_redirect_url' => '', + 'scrape' => true, + 'limit_active_tor' => true, + 'limit_seed_count' => 0, + 'limit_leech_count' => 8, + 'leech_expire_factor' => 60, + 'limit_concurrent_ips' => false, + 'limit_seed_ips' => 0, + 'limit_leech_ips' => 0, + 'tor_topic_up' => true, + 'gold_silver_enabled' => true, + 'retracker' => true, + 'retracker_host' => 'http://retracker.local/announce', ); $bb_cfg['show_dl_status_in_search'] = true; -$bb_cfg['show_dl_status_in_forum'] = true; +$bb_cfg['show_dl_status_in_forum'] = true; $bb_cfg['show_tor_info_in_dl_list'] = true; $bb_cfg['allow_dl_list_names_mode'] = true; $bb_cfg['torrent_name_style'] = true; // use torrent name style [yoursite.com].txxx.torrent -$bb_cfg['tor_help_links'] = 'terms.php'; +$bb_cfg['tor_help_links'] = 'terms.php'; // Сколько дней сохранять торрент зарегистрированным / Days to keep torrent registered, if: -$bb_cfg['seeder_last_seen_days_keep'] = 0; // сколько дней назад был сид последний раз +$bb_cfg['seeder_last_seen_days_keep'] = 0; // сколько дней назад был сид последний раз $bb_cfg['seeder_never_seen_days_keep'] = 0; // сколько дней имеется статус "Сида не было никогда" // Ratio limits @@ -224,116 +248,107 @@ define('MIN_DL_FOR_RATIO', 10737418240); // 10 GB in bytes, 0 - disable // rating < 0.6 -- only 3 // rating > 0.6 -- depend on your tracker config limits (in "ACP - Tracker Config - Limits") $rating_limits = array( - '0.4' => 1, - '0.5' => 2, - '0.6' => 3, + '0.4' => 1, + '0.5' => 2, + '0.6' => 3, ); // DL-Status (days to keep user's dlstatus records) -$bb_cfg['dl_will_days_keep'] = 360; -$bb_cfg['dl_down_days_keep'] = 180; +$bb_cfg['dl_will_days_keep'] = 360; +$bb_cfg['dl_down_days_keep'] = 180; $bb_cfg['dl_complete_days_keep'] = 180; -$bb_cfg['dl_cancel_days_keep'] = 30; +$bb_cfg['dl_cancel_days_keep'] = 30; // Tor-Stats -$bb_cfg['torstat_days_keep'] = 60; // days to keep user's per-torrent stats +$bb_cfg['torstat_days_keep'] = 60; // days to keep user's per-torrent stats // Tor-Help -$bb_cfg['torhelp_enabled'] = false; // find dead torrents (without seeder) that user might help seeding +$bb_cfg['torhelp_enabled'] = false; // find dead torrents (without seeder) that user might help seeding $page_cfg['show_torhelp'] = array( # BB_SCRIPT => true - 'index' => true, - 'tracker' => true, + 'index' => true, + 'tracker' => true, ); // Path (trailing slash '/' at the end: XX_PATH - without, XX_DIR - with) -define('BB_PATH', realpath(BB_ROOT) ); -define('ADMIN_DIR', BB_PATH .'/admin/' ); -define('DATA_DIR', BB_PATH .'/data/' ); -define('INT_DATA_DIR', BB_PATH .'/internal_data/' ); -define('AJAX_HTML_DIR', BB_ROOT .'/internal_data/ajax_html/' ); -define('CACHE_DIR', BB_PATH .'/internal_data/cache/' ); -define('LOG_DIR', BB_PATH .'/internal_data/log/' ); -define('SITEMAP_DIR', BB_PATH .'/internal_data/sitemap/' ); -define('TRIGGERS_DIR', BB_PATH .'/internal_data/triggers/' ); -define('AJAX_DIR', BB_ROOT .'/library/ajax/' ); -define('ATTACH_DIR', BB_PATH .'/library/attach_mod/' ); -define('CFG_DIR', BB_PATH .'/library/config/' ); -define('INC_DIR', BB_PATH .'/library/includes/' ); -define('CLASS_DIR', BB_PATH .'/library/includes/classes/'); -define('CORE_DIR', BB_PATH .'/library/includes/core/' ); -define('UCP_DIR', BB_PATH .'/library/includes/ucp/' ); -define('LANG_ROOT_DIR', BB_PATH .'/library/language/' ); -define('IMAGES_DIR', BB_PATH .'/styles/images/' ); -define('TEMPLATES_DIR', BB_PATH .'/styles/templates/' ); +define('BB_PATH', realpath(BB_ROOT)); +define('ADMIN_DIR', BB_PATH . '/admin/'); +define('DATA_DIR', BB_PATH . '/data/'); +define('INT_DATA_DIR', BB_PATH . '/internal_data/'); +define('AJAX_HTML_DIR', BB_ROOT . '/internal_data/ajax_html/'); +define('CACHE_DIR', BB_PATH . '/internal_data/cache/'); +define('LOG_DIR', BB_PATH . '/internal_data/log/'); +define('SITEMAP_DIR', BB_PATH . '/internal_data/sitemap/'); +define('TRIGGERS_DIR', BB_PATH . '/internal_data/triggers/'); +define('AJAX_DIR', BB_ROOT . '/library/ajax/'); +define('ATTACH_DIR', BB_PATH . '/library/attach_mod/'); +define('CFG_DIR', BB_PATH . '/library/config/'); +define('INC_DIR', BB_PATH . '/library/includes/'); +define('CLASS_DIR', BB_PATH . '/library/includes/classes/'); +define('CORE_DIR', BB_PATH . '/library/includes/core/'); +define('UCP_DIR', BB_PATH . '/library/includes/ucp/'); +define('LANG_ROOT_DIR', BB_PATH . '/library/language/'); +define('IMAGES_DIR', BB_PATH . '/styles/images/'); +define('TEMPLATES_DIR', BB_PATH . '/styles/templates/'); // URL's -$bb_cfg['ajax_url'] = 'ajax.php'; # "http://{$_SERVER['SERVER_NAME']}/ajax.php" -$bb_cfg['login_url'] = 'login.php'; # "http://{$domain_name}/login.php" +$bb_cfg['ajax_url'] = 'ajax.php'; # "http://{$_SERVER['SERVER_NAME']}/ajax.php" +$bb_cfg['login_url'] = 'login.php'; # "http://{$domain_name}/login.php" $bb_cfg['posting_url'] = 'posting.php'; # "http://{$domain_name}/posting.php" -$bb_cfg['pm_url'] = 'privmsg.php'; # "http://{$domain_name}/privmsg.php" +$bb_cfg['pm_url'] = 'privmsg.php'; # "http://{$domain_name}/privmsg.php" // Language -$bb_cfg['charset'] = 'utf8'; // page charset +$bb_cfg['charset'] = 'utf8'; // page charset $bb_cfg['auto_language'] = true; // select user-preferred language automatically -if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $bb_cfg['auto_language']) -{ - $user_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); - if (file_exists(LANG_ROOT_DIR . $user_lang .'/')) - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $user_lang .'/'; - $bb_cfg['default_lang'] = $user_lang; - } - else - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR .'en/'; - $bb_cfg['default_lang'] = 'en'; - } -} -else -{ - if (isset($bb_cfg['default_lang']) && file_exists(LANG_ROOT_DIR . $bb_cfg['default_lang'] .'/')) - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $bb_cfg['default_lang'] .'/'; - } - else - { - $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR .'en/'; - } +if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $bb_cfg['auto_language']) { + $user_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); + if (file_exists(LANG_ROOT_DIR . $user_lang . '/')) { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $user_lang . '/'; + $bb_cfg['default_lang'] = $user_lang; + } else { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . 'en/'; + $bb_cfg['default_lang'] = 'en'; + } +} else { + if (isset($bb_cfg['default_lang']) && file_exists(LANG_ROOT_DIR . $bb_cfg['default_lang'] . '/')) { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . $bb_cfg['default_lang'] . '/'; + } else { + $bb_cfg['default_lang_dir'] = LANG_ROOT_DIR . 'en/'; + } } $bb_cfg['lang'] = array( - 'ru' => array( - 'name' => 'Русский', - 'locale' => 'ru_RU.UTF-8', - 'encoding' => 'UTF-8', - 'captcha' => 'ru', - ), - 'uk' => array( - 'name' => 'Український', - 'locale' => 'uk_UA.UTF-8', - 'encoding' => 'UTF-8', - 'captcha' => 'uk', - ), - 'en' => array( - 'name' => 'English', - 'locale' => 'en_US.UTF-8', - 'encoding' => 'UTF-8', - 'captcha' => 'en', - ), + 'ru' => array( + 'name' => 'Русский', + 'locale' => 'ru_RU.UTF-8', + 'encoding' => 'UTF-8', + 'captcha' => 'ru', + ), + 'uk' => array( + 'name' => 'Український', + 'locale' => 'uk_UA.UTF-8', + 'encoding' => 'UTF-8', + 'captcha' => 'uk', + ), + 'en' => array( + 'name' => 'English', + 'locale' => 'en_US.UTF-8', + 'encoding' => 'UTF-8', + 'captcha' => 'en', + ), ); // Templates -define('ADMIN_TPL_DIR', TEMPLATES_DIR .'/admin/'); +define('ADMIN_TPL_DIR', TEMPLATES_DIR . '/admin/'); $bb_cfg['templates'] = array( // 'folder' => 'Name', - 'default' => 'Стандартный', + 'default' => 'Стандартный', ); -$bb_cfg['tpl_name'] = 'default'; +$bb_cfg['tpl_name'] = 'default'; $bb_cfg['stylesheet'] = 'main.css'; $bb_cfg['show_sidebar1_on_every_page'] = false; @@ -341,11 +356,11 @@ $bb_cfg['show_sidebar2_on_every_page'] = false; $page_cfg['show_sidebar1'] = array( # BB_SCRIPT => true - 'index' => true, + 'index' => true, ); $page_cfg['show_sidebar2'] = array( # BB_SCRIPT => true - 'index' => true, + 'index' => true, ); // Cookie @@ -354,167 +369,171 @@ $bb_cfg['cookie_secure'] = (!empty($_SERVER['HTTPS']) ? 1 : 0); $bb_cfg['cookie_prefix'] = 'bb_'; // 'bb_' // Sessions -$bb_cfg['session_update_intrv'] = 180; // sec -$bb_cfg['user_session_duration'] = 1800; // sec -$bb_cfg['admin_session_duration'] = 6*3600; // sec -$bb_cfg['user_session_gc_ttl'] = 1800; // number of seconds that a staled session entry may remain in sessions table -$bb_cfg['session_cache_gc_ttl'] = 1200; // sec -$bb_cfg['max_last_visit_days'] = 14; // days +$bb_cfg['session_update_intrv'] = 180; // sec +$bb_cfg['user_session_duration'] = 1800; // sec +$bb_cfg['admin_session_duration'] = 6 * 3600; // sec +$bb_cfg['user_session_gc_ttl'] = 1800; // number of seconds that a staled session entry may remain in sessions table +$bb_cfg['session_cache_gc_ttl'] = 1200; // sec +$bb_cfg['max_last_visit_days'] = 14; // days $bb_cfg['last_visit_update_intrv'] = 3600; // sec // Registration -$bb_cfg['invalid_logins'] = 5; // Количество неверных попыток ввода пароля, перед выводом проверки капчей -$bb_cfg['new_user_reg_disabled'] = false; // Запретить регистрацию новых учетных записей -$bb_cfg['unique_ip'] = false; // Запретить регистрацию нескольких учетных записей с одного ip +$bb_cfg['invalid_logins'] = 5; // Количество неверных попыток ввода пароля, перед выводом проверки капчей +$bb_cfg['new_user_reg_disabled'] = false; // Запретить регистрацию новых учетных записей +$bb_cfg['unique_ip'] = false; // Запретить регистрацию нескольких учетных записей с одного ip $bb_cfg['new_user_reg_restricted'] = false; // Ограничить регистрацию новых пользователей по времени с 01:00 до 17:00 -$bb_cfg['reg_email_activation'] = true; // Требовать активацию учетной записи по email +$bb_cfg['reg_email_activation'] = true; // Требовать активацию учетной записи по email // Email -$bb_cfg['emailer_disabled'] = false; +$bb_cfg['emailer_disabled'] = false; -$bb_cfg['smtp_delivery'] = false; // send email via a named server instead of the local mail function -$bb_cfg['smtp_ssl'] = false; // use ssl connect -$bb_cfg['smtp_host'] = ''; // SMTP server host -$bb_cfg['smtp_port'] = 25; // SMTP server port -$bb_cfg['smtp_username'] = ''; // enter a username if your SMTP server requires it -$bb_cfg['smtp_password'] = ''; // enter a password if your SMTP server requires it +$bb_cfg['smtp_delivery'] = false; // send email via a named server instead of the local mail function +$bb_cfg['smtp_ssl'] = false; // use ssl connect +$bb_cfg['smtp_host'] = ''; // SMTP server host +$bb_cfg['smtp_port'] = 25; // SMTP server port +$bb_cfg['smtp_username'] = ''; // enter a username if your SMTP server requires it +$bb_cfg['smtp_password'] = ''; // enter a password if your SMTP server requires it -$bb_cfg['board_email'] = "noreply@$domain_name"; // admin email address -$bb_cfg['board_email_form'] = false; // can users send email to each other via board -$bb_cfg['board_email_sig'] = ''; // this text will be attached to all emails the board sends -$bb_cfg['board_email_sitename'] = $domain_name; // sitename used in all emails header +$bb_cfg['board_email'] = "noreply@$domain_name"; // admin email address +$bb_cfg['board_email_form'] = false; // can users send email to each other via board +$bb_cfg['board_email_sig'] = ''; // this text will be attached to all emails the board sends +$bb_cfg['board_email_sitename'] = $domain_name; // sitename used in all emails header -$bb_cfg['topic_notify_enabled'] = true; -$bb_cfg['pm_notify_enabled'] = true; -$bb_cfg['group_send_email'] = true; -$bb_cfg['email_change_disabled'] = false; // disable changing email by user +$bb_cfg['topic_notify_enabled'] = true; +$bb_cfg['pm_notify_enabled'] = true; +$bb_cfg['group_send_email'] = true; +$bb_cfg['email_change_disabled'] = false; // disable changing email by user -$bb_cfg['tech_admin_email'] = "admin@$domain_name"; // email for sending error reports -$bb_cfg['abuse_email'] = "abuse@$domain_name"; -$bb_cfg['adv_email'] = "adv@$domain_name"; +$bb_cfg['tech_admin_email'] = "admin@$domain_name"; // email for sending error reports +$bb_cfg['abuse_email'] = "abuse@$domain_name"; +$bb_cfg['adv_email'] = "adv@$domain_name"; // Debug -define('DBG_LOG', false); // enable forum debug (off on production) -define('DBG_TRACKER', false); // enable tracker debug (off on production) -define('COOKIE_DBG', 'bb_dbg'); // debug cookie name -define('SQL_DEBUG', true); // enable forum sql & cache debug -define('SQL_LOG_ERRORS', true); // all SQL_xxx options enabled only if SQL_DEBUG == TRUE -define('SQL_CALC_QUERY_TIME', true); // for stats +define('DBG_LOG', false); // enable forum debug (off on production) +define('DBG_TRACKER', false); // enable tracker debug (off on production) +define('COOKIE_DBG', 'bb_dbg'); // debug cookie name +define('SQL_DEBUG', true); // enable forum sql & cache debug +define('SQL_LOG_ERRORS', true); // all SQL_xxx options enabled only if SQL_DEBUG == TRUE +define('SQL_CALC_QUERY_TIME', true); // for stats define('SQL_LOG_SLOW_QUERIES', true); // log sql slow queries -define('SQL_SLOW_QUERY_TIME', 10); // slow query in seconds +define('SQL_SLOW_QUERY_TIME', 10); // slow query in seconds define('SQL_PREPEND_SRC_COMM', false); // prepend source file comment to sql query // Special users $bb_cfg['dbg_users'] = array( # user_id => 'name', - 2 => 'admin', + 2 => 'admin', ); $bb_cfg['unlimited_users'] = array( # user_id => 'name', - 2 => 'admin', + 2 => 'admin', ); $bb_cfg['super_admins'] = array( # user_id => 'name', - 2 => 'admin', + 2 => 'admin', ); // Log options -define('LOG_EXT', 'log'); -define('LOG_SEPR', ' | '); -define('LOG_LF', "\n"); +define('LOG_EXT', 'log'); +define('LOG_SEPR', ' | '); +define('LOG_LF', "\n"); define('LOG_MAX_SIZE', 1048576); // bytes // Error reporting ini_set('error_reporting', E_ALL); -ini_set('display_errors', 0); -ini_set('log_errors', 1); -ini_set('error_log', LOG_DIR .'php_err.log'); +ini_set('display_errors', 0); +ini_set('log_errors', 1); +ini_set('error_log', LOG_DIR . 'php_err.log'); // Check some variable // Magic quotes -if (get_magic_quotes_gpc()) die('Set magic_quotes off'); +if (get_magic_quotes_gpc()) { + die('Set magic_quotes off'); +} // JSON -if (!function_exists('json_encode')) die('Json_encode not installed'); +if (!function_exists('json_encode')) { + die('Json_encode not installed'); +} // Triggers -define('BB_ENABLED', TRIGGERS_DIR .'$on'); -define('BB_DISABLED', TRIGGERS_DIR .'$off'); -define('CRON_ALLOWED', TRIGGERS_DIR .'cron_allowed'); -define('CRON_RUNNING', TRIGGERS_DIR .'cron_running'); +define('BB_ENABLED', TRIGGERS_DIR . '$on'); +define('BB_DISABLED', TRIGGERS_DIR . '$off'); +define('CRON_ALLOWED', TRIGGERS_DIR . 'cron_allowed'); +define('CRON_RUNNING', TRIGGERS_DIR . 'cron_running'); // Date format -$bb_cfg['date_format'] = 'Y-m-d'; +$bb_cfg['date_format'] = 'Y-m-d'; // Subforums -$bb_cfg['sf_on_first_page_only'] = true; +$bb_cfg['sf_on_first_page_only'] = true; // Forums $bb_cfg['allowed_topics_per_page'] = array(50, 100, 150, 200, 250, 300); // Topics -$bb_cfg['show_quick_reply'] = true; -$bb_cfg['show_rank_text'] = false; -$bb_cfg['show_rank_image'] = true; -$bb_cfg['show_poster_joined'] = true; -$bb_cfg['show_poster_posts'] = true; -$bb_cfg['show_poster_from'] = true; -$bb_cfg['show_bot_nick'] = false; -$bb_cfg['text_buttons'] = false; // replace EDIT, QUOTE... images with text links -$bb_cfg['parse_ed2k_links'] = true; // make ed2k links clickable -$bb_cfg['post_date_format'] = 'd-M-Y H:i'; -$bb_cfg['ext_link_new_win'] = true; // open external links in new window +$bb_cfg['show_quick_reply'] = true; +$bb_cfg['show_rank_text'] = false; +$bb_cfg['show_rank_image'] = true; +$bb_cfg['show_poster_joined'] = true; +$bb_cfg['show_poster_posts'] = true; +$bb_cfg['show_poster_from'] = true; +$bb_cfg['show_bot_nick'] = false; +$bb_cfg['text_buttons'] = false; // replace EDIT, QUOTE... images with text links +$bb_cfg['parse_ed2k_links'] = true; // make ed2k links clickable +$bb_cfg['post_date_format'] = 'd-M-Y H:i'; +$bb_cfg['ext_link_new_win'] = true; // open external links in new window -$bb_cfg['topic_moved_days_keep'] = 7; // remove topic moved links after xx days (or FALSE to disable) +$bb_cfg['topic_moved_days_keep'] = 7; // remove topic moved links after xx days (or FALSE to disable) $bb_cfg['allowed_posts_per_page'] = array(15, 30, 50, 100); -$bb_cfg['user_signature_start'] = '

        _________________
        '; -$bb_cfg['user_signature_end'] = '
        '; // Это позволит использовать html теги, которые требуют закрытия. Например или +$bb_cfg['user_signature_start'] = '

        _________________
        '; +$bb_cfg['user_signature_end'] = '
        '; // Это позволит использовать html теги, которые требуют закрытия. Например
        или // Posts -$bb_cfg['use_posts_cache'] = true; // if you switch from ON to OFF, you need to TRUNCATE `bb_posts_html` table +$bb_cfg['use_posts_cache'] = true; // if you switch from ON to OFF, you need to TRUNCATE `bb_posts_html` table $bb_cfg['posts_cache_days_keep'] = 14; -$bb_cfg['max_post_length'] = 120000; // bytes -$bb_cfg['use_ajax_posts'] = true; +$bb_cfg['max_post_length'] = 120000; // bytes +$bb_cfg['use_ajax_posts'] = true; // Search -$bb_cfg['search_engine_type'] = 'mysql'; // none, mysql, sphinx -$bb_cfg['sphinx_topic_titles_host'] = '127.0.0.1'; -$bb_cfg['sphinx_topic_titles_port'] = 3312; -$bb_cfg['sphinx_config_path'] = realpath("../install/sphinx/sphinx.conf"); +$bb_cfg['search_engine_type'] = 'mysql'; // none, mysql, sphinx +$bb_cfg['sphinx_topic_titles_host'] = '127.0.0.1'; +$bb_cfg['sphinx_topic_titles_port'] = 3312; +$bb_cfg['sphinx_config_path'] = realpath("../install/sphinx/sphinx.conf"); $bb_cfg['disable_ft_search_in_posts'] = false; // disable searching in post bodies -$bb_cfg['disable_search_for_guest'] = true; -$bb_cfg['allow_search_in_bool_mode'] = true; -$bb_cfg['max_search_words_per_post'] = 200; -$bb_cfg['search_min_word_len'] = 3; -$bb_cfg['search_max_word_len'] = 35; -$bb_cfg['limit_max_search_results'] = false; -$bb_cfg['spam_filter_file_path'] = ''; // BB_PATH .'/misc/spam_filter_words.txt'; -$bb_cfg['autocorrect_wkl'] = true; // autocorrect wrong keyboard layout +$bb_cfg['disable_search_for_guest'] = true; +$bb_cfg['allow_search_in_bool_mode'] = true; +$bb_cfg['max_search_words_per_post'] = 200; +$bb_cfg['search_min_word_len'] = 3; +$bb_cfg['search_max_word_len'] = 35; +$bb_cfg['limit_max_search_results'] = false; +$bb_cfg['spam_filter_file_path'] = ''; // BB_PATH .'/misc/spam_filter_words.txt'; +$bb_cfg['autocorrect_wkl'] = true; // autocorrect wrong keyboard layout // Posting -$bb_cfg['prevent_multiposting'] = true; // replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster -$bb_cfg['max_smilies'] = 10; // Максимальное число смайлов в посте (0 - без ограничения) +$bb_cfg['prevent_multiposting'] = true; // replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster +$bb_cfg['max_smilies'] = 10; // Максимальное число смайлов в посте (0 - без ограничения) // PM -$bb_cfg['privmsg_disable'] = false; // отключить систему личных сообщений на форуме -$bb_cfg['max_outgoing_pm_cnt'] = 10; // ограничение на кол. одновременных исходящих лс (для замедления рассылки спама) -$bb_cfg['max_inbox_privmsgs'] = 200; // максимальное число сообщений в папке входящие +$bb_cfg['privmsg_disable'] = false; // отключить систему личных сообщений на форуме +$bb_cfg['max_outgoing_pm_cnt'] = 10; // ограничение на кол. одновременных исходящих лс (для замедления рассылки спама) +$bb_cfg['max_inbox_privmsgs'] = 200; // максимальное число сообщений в папке входящие $bb_cfg['max_savebox_privmsgs'] = 25; // максимальное число сообщений в папке сохраненные $bb_cfg['max_sentbox_privmsgs'] = 50; // максимальное число сообщений в папке отправленные -$bb_cfg['pm_days_keep'] = 180; // время хранения ЛС +$bb_cfg['pm_days_keep'] = 180; // время хранения ЛС // Actions log $bb_cfg['log_days_keep'] = 90; // Users -$bb_cfg['color_nick'] = true; // Окраска ников пользователей по user_rank +$bb_cfg['color_nick'] = true; // Окраска ников пользователей по user_rank $bb_cfg['user_not_activated_days_keep'] = 7; // "not activated" == "not finished registration" -$bb_cfg['user_not_active_days_keep'] = 180; // inactive users but only with no posts +$bb_cfg['user_not_active_days_keep'] = 180; // inactive users but only with no posts // Groups -$bb_cfg['group_members_per_page'] = 50; +$bb_cfg['group_members_per_page'] = 50; // Tidy $bb_cfg['tidy_post'] = (!in_array('tidy', get_loaded_extensions())) ? false : true; @@ -523,17 +542,17 @@ $bb_cfg['tidy_post'] = (!in_array('tidy', get_loaded_extensions())) ? false : tr $bb_cfg['show_ads'] = false; $bb_cfg['show_ads_users'] = array( # user_id => 'name', - 2 => 'admin', + 2 => 'admin', ); // block_type => [block_id => block_desc] $bb_cfg['ad_blocks'] = array( - 'trans' => array( - 100 => 'сквозная сверху', - ), - 'index' => array( - 200 => 'главная, под новостями', - ), + 'trans' => array( + 100 => 'сквозная сверху', + ), + 'index' => array( + 200 => 'главная, под новостями', + ), ); // Misc @@ -545,12 +564,12 @@ $bb_cfg['translate_dates'] = true; // in displaying time $bb_cfg['use_word_censor'] = true; $bb_cfg['last_visit_date_format'] = 'd-M H:i'; -$bb_cfg['last_post_date_format'] = 'd-M-y H:i'; -$bb_cfg['poll_max_days'] = 180; // сколько дней с момента создания темы опрос будет активным +$bb_cfg['last_post_date_format'] = 'd-M-y H:i'; +$bb_cfg['poll_max_days'] = 180; // сколько дней с момента создания темы опрос будет активным $bb_cfg['allow_change'] = array( - 'language' => true, - 'dateformat' => true, + 'language' => true, + 'dateformat' => true, ); define('GZIP_OUTPUT_ALLOWED', (extension_loaded('zlib') && !ini_get('zlib.output_compression'))); @@ -568,27 +587,27 @@ $bb_cfg['trash_forum_id'] = 0; // (int) 7 $bb_cfg['first_logon_redirect_url'] = 'index.php'; $bb_cfg['terms_and_conditions_url'] = 'terms.php'; -$bb_cfg['user_agreement_url'] = 'info.php?show=user_agreement'; -$bb_cfg['copyright_holders_url'] = 'info.php?show=copyright_holders'; -$bb_cfg['advert_url'] = 'info.php?show=advert'; +$bb_cfg['user_agreement_url'] = 'info.php?show=user_agreement'; +$bb_cfg['copyright_holders_url'] = 'info.php?show=copyright_holders'; +$bb_cfg['advert_url'] = 'info.php?show=advert'; // Extensions $bb_cfg['file_id_ext'] = array( - 1 => 'gif', - 2 => 'gz', - 3 => 'jpg', - 4 => 'png', - 5 => 'rar', - 6 => 'tar', - 7 => 'tiff', - 8 => 'torrent', - 9 => 'zip', + 1 => 'gif', + 2 => 'gz', + 3 => 'jpg', + 4 => 'png', + 5 => 'rar', + 6 => 'tar', + 7 => 'tiff', + 8 => 'torrent', + 9 => 'zip', ); // Attachments $bb_cfg['attach'] = array( - 'upload_path' => DATA_DIR . 'torrent_files', // путь к директории с torrent файлами - 'max_size' => 250*1024, // размер аватары в байтах + 'upload_path' => DATA_DIR . 'torrent_files', // путь к директории с torrent файлами + 'max_size' => 250 * 1024, // размер аватары в байтах ); $bb_cfg['tor_forums_allowed_ext'] = array('torrent', 'zip', 'rar'); // для разделов с раздачами @@ -596,52 +615,51 @@ $bb_cfg['gen_forums_allowed_ext'] = array('zip', 'rar'); // для о // Avatars $bb_cfg['avatars'] = array( - 'allowed_ext' => array('gif','jpg','jpeg','png'), // разрешенные форматы файлов - 'bot_avatar' => 'gallery/bot.gif', // аватара бота - 'max_size' => 100*1024, // размер аватары в байтах - 'max_height' => 100, // высота аватара в px - 'max_width' => 100, // ширина аватара в px - 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара - 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами - 'up_allowed' => true, // разрешить загрузку аватар + 'allowed_ext' => array('gif', 'jpg', 'jpeg', 'png'), // разрешенные форматы файлов + 'bot_avatar' => 'gallery/bot.gif', // аватара бота + 'max_size' => 100 * 1024, // размер аватары в байтах + 'max_height' => 100, // высота аватара в px + 'max_width' => 100, // ширина аватара в px + 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара + 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами + 'up_allowed' => true, // разрешить загрузку аватар ); // Group avatars $bb_cfg['group_avatars'] = array( - 'allowed_ext' => array('gif','jpg','jpeg','png'), // разрешенные форматы файлов - 'max_size' => 300*1024, // размер аватары в байтах - 'max_height' => 300, // высота аватара в px - 'max_width' => 300, // ширина аватара в px - 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара - 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами - 'up_allowed' => true, // разрешить загрузку аватар + 'allowed_ext' => array('gif', 'jpg', 'jpeg', 'png'), // разрешенные форматы файлов + 'max_size' => 300 * 1024, // размер аватары в байтах + 'max_height' => 300, // высота аватара в px + 'max_width' => 300, // ширина аватара в px + 'no_avatar' => 'gallery/noavatar.png', // дефолтная аватара + 'upload_path' => BB_ROOT . 'data/avatars/', // путь к директории с аватарами + 'up_allowed' => true, // разрешить загрузку аватар ); // Captcha // Get a Google reCAPTCHA API Key: https://www.google.com/recaptcha/admin $bb_cfg['captcha'] = array( - 'disabled' => false, - 'public_key' => '', // your public key - 'secret_key' => '', // your secret key - 'theme' => 'light', // light or dark + 'disabled' => false, + 'public_key' => '', // your public key + 'secret_key' => '', // your secret key + 'theme' => 'light', // light or dark ); // Atom feed $bb_cfg['atom'] = array( - 'path' => INT_DATA_DIR .'atom', // without ending slash - 'url' => './internal_data/atom', // without ending slash + 'path' => INT_DATA_DIR . 'atom', // without ending slash + 'url' => './internal_data/atom', // without ending slash ); // Nofollow $bb_cfg['nofollow'] = array( - 'disabled' => false, - 'allowed_url' => array($domain_name), // 'allowed.site', 'www.allowed.site' + 'disabled' => false, + 'allowed_url' => array($domain_name), // 'allowed.site', 'www.allowed.site' ); // Local config -if (file_exists(BB_ROOT. '/library/config.local.php')) -{ - include_once(BB_ROOT. '/library/config.local.php'); +if (file_exists(BB_ROOT . '/library/config.local.php')) { + include_once(BB_ROOT . '/library/config.local.php'); } -define('BB_CFG_LOADED', true); \ No newline at end of file +define('BB_CFG_LOADED', true); diff --git a/library/includes/api/sphinx.php b/library/includes/api/sphinx.php index 62e97dd8d..7cab38a6f 100644 --- a/library/includes/api/sphinx.php +++ b/library/includes/api/sphinx.php @@ -1,6 +1,31 @@ =8 ) - { - $v = (int)$v; - return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); - } + // x64 + if (PHP_INT_SIZE >= 8) { + $v = (int)$v; + return pack("NN", $v >> 32, $v & 0xFFFFFFFF); + } - // x32, int - if ( is_int($v) ) - return pack ( "NN", $v < 0 ? -1 : 0, $v ); + // x32, int + if (is_int($v)) { + return pack("NN", $v < 0 ? -1 : 0, $v); + } - // x32, bcmath - if ( function_exists("bcmul") ) - { - if ( bccomp ( $v, 0 ) == -1 ) - $v = bcadd ( "18446744073709551616", $v ); - $h = bcdiv ( $v, "4294967296", 0 ); - $l = bcmod ( $v, "4294967296" ); - return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit - } + // x32, bcmath + if (function_exists("bcmul")) { + if (bccomp($v, 0) == -1) { + $v = bcadd("18446744073709551616", $v); + } + $h = bcdiv($v, "4294967296", 0); + $l = bcmod($v, "4294967296"); + return pack("NN", (float)$h, (float)$l); // conversion to float is intentional; int would lose 31st bit + } - // x32, no-bcmath - $p = max(0, strlen($v) - 13); - $lo = abs((float)substr($v, $p)); - $hi = abs((float)substr($v, 0, $p)); + // x32, no-bcmath + $p = max(0, strlen($v) - 13); + $lo = abs((float)substr($v, $p)); + $hi = abs((float)substr($v, 0, $p)); - $m = $lo + $hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912 - $q = floor($m/4294967296.0); - $l = $m - ($q*4294967296.0); - $h = $hi*2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328 + $m = $lo + $hi * 1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912 + $q = floor($m / 4294967296.0); + $l = $m - ($q * 4294967296.0); + $h = $hi * 2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328 - if ( $v<0 ) - { - if ( $l==0 ) - $h = 4294967296.0 - $h; - else - { - $h = 4294967295.0 - $h; - $l = 4294967296.0 - $l; - } - } - return pack ( "NN", $h, $l ); + if ($v < 0) { + if ($l == 0) { + $h = 4294967296.0 - $h; + } else { + $h = 4294967295.0 - $h; + $l = 4294967296.0 - $l; + } + } + return pack("NN", $h, $l); } /// pack 64-bit unsigned -function sphPackU64 ( $v ) +function sphPackU64($v) { - assert ( is_numeric($v) ); + assert(is_numeric($v)); - // x64 - if ( PHP_INT_SIZE>=8 ) - { - assert ( $v>=0 ); + // x64 + if (PHP_INT_SIZE >= 8) { + assert($v >= 0); - // x64, int - if ( is_int($v) ) - return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); + // x64, int + if (is_int($v)) { + return pack("NN", $v >> 32, $v & 0xFFFFFFFF); + } - // x64, bcmath - if ( function_exists("bcmul") ) - { - $h = bcdiv ( $v, 4294967296, 0 ); - $l = bcmod ( $v, 4294967296 ); - return pack ( "NN", $h, $l ); - } + // x64, bcmath + if (function_exists("bcmul")) { + $h = bcdiv($v, 4294967296, 0); + $l = bcmod($v, 4294967296); + return pack("NN", $h, $l); + } - // x64, no-bcmath - $p = max ( 0, strlen($v) - 13 ); - $lo = (int)substr ( $v, $p ); - $hi = (int)substr ( $v, 0, $p ); + // x64, no-bcmath + $p = max(0, strlen($v) - 13); + $lo = (int)substr($v, $p); + $hi = (int)substr($v, 0, $p); - $m = $lo + $hi*1316134912; - $l = $m % 4294967296; - $h = $hi*2328 + (int)($m/4294967296); + $m = $lo + $hi * 1316134912; + $l = $m % 4294967296; + $h = $hi * 2328 + (int)($m / 4294967296); - return pack ( "NN", $h, $l ); - } + return pack("NN", $h, $l); + } - // x32, int - if ( is_int($v) ) - return pack ( "NN", 0, $v ); + // x32, int + if (is_int($v)) { + return pack("NN", 0, $v); + } - // x32, bcmath - if ( function_exists("bcmul") ) - { - $h = bcdiv ( $v, "4294967296", 0 ); - $l = bcmod ( $v, "4294967296" ); - return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit - } + // x32, bcmath + if (function_exists("bcmul")) { + $h = bcdiv($v, "4294967296", 0); + $l = bcmod($v, "4294967296"); + return pack("NN", (float)$h, (float)$l); // conversion to float is intentional; int would lose 31st bit + } - // x32, no-bcmath - $p = max(0, strlen($v) - 13); - $lo = (float)substr($v, $p); - $hi = (float)substr($v, 0, $p); + // x32, no-bcmath + $p = max(0, strlen($v) - 13); + $lo = (float)substr($v, $p); + $hi = (float)substr($v, 0, $p); - $m = $lo + $hi*1316134912.0; - $q = floor($m / 4294967296.0); - $l = $m - ($q * 4294967296.0); - $h = $hi*2328.0 + $q; + $m = $lo + $hi * 1316134912.0; + $q = floor($m / 4294967296.0); + $l = $m - ($q * 4294967296.0); + $h = $hi * 2328.0 + $q; - return pack ( "NN", $h, $l ); + return pack("NN", $h, $l); } // unpack 64-bit unsigned -function sphUnpackU64 ( $v ) +function sphUnpackU64($v) { - list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); + list($hi, $lo) = array_values(unpack("N*N*", $v)); - if ( PHP_INT_SIZE>=8 ) - { - if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again - if ( $lo<0 ) $lo += (1<<32); + if (PHP_INT_SIZE >= 8) { + if ($hi < 0) { + $hi += (1 << 32); + } // because php 5.2.2 to 5.2.5 is totally fucked up again + if ($lo < 0) { + $lo += (1 << 32); + } - // x64, int - if ( $hi<=2147483647 ) - return ($hi<<32) + $lo; + // x64, int + if ($hi <= 2147483647) { + return ($hi << 32) + $lo; + } - // x64, bcmath - if ( function_exists("bcmul") ) - return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); + // x64, bcmath + if (function_exists("bcmul")) { + return bcadd($lo, bcmul($hi, "4294967296")); + } - // x64, no-bcmath - $C = 100000; - $h = ((int)($hi / $C) << 32) + (int)($lo / $C); - $l = (($hi % $C) << 32) + ($lo % $C); - if ( $l>$C ) - { - $h += (int)($l / $C); - $l = $l % $C; - } + // x64, no-bcmath + $C = 100000; + $h = ((int)($hi / $C) << 32) + (int)($lo / $C); + $l = (($hi % $C) << 32) + ($lo % $C); + if ($l > $C) { + $h += (int)($l / $C); + $l = $l % $C; + } - if ( $h==0 ) - return $l; - return sprintf ( "%d%05d", $h, $l ); - } + if ($h == 0) { + return $l; + } + return sprintf("%d%05d", $h, $l); + } - // x32, int - if ( $hi==0 ) - { - if ( $lo>0 ) - return $lo; - return sprintf ( "%u", $lo ); - } + // x32, int + if ($hi == 0) { + if ($lo > 0) { + return $lo; + } + return sprintf("%u", $lo); + } - $hi = sprintf ( "%u", $hi ); - $lo = sprintf ( "%u", $lo ); + $hi = sprintf("%u", $hi); + $lo = sprintf("%u", $lo); - // x32, bcmath - if ( function_exists("bcmul") ) - return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); + // x32, bcmath + if (function_exists("bcmul")) { + return bcadd($lo, bcmul($hi, "4294967296")); + } - // x32, no-bcmath - $hi = (float)$hi; - $lo = (float)$lo; + // x32, no-bcmath + $hi = (float)$hi; + $lo = (float)$lo; - $q = floor($hi/10000000.0); - $r = $hi - $q*10000000.0; - $m = $lo + $r*4967296.0; - $mq = floor($m/10000000.0); - $l = $m - $mq*10000000.0; - $h = $q*4294967296.0 + $r*429.0 + $mq; + $q = floor($hi / 10000000.0); + $r = $hi - $q * 10000000.0; + $m = $lo + $r * 4967296.0; + $mq = floor($m / 10000000.0); + $l = $m - $mq * 10000000.0; + $h = $q * 4294967296.0 + $r * 429.0 + $mq; - $h = sprintf ( "%.0f", $h ); - $l = sprintf ( "%07.0f", $l ); - if ( $h=="0" ) - return sprintf( "%.0f", (float)$l ); - return $h . $l; + $h = sprintf("%.0f", $h); + $l = sprintf("%07.0f", $l); + if ($h == "0") { + return sprintf("%.0f", (float)$l); + } + return $h . $l; } // unpack 64-bit signed -function sphUnpackI64 ( $v ) +function sphUnpackI64($v) { - list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); + list($hi, $lo) = array_values(unpack("N*N*", $v)); - // x64 - if ( PHP_INT_SIZE>=8 ) - { - if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again - if ( $lo<0 ) $lo += (1<<32); + // x64 + if (PHP_INT_SIZE >= 8) { + if ($hi < 0) { + $hi += (1 << 32); + } // because php 5.2.2 to 5.2.5 is totally fucked up again + if ($lo < 0) { + $lo += (1 << 32); + } - return ($hi<<32) + $lo; - } + return ($hi << 32) + $lo; + } - // x32, int - if ( $hi==0 ) - { - if ( $lo>0 ) - return $lo; - return sprintf ( "%u", $lo ); - } - // x32, int - elseif ( $hi==-1 ) - { - if ( $lo<0 ) - return $lo; - return sprintf ( "%.0f", $lo - 4294967296.0 ); - } + // x32, int + if ($hi == 0) { + if ($lo > 0) { + return $lo; + } + return sprintf("%u", $lo); + } // x32, int + elseif ($hi == -1) { + if ($lo < 0) { + return $lo; + } + return sprintf("%.0f", $lo - 4294967296.0); + } - $neg = ""; - $c = 0; - if ( $hi<0 ) - { - $hi = ~$hi; - $lo = ~$lo; - $c = 1; - $neg = "-"; - } + $neg = ""; + $c = 0; + if ($hi < 0) { + $hi = ~$hi; + $lo = ~$lo; + $c = 1; + $neg = "-"; + } - $hi = sprintf ( "%u", $hi ); - $lo = sprintf ( "%u", $lo ); + $hi = sprintf("%u", $hi); + $lo = sprintf("%u", $lo); - // x32, bcmath - if ( function_exists("bcmul") ) - return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c ); + // x32, bcmath + if (function_exists("bcmul")) { + return $neg . bcadd(bcadd($lo, bcmul($hi, "4294967296")), $c); + } - // x32, no-bcmath - $hi = (float)$hi; - $lo = (float)$lo; + // x32, no-bcmath + $hi = (float)$hi; + $lo = (float)$lo; - $q = floor($hi/10000000.0); - $r = $hi - $q*10000000.0; - $m = $lo + $r*4967296.0; - $mq = floor($m/10000000.0); - $l = $m - $mq*10000000.0 + $c; - $h = $q*4294967296.0 + $r*429.0 + $mq; - if ( $l==10000000 ) - { - $l = 0; - $h += 1; - } + $q = floor($hi / 10000000.0); + $r = $hi - $q * 10000000.0; + $m = $lo + $r * 4967296.0; + $mq = floor($m / 10000000.0); + $l = $m - $mq * 10000000.0 + $c; + $h = $q * 4294967296.0 + $r * 429.0 + $mq; + if ($l == 10000000) { + $l = 0; + $h += 1; + } - $h = sprintf ( "%.0f", $h ); - $l = sprintf ( "%07.0f", $l ); - if ( $h=="0" ) - return $neg . sprintf( "%.0f", (float)$l ); - return $neg . $h . $l; + $h = sprintf("%.0f", $h); + $l = sprintf("%07.0f", $l); + if ($h == "0") { + return $neg . sprintf("%.0f", (float)$l); + } + return $neg . $h . $l; } -function sphFixUint ( $value ) +function sphFixUint($value) { - if ( PHP_INT_SIZE>=8 ) - { - // x64 route, workaround broken unpack() in 5.2.2+ - if ( $value<0 ) $value += (1<<32); - return $value; - } - else - { - // x32 route, workaround php signed/unsigned braindamage - return sprintf ( "%u", $value ); - } + if (PHP_INT_SIZE >= 8) { + // x64 route, workaround broken unpack() in 5.2.2+ + if ($value < 0) { + $value += (1 << 32); + } + return $value; + } else { + // x32 route, workaround php signed/unsigned braindamage + return sprintf("%u", $value); + } } /// sphinx searchd client class class SphinxClient extends cache_common { - public $_host; ///< searchd host (default is "localhost") - public $_port; ///< searchd port (default is 9312) - public $_offset; ///< how many records to seek from result-set start (default is 0) - public $_limit; ///< how many records to return from result-set starting at offset (default is 20) - public $_mode; ///< query matching mode (default is SPH_MATCH_ALL) - public $_weights; ///< per-field weights (default is 1 for all fields) - public $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) - public $_sortby; ///< attribute to sort by (defualt is "") - public $_min_id; ///< min ID to match (default is 0, which means no limit) - public $_max_id; ///< max ID to match (default is 0, which means no limit) - public $_filters; ///< search filters - public $_groupby; ///< group-by attribute name - public $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) - public $_groupsort; ///< group-by sorting clause (to sort groups in result set with) - public $_groupdistinct;///< group-by count-distinct attribute - public $_maxmatches; ///< max matches to retrieve - public $_cutoff; ///< cutoff to stop searching at (default is 0) - public $_retrycount; ///< distributed retries count - public $_retrydelay; ///< distributed retries delay - public $_anchor; ///< geographical anchor point - public $_indexweights; ///< per-index weights - public $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) - public $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) - public $_fieldweights; ///< per-field-name weights - public $_overrides; ///< per-query attribute values overrides - public $_select; ///< select-list (attributes or expressions, with optional aliases) - - public $_error; ///< last error message - public $_warning; ///< last warning message - public $_connerror; ///< connection error vs remote error flag - - public $_reqs; ///< requests array for multi-query - public $_mbenc; ///< stored mbstring encoding - public $_arrayresult; ///< whether $result["matches"] should be a hash or an array - public $_timeout; ///< connect timeout - - public $bb_queries = array(); - public $bb_indexes = array(); - - ///////////////////////////////////////////////////////////////////////////// - // common stuff - ///////////////////////////////////////////////////////////////////////////// - - /// create a new client object and fill defaults - public function __construct () - { - $this->dbg_enabled = sql_dbg_enabled(); - - // per-client-object settings - $this->_host = "localhost"; - $this->_port = 9312; - $this->_path = false; - $this->_socket = false; - - // per-query settings - $this->_offset = 0; - $this->_limit = 2000; - $this->_mode = SPH_MATCH_ALL; - $this->_weights = array (); - $this->_sort = SPH_SORT_RELEVANCE; - $this->_sortby = ""; - $this->_min_id = 0; - $this->_max_id = 0; - $this->_filters = array (); - $this->_groupby = ""; - $this->_groupfunc = SPH_GROUPBY_DAY; - $this->_groupsort = "@group desc"; - $this->_groupdistinct= ""; - $this->_maxmatches = 1000; - $this->_cutoff = 0; - $this->_retrycount = 0; - $this->_retrydelay = 0; - $this->_anchor = array (); - $this->_indexweights= array (); - $this->_ranker = SPH_RANK_PROXIMITY_BM25; - $this->_maxquerytime= 0; - $this->_fieldweights= array(); - $this->_overrides = array(); - $this->_select = "*"; - - $this->_error = ""; // per-reply fields (for single-query case) - $this->_warning = ""; - $this->_connerror = false; - - $this->_reqs = array (); // requests storage (for multi-query case) - $this->_mbenc = ""; - $this->_arrayresult = false; - $this->_timeout = 0; - } - - public function __destruct() - { - if ( $this->_socket !== false ) - fclose ( $this->_socket ); - } - - /// get last error message (string) - public function GetLastError () - { - return $this->_error; - } - - /// get last warning message (string) - public function GetLastWarning () - { - return $this->_warning; - } - - /// get last error flag (to tell network connection errors from searchd errors or broken responses) - public function IsConnectError() - { - return $this->_connerror; - } - - /// set searchd host name (string) and port (integer) - public function SetServer ( $host, $port = 0 ) - { - assert ( is_string($host) ); - if ( $host[0] == '/') - { - $this->_path = 'unix://' . $host; - return; - } - if ( substr ( $host, 0, 7 )=="unix://" ) - { - $this->_path = $host; - return; - } - - assert ( is_int($port) ); - $this->_host = $host; - $this->_port = $port; - $this->_path = ''; - - } - - /// set server connection timeout (0 to remove) - public function SetConnectTimeout ( $timeout ) - { - assert ( is_numeric($timeout) ); - $this->_timeout = $timeout; - } - - - public function _Send ( $handle, $data, $length ) - { - if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length ) - { - $this->_error = 'connection unexpectedly closed (timed out?)'; - $this->_connerror = true; - return false; - } - return true; - } - - ///////////////////////////////////////////////////////////////////////////// - - /// enter mbstring workaround mode - public function _MBPush () - { - $this->_mbenc = ""; - if ( ini_get ( "mbstring.func_overload" ) & 2 ) - { - $this->_mbenc = mb_internal_encoding(); - mb_internal_encoding ( "latin1" ); - } - } - - /// leave mbstring workaround mode - public function _MBPop () - { - if ( $this->_mbenc ) - mb_internal_encoding ( $this->_mbenc ); - } - - /// connect to searchd server - public function _Connect () - { - $this->cur_query = "connect to: {$this->_host}"; - $this->debug('start'); - - if ( $this->_socket!==false ) - { - // we are in persistent connection mode, so we have a socket - // however, need to check whether it's still alive - if ( !@feof ( $this->_socket ) ) - return $this->_socket; - - // force reopen - $this->_socket = false; - } - - $errno = 0; - $errstr = ""; - $this->_connerror = false; - - if ( $this->_path ) - { - $host = $this->_path; - $port = 0; - } - else - { - $host = $this->_host; - $port = $this->_port; - } - - if ( $this->_timeout<=0 ) - $fp = @fsockopen ( $host, $port, $errno, $errstr ); - else - $fp = @fsockopen ( $host, $port, $errno, $errstr, $this->_timeout ); - - if ( !$fp ) - { - if ( $this->_path ) - $location = $this->_path; - else - $location = "{$this->_host}:{$this->_port}"; - - $errstr = trim ( $errstr ); - $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)"; - $this->_connerror = true; - return false; - } - - // send my version - // this is a subtle part. we must do it before (!) reading back from searchd. - // because otherwise under some conditions (reported on FreeBSD for instance) - // TCP stack could throttle write-write-read pattern because of Nagle. - if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) ) - { - fclose ( $fp ); - $this->_error = "failed to send client protocol version"; - return false; - } - - // check version - list(,$v) = unpack ( "N*", fread ( $fp, 4 ) ); - $v = (int)$v; - if ( $v<1 ) - { - fclose ( $fp ); - $this->_error = "expected searchd protocol version 1+, got version '$v'"; - return false; - } - - $this->debug('stop'); - return $fp; - } - - /// get and check response packet from searchd server - public function _GetResponse ( $fp, $client_ver ) - { - $response = ""; - $len = 0; - - $header = fread ( $fp, 8 ); - if ( strlen($header)==8 ) - { - list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) ); - $left = $len; - while ( $left>0 && !feof($fp) ) - { - $chunk = fread ( $fp, $left ); - if ( $chunk ) - { - $response .= $chunk; - $left -= strlen($chunk); - } - } - } - if ( $this->_socket === false ) - fclose ( $fp ); - - // check response - $read = strlen ( $response ); - if ( !$response || $read!=$len ) - { - $this->_error = $len - ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)" - : "received zero-sized searchd response"; - return false; - } - - // check status - if ( $status==SEARCHD_WARNING ) - { - list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) ); - $this->_warning = substr ( $response, 4, $wlen ); - return substr ( $response, 4+$wlen ); - } - if ( $status==SEARCHD_ERROR ) - { - $this->_error = "searchd error: " . substr ( $response, 4 ); - return false; - } - if ( $status==SEARCHD_RETRY ) - { - $this->_error = "temporary searchd error: " . substr ( $response, 4 ); - return false; - } - if ( $status!=SEARCHD_OK ) - { - $this->_error = "unknown status code '$status'"; - return false; - } - - // check version - if ( $ver<$client_ver ) - { - $this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work", - $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff ); - } - - return $response; - } - - ///////////////////////////////////////////////////////////////////////////// - // searching - ///////////////////////////////////////////////////////////////////////////// - - /// set offset and count into result set, - /// and optionally set max-matches and cutoff limits - public function SetLimits ( $offset, $limit, $max=0, $cutoff=0 ) - { - assert ( is_int($offset) ); - assert ( is_int($limit) ); - assert ( $offset>=0 ); - assert ( $limit>0 ); - assert ( $max>=0 ); - $this->_offset = $offset; - $this->_limit = $limit; - if ( $max>0 ) - $this->_maxmatches = $max; - if ( $cutoff>0 ) - $this->_cutoff = $cutoff; - } - - /// set maximum query time, in milliseconds, per-index - /// integer, 0 means "do not limit" - public function SetMaxQueryTime ( $max ) - { - assert ( is_int($max) ); - assert ( $max>=0 ); - $this->_maxquerytime = $max; - } - - /// set matching mode - public function SetMatchMode ( $mode ) - { - assert ( $mode==SPH_MATCH_ALL - || $mode==SPH_MATCH_ANY - || $mode==SPH_MATCH_PHRASE - || $mode==SPH_MATCH_BOOLEAN - || $mode==SPH_MATCH_EXTENDED - || $mode==SPH_MATCH_FULLSCAN - || $mode==SPH_MATCH_EXTENDED2 ); - $this->_mode = $mode; - } - - /// set ranking mode - public function SetRankingMode ( $ranker ) - { - assert ( $ranker==SPH_RANK_PROXIMITY_BM25 - || $ranker==SPH_RANK_BM25 - || $ranker==SPH_RANK_NONE - || $ranker==SPH_RANK_WORDCOUNT - || $ranker==SPH_RANK_PROXIMITY ); - $this->_ranker = $ranker; - } - - /// set matches sorting mode - public function SetSortMode ( $mode, $sortby="" ) - { - assert ( - $mode==SPH_SORT_RELEVANCE || - $mode==SPH_SORT_ATTR_DESC || - $mode==SPH_SORT_ATTR_ASC || - $mode==SPH_SORT_TIME_SEGMENTS || - $mode==SPH_SORT_EXTENDED || - $mode==SPH_SORT_EXPR ); - assert ( is_string($sortby) ); - assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 ); - - $this->_sort = $mode; - $this->_sortby = $sortby; - } - - /// bind per-field weights by order - /// DEPRECATED; use SetFieldWeights() instead - public function SetWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $weight ) - assert ( is_int($weight) ); - - $this->_weights = $weights; - } - - /// bind per-field weights by name - public function SetFieldWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $name=>$weight ) - { - assert ( is_string($name) ); - assert ( is_int($weight) ); - } - $this->_fieldweights = $weights; - } - - /// bind per-index weights by name - public function SetIndexWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $index=>$weight ) - { - assert ( is_string($index) ); - assert ( is_int($weight) ); - } - $this->_indexweights = $weights; - } - - /// set IDs range to match - /// only match records if document ID is beetwen $min and $max (inclusive) - public function SetIDRange ( $min, $max ) - { - assert ( is_numeric($min) ); - assert ( is_numeric($max) ); - assert ( $min<=$max ); - $this->_min_id = $min; - $this->_max_id = $max; - } - - /// set values set filter - /// only match records where $attribute value is in given set - public function SetFilter ( $attribute, $values, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_array($values) ); - assert ( count($values) ); - - if ( is_array($values) && count($values) ) - { - foreach ( $values as $value ) - assert ( is_numeric($value) ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values ); - } - } - - /// set range filter - /// only match records if $attribute value is beetwen $min and $max (inclusive) - public function SetFilterRange ( $attribute, $min, $max, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_numeric($min) ); - assert ( is_numeric($max) ); - assert ( $min<=$max ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); - } - - /// set float range filter - /// only match records if $attribute value is beetwen $min and $max (inclusive) - public function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false ) - { - assert ( is_string($attribute) ); - assert ( is_float($min) ); - assert ( is_float($max) ); - assert ( $min<=$max ); - - $this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); - } - - /// setup anchor point for geosphere distance calculations - /// required to use @geodist in filters and sorting - /// latitude and longitude must be in radians - public function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long ) - { - assert ( is_string($attrlat) ); - assert ( is_string($attrlong) ); - assert ( is_float($lat) ); - assert ( is_float($long) ); - - $this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long ); - } - - /// set grouping attribute and function - public function SetGroupBy ( $attribute, $func, $groupsort="@group desc" ) - { - assert ( is_string($attribute) ); - assert ( is_string($groupsort) ); - assert ( $func==SPH_GROUPBY_DAY - || $func==SPH_GROUPBY_WEEK - || $func==SPH_GROUPBY_MONTH - || $func==SPH_GROUPBY_YEAR - || $func==SPH_GROUPBY_ATTR - || $func==SPH_GROUPBY_ATTRPAIR ); - - $this->_groupby = $attribute; - $this->_groupfunc = $func; - $this->_groupsort = $groupsort; - } - - /// set count-distinct attribute for group-by queries - public function SetGroupDistinct ( $attribute ) - { - assert ( is_string($attribute) ); - $this->_groupdistinct = $attribute; - } - - /// set distributed retries count and delay - public function SetRetries ( $count, $delay=0 ) - { - assert ( is_int($count) && $count>=0 ); - assert ( is_int($delay) && $delay>=0 ); - $this->_retrycount = $count; - $this->_retrydelay = $delay; - } - - /// set result set format (hash or array; hash by default) - /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs - public function SetArrayResult ( $arrayresult ) - { - assert ( is_bool($arrayresult) ); - $this->_arrayresult = $arrayresult; - } - - /// set attribute values override - /// there can be only one override per attribute - /// $values must be a hash that maps document IDs to attribute values - public function SetOverride ( $attrname, $attrtype, $values ) - { - assert ( is_string ( $attrname ) ); - assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) ); - assert ( is_array ( $values ) ); - - $this->_overrides[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values ); - } - - /// set select-list (attributes or expressions), SQL-like syntax - public function SetSelect ( $select ) - { - assert ( is_string ( $select ) ); - $this->_select = $select; - } - - ////////////////////////////////////////////////////////////////////////////// - - /// clear all filters (for multi-queries) - public function ResetFilters () - { - $this->_filters = array(); - $this->_anchor = array(); - } - - /// clear groupby settings (for multi-queries) - public function ResetGroupBy () - { - $this->_groupby = ""; - $this->_groupfunc = SPH_GROUPBY_DAY; - $this->_groupsort = "@group desc"; - $this->_groupdistinct= ""; - } - - /// clear all attribute value overrides (for multi-queries) - public function ResetOverrides () + public $_host; ///< searchd host (default is "localhost") + public $_port; ///< searchd port (default is 9312) + public $_offset; ///< how many records to seek from result-set start (default is 0) + public $_limit; ///< how many records to return from result-set starting at offset (default is 20) + public $_mode; ///< query matching mode (default is SPH_MATCH_ALL) + public $_weights; ///< per-field weights (default is 1 for all fields) + public $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) + public $_sortby; ///< attribute to sort by (defualt is "") + public $_min_id; ///< min ID to match (default is 0, which means no limit) + public $_max_id; ///< max ID to match (default is 0, which means no limit) + public $_filters; ///< search filters + public $_groupby; ///< group-by attribute name + public $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) + public $_groupsort; ///< group-by sorting clause (to sort groups in result set with) + public $_groupdistinct;///< group-by count-distinct attribute + public $_maxmatches; ///< max matches to retrieve + public $_cutoff; ///< cutoff to stop searching at (default is 0) + public $_retrycount; ///< distributed retries count + public $_retrydelay; ///< distributed retries delay + public $_anchor; ///< geographical anchor point + public $_indexweights; ///< per-index weights + public $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) + public $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) + public $_fieldweights; ///< per-field-name weights + public $_overrides; ///< per-query attribute values overrides + public $_select; ///< select-list (attributes or expressions, with optional aliases) + + public $_error; ///< last error message + public $_warning; ///< last warning message + public $_connerror; ///< connection error vs remote error flag + + public $_reqs; ///< requests array for multi-query + public $_mbenc; ///< stored mbstring encoding + public $_arrayresult; ///< whether $result["matches"] should be a hash or an array + public $_timeout; ///< connect timeout + + public $bb_queries = array(); + public $bb_indexes = array(); + + ///////////////////////////////////////////////////////////////////////////// + // common stuff + ///////////////////////////////////////////////////////////////////////////// + + /// create a new client object and fill defaults + public function __construct() { - $this->_overrides = array (); + $this->dbg_enabled = sql_dbg_enabled(); + + // per-client-object settings + $this->_host = "localhost"; + $this->_port = 9312; + $this->_path = false; + $this->_socket = false; + + // per-query settings + $this->_offset = 0; + $this->_limit = 2000; + $this->_mode = SPH_MATCH_ALL; + $this->_weights = array(); + $this->_sort = SPH_SORT_RELEVANCE; + $this->_sortby = ""; + $this->_min_id = 0; + $this->_max_id = 0; + $this->_filters = array(); + $this->_groupby = ""; + $this->_groupfunc = SPH_GROUPBY_DAY; + $this->_groupsort = "@group desc"; + $this->_groupdistinct = ""; + $this->_maxmatches = 1000; + $this->_cutoff = 0; + $this->_retrycount = 0; + $this->_retrydelay = 0; + $this->_anchor = array(); + $this->_indexweights = array(); + $this->_ranker = SPH_RANK_PROXIMITY_BM25; + $this->_maxquerytime = 0; + $this->_fieldweights = array(); + $this->_overrides = array(); + $this->_select = "*"; + + $this->_error = ""; // per-reply fields (for single-query case) + $this->_warning = ""; + $this->_connerror = false; + + $this->_reqs = array(); // requests storage (for multi-query case) + $this->_mbenc = ""; + $this->_arrayresult = false; + $this->_timeout = 0; } - ////////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, run given search query through given indexes, - /// and return the search results - public function Query ( $query, $index="*", $comment="" ) - { - assert ( empty($this->_reqs) ); - - $this->AddQuery ( $query, $index, $comment ); - $results = $this->RunQueries (); - $this->_reqs = array (); // just in case it failed too early - $this->bb_queries = array(); - $this->bb_indexes = array(); - - if ( !is_array($results) ) - return false; // probably network error; error message should be already filled - - $this->_error = $results[0]["error"]; - $this->_warning = $results[0]["warning"]; - if ( $results[0]["status"]==SEARCHD_ERROR ) - return false; - else - return $results[0]; - } - - /// helper to pack floats in network byte order - public function _PackFloat ( $f ) - { - $t1 = pack ( "f", $f ); // machine order - list(,$t2) = unpack ( "L*", $t1 ); // int in machine order - return pack ( "N", $t2 ); - } - - /// add query to multi-query batch - /// returns index into results array from RunQueries() call - public function AddQuery ( $query, $index="*", $comment="" ) - { - // mbstring workaround - $this->_MBPush (); - - // build request - $req = pack ( "NNNNN", $this->_offset, $this->_limit, $this->_mode, $this->_ranker, $this->_sort ); // mode and limits - $req .= pack ( "N", strlen($this->_sortby) ) . $this->_sortby; - $req .= pack ( "N", strlen($query) ) . $query; // query itself - $req .= pack ( "N", count($this->_weights) ); // weights - foreach ( $this->_weights as $weight ) - $req .= pack ( "N", (int)$weight ); - $req .= pack ( "N", strlen($index) ) . $index; // indexes - $req .= pack ( "N", 1 ); // id64 range marker - $req .= sphPackU64 ( $this->_min_id ) . sphPackU64 ( $this->_max_id ); // id64 range - - // filters - $req .= pack ( "N", count($this->_filters) ); - foreach ( $this->_filters as $filter ) - { - $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"]; - $req .= pack ( "N", $filter["type"] ); - switch ( $filter["type"] ) - { - case SPH_FILTER_VALUES: - $req .= pack ( "N", count($filter["values"]) ); - foreach ( $filter["values"] as $value ) - $req .= sphPackI64 ( $value ); - break; - - case SPH_FILTER_RANGE: - $req .= sphPackI64 ( $filter["min"] ) . sphPackI64 ( $filter["max"] ); - break; - - case SPH_FILTER_FLOATRANGE: - $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] ); - break; - - default: - assert ( 0 && "internal error: unhandled filter type" ); - } - $req .= pack ( "N", $filter["exclude"] ); - } - - // group-by clause, max-matches count, group-sort clause, cutoff count - $req .= pack ( "NN", $this->_groupfunc, strlen($this->_groupby) ) . $this->_groupby; - $req .= pack ( "N", $this->_maxmatches ); - $req .= pack ( "N", strlen($this->_groupsort) ) . $this->_groupsort; - $req .= pack ( "NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay ); - $req .= pack ( "N", strlen($this->_groupdistinct) ) . $this->_groupdistinct; - - // anchor point - if ( empty($this->_anchor) ) - { - $req .= pack ( "N", 0 ); - } else - { - $a =& $this->_anchor; - $req .= pack ( "N", 1 ); - $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"]; - $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"]; - $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] ); - } - - // per-index weights - $req .= pack ( "N", count($this->_indexweights) ); - foreach ( $this->_indexweights as $idx=>$weight ) - $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight ); - - // max query time - $req .= pack ( "N", $this->_maxquerytime ); - - // per-field weights - $req .= pack ( "N", count($this->_fieldweights) ); - foreach ( $this->_fieldweights as $field=>$weight ) - $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight ); - - // comment - $req .= pack ( "N", strlen($comment) ) . $comment; - - // attribute overrides - $req .= pack ( "N", count($this->_overrides) ); - foreach ( $this->_overrides as $key => $entry ) - { - $req .= pack ( "N", strlen($entry["attr"]) ) . $entry["attr"]; - $req .= pack ( "NN", $entry["type"], count($entry["values"]) ); - foreach ( $entry["values"] as $id=>$val ) - { - assert ( is_numeric($id) ); - assert ( is_numeric($val) ); - - $req .= sphPackU64 ( $id ); - switch ( $entry["type"] ) - { - case SPH_ATTR_FLOAT: $req .= $this->_PackFloat ( $val ); break; - case SPH_ATTR_BIGINT: $req .= sphPackI64 ( $val ); break; - default: $req .= pack ( "N", $val ); break; - } - } - } - - // select-list - $req .= pack ( "N", strlen($this->_select) ) . $this->_select; - - // mbstring workaround - $this->_MBPop (); - - // store request to requests array - $this->_reqs[] = $req; - $this->bb_queries[] = $query; - $this->bb_indexes[] = $index; - return count($this->_reqs)-1; - } - - /// connect to searchd, run queries batch, and return an array of result sets - public function RunQueries () - { - if ( empty($this->_reqs) ) - { - $this->_error = "no queries defined, issue AddQuery() first"; - return false; - } - - // mbstring workaround - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop (); - return false; - } - - // send query, get response - $nreqs = count($this->_reqs); - $req = join ( "", $this->_reqs ); - $len = 4+strlen($req); - $req = pack ( "nnNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, $nreqs ) . $req; // add header - - $this->cur_query = 'query: `'. join ('` `', $this->bb_queries) .'` idx: `'. join ('` `', $this->bb_indexes) .'`'; - $this->debug('start'); - - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH ) ) ) - { - $this->_MBPop (); - return false; - } - - $this->debug('stop'); - - // query sent ok; we can reset reqs now - $this->_reqs = array (); - $this->bb_queries = array(); - $this->bb_indexes = array(); - - // parse and return response - return $this->_ParseSearchResponse ( $response, $nreqs ); - } - - /// parse and return search query (or queries) response - public function _ParseSearchResponse ( $response, $nreqs ) - { - $p = 0; // current position - $max = strlen($response); // max position for checks, to protect against broken responses - - $this->cur_query = "parsing results"; - $this->debug('start'); - - $results = array (); - for ( $ires=0; $ires<$nreqs && $p<$max; $ires++ ) - { - $results[] = array(); - $result =& $results[$ires]; - - $result["error"] = ""; - $result["warning"] = ""; - - // extract status - list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $result["status"] = $status; - if ( $status!=SEARCHD_OK ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $message = substr ( $response, $p, $len ); $p += $len; - - if ( $status==SEARCHD_WARNING ) - { - $result["warning"] = $message; - } else - { - $result["error"] = $message; - continue; - } - } - - // read schema - $fields = array (); - $attrs = array (); - - list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - while ( $nfields-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $fields[] = substr ( $response, $p, $len ); $p += $len; - } - $result["fields"] = $fields; - - list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - while ( $nattrs-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attr = substr ( $response, $p, $len ); $p += $len; - list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attrs[$attr] = $type; - } - $result["attrs"] = $attrs; - - // read match count - list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - - // read matches - $idx = -1; - while ( $count-->0 && $p<$max ) - { - // index into result array - $idx++; - - // parse document id and weight - if ( $id64 ) - { - $doc = sphUnpackU64 ( substr ( $response, $p, 8 ) ); $p += 8; - list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - } - else - { - list ( $doc, $weight ) = array_values ( unpack ( "N*N*", - substr ( $response, $p, 8 ) ) ); - $p += 8; - $doc = sphFixUint($doc); - } - $weight = sprintf ( "%u", $weight ); - - // create match entry - if ( $this->_arrayresult ) - $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight ); - else - $result["matches"][$doc]["weight"] = $weight; - - // parse and create attributes - $attrvals = array (); - foreach ( $attrs as $attr=>$type ) - { - // handle 64bit ints - if ( $type==SPH_ATTR_BIGINT ) - { - $attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8; - continue; - } - - // handle floats - if ( $type==SPH_ATTR_FLOAT ) - { - list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - list(,$fval) = unpack ( "f*", pack ( "L", $uval ) ); - $attrvals[$attr] = $fval; - continue; - } - - // handle everything else as unsigned ints - list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - if ( $type & SPH_ATTR_MULTI ) - { - $attrvals[$attr] = array (); - $nvalues = $val; - while ( $nvalues-->0 && $p<$max ) - { - list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $attrvals[$attr][] = sphFixUint($val); - } - } else - { - $attrvals[$attr] = sphFixUint($val); - } - } - - if ( $this->_arrayresult ) - $result["matches"][$idx]["attrs"] = $attrvals; - else - $result["matches"][$doc]["attrs"] = $attrvals; - } - - list ( $total, $total_found, $msecs, $words ) = - array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) ); - $result["total"] = sprintf ( "%u", $total ); - $result["total_found"] = sprintf ( "%u", $total_found ); - $result["time"] = sprintf ( "%.3f", $msecs/1000 ); - $p += 16; - - while ( $words-->0 && $p<$max ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $word = substr ( $response, $p, $len ); $p += $len; - list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; - $result["words"][$word] = array ( - "docs"=>sprintf ( "%u", $docs ), - "hits"=>sprintf ( "%u", $hits ) ); - } - } - - $this->debug('stop'); - - $this->_MBPop (); - return $results; - } - - ///////////////////////////////////////////////////////////////////////////// - // excerpts generation - ///////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, and generate exceprts (snippets) - /// of given documents for given query. returns false on failure, - /// an array of snippets on success - public function BuildExcerpts ( $docs, $index, $words, $opts=array() ) - { - assert ( is_array($docs) ); - assert ( is_string($index) ); - assert ( is_string($words) ); - assert ( is_array($opts) ); - - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - ///////////////// - // fixup options - ///////////////// - - if ( !isset($opts["before_match"]) ) $opts["before_match"] = ""; - if ( !isset($opts["after_match"]) ) $opts["after_match"] = ""; - if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... "; - if ( !isset($opts["limit"]) ) $opts["limit"] = 256; - if ( !isset($opts["around"]) ) $opts["around"] = 5; - if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false; - if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false; - if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false; - if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false; - - ///////////////// - // build request - ///////////////// - - // v.1.0 req - $flags = 1; // remove spaces - if ( $opts["exact_phrase"] ) $flags |= 2; - if ( $opts["single_passage"] ) $flags |= 4; - if ( $opts["use_boundaries"] ) $flags |= 8; - if ( $opts["weight_order"] ) $flags |= 16; - $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags - $req .= pack ( "N", strlen($index) ) . $index; // req index - $req .= pack ( "N", strlen($words) ) . $words; // req words - - // options - $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"]; - $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"]; - $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"]; - $req .= pack ( "N", (int)$opts["limit"] ); - $req .= pack ( "N", (int)$opts["around"] ); - - // documents - $req .= pack ( "N", count($docs) ); - foreach ( $docs as $doc ) - { - assert ( is_string($doc) ); - $req .= pack ( "N", strlen($doc) ) . $doc; - } - - //////////////////////////// - // send query, get response - //////////////////////////// - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len ) . $req; // add header - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT ) ) ) - { - $this->_MBPop (); - return false; - } - - ////////////////// - // parse response - ////////////////// - - $pos = 0; - $res = array (); - $rlen = strlen($response); - for ( $i=0; $i $rlen ) - { - $this->_error = "incomplete reply"; - $this->_MBPop (); - return false; - } - $res[] = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - } - - $this->_MBPop (); - return $res; - } - - - ///////////////////////////////////////////////////////////////////////////// - // keyword generation - ///////////////////////////////////////////////////////////////////////////// - - /// connect to searchd server, and generate keyword list for a given query - /// returns false on failure, - /// an array of words on success - public function BuildKeywords ( $query, $index, $hits ) - { - assert ( is_string($query) ); - assert ( is_string($index) ); - assert ( is_bool($hits) ); - - $this->_MBPush (); - - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - ///////////////// - // build request - ///////////////// - - // v.1.0 req - $req = pack ( "N", strlen($query) ) . $query; // req query - $req .= pack ( "N", strlen($index) ) . $index; // req index - $req .= pack ( "N", (int)$hits ); - - //////////////////////////// - // send query, get response - //////////////////////////// - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len ) . $req; // add header - if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS ) ) ) - { - $this->_MBPop (); - return false; - } - - ////////////////// - // parse response - ////////////////// - - $pos = 0; - $res = array (); - $rlen = strlen($response); - list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) ); - $pos += 4; - for ( $i=0; $i<$nwords; $i++ ) - { - list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; - $tokenized = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - - list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; - $normalized = $len ? substr ( $response, $pos, $len ) : ""; - $pos += $len; - - $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized ); - - if ( $hits ) - { - list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) ); - $pos += 8; - $res [$i]["docs"] = $ndocs; - $res [$i]["hits"] = $nhits; - } - - if ( $pos > $rlen ) - { - $this->_error = "incomplete reply"; - $this->_MBPop (); - return false; - } - } - - $this->_MBPop (); - return $res; - } - - public function EscapeString ( $string ) - { - $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' ); - $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' ); - - return str_replace ( $from, $to, $string ); - } - - ///////////////////////////////////////////////////////////////////////////// - // attribute updates - ///////////////////////////////////////////////////////////////////////////// - - /// batch update given attributes in given rows in given indexes - /// returns amount of updated documents (0 or more) on success, or -1 on failure - public function UpdateAttributes ( $index, $attrs, $values, $mva=false ) - { - // verify everything - assert ( is_string($index) ); - assert ( is_bool($mva) ); - - assert ( is_array($attrs) ); - foreach ( $attrs as $attr ) - assert ( is_string($attr) ); - - assert ( is_array($values) ); - foreach ( $values as $id=>$entry ) - { - assert ( is_numeric($id) ); - assert ( is_array($entry) ); - assert ( count($entry)==count($attrs) ); - foreach ( $entry as $v ) - { - if ( $mva ) - { - assert ( is_array($v) ); - foreach ( $v as $vv ) - assert ( is_int($vv) ); - } else - assert ( is_int($v) ); - } - } - - // build request - $req = pack ( "N", strlen($index) ) . $index; - - $req .= pack ( "N", count($attrs) ); - foreach ( $attrs as $attr ) - { - $req .= pack ( "N", strlen($attr) ) . $attr; - $req .= pack ( "N", $mva ? 1 : 0 ); - } - - $req .= pack ( "N", count($values) ); - foreach ( $values as $id=>$entry ) - { - $req .= sphPackU64 ( $id ); - foreach ( $entry as $v ) - { - $req .= pack ( "N", $mva ? count($v) : $v ); - if ( $mva ) - foreach ( $v as $vv ) - $req .= pack ( "N", $vv ); - } - } - - // connect, send query, get response - if (!( $fp = $this->_Connect() )) - return -1; - - $len = strlen($req); - $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header - if ( !$this->_Send ( $fp, $req, $len+8 ) ) - return -1; - - if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) )) - return -1; - - // parse response - list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) ); - return $updated; - } - - ///////////////////////////////////////////////////////////////////////////// - // persistent connections - ///////////////////////////////////////////////////////////////////////////// - - public function Open() - { - if ( $this->_socket !== false ) - { - $this->_error = 'already connected'; - return false; - } - if ( !$fp = $this->_Connect() ) - return false; - - // command, command version = 0, body length = 4, body = 1 - $req = pack ( "nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1 ); - if ( !$this->_Send ( $fp, $req, 12 ) ) - return false; - - $this->_socket = $fp; - return true; - } - - public function Close() - { - if ( $this->_socket === false ) - { - $this->_error = 'not connected'; - return false; - } - - fclose ( $this->_socket ); - $this->_socket = false; - - return true; - } - - ////////////////////////////////////////////////////////////////////////// - // status - ////////////////////////////////////////////////////////////////////////// - - public function Status () - { - $this->_MBPush (); - if (!( $fp = $this->_Connect() )) - { - $this->_MBPop(); - return false; - } - - $req = pack ( "nnNN", SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1 ); // len=4, body=1 - if ( !( $this->_Send ( $fp, $req, 12 ) ) || - !( $response = $this->_GetResponse ( $fp, VER_COMMAND_STATUS ) ) ) - { - $this->_MBPop (); - return false; - } - - $res = substr ( $response, 4 ); // just ignore length, error handling, etc - $p = 0; - list ( $rows, $cols ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; - - $res = array(); - for ( $i=0; $i<$rows; $i++ ) - for ( $j=0; $j<$cols; $j++ ) - { - list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; - $res[$i][] = substr ( $response, $p, $len ); $p += $len; - } - - $this->_MBPop (); - return $res; - } + public function __destruct() + { + if ($this->_socket !== false) { + fclose($this->_socket); + } + } + + /// get last error message (string) + public function GetLastError() + { + return $this->_error; + } + + /// get last warning message (string) + public function GetLastWarning() + { + return $this->_warning; + } + + /// get last error flag (to tell network connection errors from searchd errors or broken responses) + public function IsConnectError() + { + return $this->_connerror; + } + + /// set searchd host name (string) and port (integer) + public function SetServer($host, $port = 0) + { + assert(is_string($host)); + if ($host[0] == '/') { + $this->_path = 'unix://' . $host; + return; + } + if (substr($host, 0, 7) == "unix://") { + $this->_path = $host; + return; + } + + assert(is_int($port)); + $this->_host = $host; + $this->_port = $port; + $this->_path = ''; + } + + /// set server connection timeout (0 to remove) + public function SetConnectTimeout($timeout) + { + assert(is_numeric($timeout)); + $this->_timeout = $timeout; + } + + + public function _Send($handle, $data, $length) + { + if (feof($handle) || fwrite($handle, $data, $length) !== $length) { + $this->_error = 'connection unexpectedly closed (timed out?)'; + $this->_connerror = true; + return false; + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////// + + /// enter mbstring workaround mode + public function _MBPush() + { + $this->_mbenc = ""; + if (ini_get("mbstring.func_overload") & 2) { + $this->_mbenc = mb_internal_encoding(); + mb_internal_encoding("latin1"); + } + } + + /// leave mbstring workaround mode + public function _MBPop() + { + if ($this->_mbenc) { + mb_internal_encoding($this->_mbenc); + } + } + + /// connect to searchd server + public function _Connect() + { + $this->cur_query = "connect to: {$this->_host}"; + $this->debug('start'); + + if ($this->_socket !== false) { + // we are in persistent connection mode, so we have a socket + // however, need to check whether it's still alive + if (!@feof($this->_socket)) { + return $this->_socket; + } + + // force reopen + $this->_socket = false; + } + + $errno = 0; + $errstr = ""; + $this->_connerror = false; + + if ($this->_path) { + $host = $this->_path; + $port = 0; + } else { + $host = $this->_host; + $port = $this->_port; + } + + if ($this->_timeout <= 0) { + $fp = @fsockopen($host, $port, $errno, $errstr); + } else { + $fp = @fsockopen($host, $port, $errno, $errstr, $this->_timeout); + } + + if (!$fp) { + if ($this->_path) { + $location = $this->_path; + } else { + $location = "{$this->_host}:{$this->_port}"; + } + + $errstr = trim($errstr); + $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)"; + $this->_connerror = true; + return false; + } + + // send my version + // this is a subtle part. we must do it before (!) reading back from searchd. + // because otherwise under some conditions (reported on FreeBSD for instance) + // TCP stack could throttle write-write-read pattern because of Nagle. + if (!$this->_Send($fp, pack("N", 1), 4)) { + fclose($fp); + $this->_error = "failed to send client protocol version"; + return false; + } + + // check version + list(, $v) = unpack("N*", fread($fp, 4)); + $v = (int)$v; + if ($v < 1) { + fclose($fp); + $this->_error = "expected searchd protocol version 1+, got version '$v'"; + return false; + } + + $this->debug('stop'); + return $fp; + } + + /// get and check response packet from searchd server + public function _GetResponse($fp, $client_ver) + { + $response = ""; + $len = 0; + + $header = fread($fp, 8); + if (strlen($header) == 8) { + list($status, $ver, $len) = array_values(unpack("n2a/Nb", $header)); + $left = $len; + while ($left > 0 && !feof($fp)) { + $chunk = fread($fp, $left); + if ($chunk) { + $response .= $chunk; + $left -= strlen($chunk); + } + } + } + if ($this->_socket === false) { + fclose($fp); + } + + // check response + $read = strlen($response); + if (!$response || $read != $len) { + $this->_error = $len + ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)" + : "received zero-sized searchd response"; + return false; + } + + // check status + if ($status == SEARCHD_WARNING) { + list(, $wlen) = unpack("N*", substr($response, 0, 4)); + $this->_warning = substr($response, 4, $wlen); + return substr($response, 4 + $wlen); + } + if ($status == SEARCHD_ERROR) { + $this->_error = "searchd error: " . substr($response, 4); + return false; + } + if ($status == SEARCHD_RETRY) { + $this->_error = "temporary searchd error: " . substr($response, 4); + return false; + } + if ($status != SEARCHD_OK) { + $this->_error = "unknown status code '$status'"; + return false; + } + + // check version + if ($ver < $client_ver) { + $this->_warning = sprintf("searchd command v.%d.%d older than client's v.%d.%d, some options might not work", + $ver >> 8, $ver & 0xff, $client_ver >> 8, $client_ver & 0xff); + } + + return $response; + } + + ///////////////////////////////////////////////////////////////////////////// + // searching + ///////////////////////////////////////////////////////////////////////////// + + /// set offset and count into result set, + /// and optionally set max-matches and cutoff limits + public function SetLimits($offset, $limit, $max = 0, $cutoff = 0) + { + assert(is_int($offset)); + assert(is_int($limit)); + assert($offset >= 0); + assert($limit > 0); + assert($max >= 0); + $this->_offset = $offset; + $this->_limit = $limit; + if ($max > 0) { + $this->_maxmatches = $max; + } + if ($cutoff > 0) { + $this->_cutoff = $cutoff; + } + } + + /// set maximum query time, in milliseconds, per-index + /// integer, 0 means "do not limit" + public function SetMaxQueryTime($max) + { + assert(is_int($max)); + assert($max >= 0); + $this->_maxquerytime = $max; + } + + /// set matching mode + public function SetMatchMode($mode) + { + assert($mode == SPH_MATCH_ALL + || $mode == SPH_MATCH_ANY + || $mode == SPH_MATCH_PHRASE + || $mode == SPH_MATCH_BOOLEAN + || $mode == SPH_MATCH_EXTENDED + || $mode == SPH_MATCH_FULLSCAN + || $mode == SPH_MATCH_EXTENDED2); + $this->_mode = $mode; + } + + /// set ranking mode + public function SetRankingMode($ranker) + { + assert($ranker == SPH_RANK_PROXIMITY_BM25 + || $ranker == SPH_RANK_BM25 + || $ranker == SPH_RANK_NONE + || $ranker == SPH_RANK_WORDCOUNT + || $ranker == SPH_RANK_PROXIMITY); + $this->_ranker = $ranker; + } + + /// set matches sorting mode + public function SetSortMode($mode, $sortby = "") + { + assert( + $mode == SPH_SORT_RELEVANCE || + $mode == SPH_SORT_ATTR_DESC || + $mode == SPH_SORT_ATTR_ASC || + $mode == SPH_SORT_TIME_SEGMENTS || + $mode == SPH_SORT_EXTENDED || + $mode == SPH_SORT_EXPR); + assert(is_string($sortby)); + assert($mode == SPH_SORT_RELEVANCE || strlen($sortby) > 0); + + $this->_sort = $mode; + $this->_sortby = $sortby; + } + + /// bind per-field weights by order + /// DEPRECATED; use SetFieldWeights() instead + public function SetWeights($weights) + { + assert(is_array($weights)); + foreach ($weights as $weight) { + assert(is_int($weight)); + } + + $this->_weights = $weights; + } + + /// bind per-field weights by name + public function SetFieldWeights($weights) + { + assert(is_array($weights)); + foreach ($weights as $name => $weight) { + assert(is_string($name)); + assert(is_int($weight)); + } + $this->_fieldweights = $weights; + } + + /// bind per-index weights by name + public function SetIndexWeights($weights) + { + assert(is_array($weights)); + foreach ($weights as $index => $weight) { + assert(is_string($index)); + assert(is_int($weight)); + } + $this->_indexweights = $weights; + } + + /// set IDs range to match + /// only match records if document ID is beetwen $min and $max (inclusive) + public function SetIDRange($min, $max) + { + assert(is_numeric($min)); + assert(is_numeric($max)); + assert($min <= $max); + $this->_min_id = $min; + $this->_max_id = $max; + } + + /// set values set filter + /// only match records where $attribute value is in given set + public function SetFilter($attribute, $values, $exclude = false) + { + assert(is_string($attribute)); + assert(is_array($values)); + assert(count($values)); + + if (is_array($values) && count($values)) { + foreach ($values as $value) { + assert(is_numeric($value)); + } + + $this->_filters[] = array("type" => SPH_FILTER_VALUES, "attr" => $attribute, "exclude" => $exclude, "values" => $values); + } + } + + /// set range filter + /// only match records if $attribute value is beetwen $min and $max (inclusive) + public function SetFilterRange($attribute, $min, $max, $exclude = false) + { + assert(is_string($attribute)); + assert(is_numeric($min)); + assert(is_numeric($max)); + assert($min <= $max); + + $this->_filters[] = array("type" => SPH_FILTER_RANGE, "attr" => $attribute, "exclude" => $exclude, "min" => $min, "max" => $max); + } + + /// set float range filter + /// only match records if $attribute value is beetwen $min and $max (inclusive) + public function SetFilterFloatRange($attribute, $min, $max, $exclude = false) + { + assert(is_string($attribute)); + assert(is_float($min)); + assert(is_float($max)); + assert($min <= $max); + + $this->_filters[] = array("type" => SPH_FILTER_FLOATRANGE, "attr" => $attribute, "exclude" => $exclude, "min" => $min, "max" => $max); + } + + /// setup anchor point for geosphere distance calculations + /// required to use @geodist in filters and sorting + /// latitude and longitude must be in radians + public function SetGeoAnchor($attrlat, $attrlong, $lat, $long) + { + assert(is_string($attrlat)); + assert(is_string($attrlong)); + assert(is_float($lat)); + assert(is_float($long)); + + $this->_anchor = array("attrlat" => $attrlat, "attrlong" => $attrlong, "lat" => $lat, "long" => $long); + } + + /// set grouping attribute and function + public function SetGroupBy($attribute, $func, $groupsort = "@group desc") + { + assert(is_string($attribute)); + assert(is_string($groupsort)); + assert($func == SPH_GROUPBY_DAY + || $func == SPH_GROUPBY_WEEK + || $func == SPH_GROUPBY_MONTH + || $func == SPH_GROUPBY_YEAR + || $func == SPH_GROUPBY_ATTR + || $func == SPH_GROUPBY_ATTRPAIR); + + $this->_groupby = $attribute; + $this->_groupfunc = $func; + $this->_groupsort = $groupsort; + } + + /// set count-distinct attribute for group-by queries + public function SetGroupDistinct($attribute) + { + assert(is_string($attribute)); + $this->_groupdistinct = $attribute; + } + + /// set distributed retries count and delay + public function SetRetries($count, $delay = 0) + { + assert(is_int($count) && $count >= 0); + assert(is_int($delay) && $delay >= 0); + $this->_retrycount = $count; + $this->_retrydelay = $delay; + } + + /// set result set format (hash or array; hash by default) + /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs + public function SetArrayResult($arrayresult) + { + assert(is_bool($arrayresult)); + $this->_arrayresult = $arrayresult; + } + + /// set attribute values override + /// there can be only one override per attribute + /// $values must be a hash that maps document IDs to attribute values + public function SetOverride($attrname, $attrtype, $values) + { + assert(is_string($attrname)); + assert(in_array($attrtype, array(SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT))); + assert(is_array($values)); + + $this->_overrides[$attrname] = array("attr" => $attrname, "type" => $attrtype, "values" => $values); + } + + /// set select-list (attributes or expressions), SQL-like syntax + public function SetSelect($select) + { + assert(is_string($select)); + $this->_select = $select; + } + + ////////////////////////////////////////////////////////////////////////////// + + /// clear all filters (for multi-queries) + public function ResetFilters() + { + $this->_filters = array(); + $this->_anchor = array(); + } + + /// clear groupby settings (for multi-queries) + public function ResetGroupBy() + { + $this->_groupby = ""; + $this->_groupfunc = SPH_GROUPBY_DAY; + $this->_groupsort = "@group desc"; + $this->_groupdistinct = ""; + } + + /// clear all attribute value overrides (for multi-queries) + public function ResetOverrides() + { + $this->_overrides = array(); + } + + ////////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, run given search query through given indexes, + /// and return the search results + public function Query($query, $index = "*", $comment = "") + { + assert(empty($this->_reqs)); + + $this->AddQuery($query, $index, $comment); + $results = $this->RunQueries(); + $this->_reqs = array(); // just in case it failed too early + $this->bb_queries = array(); + $this->bb_indexes = array(); + + if (!is_array($results)) { + return false; + } // probably network error; error message should be already filled + + $this->_error = $results[0]["error"]; + $this->_warning = $results[0]["warning"]; + if ($results[0]["status"] == SEARCHD_ERROR) { + return false; + } else { + return $results[0]; + } + } + + /// helper to pack floats in network byte order + public function _PackFloat($f) + { + $t1 = pack("f", $f); // machine order + list(, $t2) = unpack("L*", $t1); // int in machine order + return pack("N", $t2); + } + + /// add query to multi-query batch + /// returns index into results array from RunQueries() call + public function AddQuery($query, $index = "*", $comment = "") + { + // mbstring workaround + $this->_MBPush(); + + // build request + $req = pack("NNNNN", $this->_offset, $this->_limit, $this->_mode, $this->_ranker, $this->_sort); // mode and limits + $req .= pack("N", strlen($this->_sortby)) . $this->_sortby; + $req .= pack("N", strlen($query)) . $query; // query itself + $req .= pack("N", count($this->_weights)); // weights + foreach ($this->_weights as $weight) { + $req .= pack("N", (int)$weight); + } + $req .= pack("N", strlen($index)) . $index; // indexes + $req .= pack("N", 1); // id64 range marker + $req .= sphPackU64($this->_min_id) . sphPackU64($this->_max_id); // id64 range + + // filters + $req .= pack("N", count($this->_filters)); + foreach ($this->_filters as $filter) { + $req .= pack("N", strlen($filter["attr"])) . $filter["attr"]; + $req .= pack("N", $filter["type"]); + switch ($filter["type"]) { + case SPH_FILTER_VALUES: + $req .= pack("N", count($filter["values"])); + foreach ($filter["values"] as $value) { + $req .= sphPackI64($value); + } + break; + + case SPH_FILTER_RANGE: + $req .= sphPackI64($filter["min"]) . sphPackI64($filter["max"]); + break; + + case SPH_FILTER_FLOATRANGE: + $req .= $this->_PackFloat($filter["min"]) . $this->_PackFloat($filter["max"]); + break; + + default: + assert(0 && "internal error: unhandled filter type"); + } + $req .= pack("N", $filter["exclude"]); + } + + // group-by clause, max-matches count, group-sort clause, cutoff count + $req .= pack("NN", $this->_groupfunc, strlen($this->_groupby)) . $this->_groupby; + $req .= pack("N", $this->_maxmatches); + $req .= pack("N", strlen($this->_groupsort)) . $this->_groupsort; + $req .= pack("NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay); + $req .= pack("N", strlen($this->_groupdistinct)) . $this->_groupdistinct; + + // anchor point + if (empty($this->_anchor)) { + $req .= pack("N", 0); + } else { + $a =& $this->_anchor; + $req .= pack("N", 1); + $req .= pack("N", strlen($a["attrlat"])) . $a["attrlat"]; + $req .= pack("N", strlen($a["attrlong"])) . $a["attrlong"]; + $req .= $this->_PackFloat($a["lat"]) . $this->_PackFloat($a["long"]); + } + + // per-index weights + $req .= pack("N", count($this->_indexweights)); + foreach ($this->_indexweights as $idx => $weight) { + $req .= pack("N", strlen($idx)) . $idx . pack("N", $weight); + } + + // max query time + $req .= pack("N", $this->_maxquerytime); + + // per-field weights + $req .= pack("N", count($this->_fieldweights)); + foreach ($this->_fieldweights as $field => $weight) { + $req .= pack("N", strlen($field)) . $field . pack("N", $weight); + } + + // comment + $req .= pack("N", strlen($comment)) . $comment; + + // attribute overrides + $req .= pack("N", count($this->_overrides)); + foreach ($this->_overrides as $key => $entry) { + $req .= pack("N", strlen($entry["attr"])) . $entry["attr"]; + $req .= pack("NN", $entry["type"], count($entry["values"])); + foreach ($entry["values"] as $id => $val) { + assert(is_numeric($id)); + assert(is_numeric($val)); + + $req .= sphPackU64($id); + switch ($entry["type"]) { + case SPH_ATTR_FLOAT: + $req .= $this->_PackFloat($val); + break; + case SPH_ATTR_BIGINT: + $req .= sphPackI64($val); + break; + default: + $req .= pack("N", $val); + break; + } + } + } + + // select-list + $req .= pack("N", strlen($this->_select)) . $this->_select; + + // mbstring workaround + $this->_MBPop(); + + // store request to requests array + $this->_reqs[] = $req; + $this->bb_queries[] = $query; + $this->bb_indexes[] = $index; + return count($this->_reqs) - 1; + } + + /// connect to searchd, run queries batch, and return an array of result sets + public function RunQueries() + { + if (empty($this->_reqs)) { + $this->_error = "no queries defined, issue AddQuery() first"; + return false; + } + + // mbstring workaround + $this->_MBPush(); + + if (!($fp = $this->_Connect())) { + $this->_MBPop(); + return false; + } + + // send query, get response + $nreqs = count($this->_reqs); + $req = join("", $this->_reqs); + $len = 4 + strlen($req); + $req = pack("nnNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, $nreqs) . $req; // add header + + $this->cur_query = 'query: `' . join('` `', $this->bb_queries) . '` idx: `' . join('` `', $this->bb_indexes) . '`'; + $this->debug('start'); + + if (!($this->_Send($fp, $req, $len + 8)) || + !($response = $this->_GetResponse($fp, VER_COMMAND_SEARCH)) + ) { + $this->_MBPop(); + return false; + } + + $this->debug('stop'); + + // query sent ok; we can reset reqs now + $this->_reqs = array(); + $this->bb_queries = array(); + $this->bb_indexes = array(); + + // parse and return response + return $this->_ParseSearchResponse($response, $nreqs); + } + + /// parse and return search query (or queries) response + public function _ParseSearchResponse($response, $nreqs) + { + $p = 0; // current position + $max = strlen($response); // max position for checks, to protect against broken responses + + $this->cur_query = "parsing results"; + $this->debug('start'); + + $results = array(); + for ($ires = 0; $ires < $nreqs && $p < $max; $ires++) { + $results[] = array(); + $result =& $results[$ires]; + + $result["error"] = ""; + $result["warning"] = ""; + + // extract status + list(, $status) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $result["status"] = $status; + if ($status != SEARCHD_OK) { + list(, $len) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $message = substr($response, $p, $len); + $p += $len; + + if ($status == SEARCHD_WARNING) { + $result["warning"] = $message; + } else { + $result["error"] = $message; + continue; + } + } + + // read schema + $fields = array(); + $attrs = array(); + + list(, $nfields) = unpack("N*", substr($response, $p, 4)); + $p += 4; + while ($nfields-- > 0 && $p < $max) { + list(, $len) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $fields[] = substr($response, $p, $len); + $p += $len; + } + $result["fields"] = $fields; + + list(, $nattrs) = unpack("N*", substr($response, $p, 4)); + $p += 4; + while ($nattrs-- > 0 && $p < $max) { + list(, $len) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $attr = substr($response, $p, $len); + $p += $len; + list(, $type) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $attrs[$attr] = $type; + } + $result["attrs"] = $attrs; + + // read match count + list(, $count) = unpack("N*", substr($response, $p, 4)); + $p += 4; + list(, $id64) = unpack("N*", substr($response, $p, 4)); + $p += 4; + + // read matches + $idx = -1; + while ($count-- > 0 && $p < $max) { + // index into result array + $idx++; + + // parse document id and weight + if ($id64) { + $doc = sphUnpackU64(substr($response, $p, 8)); + $p += 8; + list(, $weight) = unpack("N*", substr($response, $p, 4)); + $p += 4; + } else { + list($doc, $weight) = array_values(unpack("N*N*", + substr($response, $p, 8))); + $p += 8; + $doc = sphFixUint($doc); + } + $weight = sprintf("%u", $weight); + + // create match entry + if ($this->_arrayresult) { + $result["matches"][$idx] = array("id" => $doc, "weight" => $weight); + } else { + $result["matches"][$doc]["weight"] = $weight; + } + + // parse and create attributes + $attrvals = array(); + foreach ($attrs as $attr => $type) { + // handle 64bit ints + if ($type == SPH_ATTR_BIGINT) { + $attrvals[$attr] = sphUnpackI64(substr($response, $p, 8)); + $p += 8; + continue; + } + + // handle floats + if ($type == SPH_ATTR_FLOAT) { + list(, $uval) = unpack("N*", substr($response, $p, 4)); + $p += 4; + list(, $fval) = unpack("f*", pack("L", $uval)); + $attrvals[$attr] = $fval; + continue; + } + + // handle everything else as unsigned ints + list(, $val) = unpack("N*", substr($response, $p, 4)); + $p += 4; + if ($type & SPH_ATTR_MULTI) { + $attrvals[$attr] = array(); + $nvalues = $val; + while ($nvalues-- > 0 && $p < $max) { + list(, $val) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $attrvals[$attr][] = sphFixUint($val); + } + } else { + $attrvals[$attr] = sphFixUint($val); + } + } + + if ($this->_arrayresult) { + $result["matches"][$idx]["attrs"] = $attrvals; + } else { + $result["matches"][$doc]["attrs"] = $attrvals; + } + } + + list($total, $total_found, $msecs, $words) = + array_values(unpack("N*N*N*N*", substr($response, $p, 16))); + $result["total"] = sprintf("%u", $total); + $result["total_found"] = sprintf("%u", $total_found); + $result["time"] = sprintf("%.3f", $msecs / 1000); + $p += 16; + + while ($words-- > 0 && $p < $max) { + list(, $len) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $word = substr($response, $p, $len); + $p += $len; + list($docs, $hits) = array_values(unpack("N*N*", substr($response, $p, 8))); + $p += 8; + $result["words"][$word] = array( + "docs" => sprintf("%u", $docs), + "hits" => sprintf("%u", $hits)); + } + } + + $this->debug('stop'); + + $this->_MBPop(); + return $results; + } + + ///////////////////////////////////////////////////////////////////////////// + // excerpts generation + ///////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, and generate exceprts (snippets) + /// of given documents for given query. returns false on failure, + /// an array of snippets on success + public function BuildExcerpts($docs, $index, $words, $opts = array()) + { + assert(is_array($docs)); + assert(is_string($index)); + assert(is_string($words)); + assert(is_array($opts)); + + $this->_MBPush(); + + if (!($fp = $this->_Connect())) { + $this->_MBPop(); + return false; + } + + ///////////////// + // fixup options + ///////////////// + + if (!isset($opts["before_match"])) { + $opts["before_match"] = ""; + } + if (!isset($opts["after_match"])) { + $opts["after_match"] = ""; + } + if (!isset($opts["chunk_separator"])) { + $opts["chunk_separator"] = " ... "; + } + if (!isset($opts["limit"])) { + $opts["limit"] = 256; + } + if (!isset($opts["around"])) { + $opts["around"] = 5; + } + if (!isset($opts["exact_phrase"])) { + $opts["exact_phrase"] = false; + } + if (!isset($opts["single_passage"])) { + $opts["single_passage"] = false; + } + if (!isset($opts["use_boundaries"])) { + $opts["use_boundaries"] = false; + } + if (!isset($opts["weight_order"])) { + $opts["weight_order"] = false; + } + + ///////////////// + // build request + ///////////////// + + // v.1.0 req + $flags = 1; // remove spaces + if ($opts["exact_phrase"]) { + $flags |= 2; + } + if ($opts["single_passage"]) { + $flags |= 4; + } + if ($opts["use_boundaries"]) { + $flags |= 8; + } + if ($opts["weight_order"]) { + $flags |= 16; + } + $req = pack("NN", 0, $flags); // mode=0, flags=$flags + $req .= pack("N", strlen($index)) . $index; // req index + $req .= pack("N", strlen($words)) . $words; // req words + + // options + $req .= pack("N", strlen($opts["before_match"])) . $opts["before_match"]; + $req .= pack("N", strlen($opts["after_match"])) . $opts["after_match"]; + $req .= pack("N", strlen($opts["chunk_separator"])) . $opts["chunk_separator"]; + $req .= pack("N", (int)$opts["limit"]); + $req .= pack("N", (int)$opts["around"]); + + // documents + $req .= pack("N", count($docs)); + foreach ($docs as $doc) { + assert(is_string($doc)); + $req .= pack("N", strlen($doc)) . $doc; + } + + //////////////////////////// + // send query, get response + //////////////////////////// + + $len = strlen($req); + $req = pack("nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len) . $req; // add header + if (!($this->_Send($fp, $req, $len + 8)) || + !($response = $this->_GetResponse($fp, VER_COMMAND_EXCERPT)) + ) { + $this->_MBPop(); + return false; + } + + ////////////////// + // parse response + ////////////////// + + $pos = 0; + $res = array(); + $rlen = strlen($response); + for ($i = 0; $i < count($docs); $i++) { + list(, $len) = unpack("N*", substr($response, $pos, 4)); + $pos += 4; + + if ($pos + $len > $rlen) { + $this->_error = "incomplete reply"; + $this->_MBPop(); + return false; + } + $res[] = $len ? substr($response, $pos, $len) : ""; + $pos += $len; + } + + $this->_MBPop(); + return $res; + } + + + ///////////////////////////////////////////////////////////////////////////// + // keyword generation + ///////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, and generate keyword list for a given query + /// returns false on failure, + /// an array of words on success + public function BuildKeywords($query, $index, $hits) + { + assert(is_string($query)); + assert(is_string($index)); + assert(is_bool($hits)); + + $this->_MBPush(); + + if (!($fp = $this->_Connect())) { + $this->_MBPop(); + return false; + } + + ///////////////// + // build request + ///////////////// + + // v.1.0 req + $req = pack("N", strlen($query)) . $query; // req query + $req .= pack("N", strlen($index)) . $index; // req index + $req .= pack("N", (int)$hits); + + //////////////////////////// + // send query, get response + //////////////////////////// + + $len = strlen($req); + $req = pack("nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len) . $req; // add header + if (!($this->_Send($fp, $req, $len + 8)) || + !($response = $this->_GetResponse($fp, VER_COMMAND_KEYWORDS)) + ) { + $this->_MBPop(); + return false; + } + + ////////////////// + // parse response + ////////////////// + + $pos = 0; + $res = array(); + $rlen = strlen($response); + list(, $nwords) = unpack("N*", substr($response, $pos, 4)); + $pos += 4; + for ($i = 0; $i < $nwords; $i++) { + list(, $len) = unpack("N*", substr($response, $pos, 4)); + $pos += 4; + $tokenized = $len ? substr($response, $pos, $len) : ""; + $pos += $len; + + list(, $len) = unpack("N*", substr($response, $pos, 4)); + $pos += 4; + $normalized = $len ? substr($response, $pos, $len) : ""; + $pos += $len; + + $res[] = array("tokenized" => $tokenized, "normalized" => $normalized); + + if ($hits) { + list($ndocs, $nhits) = array_values(unpack("N*N*", substr($response, $pos, 8))); + $pos += 8; + $res [$i]["docs"] = $ndocs; + $res [$i]["hits"] = $nhits; + } + + if ($pos > $rlen) { + $this->_error = "incomplete reply"; + $this->_MBPop(); + return false; + } + } + + $this->_MBPop(); + return $res; + } + + public function EscapeString($string) + { + $from = array('\\', '(', ')', '|', '-', '!', '@', '~', '"', '&', '/', '^', '$', '='); + $to = array('\\\\', '\(', '\)', '\|', '\-', '\!', '\@', '\~', '\"', '\&', '\/', '\^', '\$', '\='); + + return str_replace($from, $to, $string); + } + + ///////////////////////////////////////////////////////////////////////////// + // attribute updates + ///////////////////////////////////////////////////////////////////////////// + + /// batch update given attributes in given rows in given indexes + /// returns amount of updated documents (0 or more) on success, or -1 on failure + public function UpdateAttributes($index, $attrs, $values, $mva = false) + { + // verify everything + assert(is_string($index)); + assert(is_bool($mva)); + + assert(is_array($attrs)); + foreach ($attrs as $attr) { + assert(is_string($attr)); + } + + assert(is_array($values)); + foreach ($values as $id => $entry) { + assert(is_numeric($id)); + assert(is_array($entry)); + assert(count($entry) == count($attrs)); + foreach ($entry as $v) { + if ($mva) { + assert(is_array($v)); + foreach ($v as $vv) { + assert(is_int($vv)); + } + } else { + assert(is_int($v)); + } + } + } + + // build request + $req = pack("N", strlen($index)) . $index; + + $req .= pack("N", count($attrs)); + foreach ($attrs as $attr) { + $req .= pack("N", strlen($attr)) . $attr; + $req .= pack("N", $mva ? 1 : 0); + } + + $req .= pack("N", count($values)); + foreach ($values as $id => $entry) { + $req .= sphPackU64($id); + foreach ($entry as $v) { + $req .= pack("N", $mva ? count($v) : $v); + if ($mva) { + foreach ($v as $vv) { + $req .= pack("N", $vv); + } + } + } + } + + // connect, send query, get response + if (!($fp = $this->_Connect())) { + return -1; + } + + $len = strlen($req); + $req = pack("nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len) . $req; // add header + if (!$this->_Send($fp, $req, $len + 8)) { + return -1; + } + + if (!($response = $this->_GetResponse($fp, VER_COMMAND_UPDATE))) { + return -1; + } + + // parse response + list(, $updated) = unpack("N*", substr($response, 0, 4)); + return $updated; + } + + ///////////////////////////////////////////////////////////////////////////// + // persistent connections + ///////////////////////////////////////////////////////////////////////////// + + public function Open() + { + if ($this->_socket !== false) { + $this->_error = 'already connected'; + return false; + } + if (!$fp = $this->_Connect()) { + return false; + } + + // command, command version = 0, body length = 4, body = 1 + $req = pack("nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1); + if (!$this->_Send($fp, $req, 12)) { + return false; + } + + $this->_socket = $fp; + return true; + } + + public function Close() + { + if ($this->_socket === false) { + $this->_error = 'not connected'; + return false; + } + + fclose($this->_socket); + $this->_socket = false; + + return true; + } + + ////////////////////////////////////////////////////////////////////////// + // status + ////////////////////////////////////////////////////////////////////////// + + public function Status() + { + $this->_MBPush(); + if (!($fp = $this->_Connect())) { + $this->_MBPop(); + return false; + } + + $req = pack("nnNN", SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1); // len=4, body=1 + if (!($this->_Send($fp, $req, 12)) || + !($response = $this->_GetResponse($fp, VER_COMMAND_STATUS)) + ) { + $this->_MBPop(); + return false; + } + + $res = substr($response, 4); // just ignore length, error handling, etc + $p = 0; + list($rows, $cols) = array_values(unpack("N*N*", substr($response, $p, 8))); + $p += 8; + + $res = array(); + for ($i = 0; $i < $rows; $i++) { + for ($j = 0; $j < $cols; $j++) { + list(, $len) = unpack("N*", substr($response, $p, 4)); + $p += 4; + $res[$i][] = substr($response, $p, $len); + $p += $len; + } + } + + $this->_MBPop(); + return $res; + } } // diff --git a/library/includes/bbcode.php b/library/includes/bbcode.php index 1884c1ec4..8f14f1186 100644 --- a/library/includes/bbcode.php +++ b/library/includes/bbcode.php @@ -1,9 +1,34 @@ enqueue(array( - 'smile_replacements', + 'smile_replacements', )); $page_cfg['include_bbcode_js'] = true; @@ -11,730 +36,678 @@ $page_cfg['include_bbcode_js'] = true; // // BBCode templates // -function get_bbcode_tpl () +function get_bbcode_tpl() { -$bbcode_tpl = array(); + $bbcode_tpl = array(); // Quote -$bbcode_tpl['quote_open'] = <<
        HTML; -$bbcode_tpl['quote_username_open'] = <<
        HTML; -$bbcode_tpl['quote_close'] = <<
        HTML; // Code -$bbcode_tpl['code_open'] = <<
        HTML; -$bbcode_tpl['code_close'] = <<
        HTML; // Spoiler -$bbcode_tpl['spoiler_open'] = <<
        HTML; -$bbcode_tpl['spoiler_title_open'] = <<

        \\1

        HTML; -$bbcode_tpl['spoiler_close'] = <<
        HTML; // Image -$bbcode_tpl['img'] = << HTML; -$bbcode_tpl['img_aligned'] = << HTML; // HR -$bbcode_tpl['hr'] = <<- HTML; -array_deep($bbcode_tpl, 'bbcode_tpl_compact'); -return $bbcode_tpl; + array_deep($bbcode_tpl, 'bbcode_tpl_compact'); + return $bbcode_tpl; } -function bbcode_tpl_compact ($text) +function bbcode_tpl_compact($text) { - $text = str_compact($text); - $text = str_replace('> <', '><', $text); - return $text; + $text = str_compact($text); + $text = str_replace('> <', '><', $text); + return $text; } // prepare a posted message for entry into the database -function prepare_message ($message) +function prepare_message($message) { - $message = bbcode::clean_up($message); - $message = htmlCHR($message, false, ENT_NOQUOTES); - return $message; + $message = bbcode::clean_up($message); + $message = htmlCHR($message, false, ENT_NOQUOTES); + return $message; } // Fill smiley templates (or just the variables) with smileys // Either in a window or inline function generate_smilies($mode) { - global $bb_cfg, $template, $lang, $user, $datastore; + global $bb_cfg, $template, $lang, $user, $datastore; - $inline_columns = 4; - $inline_rows = 7; - $window_columns = 8; + $inline_columns = 4; + $inline_rows = 7; + $window_columns = 8; - if ($mode == 'window') - { - $user->session_start(); - } + if ($mode == 'window') { + $user->session_start(); + } - $data = $datastore->get('smile_replacements'); + $data = $datastore->get('smile_replacements'); - if ($sql = $data['smile']) - { - $num_smilies = 0; - $rowset = array(); - foreach ($sql as $row) - { - if (empty($rowset[$row['smile_url']])) - { - $rowset[$row['smile_url']]['code'] = addslashes($row['code']); - $rowset[$row['smile_url']]['emoticon'] = $row['emoticon']; - $num_smilies++; - } - } + if ($sql = $data['smile']) { + $num_smilies = 0; + $rowset = array(); + foreach ($sql as $row) { + if (empty($rowset[$row['smile_url']])) { + $rowset[$row['smile_url']]['code'] = addslashes($row['code']); + $rowset[$row['smile_url']]['emoticon'] = $row['emoticon']; + $num_smilies++; + } + } - if ($num_smilies) - { - $smilies_count = ($mode == 'inline') ? min(19, $num_smilies) : $num_smilies; - $smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; + if ($num_smilies) { + $smilies_count = ($mode == 'inline') ? min(19, $num_smilies) : $num_smilies; + $smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; - $s_colspan = 0; - $row = 0; - $col = 0; + $s_colspan = 0; + $row = 0; + $col = 0; - while (list($smile_url, $data) = @each($rowset)) - { - if (!$col) - { - $template->assign_block_vars('smilies_row', array()); - } + while (list($smile_url, $data) = @each($rowset)) { + if (!$col) { + $template->assign_block_vars('smilies_row', array()); + } - $template->assign_block_vars('smilies_row.smilies_col', array( - 'SMILEY_CODE' => $data['code'], - 'SMILEY_IMG' => $bb_cfg['smilies_path'] . '/' . $smile_url, - 'SMILEY_DESC' => $data['emoticon'], - )); + $template->assign_block_vars('smilies_row.smilies_col', array( + 'SMILEY_CODE' => $data['code'], + 'SMILEY_IMG' => $bb_cfg['smilies_path'] . '/' . $smile_url, + 'SMILEY_DESC' => $data['emoticon'], + )); - $s_colspan = max($s_colspan, $col + 1); + $s_colspan = max($s_colspan, $col + 1); - if ($col == $smilies_split_row) - { - if ($mode == 'inline' && $row == $inline_rows - 1) - { - break; - } - $col = 0; - $row++; - } - else - { - $col++; - } - } + if ($col == $smilies_split_row) { + if ($mode == 'inline' && $row == $inline_rows - 1) { + break; + } + $col = 0; + $row++; + } else { + $col++; + } + } - if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) - { - $template->assign_block_vars('switch_smilies_extra', array()); + if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) { + $template->assign_block_vars('switch_smilies_extra', array()); - $template->assign_vars(array( - 'U_MORE_SMILIES' => POSTING_URL ."?mode=smilies", - )); - } + $template->assign_vars(array( + 'U_MORE_SMILIES' => POSTING_URL . "?mode=smilies", + )); + } - $template->assign_vars(array( - 'PAGE_TITLE' => $lang['EMOTICONS'], - 'S_SMILIES_COLSPAN' => $s_colspan, - )); - } - } + $template->assign_vars(array( + 'PAGE_TITLE' => $lang['EMOTICONS'], + 'S_SMILIES_COLSPAN' => $s_colspan, + )); + } + } - if ($mode == 'window') - { - print_page('posting_smilies.tpl', 'simple'); - } + if ($mode == 'window') { + print_page('posting_smilies.tpl', 'simple'); + } } // some functions from vB // ############################################################################# /** -* Strips away [quote] tags and their contents from the specified string -* -* @param string Text to be stripped of quote tags -* -* @return string -*/ -function strip_quotes ($text) + * Strips away [quote] tags and their contents from the specified string + * + * @param string Text to be stripped of quote tags + * + * @return string + */ +function strip_quotes($text) { - $lowertext = strtolower($text); + $lowertext = strtolower($text); - // find all [quote tags - $start_pos = array(); - $curpos = 0; - do - { - $pos = strpos($lowertext, '[quote', $curpos); - if ($pos !== false) - { - $start_pos["$pos"] = 'start'; - $curpos = $pos + 6; - } - } - while ($pos !== false); + // find all [quote tags + $start_pos = array(); + $curpos = 0; + do { + $pos = strpos($lowertext, '[quote', $curpos); + if ($pos !== false) { + $start_pos["$pos"] = 'start'; + $curpos = $pos + 6; + } + } while ($pos !== false); - if (sizeof($start_pos) == 0) - { - return $text; - } + if (sizeof($start_pos) == 0) { + return $text; + } - // find all [/quote] tags - $end_pos = array(); - $curpos = 0; - do - { - $pos = strpos($lowertext, '[/quote', $curpos); - if ($pos !== false) - { - $end_pos["$pos"] = 'end'; - $curpos = $pos + 8; - } - } - while ($pos !== false); + // find all [/quote] tags + $end_pos = array(); + $curpos = 0; + do { + $pos = strpos($lowertext, '[/quote', $curpos); + if ($pos !== false) { + $end_pos["$pos"] = 'end'; + $curpos = $pos + 8; + } + } while ($pos !== false); - if (sizeof($end_pos) == 0) - { - return $text; - } + if (sizeof($end_pos) == 0) { + return $text; + } - // merge them together and sort based on position in string - $pos_list = $start_pos + $end_pos; - ksort($pos_list); + // merge them together and sort based on position in string + $pos_list = $start_pos + $end_pos; + ksort($pos_list); - do - { - // build a stack that represents when a quote tag is opened - // and add non-quote text to the new string - $stack = array(); - $newtext = '[...] '; - $substr_pos = 0; - foreach ($pos_list AS $pos => $type) - { - $stacksize = sizeof($stack); - if ($type == 'start') - { - // empty stack, so add from the last close tag or the beginning of the string - if ($stacksize == 0) - { - $newtext .= substr($text, $substr_pos, $pos - $substr_pos); - } - array_push($stack, $pos); - } - else - { - // pop off the latest opened tag - if ($stacksize) - { - array_pop($stack); - $substr_pos = $pos + 8; - } - } - } + do { + // build a stack that represents when a quote tag is opened + // and add non-quote text to the new string + $stack = array(); + $newtext = '[...] '; + $substr_pos = 0; + foreach ($pos_list as $pos => $type) { + $stacksize = sizeof($stack); + if ($type == 'start') { + // empty stack, so add from the last close tag or the beginning of the string + if ($stacksize == 0) { + $newtext .= substr($text, $substr_pos, $pos - $substr_pos); + } + array_push($stack, $pos); + } else { + // pop off the latest opened tag + if ($stacksize) { + array_pop($stack); + $substr_pos = $pos + 8; + } + } + } - // add any trailing text - $newtext .= substr($text, $substr_pos); + // add any trailing text + $newtext .= substr($text, $substr_pos); - // check to see if there's a stack remaining, remove those points - // as key points, and repeat. Allows emulation of a non-greedy-type - // recursion. - if ($stack) - { - foreach ($stack AS $pos) - { - unset($pos_list["$pos"]); - } - } - } - while ($stack); + // check to see if there's a stack remaining, remove those points + // as key points, and repeat. Allows emulation of a non-greedy-type + // recursion. + if ($stack) { + foreach ($stack as $pos) { + unset($pos_list["$pos"]); + } + } + } while ($stack); - return $newtext; + return $newtext; } // ############################################################################# /** * Strips away bbcode from a given string, leaving plain text * - * @param string Text to be stripped of bbcode tags - * @param boolean If true, strip away quote tags AND their contents - * @param boolean If true, use the fast-and-dirty method rather than the shiny and nice method + * @param string Text to be stripped of bbcode tags + * @param boolean If true, strip away quote tags AND their contents + * @param boolean If true, use the fast-and-dirty method rather than the shiny and nice method * - * @return string + * @return string */ -function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true) +function strip_bbcode($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true) { - $find = array(); - $replace = array(); + $find = array(); + $replace = array(); - if ($stripquotes) - { - // [quote=username] and [quote] - $message = strip_quotes($message); - } + if ($stripquotes) { + // [quote=username] and [quote] + $message = strip_quotes($message); + } - // a really quick and rather nasty way of removing bbcode - if ($fast_and_dirty) - { - // any old thing in square brackets - $find[] = '#\[.*/?\]#siU'; - $replace = ''; + // a really quick and rather nasty way of removing bbcode + if ($fast_and_dirty) { + // any old thing in square brackets + $find[] = '#\[.*/?\]#siU'; + $replace = ''; - $message = preg_replace($find, $replace, $message); - } - // the preferable way to remove bbcode - else - { - // simple links - $find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU'; - $replace[] = '\3'; + $message = preg_replace($find, $replace, $message); + } // the preferable way to remove bbcode + else { + // simple links + $find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU'; + $replace[] = '\3'; - // named links - $find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU'; - $replace[] = ($showlinks ? '\4 (\3)' : '\4'); + // named links + $find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU'; + $replace[] = ($showlinks ? '\4 (\3)' : '\4'); - // smilies - $find[] = '#(?<=^|\W)(:\w+?:)(?=$|\W)#'; - $replace[] = ''; + // smilies + $find[] = '#(?<=^|\W)(:\w+?:)(?=$|\W)#'; + $replace[] = ''; - // replace - $message = preg_replace($find, $replace, $message); + // replace + $message = preg_replace($find, $replace, $message); - // strip out all other instances of [x]...[/x] - while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) - { - $message = str_replace($m[0], $m[2], $message); - } + // strip out all other instances of [x]...[/x] + while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) { + $message = str_replace($m[0], $m[2], $message); + } - $replace = array('[*]', '[hr]', '[br]', '[align=center]', '[align=left]', '[align=right]'); - $message = str_replace($replace, ' ', $message); - } + $replace = array('[*]', '[hr]', '[br]', '[align=center]', '[align=left]', '[align=right]'); + $message = str_replace($replace, ' ', $message); + } - return $message; + return $message; } -function extract_search_words ($text) +function extract_search_words($text) { - global $bb_cfg; + global $bb_cfg; - $max_words_count = $bb_cfg['max_search_words_per_post']; - $min_word_len = max(2, $bb_cfg['search_min_word_len'] - 1); - $max_word_len = $bb_cfg['search_max_word_len']; + $max_words_count = $bb_cfg['max_search_words_per_post']; + $min_word_len = max(2, $bb_cfg['search_min_word_len'] - 1); + $max_word_len = $bb_cfg['search_max_word_len']; - $text = ' ' . str_compact(strip_tags(mb_strtolower($text))) . ' '; - $text = str_replace(array('[', ']'), array('[', ']'), $text); + $text = ' ' . str_compact(strip_tags(mb_strtolower($text))) . ' '; + $text = str_replace(array('[', ']'), array('[', ']'), $text); - // HTML entities like   - $text = preg_replace('/(\w*?)&#?[0-9a-z]+;(\w*?)/iu', '', $text); - // Remove URL's ((www|ftp)\.[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]*?) - $text = preg_replace('#\b[a-z0-9]+://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+(/[0-9a-z\?\.%_\-\+=&/]+)?#u', ' ', $text); - $text = str_replace('[url=', ' ', $text); - $text = str_replace('?', ' ', $text); - $text = str_replace('!', ' ', $text); + // HTML entities like   + $text = preg_replace('/(\w*?)&#?[0-9a-z]+;(\w*?)/iu', '', $text); + // Remove URL's ((www|ftp)\.[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]*?) + $text = preg_replace('#\b[a-z0-9]+://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+(/[0-9a-z\?\.%_\-\+=&/]+)?#u', ' ', $text); + $text = str_replace('[url=', ' ', $text); + $text = str_replace('?', ' ', $text); + $text = str_replace('!', ' ', $text); - $text = strip_bbcode($text); + $text = strip_bbcode($text); - // Filter out characters like ^, $, &, change "it's" to "its" - $text = preg_replace('#[.,:;]#u', ' ', $text); + // Filter out characters like ^, $, &, change "it's" to "its" + $text = preg_replace('#[.,:;]#u', ' ', $text); - // short & long words - // $text = preg_replace('#(?<=^|\s)(\S{1,'.$min_word_len.'}|\S{'.$max_word_len.',}|\W*)(?=$|\s)#u', ' ', $text); + // short & long words + // $text = preg_replace('#(?<=^|\s)(\S{1,'.$min_word_len.'}|\S{'.$max_word_len.',}|\W*)(?=$|\s)#u', ' ', $text); - $text = remove_stopwords($text); + $text = remove_stopwords($text); # $text = replace_synonyms($text); - // Trim 1+ spaces to one space and split this string into unique words - $text = array_unique(explode(' ', str_compact($text))); + // Trim 1+ spaces to one space and split this string into unique words + $text = array_unique(explode(' ', str_compact($text))); - // short & long words 2 - $text_out = array(); - foreach ($text as $word) - { - if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) $text_out[] = $word; - } - $text = $text_out; + // short & long words 2 + $text_out = array(); + foreach ($text as $word) { + if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) { + $text_out[] = $word; + } + } + $text = $text_out; - if (sizeof($text) > $max_words_count) - { -# shuffle($text); - $text = array_splice($text, 0, $max_words_count); - } + if (sizeof($text) > $max_words_count) { + # shuffle($text); + $text = array_splice($text, 0, $max_words_count); + } - return $text; + return $text; } -function replace_synonyms ($text) +function replace_synonyms($text) { - static $syn_match = null, $syn_replace = null; + static $syn_match = null, $syn_replace = null; - if (is_null($syn_match)) - { - preg_match_all("#(\w+) (\w+)(\r?\n|$)#", @file_get_contents(LANG_DIR .'search_synonyms.txt'), $m); + if (is_null($syn_match)) { + preg_match_all("#(\w+) (\w+)(\r?\n|$)#", @file_get_contents(LANG_DIR . 'search_synonyms.txt'), $m); - $syn_match = $m[2]; - $syn_replace = $m[1]; + $syn_match = $m[2]; + $syn_replace = $m[1]; - array_deep($syn_match, 'pad_with_space'); - array_deep($syn_replace, 'pad_with_space'); - } + array_deep($syn_match, 'pad_with_space'); + array_deep($syn_replace, 'pad_with_space'); + } - return ($syn_match && $syn_replace) ? str_replace($syn_match, $syn_replace, $text) : $text; + return ($syn_match && $syn_replace) ? str_replace($syn_match, $syn_replace, $text) : $text; } -function add_search_words ($post_id, $post_message, $topic_title = '', $only_return_words = false) +function add_search_words($post_id, $post_message, $topic_title = '', $only_return_words = false) { - global $bb_cfg; + global $bb_cfg; - $text = $topic_title .' '. $post_message; - $words = ($text) ? extract_search_words($text) : array(); + $text = $topic_title . ' ' . $post_message; + $words = ($text) ? extract_search_words($text) : array(); - if ($only_return_words || $bb_cfg['search_engine_type'] == 'sphinx') - { - return join("\n", $words); - } - else - { - DB()->query("DELETE FROM ". BB_POSTS_SEARCH ." WHERE post_id = $post_id"); + if ($only_return_words || $bb_cfg['search_engine_type'] == 'sphinx') { + return join("\n", $words); + } else { + DB()->query("DELETE FROM " . BB_POSTS_SEARCH . " WHERE post_id = $post_id"); - if ($words_sql = DB()->escape(join("\n", $words))) - { - DB()->query("REPLACE INTO ". BB_POSTS_SEARCH ." (post_id, search_words) VALUES ($post_id, '$words_sql')"); - } - } + if ($words_sql = DB()->escape(join("\n", $words))) { + DB()->query("REPLACE INTO " . BB_POSTS_SEARCH . " (post_id, search_words) VALUES ($post_id, '$words_sql')"); + } + } } class bbcode { - public $tpl = array(); // шаблоны для замены тегов - public $smilies = null; // смайлы - public $found_spam = null; // найденные спам "слова" - public $del_words = array(); // см. get_words_rate() - public $tidy_cfg = array( - 'drop-empty-paras' => false, - 'fix-uri' => false, - 'force-output' => true, - 'hide-comments' => true, - 'join-classes' => false, - 'join-styles' => false, - 'merge-divs' => false, - 'merge-spans' => false, - 'newline' => 'LF', - 'output-xhtml' => true, - 'preserve-entities' => true, - 'quiet' => true, - 'quote-ampersand' => false, - 'show-body-only' => true, - 'show-errors' => false, - 'show-warnings' => false, - 'wrap' => 0, - ); - public $block_tags = array( - 'align', - 'br', - 'clear', - 'hr', - 'list', - 'pre', - 'quote', - 'spoiler', - ); - public $preg = array(); - public $str = array(); - public $preg_search = array(); - public $preg_repl = array(); - public $str_search = array(); - public $str_repl = array(); + public $tpl = array(); // шаблоны для замены тегов + public $smilies = null; // смайлы + public $found_spam = null; // найденные спам "слова" + public $del_words = array(); // см. get_words_rate() + public $tidy_cfg = array( + 'drop-empty-paras' => false, + 'fix-uri' => false, + 'force-output' => true, + 'hide-comments' => true, + 'join-classes' => false, + 'join-styles' => false, + 'merge-divs' => false, + 'merge-spans' => false, + 'newline' => 'LF', + 'output-xhtml' => true, + 'preserve-entities' => true, + 'quiet' => true, + 'quote-ampersand' => false, + 'show-body-only' => true, + 'show-errors' => false, + 'show-warnings' => false, + 'wrap' => 0, + ); + public $block_tags = array( + 'align', + 'br', + 'clear', + 'hr', + 'list', + 'pre', + 'quote', + 'spoiler', + ); + public $preg = array(); + public $str = array(); + public $preg_search = array(); + public $preg_repl = array(); + public $str_search = array(); + public $str_repl = array(); - /** - * Constructor - */ - public function __construct () - { - $this->tpl = get_bbcode_tpl(); + /** + * Constructor + */ + public function __construct() + { + $this->tpl = get_bbcode_tpl(); - $this->init_replacements(); - } + $this->init_replacements(); + } - /** - * init_replacements - */ - public function init_replacements () - { - $tpl = $this->tpl; - $img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?'; - $email_exp = '[a-z0-9&\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+'; + /** + * init_replacements + */ + public function init_replacements() + { + $tpl = $this->tpl; + $img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?'; + $email_exp = '[a-z0-9&\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+'; - $this->preg = array( - '#\[quote="(.+?)"\]#isu' => $tpl['quote_username_open'], - '#\[spoiler="(.+?)"\]#isu' => $tpl['spoiler_title_open'], - '#\[list=(a|A|i|I|1)\]#isu' => '
          ', - '#\[\*=(\d+)\]#isu' => '
        • ', - '#\[pre\](.*?)\[/pre\]#isu' => '
          $1
          ', - '#\[name=([a-zA-Z0-9_]+?)\]#isu' => '', - '#\[url=\#([a-zA-Z0-9_]+?)\](.*?)\[/url\]#isu' => '$2', - '#\[color=([\#0-9a-zA-Z]+)\]#isu' => '', - '#\[size=([1-2]?[0-9])\]#isu' => '', - '#\[align=(left|right|center|justify)\]#isu' => '', - '#\[font="([\w\- \']+)"\]#isu' => '', - "#\[img\]($img_exp)\[/img\]#isu" => $tpl['img'], - "#\[img=(left|right|center)\]($img_exp)\[/img\]\s*#isu" => $tpl['img_aligned'], - "#\[email\]($email_exp)\[/email\]#isu" => '$1', - "#\[qpost=([0-9]*)\]#isu" => '$1', - ); + $this->preg = array( + '#\[quote="(.+?)"\]#isu' => $tpl['quote_username_open'], + '#\[spoiler="(.+?)"\]#isu' => $tpl['spoiler_title_open'], + '#\[list=(a|A|i|I|1)\]#isu' => '
            ', + '#\[\*=(\d+)\]#isu' => '
          • ', + '#\[pre\](.*?)\[/pre\]#isu' => '
            $1
            ', + '#\[name=([a-zA-Z0-9_]+?)\]#isu' => '', + '#\[url=\#([a-zA-Z0-9_]+?)\](.*?)\[/url\]#isu' => '$2', + '#\[color=([\#0-9a-zA-Z]+)\]#isu' => '', + '#\[size=([1-2]?[0-9])\]#isu' => '', + '#\[align=(left|right|center|justify)\]#isu' => '', + '#\[font="([\w\- \']+)"\]#isu' => '', + "#\[img\]($img_exp)\[/img\]#isu" => $tpl['img'], + "#\[img=(left|right|center)\]($img_exp)\[/img\]\s*#isu" => $tpl['img_aligned'], + "#\[email\]($email_exp)\[/email\]#isu" => '$1', + "#\[qpost=([0-9]*)\]#isu" => '$1', + ); - $this->str = array( - '[quote]' => $tpl['quote_open'], - '[/quote]' => $tpl['quote_close'], - '[spoiler]' => $tpl['spoiler_open'], - '[/spoiler]' => $tpl['spoiler_close'], - '[list]' => '
              ', - '[*]' => '
            • ', - '[/list]' => '
            ', - '[/color]' => '
            ', - '[/size]' => '
            ', - '[/align]' => '
            ', - '[/font]' => '
            ', - '[tab]' => '    ', - '[br]' => "\n\n", - '[hr]' => $tpl['hr'], - '[b]' => '', - '[/b]' => '', - '[u]' => '', - '[/u]' => '', - '[i]' => '', - '[/i]' => '', - '[s]' => '', - '[/s]' => '', - '[del]' => '', - '[/del]' => '', - '[clear]' => '
             
            ', - ); + $this->str = array( + '[quote]' => $tpl['quote_open'], + '[/quote]' => $tpl['quote_close'], + '[spoiler]' => $tpl['spoiler_open'], + '[/spoiler]' => $tpl['spoiler_close'], + '[list]' => '
              ', + '[*]' => '
            • ', + '[/list]' => '
            ', + '[/color]' => '', + '[/size]' => '', + '[/align]' => '', + '[/font]' => '', + '[tab]' => '    ', + '[br]' => "\n\n", + '[hr]' => $tpl['hr'], + '[b]' => '', + '[/b]' => '', + '[u]' => '', + '[/u]' => '', + '[i]' => '', + '[/i]' => '', + '[s]' => '', + '[/s]' => '', + '[del]' => '', + '[/del]' => '', + '[clear]' => '
             
            ', + ); - $this->preg_search = array_keys($this->preg); - $this->preg_repl = array_values($this->preg); - $this->str_search = array_keys($this->str); - $this->str_repl = array_values($this->str); - } + $this->preg_search = array_keys($this->preg); + $this->preg_repl = array_values($this->preg); + $this->str_search = array_keys($this->str); + $this->str_repl = array_values($this->str); + } - /** - * bbcode2html - * $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES); - */ - public function bbcode2html ($text) - { - global $bb_cfg; + /** + * bbcode2html + * $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES); + */ + public function bbcode2html($text) + { + global $bb_cfg; - $text = " $text "; - $text = $this->clean_up($text); - $text = $this->spam_filter($text); + $text = " $text "; + $text = $this->clean_up($text); + $text = $this->spam_filter($text); - // Tag parse - if (strpos($text, '[') !== false) - { - // [code] - $text = preg_replace_callback('#(\s*)\[code\](.+?)\[/code\](\s*)#s', array(&$this, 'code_callback'), $text); + // Tag parse + if (strpos($text, '[') !== false) { + // [code] + $text = preg_replace_callback('#(\s*)\[code\](.+?)\[/code\](\s*)#s', array(&$this, 'code_callback'), $text); - // Escape tags inside tiltes in [quote="tilte"] - $text = preg_replace_callback('#(\[(quote|spoiler)=")(.+?)("\])#', array(&$this, 'escape_tiltes_callback'), $text); + // Escape tags inside tiltes in [quote="tilte"] + $text = preg_replace_callback('#(\[(quote|spoiler)=")(.+?)("\])#', array(&$this, 'escape_tiltes_callback'), $text); - // [url] - $url_exp = '[\w\#!$%&~/.\-;:=,?@а-яА-Я()\[\]+]+?'; - $text = preg_replace_callback("#\[url\]((?:https?://)?$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url\](www\.$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url=((?:https?://)?$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); - $text = preg_replace_callback("#\[url=(www\.$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); + // [url] + $url_exp = '[\w\#!$%&~/.\-;:=,?@а-яА-Я()\[\]+]+?'; + $text = preg_replace_callback("#\[url\]((?:https?://)?$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); + $text = preg_replace_callback("#\[url\](www\.$url_exp)\[/url\]#isu", array(&$this, 'url_callback'), $text); + $text = preg_replace_callback("#\[url=((?:https?://)?$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); + $text = preg_replace_callback("#\[url=(www\.$url_exp)\]([^?\n\t].*?)\[/url\]#isu", array(&$this, 'url_callback'), $text); - // Normalize block level tags wrapped with new lines - $block_tags = join('|', $this->block_tags); - $text = str_replace("\n\n[hr]\n\n", '[br][hr][br]', $text); - $text = preg_replace("#(\s*)(\[/?($block_tags)(.*?)\])(\s*)#", '$2', $text); + // Normalize block level tags wrapped with new lines + $block_tags = join('|', $this->block_tags); + $text = str_replace("\n\n[hr]\n\n", '[br][hr][br]', $text); + $text = preg_replace("#(\s*)(\[/?($block_tags)(.*?)\])(\s*)#", '$2', $text); - // Tag replacements - $text = preg_replace($this->preg_search, $this->preg_repl, $text); - $text = str_replace($this->str_search, $this->str_repl, $text); - } + // Tag replacements + $text = preg_replace($this->preg_search, $this->preg_repl, $text); + $text = str_replace($this->str_search, $this->str_repl, $text); + } - $text = $this->make_clickable($text); - $text = $this->smilies_pass($text); - $text = $this->new_line2html($text); - $text = trim($text); + $text = $this->make_clickable($text); + $text = $this->smilies_pass($text); + $text = $this->new_line2html($text); + $text = trim($text); - if ($bb_cfg['tidy_post']) - { - $text = $this->tidy($text); - } + if ($bb_cfg['tidy_post']) { + $text = $this->tidy($text); + } - return trim($text); - } + return trim($text); + } - /** - * Clean up - */ - static public function clean_up ($text) - { - $text = trim($text); - $text = str_replace("\r", '', $text); - $text = preg_replace('#[ \t]+$#m', '', $text); // trailing spaces - $text = preg_replace('#\n{3,}#', "\n\n", $text); - return $text; - } + /** + * Clean up + */ + public static function clean_up($text) + { + $text = trim($text); + $text = str_replace("\r", '', $text); + $text = preg_replace('#[ \t]+$#m', '', $text); // trailing spaces + $text = preg_replace('#\n{3,}#', "\n\n", $text); + return $text; + } - /** - * Spam filter - */ - private function spam_filter ($text) - { - global $bb_cfg; - static $spam_words = null; - static $spam_replace = ' СПАМ'; + /** + * Spam filter + */ + private function spam_filter($text) + { + global $bb_cfg; + static $spam_words = null; + static $spam_replace = ' СПАМ'; - if (isset($this)) - { - $found_spam =& $this->found_spam; - } + if (isset($this)) { + $found_spam =& $this->found_spam; + } - // set $spam_words and $spam_replace - if (!$bb_cfg['spam_filter_file_path']) - { - return $text; - } - if (is_null($spam_words)) - { - $spam_words = file_get_contents($bb_cfg['spam_filter_file_path']); - $spam_words = strtolower($spam_words); - $spam_words = explode("\n", $spam_words); - } + // set $spam_words and $spam_replace + if (!$bb_cfg['spam_filter_file_path']) { + return $text; + } + if (is_null($spam_words)) { + $spam_words = file_get_contents($bb_cfg['spam_filter_file_path']); + $spam_words = strtolower($spam_words); + $spam_words = explode("\n", $spam_words); + } - $found_spam = array(); + $found_spam = array(); - $tm_start = utime(); + $tm_start = utime(); - $msg_decoded = $text; - $msg_decoded = html_entity_decode($msg_decoded); - $msg_decoded = urldecode($msg_decoded); - $msg_decoded = str_replace('&', ' &', $msg_decoded); + $msg_decoded = $text; + $msg_decoded = html_entity_decode($msg_decoded); + $msg_decoded = urldecode($msg_decoded); + $msg_decoded = str_replace('&', ' &', $msg_decoded); - $msg_search = strtolower($msg_decoded); + $msg_search = strtolower($msg_decoded); - foreach ($spam_words as $spam_str) - { - if (!$spam_str = trim($spam_str)) - { - continue; - } - if (strpos($msg_search, $spam_str) !== false) - { - $found_spam[] = $spam_str; - } - } - if ($found_spam) - { - $spam_exp = array(); - foreach ($found_spam as $keyword) - { - $spam_exp[] = preg_quote($keyword, '/'); - } - $spam_exp = join('|', $spam_exp); + foreach ($spam_words as $spam_str) { + if (!$spam_str = trim($spam_str)) { + continue; + } + if (strpos($msg_search, $spam_str) !== false) { + $found_spam[] = $spam_str; + } + } + if ($found_spam) { + $spam_exp = array(); + foreach ($found_spam as $keyword) { + $spam_exp[] = preg_quote($keyword, '/'); + } + $spam_exp = join('|', $spam_exp); - $text = preg_replace("/($spam_exp)(\S*)/i", $spam_replace, $msg_decoded); - $text = htmlCHR($text, false, ENT_NOQUOTES); + $text = preg_replace("/($spam_exp)(\S*)/i", $spam_replace, $msg_decoded); + $text = htmlCHR($text, false, ENT_NOQUOTES); # bb_log(date("H:i:s") ." | ". sprintf('%.4f', (utime() - $tm_start)) ." | ". sprintf('%-6s', strlen($text)) ." | ". join(' ** ', $found_spam) ."\n", 'spam_filter'); - } + } - return $text; - } + return $text; + } - /** - * [code] callback - */ - public function code_callback ($m) - { - $code = trim($m[2]); - $code = str_replace(' ', '  ', $code); - $code = str_replace(' ', '  ', $code); - $code = str_replace("\t", '  ', $code); - $code = str_replace(array('[', ']', ':', ')'), array('[', ']', ':', ')'), $code); - return $this->tpl['code_open'] . $code . $this->tpl['code_close']; - } + /** + * [code] callback + */ + public function code_callback($m) + { + $code = trim($m[2]); + $code = str_replace(' ', '  ', $code); + $code = str_replace(' ', '  ', $code); + $code = str_replace("\t", '  ', $code); + $code = str_replace(array('[', ']', ':', ')'), array('[', ']', ':', ')'), $code); + return $this->tpl['code_open'] . $code . $this->tpl['code_close']; + } - /** - * [url] callback - */ - public function url_callback ($m) - { - global $bb_cfg; + /** + * [url] callback + */ + public function url_callback($m) + { + global $bb_cfg; - $url = trim($m[1]); - $url_name = (isset($m[2])) ? trim($m[2]) : $url; + $url = trim($m[1]); + $url_name = (isset($m[2])) ? trim($m[2]) : $url; - if (!preg_match("#^https?://#isu", $url) && !preg_match("/^#/", $url)) $url = 'http://' . $url; + if (!preg_match("#^https?://#isu", $url) && !preg_match("/^#/", $url)) { + $url = 'http://' . $url; + } - if (in_array(parse_url($url, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) - { - $link = "$url_name"; - } - else - { - $link = "$url_name"; - } + if (in_array(parse_url($url, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) { + $link = "$url_name"; + } else { + $link = "$url_name"; + } - return $link; - } + return $link; + } - /** - * Escape tags inside tiltes in [quote="tilte"] - */ - public function escape_tiltes_callback ($m) - { - $tilte = substr($m[3], 0, 250); - $tilte = str_replace(array('[', ']', ':', ')', '"'), array('[', ']', ':', ')', '"'), $tilte); - // еще раз htmlspecialchars, т.к. при извлечении из title происходит обратное преобразование - $tilte = htmlspecialchars($tilte, ENT_QUOTES); - return $m[1] . $tilte . $m[4]; - } + /** + * Escape tags inside tiltes in [quote="tilte"] + */ + public function escape_tiltes_callback($m) + { + $tilte = substr($m[3], 0, 250); + $tilte = str_replace(array('[', ']', ':', ')', '"'), array('[', ']', ':', ')', '"'), $tilte); + // еще раз htmlspecialchars, т.к. при извлечении из title происходит обратное преобразование + $tilte = htmlspecialchars($tilte, ENT_QUOTES); + return $m[1] . $tilte . $m[4]; + } - /** - * make_clickable - */ - public function make_clickable ($text) - { - $url_regexp = "# + /** + * make_clickable + */ + public function make_clickable($text) + { + $url_regexp = "# (? $max_len) ? mb_substr($href, 0, $max_len - 19) .'...'. mb_substr($href, -16) : $href; + $max_len = 70; + $href = $m[1]; + $name = (mb_strlen($href, 'UTF-8') > $max_len) ? mb_substr($href, 0, $max_len - 19) . '...' . mb_substr($href, -16) : $href; - if (in_array(parse_url($href, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) - { - $link = "$name"; - } - else - { - $link = "$name"; - } + if (in_array(parse_url($href, PHP_URL_HOST), $bb_cfg['nofollow']['allowed_url']) || $bb_cfg['nofollow']['disabled']) { + $link = "$name"; + } else { + $link = "$name"; + } - return $link; - } + return $link; + } - /** - * smilies_pass - */ - public function smilies_pass ($text) - { - global $datastore; + /** + * smilies_pass + */ + public function smilies_pass($text) + { + global $datastore; - if (is_null($this->smilies)) - { - $this->smilies = $datastore->get('smile_replacements'); - } - if ($this->smilies) - { - $parsed_text = preg_replace($this->smilies['orig'], $this->smilies['repl'], $text, 101, $smilies_cnt); - $text = ($smilies_cnt <= 100) ? $parsed_text : $text; - } + if (is_null($this->smilies)) { + $this->smilies = $datastore->get('smile_replacements'); + } + if ($this->smilies) { + $parsed_text = preg_replace($this->smilies['orig'], $this->smilies['repl'], $text, 101, $smilies_cnt); + $text = ($smilies_cnt <= 100) ? $parsed_text : $text; + } - return $text; - } + return $text; + } - /** - * new_line2html - */ - public function new_line2html ($text) - { - $text = preg_replace('#\n{2,}#', '
            ', $text); - $text = str_replace("\n", '
            ', $text); - return $text; - } + /** + * new_line2html + */ + public function new_line2html($text) + { + $text = preg_replace('#\n{2,}#', '
            ', $text); + $text = str_replace("\n", '
            ', $text); + return $text; + } - /** - * tidy - */ - public function tidy ($text) - { - $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); - return $text; - } + /** + * tidy + */ + public function tidy($text) + { + $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); + return $text; + } } -function bbcode2html ($text) +function bbcode2html($text) { - global $bbcode; + global $bbcode; - if (!isset($bbcode)) - { - $bbcode = new bbcode(); - } - $orig_word = array(); - $replacement_word = array(); - obtain_word_list($orig_word, $replacement_word); - if ( count($orig_word) ) - { - $text = preg_replace($orig_word, $replacement_word, $text); - } - return $bbcode->bbcode2html($text); + if (!isset($bbcode)) { + $bbcode = new bbcode(); + } + $orig_word = array(); + $replacement_word = array(); + obtain_word_list($orig_word, $replacement_word); + if (count($orig_word)) { + $text = preg_replace($orig_word, $replacement_word, $text); + } + return $bbcode->bbcode2html($text); } class words_rate { - public $dbg_mode = false; - public $words_rate = 0; - public $deleted_words = array(); - public $del_text_hl = ''; - public $words_del_exp = ''; - public $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; + public $dbg_mode = false; + public $words_rate = 0; + public $deleted_words = array(); + public $del_text_hl = ''; + public $words_del_exp = ''; + public $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; - public function __construct () - { - // слова начинающиеся на.. - $del_list = file_get_contents(BB_ROOT .'/library/words_rate_del_list.txt'); - $del_list = str_compact($del_list); - $del_list = str_replace(' ', '|', preg_quote($del_list, '/')); - $del_exp = '/\b('.$del_list.')[\w\-]*/i'; + public function __construct() + { + // слова начинающиеся на.. + $del_list = file_get_contents(BB_ROOT . '/library/words_rate_del_list.txt'); + $del_list = str_compact($del_list); + $del_list = str_replace(' ', '|', preg_quote($del_list, '/')); + $del_exp = '/\b(' . $del_list . ')[\w\-]*/i'; - $this->words_del_exp = $del_exp; - } + $this->words_del_exp = $del_exp; + } - /** - * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. - */ - public function get_words_rate ($text) - { - $this->words_rate = 127; // максимальное значение по умолчанию - $this->deleted_words = array(); - $this->del_text_hl = $text; + /** + * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. + */ + public function get_words_rate($text) + { + $this->words_rate = 127; // максимальное значение по умолчанию + $this->deleted_words = array(); + $this->del_text_hl = $text; - // длинное сообщение - if (strlen($text) > 600) - { - return $this->words_rate; - } - // вырезаем цитаты если содержит +1 - if (preg_match('#\+\d+#', $text)) - { - $text = strip_quotes($text); - } - // содержит ссылку - if (strpos($text, '://')) - { - return $this->words_rate; - } - // вопрос - if ($questions = preg_match_all('#\w\?+#', $text, $m)) - { - if ($questions >= 1) - { - return $this->words_rate; - } - } + // длинное сообщение + if (strlen($text) > 600) { + return $this->words_rate; + } + // вырезаем цитаты если содержит +1 + if (preg_match('#\+\d+#', $text)) { + $text = strip_quotes($text); + } + // содержит ссылку + if (strpos($text, '://')) { + return $this->words_rate; + } + // вопрос + if ($questions = preg_match_all('#\w\?+#', $text, $m)) { + if ($questions >= 1) { + return $this->words_rate; + } + } - if ($this->dbg_mode) - { - preg_match_all($this->words_del_exp, $text, $this->deleted_words); - $text_dbg = preg_replace($this->words_del_exp, '$0', $text); - $this->del_text_hl = '
            '. $text_dbg . '
            '; - } - $text = preg_replace($this->words_del_exp, '', $text); + if ($this->dbg_mode) { + preg_match_all($this->words_del_exp, $text, $this->deleted_words); + $text_dbg = preg_replace($this->words_del_exp, '$0', $text); + $this->del_text_hl = '
            ' . $text_dbg . '
            '; + } + $text = preg_replace($this->words_del_exp, '', $text); - // удаление смайлов - $text = preg_replace('#:\w+:#', '', $text); - // удаление bbcode тегов - $text = preg_replace('#\[\S+\]#', '', $text); + // удаление смайлов + $text = preg_replace('#:\w+:#', '', $text); + // удаление bbcode тегов + $text = preg_replace('#\[\S+\]#', '', $text); - $words_count = preg_match_all($this->words_cnt_exp, $text, $m); + $words_count = preg_match_all($this->words_cnt_exp, $text, $m); - if ($words_count !== false && $words_count < 127) - { - $this->words_rate = ($words_count == 0) ? 1 : $words_count; - } + if ($words_count !== false && $words_count < 127) { + $this->words_rate = ($words_count == 0) ? 1 : $words_count; + } - return $this->words_rate; - } + return $this->words_rate; + } } -function get_words_rate ($text) +function get_words_rate($text) { - static $wr = null; - if (!isset($wr)) - { - $wr = new words_rate(); - } - return $wr->get_words_rate($text); + static $wr = null; + if (!isset($wr)) { + $wr = new words_rate(); + } + return $wr->get_words_rate($text); } -function hide_passkey ($str) +function hide_passkey($str) { - global $bb_cfg; - return preg_replace("#\?{$bb_cfg['passkey_key']}=[a-zA-Z0-9]{". BT_AUTH_KEY_LENGTH ."}#", "?{$bb_cfg['passkey_key']}=passkey", $str); + global $bb_cfg; + return preg_replace("#\?{$bb_cfg['passkey_key']}=[a-zA-Z0-9]{" . BT_AUTH_KEY_LENGTH . "}#", "?{$bb_cfg['passkey_key']}=passkey", $str); } -function get_parsed_post ($postrow, $mode = 'full', $return_chars = 600) +function get_parsed_post($postrow, $mode = 'full', $return_chars = 600) { - global $bb_cfg; + global $bb_cfg; - if ($bb_cfg['use_posts_cache'] && !empty($postrow['post_html'])) - { - return $postrow['post_html']; - } + if ($bb_cfg['use_posts_cache'] && !empty($postrow['post_html'])) { + return $postrow['post_html']; + } - $message = bbcode2html($postrow['post_text']); + $message = bbcode2html($postrow['post_text']); - // Posts cache - if ($bb_cfg['use_posts_cache']) - { - DB()->shutdown['post_html'][] = array( - 'post_id' => (int) $postrow['post_id'], - 'post_html' => (string) $message, - ); - } + // Posts cache + if ($bb_cfg['use_posts_cache']) { + DB()->shutdown['post_html'][] = array( + 'post_id' => (int)$postrow['post_id'], + 'post_html' => (string)$message, + ); + } - return $message; + return $message; } -function update_post_html ($postrow) +function update_post_html($postrow) { - DB()->query("DELETE FROM ". BB_POSTS_HTML ." WHERE post_id = ". (int) $postrow['post_id'] ." LIMIT 1"); + DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_id = " . (int)$postrow['post_id'] . " LIMIT 1"); } diff --git a/library/includes/cache/apc.php b/library/includes/cache/apc.php index fef484190..da475beb3 100644 --- a/library/includes/cache/apc.php +++ b/library/includes/cache/apc.php @@ -1,65 +1,86 @@ is_installed()) - { - die('Error: APC extension not installed'); - } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } + public function __construct($prefix = null) + { + if (!$this->is_installed()) { + die('Error: APC extension not installed'); + } + $this->dbg_enabled = sql_dbg_enabled(); + $this->prefix = $prefix; + } - public function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function get($name, $get_miss_key_callback = '', $ttl = 0) + { + $this->cur_query = "cache->get('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return apc_fetch($this->prefix . $name); - } + return apc_fetch($this->prefix . $name); + } - public function set ($name, $value, $ttl = 0) - { - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function set($name, $value, $ttl = 0) + { + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return apc_store($this->prefix . $name, $value, $ttl); - } + return apc_store($this->prefix . $name, $value, $ttl); + } - public function rm ($name = '') - { - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function rm($name = '') + { + if ($name) { + $this->cur_query = "cache->rm('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return apc_delete($this->prefix . $name); - } - else - { - return apc_clear_cache(); - } - } + return apc_delete($this->prefix . $name); + } else { + return apc_clear_cache(); + } + } - public function is_installed () - { - return function_exists('apc_fetch'); - } + public function is_installed() + { + return function_exists('apc_fetch'); + } } diff --git a/library/includes/cache/common.php b/library/includes/cache/common.php index 65de44cfd..42ce97b44 100644 --- a/library/includes/cache/common.php +++ b/library/includes/cache/common.php @@ -1,84 +1,113 @@ dbg_enabled) return; + /** + * Remove variable + */ + public function rm($name = '') + { + return false; + } - $id =& $this->dbg_id; - $dbg =& $this->dbg[$id]; + public $num_queries = 0; + public $sql_starttime = 0; + public $sql_inittime = 0; + public $sql_timetotal = 0; + public $cur_query_time = 0; - if ($mode == 'start') - { - $this->sql_starttime = utime(); + public $dbg = array(); + public $dbg_id = 0; + public $dbg_enabled = false; + public $cur_query = null; - $dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query); - $dbg['src'] = $this->debug_find_source(); - $dbg['file'] = $this->debug_find_source('file'); - $dbg['line'] = $this->debug_find_source('line'); - $dbg['time'] = ''; - } - else if ($mode == 'stop') - { - $this->cur_query_time = utime() - $this->sql_starttime; - $this->sql_timetotal += $this->cur_query_time; - $dbg['time'] = $this->cur_query_time; - $id++; - } - } + public function debug($mode, $cur_query = null) + { + if (!$this->dbg_enabled) { + return; + } - public function debug_find_source ($mode = '') - { - foreach (debug_backtrace() as $trace) - { - if ($trace['file'] !== __FILE__) - { - switch ($mode) - { - case 'file': return $trace['file']; - case 'line': return $trace['line']; - default: return hide_bb_path($trace['file']) .'('. $trace['line'] .')'; - } - } - } - return 'src not found'; - } + $id =& $this->dbg_id; + $dbg =& $this->dbg[$id]; + + if ($mode == 'start') { + $this->sql_starttime = utime(); + + $dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query); + $dbg['src'] = $this->debug_find_source(); + $dbg['file'] = $this->debug_find_source('file'); + $dbg['line'] = $this->debug_find_source('line'); + $dbg['time'] = ''; + } elseif ($mode == 'stop') { + $this->cur_query_time = utime() - $this->sql_starttime; + $this->sql_timetotal += $this->cur_query_time; + $dbg['time'] = $this->cur_query_time; + $id++; + } + } + + public function debug_find_source($mode = '') + { + foreach (debug_backtrace() as $trace) { + if ($trace['file'] !== __FILE__) { + switch ($mode) { + case 'file': + return $trace['file']; + case 'line': + return $trace['line']; + default: + return hide_bb_path($trace['file']) . '(' . $trace['line'] . ')'; + } + } + } + return 'src not found'; + } } diff --git a/library/includes/cache/file.php b/library/includes/cache/file.php index 9eb7b1aad..d1a4c559e 100644 --- a/library/includes/cache/file.php +++ b/library/includes/cache/file.php @@ -1,136 +1,146 @@ dir = $dir; - $this->prefix = $prefix; - $this->dbg_enabled = sql_dbg_enabled(); - } + public function __construct($dir, $prefix = null) + { + $this->dir = $dir; + $this->prefix = $prefix; + $this->dbg_enabled = sql_dbg_enabled(); + } - public function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; + public function get($name, $get_miss_key_callback = '', $ttl = 0) + { + $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); - if (file_exists($filename)) - { - require($filename); - } + if (file_exists($filename)) { + require($filename); + } - $this->debug('stop'); - $this->cur_query = null; + $this->debug('stop'); + $this->cur_query = null; - return (!empty($filecache['value'])) ? $filecache['value'] : false; - } + return (!empty($filecache['value'])) ? $filecache['value'] : false; + } - public function set ($name, $value, $ttl = 86400) - { - if (!function_exists('var_export')) - { - return false; - } + public function set($name, $value, $ttl = 86400) + { + if (!function_exists('var_export')) { + return false; + } - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - $expire = TIMENOW + $ttl; - $cache_data = array( - 'expire' => $expire, - 'value' => $value, - ); + $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; + $expire = TIMENOW + $ttl; + $cache_data = array( + 'expire' => $expire, + 'value' => $value, + ); - $filecache = "'; + $filecache = "'; - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return (bool) file_write($filecache, $filename, false, true, true); - } + return (bool)file_write($filecache, $filename, false, true, true); + } - public function rm ($name = '') - { - $clear = false; - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); + public function rm($name = '') + { + $clear = false; + if ($name) { + $this->cur_query = "cache->rm('$name')"; + $this->debug('start'); - $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; - if (file_exists($filename)) - { - $clear = (bool) unlink($filename); - } + $filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; + if (file_exists($filename)) { + $clear = (bool)unlink($filename); + } - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; - } - else - { - if (is_dir($this->dir)) - { - if ($dh = opendir($this->dir)) - { - while (($file = readdir($dh)) !== false) - { - if ($file != "." && $file != "..") - { - $filename = $this->dir . $file; + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; + } else { + if (is_dir($this->dir)) { + if ($dh = opendir($this->dir)) { + while (($file = readdir($dh)) !== false) { + if ($file != "." && $file != "..") { + $filename = $this->dir . $file; - unlink($filename); - $clear = true; - } - } - closedir($dh); - } - } - } - return $clear; - } + unlink($filename); + $clear = true; + } + } + closedir($dh); + } + } + } + return $clear; + } - public function gc ($expire_time = TIMENOW) - { - $clear = false; + public function gc($expire_time = TIMENOW) + { + $clear = false; - if (is_dir($this->dir)) - { - if ($dh = opendir($this->dir)) - { - while (($file = readdir($dh)) !== false) - { - if ($file != "." && $file != "..") - { - $filename = $this->dir . $file; + if (is_dir($this->dir)) { + if ($dh = opendir($this->dir)) { + while (($file = readdir($dh)) !== false) { + if ($file != "." && $file != "..") { + $filename = $this->dir . $file; - require($filename); + require($filename); - if(!empty($filecache['expire']) && ($filecache['expire'] < $expire_time)) - { - unlink($filename); - $clear = true; - } - } - } - closedir($dh); - } - } + if (!empty($filecache['expire']) && ($filecache['expire'] < $expire_time)) { + unlink($filename); + $clear = true; + } + } + } + closedir($dh); + } + } - return $clear; - } + return $clear; + } } diff --git a/library/includes/cache/memcache.php b/library/includes/cache/memcache.php index c642638fd..6a3dc3269 100644 --- a/library/includes/cache/memcache.php +++ b/library/includes/cache/memcache.php @@ -1,100 +1,127 @@ is_installed()) - { - die('Error: Memcached extension not installed'); - } + public function __construct($cfg, $prefix = null) + { + if (!$this->is_installed()) { + die('Error: Memcached extension not installed'); + } - $this->cfg = $cfg; - $this->prefix = $prefix; - $this->memcache = new Memcache; - $this->dbg_enabled = sql_dbg_enabled(); - } + $this->cfg = $cfg; + $this->prefix = $prefix; + $this->memcache = new Memcache; + $this->dbg_enabled = sql_dbg_enabled(); + } - public function connect () - { - $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; + public function connect() + { + $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; - $this->cur_query = $connect_type .' '. $this->cfg['host'] .':'. $this->cfg['port']; - $this->debug('start'); + $this->cur_query = $connect_type . ' ' . $this->cfg['host'] . ':' . $this->cfg['port']; + $this->debug('start'); - if (@$this->memcache->$connect_type($this->cfg['host'], $this->cfg['port'])) - { - $this->connected = true; - } + if (@$this->memcache->$connect_type($this->cfg['host'], $this->cfg['port'])) { + $this->connected = true; + } - if (DBG_LOG) dbg_log(' ', 'CACHE-connect'. ($this->connected ? '' : '-FAIL')); + if (DBG_LOG) { + dbg_log(' ', 'CACHE-connect' . ($this->connected ? '' : '-FAIL')); + } - if (!$this->connected && $this->cfg['con_required']) - { - die('Could not connect to memcached server'); - } + if (!$this->connected && $this->cfg['con_required']) { + die('Could not connect to memcached server'); + } - $this->debug('stop'); - $this->cur_query = null; - } + $this->debug('stop'); + $this->cur_query = null; + } - public function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - if (!$this->connected) $this->connect(); + public function get($name, $get_miss_key_callback = '', $ttl = 0) + { + if (!$this->connected) { + $this->connect(); + } - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->get('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false; - } + return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false; + } - public function set ($name, $value, $ttl = 0) - { - if (!$this->connected) $this->connect(); + public function set($name, $value, $ttl = 0) + { + if (!$this->connected) { + $this->connect(); + } - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false; - } + return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false; + } - public function rm ($name = '') - { - if (!$this->connected) $this->connect(); + public function rm($name = '') + { + if (!$this->connected) { + $this->connect(); + } - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + if ($name) { + $this->cur_query = "cache->rm('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return ($this->connected) ? $this->memcache->delete($this->prefix . $name, 0) : false; - } - else - { - return ($this->connected) ? $this->memcache->flush() : false; - } - } + return ($this->connected) ? $this->memcache->delete($this->prefix . $name, 0) : false; + } else { + return ($this->connected) ? $this->memcache->flush() : false; + } + } - public function is_installed () - { - return class_exists('Memcache'); - } + public function is_installed() + { + return class_exists('Memcache'); + } } diff --git a/library/includes/cache/redis.php b/library/includes/cache/redis.php index 489c1bec8..64598fabb 100644 --- a/library/includes/cache/redis.php +++ b/library/includes/cache/redis.php @@ -1,109 +1,130 @@ is_installed()) - { - die('Error: Redis extension not installed'); - } + public function __construct($cfg, $prefix = null) + { + if (!$this->is_installed()) { + die('Error: Redis extension not installed'); + } - $this->cfg = $cfg; - $this->prefix = $prefix; - $this->redis = new Redis(); - $this->dbg_enabled = sql_dbg_enabled(); - } + $this->cfg = $cfg; + $this->prefix = $prefix; + $this->redis = new Redis(); + $this->dbg_enabled = sql_dbg_enabled(); + } - public function connect () - { - $this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port']; - $this->debug('start'); + public function connect() + { + $this->cur_query = 'connect ' . $this->cfg['host'] . ':' . $this->cfg['port']; + $this->debug('start'); - if (@$this->redis->connect($this->cfg['host'], $this->cfg['port'])) - { - $this->connected = true; - } + if (@$this->redis->connect($this->cfg['host'], $this->cfg['port'])) { + $this->connected = true; + } - if (!$this->connected && $this->cfg['con_required']) - { - die('Could not connect to redis server'); - } + if (!$this->connected && $this->cfg['con_required']) { + die('Could not connect to redis server'); + } - $this->debug('stop'); - $this->cur_query = null; - } + $this->debug('stop'); + $this->cur_query = null; + } - public function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - if (!$this->connected) $this->connect(); + public function get($name, $get_miss_key_callback = '', $ttl = 0) + { + if (!$this->connected) { + $this->connect(); + } - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->get('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false; - } + return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false; + } - public function set ($name, $value, $ttl = 0) - { - if (!$this->connected) $this->connect(); + public function set($name, $value, $ttl = 0) + { + if (!$this->connected) { + $this->connect(); + } - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); - if ($this->redis->set($this->prefix . $name, serialize($value))) - { - if ($ttl > 0) - { - $this->redis->expire($this->prefix . $name, $ttl); - } + if ($this->redis->set($this->prefix . $name, serialize($value))) { + if ($ttl > 0) { + $this->redis->expire($this->prefix . $name, $ttl); + } - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return true; - } - else - { - return false; - } - } + return true; + } else { + return false; + } + } - public function rm ($name = '') - { - if (!$this->connected) $this->connect(); + public function rm($name = '') + { + if (!$this->connected) { + $this->connect(); + } - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + if ($name) { + $this->cur_query = "cache->rm('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return ($this->connected) ? $this->redis->del($this->prefix . $name) : false; - } - else - { - return ($this->connected) ? $this->redis->flushdb() : false; - } - } + return ($this->connected) ? $this->redis->del($this->prefix . $name) : false; + } else { + return ($this->connected) ? $this->redis->flushdb() : false; + } + } - public function is_installed () - { - return class_exists('Redis'); - } + public function is_installed() + { + return class_exists('Redis'); + } } diff --git a/library/includes/cache/sqlite.php b/library/includes/cache/sqlite.php index 9abbc9a9b..f7fed7456 100644 --- a/library/includes/cache/sqlite.php +++ b/library/includes/cache/sqlite.php @@ -1,288 +1,295 @@ '/path/to/cache.db.sqlite', - 'table_name' => 'cache', - 'table_schema' => 'CREATE TABLE cache ( + public $used = true; + public $db = null; + public $prefix = null; + public $cfg = array( + 'db_file_path' => '/path/to/cache.db.sqlite', + 'table_name' => 'cache', + 'table_schema' => 'CREATE TABLE cache ( cache_name VARCHAR(255), cache_expire_time INT, cache_value TEXT, PRIMARY KEY (cache_name) )', - 'pconnect' => true, - 'con_required' => true, - 'log_name' => 'CACHE', - ); + 'pconnect' => true, + 'con_required' => true, + 'log_name' => 'CACHE', + ); - function __construct ($cfg, $prefix = null) - { - $this->cfg = array_merge($this->cfg, $cfg); - $this->db = new sqlite_common($this->cfg); - $this->prefix = $prefix; - } + public function __construct($cfg, $prefix = null) + { + $this->cfg = array_merge($this->cfg, $cfg); + $this->db = new sqlite_common($this->cfg); + $this->prefix = $prefix; + } - function get ($name, $get_miss_key_callback = '', $ttl = 604800) - { - if (empty($name)) - { - return is_array($name) ? array() : false; - } - $this->db->shard($name); - $cached_items = array(); - $this->prefix_len = strlen($this->prefix); - $this->prefix_sql = SQLite3::escapeString($this->prefix); + public function get($name, $get_miss_key_callback = '', $ttl = 604800) + { + if (empty($name)) { + return is_array($name) ? array() : false; + } + $this->db->shard($name); + $cached_items = array(); + $this->prefix_len = strlen($this->prefix); + $this->prefix_sql = SQLite3::escapeString($this->prefix); - $name_ary = $name_sql = (array) $name; - array_deep($name_sql, 'SQLite3::escapeString'); + $name_ary = $name_sql = (array)$name; + array_deep($name_sql, 'SQLite3::escapeString'); - // get available items - $rowset = $this->db->fetch_rowset(" + // get available items + $rowset = $this->db->fetch_rowset(" SELECT cache_name, cache_value - FROM ". $this->cfg['table_name'] ." - WHERE cache_name IN('$this->prefix_sql". join("','$this->prefix_sql", $name_sql) ."') AND cache_expire_time > ". TIMENOW ." - LIMIT ". count($name) ." + FROM " . $this->cfg['table_name'] . " + WHERE cache_name IN('$this->prefix_sql" . join("','$this->prefix_sql", $name_sql) . "') AND cache_expire_time > " . TIMENOW . " + LIMIT " . count($name) . " "); - $this->db->debug('start', 'unserialize()'); - foreach ($rowset as $row) - { - $cached_items[substr($row['cache_name'], $this->prefix_len)] = unserialize($row['cache_value']); - } - $this->db->debug('stop'); + $this->db->debug('start', 'unserialize()'); + foreach ($rowset as $row) { + $cached_items[substr($row['cache_name'], $this->prefix_len)] = unserialize($row['cache_value']); + } + $this->db->debug('stop'); - // get miss items - if ($get_miss_key_callback AND $miss_key = array_diff($name_ary, array_keys($cached_items))) - { - foreach ($get_miss_key_callback($miss_key) as $k => $v) - { - $this->set($this->prefix . $k, $v, $ttl); - $cached_items[$k] = $v; - } - } - // return - if (is_array($this->prefix . $name)) - { - return $cached_items; - } - else - { - return isset($cached_items[$name]) ? $cached_items[$name] : false; - } - } + // get miss items + if ($get_miss_key_callback and $miss_key = array_diff($name_ary, array_keys($cached_items))) { + foreach ($get_miss_key_callback($miss_key) as $k => $v) { + $this->set($this->prefix . $k, $v, $ttl); + $cached_items[$k] = $v; + } + } + // return + if (is_array($this->prefix . $name)) { + return $cached_items; + } else { + return isset($cached_items[$name]) ? $cached_items[$name] : false; + } + } - function set ($name, $value, $ttl = 604800) - { - $this->db->shard($this->prefix . $name); - $name_sql = SQLite3::escapeString($this->prefix . $name); - $expire = TIMENOW + $ttl; - $value_sql = SQLite3::escapeString(serialize($value)); + public function set($name, $value, $ttl = 604800) + { + $this->db->shard($this->prefix . $name); + $name_sql = SQLite3::escapeString($this->prefix . $name); + $expire = TIMENOW + $ttl; + $value_sql = SQLite3::escapeString(serialize($value)); - $result = $this->db->query("REPLACE INTO ". $this->cfg['table_name'] ." (cache_name, cache_expire_time, cache_value) VALUES ('$name_sql', $expire, '$value_sql')"); - return (bool) $result; - } + $result = $this->db->query("REPLACE INTO " . $this->cfg['table_name'] . " (cache_name, cache_expire_time, cache_value) VALUES ('$name_sql', $expire, '$value_sql')"); + return (bool)$result; + } - function rm ($name = '') - { - if ($name) - { - $this->db->shard($this->prefix . $name); - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'"); - } - else - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name']); - } - return (bool) $result; - } + public function rm($name = '') + { + if ($name) { + $this->db->shard($this->prefix . $name); + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name'] . " WHERE cache_name = '" . SQLite3::escapeString($this->prefix . $name) . "'"); + } else { + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name']); + } + return (bool)$result; + } - function gc ($expire_time = TIMENOW) - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time"); - return ($result) ? $this->db->changes() : 0; - } + public function gc($expire_time = TIMENOW) + { + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name'] . " WHERE cache_expire_time < $expire_time"); + return ($result) ? $this->db->changes() : 0; + } } class sqlite_common extends cache_common { - public $cfg = array( - 'db_file_path' => 'sqlite.db', - 'table_name' => 'table_name', - 'table_schema' => 'CREATE TABLE table_name (...)', - 'pconnect' => true, - 'con_required' => true, - 'log_name' => 'SQLite', - 'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга) - 'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления) - ); - public $engine = 'SQLite'; - public $dbh = null; - public $connected = false; - public $shard_val = false; + public $cfg = array( + 'db_file_path' => 'sqlite.db', + 'table_name' => 'table_name', + 'table_schema' => 'CREATE TABLE table_name (...)', + 'pconnect' => true, + 'con_required' => true, + 'log_name' => 'SQLite', + 'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга) + 'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления) + ); + public $engine = 'SQLite'; + public $dbh = null; + public $connected = false; + public $shard_val = false; - public $table_create_attempts = 0; + public $table_create_attempts = 0; - public function __construct ($cfg) - { - $this->cfg = array_merge($this->cfg, $cfg); - $this->dbg_enabled = sql_dbg_enabled(); - } + public function __construct($cfg) + { + $this->cfg = array_merge($this->cfg, $cfg); + $this->dbg_enabled = sql_dbg_enabled(); + } - public function connect () - { - $this->cur_query = ($this->dbg_enabled) ? 'connect to: '. $this->cfg['db_file_path'] : 'connect'; - $this->debug('start'); + public function connect() + { + $this->cur_query = ($this->dbg_enabled) ? 'connect to: ' . $this->cfg['db_file_path'] : 'connect'; + $this->debug('start'); - if (@$this->dbh = new SQLite3($this->cfg['db_file_path'])) - { - $this->connected = true; - } + if (@$this->dbh = new SQLite3($this->cfg['db_file_path'])) { + $this->connected = true; + } - if (DBG_LOG) dbg_log(' ', $this->cfg['log_name'] .'-connect'. ($this->connected ? '' : '-FAIL')); + if (DBG_LOG) { + dbg_log(' ', $this->cfg['log_name'] . '-connect' . ($this->connected ? '' : '-FAIL')); + } - if (!$this->connected && $this->cfg['con_required']) - { - trigger_error('SQLite not connected', E_USER_ERROR); - } + if (!$this->connected && $this->cfg['con_required']) { + trigger_error('SQLite not connected', E_USER_ERROR); + } - $this->debug('stop'); - $this->cur_query = null; - } + $this->debug('stop'); + $this->cur_query = null; + } - public function create_table () - { - $this->table_create_attempts++; - return $this->dbh->query($this->cfg['table_schema']); - } + public function create_table() + { + $this->table_create_attempts++; + return $this->dbh->query($this->cfg['table_schema']); + } - public function shard ($name) - { - $type = $this->cfg['shard_type']; + public function shard($name) + { + $type = $this->cfg['shard_type']; - if ($type == 'none') return; - if (is_array($name)) trigger_error('cannot shard: $name is array', E_USER_ERROR); + if ($type == 'none') { + return; + } + if (is_array($name)) { + trigger_error('cannot shard: $name is array', E_USER_ERROR); + } - // define shard_val - if ($type == 'string') - { - $shard_val = substr($name, 0, $this->cfg['shard_val']); - } - else - { - $shard_val = $name % $this->cfg['shard_val']; - } - // все запросы должны быть к одному и тому же шарду - if ($this->shard_val !== false) - { - if ($shard_val != $this->shard_val) - { - trigger_error("shard cannot be reassigned. [{$this->shard_val}, $shard_val, $name]", E_USER_ERROR); - } - else - { - return; - } - } - $this->shard_val = $shard_val; - $this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']); - } + // define shard_val + if ($type == 'string') { + $shard_val = substr($name, 0, $this->cfg['shard_val']); + } else { + $shard_val = $name % $this->cfg['shard_val']; + } + // все запросы должны быть к одному и тому же шарду + if ($this->shard_val !== false) { + if ($shard_val != $this->shard_val) { + trigger_error("shard cannot be reassigned. [{$this->shard_val}, $shard_val, $name]", E_USER_ERROR); + } else { + return; + } + } + $this->shard_val = $shard_val; + $this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']); + } - public function query ($query) - { - if (!$this->connected) $this->connect(); + public function query($query) + { + if (!$this->connected) { + $this->connect(); + } - $this->cur_query = $query; - $this->debug('start'); + $this->cur_query = $query; + $this->debug('start'); - if (!$result = @$this->dbh->query($query)) - { - $rowsresult = $this->dbh->query("PRAGMA table_info({$this->cfg['table_name']})"); - $rowscount = 0; - while ($row = $rowsresult->fetchArray(SQLITE3_ASSOC)) - { - $rowscount++; - } - if (!$this->table_create_attempts && !$rowscount) - { - if ($this->create_table()) - { - $result = $this->dbh->query($query); - } - } - if (!$result) - { - $this->trigger_error($this->get_error_msg()); - } - } + if (!$result = @$this->dbh->query($query)) { + $rowsresult = $this->dbh->query("PRAGMA table_info({$this->cfg['table_name']})"); + $rowscount = 0; + while ($row = $rowsresult->fetchArray(SQLITE3_ASSOC)) { + $rowscount++; + } + if (!$this->table_create_attempts && !$rowscount) { + if ($this->create_table()) { + $result = $this->dbh->query($query); + } + } + if (!$result) { + $this->trigger_error($this->get_error_msg()); + } + } - $this->debug('stop'); - $this->cur_query = null; + $this->debug('stop'); + $this->cur_query = null; - $this->num_queries++; + $this->num_queries++; - return $result; - } + return $result; + } - public function fetch_row ($query) - { - $result = $this->query($query); - return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false; - } + public function fetch_row($query) + { + $result = $this->query($query); + return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false; + } - public function fetch_rowset ($query) - { - $result = $this->query($query); - $rowset = array(); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) - { - $rowset[] = $row; - } - return $rowset; - } + public function fetch_rowset($query) + { + $result = $this->query($query); + $rowset = array(); + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $rowset[] = $row; + } + return $rowset; + } - public function changes () - { - return is_resource($this->dbh) ? $this->dbh->changes() : 0; - } + public function changes() + { + return is_resource($this->dbh) ? $this->dbh->changes() : 0; + } - public function escape ($str) - { - return SQLite3::escapeString($str); - } + public function escape($str) + { + return SQLite3::escapeString($str); + } - public function get_error_msg () - { - return 'SQLite error #'. ($err_code = $this->dbh->lastErrorCode()) .': '. $this->dbh->lastErrorMsg(); - } + public function get_error_msg() + { + return 'SQLite error #' . ($err_code = $this->dbh->lastErrorCode()) . ': ' . $this->dbh->lastErrorMsg(); + } - public function rm ($name = '') - { - if ($name) - { - $this->db->shard($this->prefix . $name); - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'"); - } - else - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name']); - } - return (bool) $result; - } + public function rm($name = '') + { + if ($name) { + $this->db->shard($this->prefix . $name); + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name'] . " WHERE cache_name = '" . SQLite3::escapeString($this->prefix . $name) . "'"); + } else { + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name']); + } + return (bool)$result; + } - public function gc ($expire_time = TIMENOW) - { - $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time"); - return ($result) ? sqlite_changes($this->db->dbh) : 0; - } + public function gc($expire_time = TIMENOW) + { + $result = $this->db->query("DELETE FROM " . $this->cfg['table_name'] . " WHERE cache_expire_time < $expire_time"); + return ($result) ? sqlite_changes($this->db->dbh) : 0; + } - public function trigger_error ($msg = 'DB Error') - { - if (error_reporting()) trigger_error($msg, E_USER_ERROR); - } + public function trigger_error($msg = 'DB Error') + { + if (error_reporting()) { + trigger_error($msg, E_USER_ERROR); + } + } } diff --git a/library/includes/cache/xcache.php b/library/includes/cache/xcache.php index 8da30667c..f762c43ac 100644 --- a/library/includes/cache/xcache.php +++ b/library/includes/cache/xcache.php @@ -1,67 +1,88 @@ is_installed()) - { - die('Error: XCache extension not installed'); - } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } + public function __construct($prefix = null) + { + if (!$this->is_installed()) { + die('Error: XCache extension not installed'); + } + $this->dbg_enabled = sql_dbg_enabled(); + $this->prefix = $prefix; + } - public function get ($name, $get_miss_key_callback = '', $ttl = 0) - { - $this->cur_query = "cache->get('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function get($name, $get_miss_key_callback = '', $ttl = 0) + { + $this->cur_query = "cache->get('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return xcache_get($this->prefix . $name); - } + return xcache_get($this->prefix . $name); + } - public function set ($name, $value, $ttl = 0) - { - $this->cur_query = "cache->set('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function set($name, $value, $ttl = 0) + { + $this->cur_query = "cache->set('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return xcache_set($this->prefix . $name, $value, $ttl); - } + return xcache_set($this->prefix . $name, $value, $ttl); + } - public function rm ($name = '') - { - if ($name) - { - $this->cur_query = "cache->rm('$name')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + public function rm($name = '') + { + if ($name) { + $this->cur_query = "cache->rm('$name')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return xcache_unset($this->prefix . $name); - } - else - { - xcache_clear_cache(XC_TYPE_PHP, 0); - xcache_clear_cache(XC_TYPE_VAR, 0); - return; - } - } + return xcache_unset($this->prefix . $name); + } else { + xcache_clear_cache(XC_TYPE_PHP, 0); + xcache_clear_cache(XC_TYPE_VAR, 0); + return; + } + } - public function is_installed () - { - return function_exists('xcache_get'); - } + public function is_installed() + { + return function_exists('xcache_get'); + } } diff --git a/library/includes/classes/correct.php b/library/includes/classes/correct.php index 87a40be86..14ceb602c 100644 --- a/library/includes/classes/correct.php +++ b/library/includes/classes/correct.php @@ -1,6 +1,31 @@ бюст)" - * ^ ^^ ^ - */ - const ADD_FIX = 4; + /** + * Флаг для добавления исправлений, если влючён флаг KEYBOARD_LAYOUT + * Синтаксис и пример: "(,.cn=>бюст)" + * ^ ^^ ^ + */ + const ADD_FIX = 4; - #английский (all) - private $en = '[a-zA-Z]'; + #английский (all) + private $en = '[a-zA-Z]'; - #английский (uppercase) - private $en_uc = '[A-Z]'; + #английский (uppercase) + private $en_uc = '[A-Z]'; - #английский + символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв (all) - private $en_sc = '[a-zA-Z\'`~<>,.:;{}\[\]"]'; + #английский + символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв (all) + private $en_sc = '[a-zA-Z\'`~<>,.:;{}\[\]"]'; - #символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв - private $sc = '[\'`~<>,.:;{}\[\]"]'; - private $no_sc = '[^\'`~<>,.:;{}\[\]"]'; + #символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв + private $sc = '[\'`~<>,.:;{}\[\]"]'; + private $no_sc = '[^\'`~<>,.:;{}\[\]"]'; - #русский + татарский (all) - private $tt = '[\xd0-\xd3][\x80-\xbf] + #русский + татарский (all) + private $tt = '[\xd0-\xd3][\x80-\xbf] (?<=\xd0[\x90-\xbf\x81]|\xd1[\x80-\x8f\x91]|\xd2[\x96\x97\xa2\xa3\xae\xaf\xba\xbb]|\xd3[\x98\x99\xa8\xa9])'; - #русский + татарский (uppercase) - private $tt_uc = '[\xd0\xd2\xd3][\x81-\xba] + #русский + татарский (uppercase) + private $tt_uc = '[\xd0\xd2\xd3][\x81-\xba] (?<=\xd0[\x90-\xaf\x81]|\xd2[\x96\xa2\xae\xba]|\xd3[\x98\xa8])'; - #русский + татарский (для фильтрованных текстов) (all) - private $tt_f = '[\xd0-\xd3][\x80-\xbf] + #русский + татарский (для фильтрованных текстов) (all) + private $tt_f = '[\xd0-\xd3][\x80-\xbf] #комментируем для увеличения скорости, т.к. остальные символы отфильтрованы #(?<=\xd0[\x90-\xbf\x81]|\xd1[\x80-\x8f\x91]|\xd2[\x96\x97\xa2\xa3\xae\xaf\xba\xbb]|\xd3[\x98\x99\xa8\xa9]) '; - #гласная (vowel) (lowercase) - private $vowel_lc = array( - 'tt' => '\xd0[\xb0\xb5\xb8\xbe]|\xd1[\x83\x8b\x8d\x8e\x8f\x91] #аеиоуыэюяё (гласные, 10 шт.) + #гласная (vowel) (lowercase) + private $vowel_lc = array( + 'tt' => '\xd0[\xb0\xb5\xb8\xbe]|\xd1[\x83\x8b\x8d\x8e\x8f\x91] #аеиоуыэюяё (гласные, 10 шт.) #| \xd0[\x90\x95\x98\x9e\xa3\xab\xad\xae\xaf\x81] #АЕИОУЫЭЮЯЁ (гласные, 10 шт.) ', - 'en' => '[aeiouy]', #латинских 6 шт. - ); + 'en' => '[aeiouy]', #латинских 6 шт. + ); - #согласная (consonant) + графические знаки для русского языка (ъ, ь) (lowercase) - private $consonant_lc = array( - 'tt' => '\xd0[\xb1-\xb4\xb6\xb7\xb9\xba-\xbd\xbf]|\xd1[\x80\x81\x82\x84-\x89\x8a\x8c] #бвгджзйклмнпрстфхцчшщ ъь (согласные, 21+2 шт.) + #согласная (consonant) + графические знаки для русского языка (ъ, ь) (lowercase) + private $consonant_lc = array( + 'tt' => '\xd0[\xb1-\xb4\xb6\xb7\xb9\xba-\xbd\xbf]|\xd1[\x80\x81\x82\x84-\x89\x8a\x8c] #бвгджзйклмнпрстфхцчшщ ъь (согласные, 21+2 шт.) #| \xd0[\x91-\x94\x96\x97\x99\x9a-\x9d\x9f-\xa2\xa4-\xa9\xaa\xac] #БВГДЖЗЙКЛМНПРСТФХЦЧШЩ ЪЬ (согласные, 21+2 шт.) ', - 'en' => '[bcdfghjklmnpqrstvwxz]', #латинских 20 шт. - ); + 'en' => '[bcdfghjklmnpqrstvwxz]', #латинских 20 шт. + ); - private $words_exceptions = array( - 'tt' => array( - 'трлн' => null, - 'ющенко' => null, - 'мебельград' => null, - 'дэнис' => null, - ), - 'en' => array( - 'heuer' => null, - ), - ); + private $words_exceptions = array( + 'tt' => array( + 'трлн' => null, + 'ющенко' => null, + 'мебельград' => null, + 'дэнис' => null, + ), + 'en' => array( + 'heuer' => null, + ), + ); - #русские буквы, похожие на англ. (uppercase) - private $ru_similar_uc = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5]"; + #русские буквы, похожие на англ. (uppercase) + private $ru_similar_uc = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5]"; - #русские буквы, похожие на англ. (all) - private $ru_similar = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5\xb0\xb5\xbe]|\xd1[\x80\x81\x83\x85]"; + #русские буквы, похожие на англ. (all) + private $ru_similar = "\xd0[\x90\x92\x95\x9a\x9c\x9d\x9e\xa0-\xa3\xa5\xb0\xb5\xbe]|\xd1[\x80\x81\x83\x85]"; - #англ. буквы, похожие на русские (uppercase) - private $en_similar_uc = '[ABEKMHOPCTYX]'; + #англ. буквы, похожие на русские (uppercase) + private $en_similar_uc = '[ABEKMHOPCTYX]'; - /* + /* #$tt_fake = '\xd0[\xb0\xb5\xbe\x90\x92\x95\x9a\x9c\x9d\x9e\xa0\xa1\xa2\xa3\xa5]|\xd1[\x80\x81\x83\x85]'; $tt_fake = '[\xd0\xd1][\x80-\xbe] (?<=\xd0[\xb0\xb5\xbe\x90\x92\x95\x9a\x9c\x9d\x9e\xa0\xa1\xa2\xa3\xa5]|\xd1[\x80\x81\x83\x85])'; $en_fake = '[aeopcyxABEKMHOPCTYX]'; - */ + */ - #уникальные русские буквы - /* + #уникальные русские буквы + /* CASE_UPPER, case_lower "\xd0\x81", "\xd1\x91", #Ё ё "\xd0\x91", "\xd0\xb1", #Б б @@ -170,13 +194,13 @@ class Text_LangCorrect "\xd0\xad", "\xd1\x8d", #Э э "\xd0\xae", "\xd1\x8e", #Ю ю "\xd0\xaf", "\xd1\x8f", #Я я - */ - #$tt_uniq = "\xd0[\xb1-\xb4\xb6-\xbb\xbd\xbf\x81\x91-\x94\x96-\x99\x9b\x9f\xa4\xa6-\xaf]|\xd1[\x82\x84\x86-\x8f\x91]"; - private $tt_uniq = "[\xd0\xd1][\x82-\xbf] + */ + #$tt_uniq = "\xd0[\xb1-\xb4\xb6-\xbb\xbd\xbf\x81\x91-\x94\x96-\x99\x9b\x9f\xa4\xa6-\xaf]|\xd1[\x82\x84\x86-\x8f\x91]"; + private $tt_uniq = "[\xd0\xd1][\x82-\xbf] (?<=\xd0[\xb1-\xb4\xb6-\xbb\xbd\xbf\x81\x91-\x94\x96-\x99\x9b\x9f\xa4\xa6-\xaf]|\xd1[\x82\x84\x86-\x8f\x91])"; - #уникальные латинские буквы - /* + #уникальные латинские буквы + /* CASE_UPPER, case_lower "\x42", "\x62", #B b "\x44", "\x64", #D d @@ -196,2609 +220,2611 @@ class Text_LangCorrect "\x56", "\x76", #V v "\x57", "\x77", #W w "\x5a", "\x7a", #Z z - */ - private $en_uniq = "[\x42\x44\x46\x49\x4a\x4c\x4e\x51\x52\x53\x55\x57\x56\x5a\x62\x64\x66\x68\x69\x6a-\x6e\x71-\x77\x7a]"; + */ + private $en_uniq = "[\x42\x44\x46\x49\x4a\x4c\x4e\x51\x52\x53\x55\x57\x56\x5a\x62\x64\x66\x68\x69\x6a-\x6e\x71-\x77\x7a]"; - private $table_flip; #array - private $words; #corrected words - private $en_correct; #string - private $tt_correct; #string - private $mode; #bool + private $table_flip; #array + private $words; #corrected words + private $en_correct; #string + private $tt_correct; #string + private $mode; #bool - private $is_flip = false; - private $method = 0; + private $is_flip = false; + private $method = 0; - private $table = array( - #метод 0: таблица исправления ошибочно набранных букв, которые выглядят одинаково (русский <--> английский) - 0 => array( - #lowercase #UPPERCASE - "\xd0\xb0" => 'a', "\xd0\x90" => 'A', - "\xd0\x92" => 'B', - "\xd0\xb5" => 'e', "\xd0\x95" => 'E', - "\xd0\x9a" => 'K', - "\xd0\x9c" => 'M', - "\xd0\x9d" => 'H', - "\xd0\xbe" => 'o', "\xd0\x9e" => 'O', - "\xd1\x80" => 'p', "\xd0\xa0" => 'P', - "\xd1\x81" => 'c', "\xd0\xa1" => 'C', - "\xd0\xa2" => 'T', - "\xd1\x83" => 'y', "\xd0\xa3" => 'Y', - "\xd1\x85" => 'x', "\xd0\xa5" => 'X', - ), - #метод 1: таблица исправления ошибочно набранных букв в другой раскладке клавиатуры (русский <--> английский) - 1 => array( - #CASE_UPPER #case_lower - "\xd0\x81" => '~', "\xd1\x91" => '`', #Ё ё - "\xd0\x90" => 'F', "\xd0\xb0" => 'f', #А а - "\xd0\x91" => '<', "\xd0\xb1" => ',', #Б б - "\xd0\x92" => 'D', "\xd0\xb2" => 'd', #В в - "\xd0\x93" => 'U', "\xd0\xb3" => 'u', #Г г - "\xd0\x94" => 'L', "\xd0\xb4" => 'l', #Д д - "\xd0\x95" => 'T', "\xd0\xb5" => 't', #Е е - "\xd0\x96" => ':', "\xd0\xb6" => ';', #Ж ж - "\xd0\x97" => 'P', "\xd0\xb7" => 'p', #З з - "\xd0\x98" => 'B', "\xd0\xb8" => 'b', #И и - "\xd0\x99" => 'Q', "\xd0\xb9" => 'q', #Й й - "\xd0\x9a" => 'R', "\xd0\xba" => 'r', #К к - "\xd0\x9b" => 'K', "\xd0\xbb" => 'k', #Л л - "\xd0\x9c" => 'V', "\xd0\xbc" => 'v', #М м - "\xd0\x9d" => 'Y', "\xd0\xbd" => 'y', #Н н - "\xd0\x9e" => 'J', "\xd0\xbe" => 'j', #О о - "\xd0\x9f" => 'G', "\xd0\xbf" => 'g', #П п - #CASE_UPPER #case_lower - "\xd0\xa0" => 'H', "\xd1\x80" => 'h', #Р р - "\xd0\xa1" => 'C', "\xd1\x81" => 'c', #С с - "\xd0\xa2" => 'N', "\xd1\x82" => 'n', #Т т - "\xd0\xa3" => 'E', "\xd1\x83" => 'e', #У у - "\xd0\xa4" => 'A', "\xd1\x84" => 'a', #Ф ф - "\xd0\xa5" => '{', "\xd1\x85" => '[', #Х х - "\xd0\xa6" => 'W', "\xd1\x86" => 'w', #Ц ц - "\xd0\xa7" => 'X', "\xd1\x87" => 'x', #Ч ч - "\xd0\xa8" => 'I', "\xd1\x88" => 'i', #Ш ш - "\xd0\xa9" => 'O', "\xd1\x89" => 'o', #Щ щ - "\xd0\xaa" => '}', "\xd1\x8a" => ']', #Ъ ъ - "\xd0\xab" => 'S', "\xd1\x8b" => 's', #Ы ы - "\xd0\xac" => 'M', "\xd1\x8c" => 'm', #Ь ь - "\xd0\xad" => '"', "\xd1\x8d" => "'", #Э э - "\xd0\xae" => '>', "\xd1\x8e" => '.', #Ю ю - "\xd0\xaf" => 'Z', "\xd1\x8f" => 'z', #Я я - ), - ); + private $table = array( + #метод 0: таблица исправления ошибочно набранных букв, которые выглядят одинаково (русский <--> английский) + 0 => array( + #lowercase #UPPERCASE + "\xd0\xb0" => 'a', "\xd0\x90" => 'A', + "\xd0\x92" => 'B', + "\xd0\xb5" => 'e', "\xd0\x95" => 'E', + "\xd0\x9a" => 'K', + "\xd0\x9c" => 'M', + "\xd0\x9d" => 'H', + "\xd0\xbe" => 'o', "\xd0\x9e" => 'O', + "\xd1\x80" => 'p', "\xd0\xa0" => 'P', + "\xd1\x81" => 'c', "\xd0\xa1" => 'C', + "\xd0\xa2" => 'T', + "\xd1\x83" => 'y', "\xd0\xa3" => 'Y', + "\xd1\x85" => 'x', "\xd0\xa5" => 'X', + ), + #метод 1: таблица исправления ошибочно набранных букв в другой раскладке клавиатуры (русский <--> английский) + 1 => array( + #CASE_UPPER #case_lower + "\xd0\x81" => '~', "\xd1\x91" => '`', #Ё ё + "\xd0\x90" => 'F', "\xd0\xb0" => 'f', #А а + "\xd0\x91" => '<', "\xd0\xb1" => ',', #Б б + "\xd0\x92" => 'D', "\xd0\xb2" => 'd', #В в + "\xd0\x93" => 'U', "\xd0\xb3" => 'u', #Г г + "\xd0\x94" => 'L', "\xd0\xb4" => 'l', #Д д + "\xd0\x95" => 'T', "\xd0\xb5" => 't', #Е е + "\xd0\x96" => ':', "\xd0\xb6" => ';', #Ж ж + "\xd0\x97" => 'P', "\xd0\xb7" => 'p', #З з + "\xd0\x98" => 'B', "\xd0\xb8" => 'b', #И и + "\xd0\x99" => 'Q', "\xd0\xb9" => 'q', #Й й + "\xd0\x9a" => 'R', "\xd0\xba" => 'r', #К к + "\xd0\x9b" => 'K', "\xd0\xbb" => 'k', #Л л + "\xd0\x9c" => 'V', "\xd0\xbc" => 'v', #М м + "\xd0\x9d" => 'Y', "\xd0\xbd" => 'y', #Н н + "\xd0\x9e" => 'J', "\xd0\xbe" => 'j', #О о + "\xd0\x9f" => 'G', "\xd0\xbf" => 'g', #П п + #CASE_UPPER #case_lower + "\xd0\xa0" => 'H', "\xd1\x80" => 'h', #Р р + "\xd0\xa1" => 'C', "\xd1\x81" => 'c', #С с + "\xd0\xa2" => 'N', "\xd1\x82" => 'n', #Т т + "\xd0\xa3" => 'E', "\xd1\x83" => 'e', #У у + "\xd0\xa4" => 'A', "\xd1\x84" => 'a', #Ф ф + "\xd0\xa5" => '{', "\xd1\x85" => '[', #Х х + "\xd0\xa6" => 'W', "\xd1\x86" => 'w', #Ц ц + "\xd0\xa7" => 'X', "\xd1\x87" => 'x', #Ч ч + "\xd0\xa8" => 'I', "\xd1\x88" => 'i', #Ш ш + "\xd0\xa9" => 'O', "\xd1\x89" => 'o', #Щ щ + "\xd0\xaa" => '}', "\xd1\x8a" => ']', #Ъ ъ + "\xd0\xab" => 'S', "\xd1\x8b" => 's', #Ы ы + "\xd0\xac" => 'M', "\xd1\x8c" => 'm', #Ь ь + "\xd0\xad" => '"', "\xd1\x8d" => "'", #Э э + "\xd0\xae" => '>', "\xd1\x8e" => '.', #Ю ю + "\xd0\xaf" => 'Z', "\xd1\x8f" => 'z', #Я я + ), + ); - #несуществующие N-граммы для гласных букв - private $vowels3_lc = array( - 'en' => array( - 'aea' => 0, - 'aei' => 1, - 'aeo' => 2, - 'aeu' => 3, - 'aia' => 4, - 'aie' => 5, - 'aii' => 6, - 'aoi' => 7, - 'aou' => 8, - 'aue' => 9, - 'aya' => 10, - 'aye' => 11, - 'ayi' => 12, - 'ayo' => 13, - 'ayu' => 14, - 'eae' => 15, - 'eau' => 16, - 'eea' => 17, - 'eei' => 18, - 'eeu' => 19, - 'eia' => 20, - 'eiu' => 21, - 'eoi' => 22, - 'eou' => 23, - 'eya' => 24, - 'eye' => 25, - 'eyi' => 26, - 'eyo' => 27, - 'iae' => 28, - 'iai' => 29, - 'iao' => 30, - 'iau' => 31, - 'iei' => 32, - 'ieu' => 33, - 'ioa' => 34, - 'ioe' => 35, - 'iou' => 36, - 'iya' => 37, - 'oae' => 38, - 'oea' => 39, - 'oei' => 40, - 'oeo' => 41, - 'oeu' => 42, - 'oey' => 43, - 'oia' => 44, - 'oie' => 45, - 'ooe' => 46, - 'ooi' => 47, - 'oou' => 48, - 'oua' => 49, - 'oue' => 50, - 'oui' => 51, - 'oya' => 52, - 'oye' => 53, - 'oyi' => 54, - 'oyo' => 55, - 'uae' => 56, - 'uai' => 57, - 'uay' => 58, - 'uea' => 59, - 'uee' => 60, - 'uei' => 61, - 'ueo' => 62, - 'ueu' => 63, - 'uey' => 64, - 'uia' => 65, - 'uie' => 66, - 'uio' => 67, - 'uiu' => 68, - 'uoa' => 69, - 'uoi' => 70, - 'uou' => 71, - 'uoy' => 72, - 'uya' => 73, - 'uye' => 74, - 'uyi' => 75, - 'yae' => 76, - 'yao' => 77, - 'yau' => 78, - 'yea' => 79, - 'yei' => 80, - 'yeo' => 81, - 'yey' => 82, - 'yie' => 83, - 'yoi' => 84, - 'you' => 85, - 'yoy' => 86, - 'yua' => 87, - ), - 'tt' => array( - 'аау' => 0, - 'аео' => 1, - 'аеу' => 2, - 'аиа' => 3, - 'аио' => 4, - 'аиу' => 5, - 'аои' => 6, - 'ауэ' => 7, - 'аяя' => 8, - 'еаэ' => 9, - 'еее' => 10, - 'еео' => 11, - 'еоа' => 12, - 'еои' => 13, - 'еоо' => 14, - 'еую' => 15, - 'еуя' => 16, - 'еуё' => 17, - 'иау' => 18, - 'иео' => 19, - 'иие' => 20, - 'иоа' => 21, - 'иои' => 22, - 'иоу' => 23, - 'иоэ' => 24, - 'ияе' => 25, - 'ияи' => 26, - 'ияю' => 27, - 'оаэ' => 28, - 'оео' => 29, - 'оею' => 30, - 'оие' => 31, - 'оуе' => 32, - 'оуя' => 33, - 'оюе' => 34, - 'оюю' => 35, - 'ояе' => 36, - 'уео' => 37, - 'уюю' => 38, - ), - ); + #несуществующие N-граммы для гласных букв + private $vowels3_lc = array( + 'en' => array( + 'aea' => 0, + 'aei' => 1, + 'aeo' => 2, + 'aeu' => 3, + 'aia' => 4, + 'aie' => 5, + 'aii' => 6, + 'aoi' => 7, + 'aou' => 8, + 'aue' => 9, + 'aya' => 10, + 'aye' => 11, + 'ayi' => 12, + 'ayo' => 13, + 'ayu' => 14, + 'eae' => 15, + 'eau' => 16, + 'eea' => 17, + 'eei' => 18, + 'eeu' => 19, + 'eia' => 20, + 'eiu' => 21, + 'eoi' => 22, + 'eou' => 23, + 'eya' => 24, + 'eye' => 25, + 'eyi' => 26, + 'eyo' => 27, + 'iae' => 28, + 'iai' => 29, + 'iao' => 30, + 'iau' => 31, + 'iei' => 32, + 'ieu' => 33, + 'ioa' => 34, + 'ioe' => 35, + 'iou' => 36, + 'iya' => 37, + 'oae' => 38, + 'oea' => 39, + 'oei' => 40, + 'oeo' => 41, + 'oeu' => 42, + 'oey' => 43, + 'oia' => 44, + 'oie' => 45, + 'ooe' => 46, + 'ooi' => 47, + 'oou' => 48, + 'oua' => 49, + 'oue' => 50, + 'oui' => 51, + 'oya' => 52, + 'oye' => 53, + 'oyi' => 54, + 'oyo' => 55, + 'uae' => 56, + 'uai' => 57, + 'uay' => 58, + 'uea' => 59, + 'uee' => 60, + 'uei' => 61, + 'ueo' => 62, + 'ueu' => 63, + 'uey' => 64, + 'uia' => 65, + 'uie' => 66, + 'uio' => 67, + 'uiu' => 68, + 'uoa' => 69, + 'uoi' => 70, + 'uou' => 71, + 'uoy' => 72, + 'uya' => 73, + 'uye' => 74, + 'uyi' => 75, + 'yae' => 76, + 'yao' => 77, + 'yau' => 78, + 'yea' => 79, + 'yei' => 80, + 'yeo' => 81, + 'yey' => 82, + 'yie' => 83, + 'yoi' => 84, + 'you' => 85, + 'yoy' => 86, + 'yua' => 87, + ), + 'tt' => array( + 'аау' => 0, + 'аео' => 1, + 'аеу' => 2, + 'аиа' => 3, + 'аио' => 4, + 'аиу' => 5, + 'аои' => 6, + 'ауэ' => 7, + 'аяя' => 8, + 'еаэ' => 9, + 'еее' => 10, + 'еео' => 11, + 'еоа' => 12, + 'еои' => 13, + 'еоо' => 14, + 'еую' => 15, + 'еуя' => 16, + 'еуё' => 17, + 'иау' => 18, + 'иео' => 19, + 'иие' => 20, + 'иоа' => 21, + 'иои' => 22, + 'иоу' => 23, + 'иоэ' => 24, + 'ияе' => 25, + 'ияи' => 26, + 'ияю' => 27, + 'оаэ' => 28, + 'оео' => 29, + 'оею' => 30, + 'оие' => 31, + 'оуе' => 32, + 'оуя' => 33, + 'оюе' => 34, + 'оюю' => 35, + 'ояе' => 36, + 'уео' => 37, + 'уюю' => 38, + ), + ); - #несуществующие N-граммы для согласных букв - private $consonants4_lc = array( - 'en' => array( - 'bldg' => 0, - 'blvd' => 1, - 'bscr' => 2, - 'bstr' => 3, - 'cbcm' => 4, - 'cbft' => 5, - 'chfr' => 6, - 'chmn' => 7, - 'chsc' => 8, - 'chsh' => 9, - 'chst' => 10, - 'chth' => 11, - 'chts' => 12, - 'ckbr' => 13, - 'ckch' => 14, - 'ckcl' => 15, - 'ckdr' => 16, - 'ckgr' => 17, - 'cksc' => 18, - 'cksf' => 19, - 'cksh' => 20, - 'cksk' => 21, - 'cksl' => 22, - 'cksm' => 23, - 'cksn' => 24, - 'cksp' => 25, - 'ckst' => 26, - 'cksw' => 27, - 'ckth' => 28, - 'cktr' => 29, - 'ckwh' => 30, - 'cmps' => 31, - 'dspr' => 32, - 'dstr' => 33, - 'dthw' => 34, - 'ffsc' => 35, - 'ffsh' => 36, - 'ffsp' => 37, - 'fthl' => 38, - 'ftsm' => 39, - 'ftsp' => 40, - 'gdns' => 41, - 'ghbr' => 42, - 'ghfl' => 43, - 'ghsh' => 44, - 'ghtb' => 45, - 'ghtc' => 46, - 'ghtf' => 47, - 'ghth' => 48, - 'ghtj' => 49, - 'ghtl' => 50, - 'ghtm' => 51, - 'ghtn' => 52, - 'ghtr' => 53, - 'ghts' => 54, - 'ghtw' => 55, - 'hdbk' => 56, - 'hnst' => 57, - 'jctn' => 58, - 'khsh' => 59, - 'khst' => 60, - 'lchr' => 61, - 'ldpr' => 62, - 'ldsh' => 63, - 'ldsm' => 64, - 'ldsp' => 65, - 'ldst' => 66, - 'lfsk' => 67, - 'lfth' => 68, - 'lgth' => 69, - 'llfl' => 70, - 'llfr' => 71, - 'llph' => 72, - 'llpl' => 73, - 'llsh' => 74, - 'llsp' => 75, - 'llst' => 76, - 'lltr' => 77, - 'llwr' => 78, - 'lmcr' => 79, - 'lmsm' => 80, - 'lnrk' => 81, - 'lnsh' => 82, - 'lptr' => 83, - 'lsgr' => 84, - 'lshm' => 85, - 'lshw' => 86, - 'lstr' => 87, - 'lthf' => 88, - 'ltsf' => 89, - 'ltsh' => 90, - 'ltst' => 91, - 'mbsc' => 92, - 'mbsh' => 93, - 'mbsk' => 94, - 'mbst' => 95, - 'mddx' => 96, - 'mdnt' => 97, - 'mpbl' => 98, - 'mpgr' => 99, - 'mphl' => 100, - 'mphr' => 101, - 'mpsh' => 102, - 'mpst' => 103, - 'mptl' => 104, - 'mptn' => 105, - 'mptr' => 106, - 'mpts' => 107, - 'mscr' => 108, - 'mstr' => 109, - 'nchb' => 110, - 'nchl' => 111, - 'nchm' => 112, - 'nchn' => 113, - 'nchp' => 114, - 'nchr' => 115, - 'nchw' => 116, - 'nctl' => 117, - 'nctn' => 118, - 'ndbk' => 119, - 'ndbr' => 120, - 'ndch' => 121, - 'ndfl' => 122, - 'ndgl' => 123, - 'ndgr' => 124, - 'ndsc' => 125, - 'ndsh' => 126, - 'ndsl' => 127, - 'ndsm' => 128, - 'ndsp' => 129, - 'ndst' => 130, - 'ndsw' => 131, - 'ndth' => 132, - 'ndwr' => 133, - 'ngcr' => 134, - 'ngsg' => 135, - 'ngsh' => 136, - 'ngsm' => 137, - 'ngsp' => 138, - 'ngst' => 139, - 'ngth' => 140, - 'ngtz' => 141, - 'nksg' => 142, - 'nksh' => 143, - 'nksm' => 144, - 'nkst' => 145, - 'nsch' => 146, - 'nscr' => 147, - 'nsgr' => 148, - 'nshr' => 149, - 'nskr' => 150, - 'nspl' => 151, - 'nspr' => 152, - 'nssh' => 153, - 'nstr' => 154, - 'ntbr' => 155, - 'nthl' => 156, - 'nthr' => 157, - 'nths' => 158, - 'ntsh' => 159, - 'ntsm' => 160, - 'phth' => 161, - 'pstr' => 162, - 'pthr' => 163, - 'pths' => 164, - 'ptwr' => 165, - 'rbst' => 166, - 'rchb' => 167, - 'rchd' => 168, - 'rchl' => 169, - 'rchm' => 170, - 'rchn' => 171, - 'rchp' => 172, - 'rchw' => 173, - 'rdsh' => 174, - 'rdsm' => 175, - 'rdst' => 176, - 'rghs' => 177, - 'rkpl' => 178, - 'rksc' => 179, - 'rksh' => 180, - 'rksk' => 181, - 'rksm' => 182, - 'rksp' => 183, - 'rkst' => 184, - 'rldl' => 185, - 'rldw' => 186, - 'rlfr' => 187, - 'rmch' => 188, - 'rmst' => 189, - 'rmth' => 190, - 'rnbl' => 191, - 'rndl' => 192, - 'rnsk' => 193, - 'rnsp' => 194, - 'rnst' => 195, - 'rsch' => 196, - 'rscr' => 197, - 'rshl' => 198, - 'rshn' => 199, - 'rspr' => 200, - 'rstl' => 201, - 'rstr' => 202, - 'rsts' => 203, - 'rstw' => 204, - 'rtbr' => 205, - 'rtch' => 206, - 'rtcr' => 207, - 'rthb' => 208, - 'rthc' => 209, - 'rthd' => 210, - 'rthf' => 211, - 'rthl' => 212, - 'rthm' => 213, - 'rthq' => 214, - 'rthr' => 215, - 'rths' => 216, - 'rthw' => 217, - 'rtsh' => 218, - 'rtsm' => 219, - 'rtsp' => 220, - 'rtsw' => 221, - 'schl' => 222, - 'schm' => 223, - 'schn' => 224, - 'schw' => 225, - 'scrp' => 226, - 'sgmt' => 227, - 'shcl' => 228, - 'shkh' => 229, - 'shpr' => 230, - 'shpt' => 231, - 'shst' => 232, - 'shtr' => 233, - 'shwh' => 234, - 'smth' => 235, - 'ssrs' => 236, - 'ssst' => 237, - 'sstd' => 238, - 'sstr' => 239, - 'stcr' => 240, - 'sthm' => 241, - 'stpl' => 242, - 'stpr' => 243, - 'stsc' => 244, - 'stwr' => 245, - 'tblt' => 246, - 'tchb' => 247, - 'tchc' => 248, - 'tchd' => 249, - 'tchf' => 250, - 'tchl' => 251, - 'tchm' => 252, - 'tchp' => 253, - 'tchw' => 254, - 'thdr' => 255, - 'thsh' => 256, - 'thsk' => 257, - 'thsp' => 258, - 'thst' => 259, - 'tsch' => 260, - 'tspr' => 261, - 'tstr' => 262, - 'tthr' => 263, - 'ttsb' => 264, - 'tzkr' => 265, - 'whsl' => 266, - 'wnbr' => 267, - 'wnpl' => 268, - 'wnsf' => 269, - 'wnsh' => 270, - 'wnsm' => 271, - 'wnsp' => 272, - 'wnst' => 273, - 'wnsw' => 274, - 'wnth' => 275, - 'wntr' => 276, - 'wrnt' => 277, - 'wsfl' => 278, - 'wspr' => 279, - 'wstr' => 280, - 'xthl' => 281, - ), - 'tt' => array( - 'блзд' => 0, - 'бльд' => 1, - 'брьс' => 2, - 'бств' => 3, - 'бстр' => 4, - 'взбл' => 5, - 'взбр' => 6, - 'взгл' => 7, - 'взгр' => 8, - 'вздв' => 9, - 'вздр' => 10, - 'врвг' => 11, - 'врск' => 12, - 'вскл' => 13, - 'вскр' => 14, - 'вспл' => 15, - 'вспр' => 16, - 'вств' => 17, - 'встр' => 18, - 'всхл' => 19, - 'всхр' => 20, - 'втск' => 21, - 'вхск' => 22, - 'грск' => 23, - 'гств' => 24, - 'гтст' => 25, - 'гшпр' => 26, - 'двзд' => 27, - 'джск' => 28, - 'дрст' => 29, - 'дскр' => 30, - 'дств' => 31, - 'дстр' => 32, - 'дтск' => 33, - 'жств' => 34, - 'звзд' => 35, - 'знст' => 36, - 'зтьс' => 37, - 'йздр' => 38, - 'йкбр' => 39, - 'йльн' => 40, - 'йншт' => 41, - 'йпфр' => 42, - 'йств' => 43, - 'йстр' => 44, - 'йтск' => 45, - 'йфст' => 46, - 'йхсв' => 47, - 'йхск' => 48, - 'йхср' => 49, - 'йхст' => 50, - 'кскл' => 51, - 'кскр' => 52, - 'кспл' => 53, - 'кспр' => 54, - 'кств' => 55, - 'кстн' => 56, - 'кстр' => 57, - 'лвст' => 58, - 'лжск' => 59, - 'лльн' => 60, - 'лльс' => 61, - 'лстр' => 62, - 'лсть' => 63, - 'льгв' => 64, - 'льдж' => 65, - 'льдк' => 66, - 'льдм' => 67, - 'льдс' => 68, - 'льдф' => 69, - 'льдц' => 70, - 'льдш' => 71, - 'льдъ' => 72, - 'льдь' => 73, - 'льзк' => 74, - 'льзн' => 75, - 'льзь' => 76, - 'лькл' => 77, - 'лькн' => 78, - 'льпн' => 79, - 'льпт' => 80, - 'льск' => 81, - 'льсн' => 82, - 'льст' => 83, - 'льтк' => 84, - 'льтм' => 85, - 'льтн' => 86, - 'льтп' => 87, - 'льтр' => 88, - 'льтс' => 89, - 'льтт' => 90, - 'льтф' => 91, - 'льфр' => 92, - 'льцг' => 93, - 'льчс' => 94, - 'льшб' => 95, - 'льшк' => 96, - 'льшн' => 97, - 'льшп' => 98, - 'льшф' => 99, - 'льшь' => 100, - 'мбль' => 101, - 'мбрс' => 102, - 'мвзв' => 103, - 'мздр' => 104, - 'мств' => 105, - 'мтск' => 106, - 'нгль' => 107, - 'нгст' => 108, - 'ндгр' => 109, - 'ндск' => 110, - 'ндсп' => 111, - 'ндшп' => 112, - 'ндшт' => 113, - 'нкск' => 114, - 'нктн' => 115, - 'нктс' => 116, - 'нсгр' => 117, - 'нскм' => 118, - 'нскр' => 119, - 'нспл' => 120, - 'нств' => 121, - 'нстк' => 122, - 'нстр' => 123, - 'нтгл' => 124, - 'нтль' => 125, - 'нтрб' => 126, - 'нтрв' => 127, - 'нтрг' => 128, - 'нтрд' => 129, - 'нтрм' => 130, - 'нтрн' => 131, - 'нтрп' => 132, - 'нтрр' => 133, - 'нтрф' => 134, - 'нтск' => 135, - 'нтст' => 136, - 'нфск' => 137, - 'нцкл' => 138, - 'нцпл' => 139, - 'нькн' => 140, - 'ньск' => 141, - 'ньчж' => 142, - 'псск' => 143, - 'пств' => 144, - 'птск' => 145, - 'рбск' => 146, - 'ргпр' => 147, - 'ргск' => 148, - 'ргфл' => 149, - 'рдск' => 150, - 'рдсм' => 151, - 'рдст' => 152, - 'рздр' => 153, - 'рзть' => 154, - 'ркгр' => 155, - 'ркск' => 156, - 'рктн' => 157, - 'рльс' => 158, - 'рмск' => 159, - 'рмтр' => 160, - 'рнск' => 161, - 'рпск' => 162, - 'рсдр' => 163, - 'рсск' => 164, - 'рств' => 165, - 'рстк' => 166, - 'рстн' => 167, - 'рстр' => 168, - 'рстс' => 169, - 'рсть' => 170, - 'ртвл' => 171, - 'ртвр' => 172, - 'ртгр' => 173, - 'рткр' => 174, - 'ртпл' => 175, - 'ртпр' => 176, - 'ртск' => 177, - 'ртсм' => 178, - 'ртшк' => 179, - 'ртьф' => 180, - 'рхзв' => 181, - 'рхпл' => 182, - 'рхпр' => 183, - 'рхсв' => 184, - 'рхск' => 185, - 'рхсм' => 186, - 'рхср' => 187, - 'рхтв' => 188, - 'рхшт' => 189, - 'рщвл' => 190, - 'рьмл' => 191, - 'скск' => 192, - 'спрь' => 193, - 'сспр' => 194, - 'ссср' => 195, - 'сств' => 196, - 'сстр' => 197, - 'ссшп' => 198, - 'ствл' => 199, - 'стрс' => 200, - 'стрш' => 201, - 'стск' => 202, - 'стьб' => 203, - 'стьд' => 204, - 'стьс' => 205, - 'ськн' => 206, - 'сьмн' => 207, - 'тмст' => 208, - 'тпрр' => 209, - 'трст' => 210, - 'тскр' => 211, - 'тств' => 212, - 'тстр' => 213, - 'ттль' => 214, - 'ттск' => 215, - 'тхск' => 216, - 'фств' => 217, - 'фстр' => 218, - 'хств' => 219, - 'хстр' => 220, - 'хткл' => 221, - 'хтск' => 222, - 'хтсм' => 223, - 'цстр' => 224, - ), - ); + #несуществующие N-граммы для согласных букв + private $consonants4_lc = array( + 'en' => array( + 'bldg' => 0, + 'blvd' => 1, + 'bscr' => 2, + 'bstr' => 3, + 'cbcm' => 4, + 'cbft' => 5, + 'chfr' => 6, + 'chmn' => 7, + 'chsc' => 8, + 'chsh' => 9, + 'chst' => 10, + 'chth' => 11, + 'chts' => 12, + 'ckbr' => 13, + 'ckch' => 14, + 'ckcl' => 15, + 'ckdr' => 16, + 'ckgr' => 17, + 'cksc' => 18, + 'cksf' => 19, + 'cksh' => 20, + 'cksk' => 21, + 'cksl' => 22, + 'cksm' => 23, + 'cksn' => 24, + 'cksp' => 25, + 'ckst' => 26, + 'cksw' => 27, + 'ckth' => 28, + 'cktr' => 29, + 'ckwh' => 30, + 'cmps' => 31, + 'dspr' => 32, + 'dstr' => 33, + 'dthw' => 34, + 'ffsc' => 35, + 'ffsh' => 36, + 'ffsp' => 37, + 'fthl' => 38, + 'ftsm' => 39, + 'ftsp' => 40, + 'gdns' => 41, + 'ghbr' => 42, + 'ghfl' => 43, + 'ghsh' => 44, + 'ghtb' => 45, + 'ghtc' => 46, + 'ghtf' => 47, + 'ghth' => 48, + 'ghtj' => 49, + 'ghtl' => 50, + 'ghtm' => 51, + 'ghtn' => 52, + 'ghtr' => 53, + 'ghts' => 54, + 'ghtw' => 55, + 'hdbk' => 56, + 'hnst' => 57, + 'jctn' => 58, + 'khsh' => 59, + 'khst' => 60, + 'lchr' => 61, + 'ldpr' => 62, + 'ldsh' => 63, + 'ldsm' => 64, + 'ldsp' => 65, + 'ldst' => 66, + 'lfsk' => 67, + 'lfth' => 68, + 'lgth' => 69, + 'llfl' => 70, + 'llfr' => 71, + 'llph' => 72, + 'llpl' => 73, + 'llsh' => 74, + 'llsp' => 75, + 'llst' => 76, + 'lltr' => 77, + 'llwr' => 78, + 'lmcr' => 79, + 'lmsm' => 80, + 'lnrk' => 81, + 'lnsh' => 82, + 'lptr' => 83, + 'lsgr' => 84, + 'lshm' => 85, + 'lshw' => 86, + 'lstr' => 87, + 'lthf' => 88, + 'ltsf' => 89, + 'ltsh' => 90, + 'ltst' => 91, + 'mbsc' => 92, + 'mbsh' => 93, + 'mbsk' => 94, + 'mbst' => 95, + 'mddx' => 96, + 'mdnt' => 97, + 'mpbl' => 98, + 'mpgr' => 99, + 'mphl' => 100, + 'mphr' => 101, + 'mpsh' => 102, + 'mpst' => 103, + 'mptl' => 104, + 'mptn' => 105, + 'mptr' => 106, + 'mpts' => 107, + 'mscr' => 108, + 'mstr' => 109, + 'nchb' => 110, + 'nchl' => 111, + 'nchm' => 112, + 'nchn' => 113, + 'nchp' => 114, + 'nchr' => 115, + 'nchw' => 116, + 'nctl' => 117, + 'nctn' => 118, + 'ndbk' => 119, + 'ndbr' => 120, + 'ndch' => 121, + 'ndfl' => 122, + 'ndgl' => 123, + 'ndgr' => 124, + 'ndsc' => 125, + 'ndsh' => 126, + 'ndsl' => 127, + 'ndsm' => 128, + 'ndsp' => 129, + 'ndst' => 130, + 'ndsw' => 131, + 'ndth' => 132, + 'ndwr' => 133, + 'ngcr' => 134, + 'ngsg' => 135, + 'ngsh' => 136, + 'ngsm' => 137, + 'ngsp' => 138, + 'ngst' => 139, + 'ngth' => 140, + 'ngtz' => 141, + 'nksg' => 142, + 'nksh' => 143, + 'nksm' => 144, + 'nkst' => 145, + 'nsch' => 146, + 'nscr' => 147, + 'nsgr' => 148, + 'nshr' => 149, + 'nskr' => 150, + 'nspl' => 151, + 'nspr' => 152, + 'nssh' => 153, + 'nstr' => 154, + 'ntbr' => 155, + 'nthl' => 156, + 'nthr' => 157, + 'nths' => 158, + 'ntsh' => 159, + 'ntsm' => 160, + 'phth' => 161, + 'pstr' => 162, + 'pthr' => 163, + 'pths' => 164, + 'ptwr' => 165, + 'rbst' => 166, + 'rchb' => 167, + 'rchd' => 168, + 'rchl' => 169, + 'rchm' => 170, + 'rchn' => 171, + 'rchp' => 172, + 'rchw' => 173, + 'rdsh' => 174, + 'rdsm' => 175, + 'rdst' => 176, + 'rghs' => 177, + 'rkpl' => 178, + 'rksc' => 179, + 'rksh' => 180, + 'rksk' => 181, + 'rksm' => 182, + 'rksp' => 183, + 'rkst' => 184, + 'rldl' => 185, + 'rldw' => 186, + 'rlfr' => 187, + 'rmch' => 188, + 'rmst' => 189, + 'rmth' => 190, + 'rnbl' => 191, + 'rndl' => 192, + 'rnsk' => 193, + 'rnsp' => 194, + 'rnst' => 195, + 'rsch' => 196, + 'rscr' => 197, + 'rshl' => 198, + 'rshn' => 199, + 'rspr' => 200, + 'rstl' => 201, + 'rstr' => 202, + 'rsts' => 203, + 'rstw' => 204, + 'rtbr' => 205, + 'rtch' => 206, + 'rtcr' => 207, + 'rthb' => 208, + 'rthc' => 209, + 'rthd' => 210, + 'rthf' => 211, + 'rthl' => 212, + 'rthm' => 213, + 'rthq' => 214, + 'rthr' => 215, + 'rths' => 216, + 'rthw' => 217, + 'rtsh' => 218, + 'rtsm' => 219, + 'rtsp' => 220, + 'rtsw' => 221, + 'schl' => 222, + 'schm' => 223, + 'schn' => 224, + 'schw' => 225, + 'scrp' => 226, + 'sgmt' => 227, + 'shcl' => 228, + 'shkh' => 229, + 'shpr' => 230, + 'shpt' => 231, + 'shst' => 232, + 'shtr' => 233, + 'shwh' => 234, + 'smth' => 235, + 'ssrs' => 236, + 'ssst' => 237, + 'sstd' => 238, + 'sstr' => 239, + 'stcr' => 240, + 'sthm' => 241, + 'stpl' => 242, + 'stpr' => 243, + 'stsc' => 244, + 'stwr' => 245, + 'tblt' => 246, + 'tchb' => 247, + 'tchc' => 248, + 'tchd' => 249, + 'tchf' => 250, + 'tchl' => 251, + 'tchm' => 252, + 'tchp' => 253, + 'tchw' => 254, + 'thdr' => 255, + 'thsh' => 256, + 'thsk' => 257, + 'thsp' => 258, + 'thst' => 259, + 'tsch' => 260, + 'tspr' => 261, + 'tstr' => 262, + 'tthr' => 263, + 'ttsb' => 264, + 'tzkr' => 265, + 'whsl' => 266, + 'wnbr' => 267, + 'wnpl' => 268, + 'wnsf' => 269, + 'wnsh' => 270, + 'wnsm' => 271, + 'wnsp' => 272, + 'wnst' => 273, + 'wnsw' => 274, + 'wnth' => 275, + 'wntr' => 276, + 'wrnt' => 277, + 'wsfl' => 278, + 'wspr' => 279, + 'wstr' => 280, + 'xthl' => 281, + ), + 'tt' => array( + 'блзд' => 0, + 'бльд' => 1, + 'брьс' => 2, + 'бств' => 3, + 'бстр' => 4, + 'взбл' => 5, + 'взбр' => 6, + 'взгл' => 7, + 'взгр' => 8, + 'вздв' => 9, + 'вздр' => 10, + 'врвг' => 11, + 'врск' => 12, + 'вскл' => 13, + 'вскр' => 14, + 'вспл' => 15, + 'вспр' => 16, + 'вств' => 17, + 'встр' => 18, + 'всхл' => 19, + 'всхр' => 20, + 'втск' => 21, + 'вхск' => 22, + 'грск' => 23, + 'гств' => 24, + 'гтст' => 25, + 'гшпр' => 26, + 'двзд' => 27, + 'джск' => 28, + 'дрст' => 29, + 'дскр' => 30, + 'дств' => 31, + 'дстр' => 32, + 'дтск' => 33, + 'жств' => 34, + 'звзд' => 35, + 'знст' => 36, + 'зтьс' => 37, + 'йздр' => 38, + 'йкбр' => 39, + 'йльн' => 40, + 'йншт' => 41, + 'йпфр' => 42, + 'йств' => 43, + 'йстр' => 44, + 'йтск' => 45, + 'йфст' => 46, + 'йхсв' => 47, + 'йхск' => 48, + 'йхср' => 49, + 'йхст' => 50, + 'кскл' => 51, + 'кскр' => 52, + 'кспл' => 53, + 'кспр' => 54, + 'кств' => 55, + 'кстн' => 56, + 'кстр' => 57, + 'лвст' => 58, + 'лжск' => 59, + 'лльн' => 60, + 'лльс' => 61, + 'лстр' => 62, + 'лсть' => 63, + 'льгв' => 64, + 'льдж' => 65, + 'льдк' => 66, + 'льдм' => 67, + 'льдс' => 68, + 'льдф' => 69, + 'льдц' => 70, + 'льдш' => 71, + 'льдъ' => 72, + 'льдь' => 73, + 'льзк' => 74, + 'льзн' => 75, + 'льзь' => 76, + 'лькл' => 77, + 'лькн' => 78, + 'льпн' => 79, + 'льпт' => 80, + 'льск' => 81, + 'льсн' => 82, + 'льст' => 83, + 'льтк' => 84, + 'льтм' => 85, + 'льтн' => 86, + 'льтп' => 87, + 'льтр' => 88, + 'льтс' => 89, + 'льтт' => 90, + 'льтф' => 91, + 'льфр' => 92, + 'льцг' => 93, + 'льчс' => 94, + 'льшб' => 95, + 'льшк' => 96, + 'льшн' => 97, + 'льшп' => 98, + 'льшф' => 99, + 'льшь' => 100, + 'мбль' => 101, + 'мбрс' => 102, + 'мвзв' => 103, + 'мздр' => 104, + 'мств' => 105, + 'мтск' => 106, + 'нгль' => 107, + 'нгст' => 108, + 'ндгр' => 109, + 'ндск' => 110, + 'ндсп' => 111, + 'ндшп' => 112, + 'ндшт' => 113, + 'нкск' => 114, + 'нктн' => 115, + 'нктс' => 116, + 'нсгр' => 117, + 'нскм' => 118, + 'нскр' => 119, + 'нспл' => 120, + 'нств' => 121, + 'нстк' => 122, + 'нстр' => 123, + 'нтгл' => 124, + 'нтль' => 125, + 'нтрб' => 126, + 'нтрв' => 127, + 'нтрг' => 128, + 'нтрд' => 129, + 'нтрм' => 130, + 'нтрн' => 131, + 'нтрп' => 132, + 'нтрр' => 133, + 'нтрф' => 134, + 'нтск' => 135, + 'нтст' => 136, + 'нфск' => 137, + 'нцкл' => 138, + 'нцпл' => 139, + 'нькн' => 140, + 'ньск' => 141, + 'ньчж' => 142, + 'псск' => 143, + 'пств' => 144, + 'птск' => 145, + 'рбск' => 146, + 'ргпр' => 147, + 'ргск' => 148, + 'ргфл' => 149, + 'рдск' => 150, + 'рдсм' => 151, + 'рдст' => 152, + 'рздр' => 153, + 'рзть' => 154, + 'ркгр' => 155, + 'ркск' => 156, + 'рктн' => 157, + 'рльс' => 158, + 'рмск' => 159, + 'рмтр' => 160, + 'рнск' => 161, + 'рпск' => 162, + 'рсдр' => 163, + 'рсск' => 164, + 'рств' => 165, + 'рстк' => 166, + 'рстн' => 167, + 'рстр' => 168, + 'рстс' => 169, + 'рсть' => 170, + 'ртвл' => 171, + 'ртвр' => 172, + 'ртгр' => 173, + 'рткр' => 174, + 'ртпл' => 175, + 'ртпр' => 176, + 'ртск' => 177, + 'ртсм' => 178, + 'ртшк' => 179, + 'ртьф' => 180, + 'рхзв' => 181, + 'рхпл' => 182, + 'рхпр' => 183, + 'рхсв' => 184, + 'рхск' => 185, + 'рхсм' => 186, + 'рхср' => 187, + 'рхтв' => 188, + 'рхшт' => 189, + 'рщвл' => 190, + 'рьмл' => 191, + 'скск' => 192, + 'спрь' => 193, + 'сспр' => 194, + 'ссср' => 195, + 'сств' => 196, + 'сстр' => 197, + 'ссшп' => 198, + 'ствл' => 199, + 'стрс' => 200, + 'стрш' => 201, + 'стск' => 202, + 'стьб' => 203, + 'стьд' => 204, + 'стьс' => 205, + 'ськн' => 206, + 'сьмн' => 207, + 'тмст' => 208, + 'тпрр' => 209, + 'трст' => 210, + 'тскр' => 211, + 'тств' => 212, + 'тстр' => 213, + 'ттль' => 214, + 'ттск' => 215, + 'тхск' => 216, + 'фств' => 217, + 'фстр' => 218, + 'хств' => 219, + 'хстр' => 220, + 'хткл' => 221, + 'хтск' => 222, + 'хтсм' => 223, + 'цстр' => 224, + ), + ); - #несуществующие биграммы в начале и конце слов - private $bigrams = array( - #ru - ' ёё' => 0, - ' ёа' => 0, - ' ёб' => 0, - ' ёв' => 0, - ' ёг' => 0, - ' ёд' => 0, - ' ёе' => 0, - ' ёз' => 0, - ' ёи' => 0, - ' ёй' => 0, - ' ён' => 0, - ' ёо' => 0, - ' ёп' => 0, - ' ёс' => 0, - ' ёт' => 0, - ' ёу' => 0, - ' ёф' => 0, - ' ёц' => 0, - ' ёч' => 0, - ' ёщ' => 0, - ' ёъ' => 0, - ' ёы' => 0, - ' ёь' => 0, - ' ёэ' => 0, - ' ёю' => 0, - ' ёя' => 0, - ' аё' => 0, - ' аа' => 0, - ' ае' => 0, - ' ач' => 0, - ' аъ' => 0, - ' аы' => 0, - ' аь' => 0, - ' аю' => 0, - ' ая' => 0, - ' бб' => 0, - ' бв' => 0, - ' бг' => 0, - ' бж' => 0, - ' бй' => 0, - ' бк' => 0, - ' бм' => 0, - ' бн' => 0, - ' бп' => 0, - ' бс' => 0, - ' бт' => 0, - ' бф' => 0, - ' бх' => 0, - ' бц' => 0, - ' бч' => 0, - ' бш' => 0, - ' бщ' => 0, - ' бъ' => 0, - ' вй' => 0, - ' вф' => 0, - ' вщ' => 0, - ' вэ' => 0, - ' вю' => 0, - ' гё' => 0, - ' гб' => 0, - ' гз' => 0, - ' гй' => 0, - ' гк' => 0, - ' гп' => 0, - ' гс' => 0, - ' гт' => 0, - ' гф' => 0, - ' гх' => 0, - ' гц' => 0, - ' гч' => 0, - ' гш' => 0, - ' гщ' => 0, - ' гъ' => 0, - ' гь' => 0, - ' гэ' => 0, - ' дб' => 0, - ' дг' => 0, - ' дд' => 0, - ' дй' => 0, - ' дк' => 0, - ' дп' => 0, - ' дс' => 0, - ' дт' => 0, - ' дф' => 0, - ' дх' => 0, - ' дц' => 0, - ' дч' => 0, - ' дш' => 0, - ' дъ' => 0, - ' дэ' => 0, - ' еа' => 0, - ' еб' => 0, - ' еи' => 0, - ' ео' => 0, - ' ет' => 0, - ' еу' => 0, - ' ец' => 0, - #' еш' => 0, - ' еъ' => 0, - ' еы' => 0, - ' еь' => 0, - ' еэ' => 0, - ' ея' => 0, - ' жз' => 0, - ' жй' => 0, - ' жк' => 0, - ' жл' => 0, - ' жп' => 0, - ' жс' => 0, - ' жт' => 0, - ' жф' => 0, - ' жх' => 0, - ' жц' => 0, - ' жч' => 0, - ' жш' => 0, - ' жщ' => 0, - ' жъ' => 0, - ' жы' => 0, - ' жь' => 0, - ' жэ' => 0, - #' жю' => 0, - ' жя' => 0, - ' зб' => 0, - ' зж' => 0, - ' зз' => 0, - ' зй' => 0, - ' зк' => 0, - ' зп' => 0, - ' зс' => 0, - ' зт' => 0, - ' зф' => 0, - ' зх' => 0, - ' зц' => 0, - ' зч' => 0, - ' зш' => 0, - ' зщ' => 0, - ' зъ' => 0, - ' зь' => 0, - ' зэ' => 0, - ' иё' => 0, - ' иа' => 0, - ' иф' => 0, - ' иц' => 0, - ' иъ' => 0, - ' иы' => 0, - ' иь' => 0, - ' иэ' => 0, - ' ия' => 0, - ' йё' => 0, - ' йа' => 0, - ' йб' => 0, - ' йв' => 0, - ' йг' => 0, - ' йд' => 0, - ' йж' => 0, - ' йз' => 0, - ' йи' => 0, - ' йй' => 0, - ' йк' => 0, - ' йл' => 0, - ' йм' => 0, - ' йн' => 0, - ' йп' => 0, - ' йр' => 0, - ' йс' => 0, - ' йт' => 0, - ' йу' => 0, - ' йф' => 0, - ' йх' => 0, - ' йц' => 0, - ' йч' => 0, - ' йш' => 0, - ' йщ' => 0, - ' йъ' => 0, - ' йы' => 0, - ' йь' => 0, - ' йэ' => 0, - ' йю' => 0, - ' йя' => 0, - ' кё' => 0, - ' кб' => 0, - ' кд' => 0, - ' кж' => 0, - ' кй' => 0, - ' кк' => 0, - ' кф' => 0, - ' кц' => 0, - ' кч' => 0, - ' кщ' => 0, - ' къ' => 0, - ' кя' => 0, - ' лв' => 0, - ' лд' => 0, - ' лз' => 0, - ' лй' => 0, - ' лк' => 0, - ' лл' => 0, - ' лм' => 0, - ' лн' => 0, - ' лп' => 0, - ' лр' => 0, - ' лс' => 0, - ' лт' => 0, - ' лф' => 0, - ' лх' => 0, - ' лц' => 0, - ' лч' => 0, - ' лш' => 0, - ' лщ' => 0, - ' лъ' => 0, - ' лэ' => 0, - ' мб' => 0, - ' мв' => 0, - ' мд' => 0, - ' мж' => 0, - ' мй' => 0, - ' мк' => 0, - ' мп' => 0, - ' мт' => 0, - ' мф' => 0, - ' мц' => 0, - ' мъ' => 0, - ' мь' => 0, - ' нб' => 0, - ' нв' => 0, - ' нг' => 0, - ' нд' => 0, - ' нж' => 0, - ' нз' => 0, - ' нй' => 0, - ' нк' => 0, - ' нл' => 0, - ' нм' => 0, - ' нн' => 0, - ' нп' => 0, - ' нс' => 0, - ' нт' => 0, - ' нф' => 0, - ' нх' => 0, - ' нц' => 0, - ' нч' => 0, - ' нш' => 0, - ' нщ' => 0, - ' нъ' => 0, - ' оё' => 0, - ' ои' => 0, - ' оу' => 0, - ' оъ' => 0, - ' оы' => 0, - ' оь' => 0, - ' оэ' => 0, - ' оя' => 0, - ' пб' => 0, - ' пв' => 0, - ' пг' => 0, - ' пд' => 0, - ' пж' => 0, - ' пз' => 0, - ' пй' => 0, - ' пк' => 0, - ' пм' => 0, - ' пп' => 0, - ' пц' => 0, - ' пщ' => 0, - ' пъ' => 0, - ' рб' => 0, - ' рг' => 0, - ' рз' => 0, - ' рй' => 0, - ' рк' => 0, - ' рл' => 0, - ' рм' => 0, - ' рн' => 0, - ' рп' => 0, - ' рр' => 0, - ' рф' => 0, - ' рх' => 0, - ' рч' => 0, - ' рш' => 0, - ' рщ' => 0, - ' ръ' => 0, - ' сй' => 0, - ' сщ' => 0, - ' тб' => 0, - ' тг' => 0, - ' тд' => 0, - ' тж' => 0, - ' тз' => 0, - ' тй' => 0, - ' тн' => 0, - ' тт' => 0, - ' тх' => 0, - ' тц' => 0, - ' тч' => 0, - ' тш' => 0, - ' тъ' => 0, - ' уу' => 0, - ' уъ' => 0, - ' уы' => 0, - ' уь' => 0, - ' фб' => 0, - ' фв' => 0, - ' фг' => 0, - ' фд' => 0, - ' фж' => 0, - ' фз' => 0, - ' фй' => 0, - ' фк' => 0, - ' фм' => 0, - ' фн' => 0, - ' фп' => 0, - ' фс' => 0, - ' фх' => 0, - ' фц' => 0, - ' фч' => 0, - ' фш' => 0, - ' фщ' => 0, - ' фъ' => 0, - ' фэ' => 0, - ' фя' => 0, - ' хё' => 0, - ' хб' => 0, - ' хг' => 0, - ' хд' => 0, - ' хж' => 0, - ' хз' => 0, - ' хй' => 0, - ' хк' => 0, - ' хп' => 0, - ' хс' => 0, - ' хт' => 0, - ' хф' => 0, - ' хц' => 0, - ' хч' => 0, - ' хш' => 0, - ' хщ' => 0, - ' хъ' => 0, - ' хы' => 0, - ' хь' => 0, - #' хэ' => 0, - ' хю' => 0, - ' хя' => 0, - ' цё' => 0, - ' цб' => 0, - ' цг' => 0, - ' цд' => 0, - ' цж' => 0, - ' цй' => 0, - ' цл' => 0, - ' цм' => 0, - ' цн' => 0, - ' цп' => 0, - ' цр' => 0, - ' цс' => 0, - ' цт' => 0, - ' цф' => 0, - ' цх' => 0, - ' цц' => 0, - ' цч' => 0, - ' цш' => 0, - ' цщ' => 0, - ' цъ' => 0, - ' ць' => 0, - ' цэ' => 0, - ' цю' => 0, - ' ця' => 0, - ' чб' => 0, - ' чг' => 0, - ' чд' => 0, - ' чж' => 0, - ' чз' => 0, - ' чй' => 0, - ' чн' => 0, - ' чп' => 0, - ' чс' => 0, - ' чф' => 0, - ' чц' => 0, - ' чч' => 0, - ' чщ' => 0, - ' чъ' => 0, - ' чы' => 0, - ' чэ' => 0, - ' чю' => 0, - ' чя' => 0, - ' шб' => 0, - ' шг' => 0, - ' шд' => 0, - ' шж' => 0, - ' шз' => 0, - ' шй' => 0, - ' шс' => 0, - ' шф' => 0, - ' шц' => 0, - ' шч' => 0, - ' шщ' => 0, - ' шъ' => 0, - ' шы' => 0, - ' шэ' => 0, - ' шю' => 0, - ' шя' => 0, - ' щб' => 0, - ' щв' => 0, - ' щг' => 0, - ' щд' => 0, - ' щж' => 0, - ' щз' => 0, - ' щй' => 0, - ' щк' => 0, - ' щл' => 0, - ' щм' => 0, - ' щн' => 0, - ' що' => 0, - ' щп' => 0, - ' щр' => 0, - ' щс' => 0, - ' щт' => 0, - ' щф' => 0, - ' щх' => 0, - ' щц' => 0, - ' щч' => 0, - ' щш' => 0, - ' щщ' => 0, - ' щъ' => 0, - ' щы' => 0, - ' щь' => 0, - ' щэ' => 0, - ' щю' => 0, - ' щя' => 0, - ' ъё' => 0, - ' ъа' => 0, - ' ъб' => 0, - ' ъв' => 0, - ' ъг' => 0, - ' ъд' => 0, - ' ъе' => 0, - ' ъж' => 0, - ' ъз' => 0, - ' ъи' => 0, - ' ъй' => 0, - ' ък' => 0, - ' ъл' => 0, - ' ъм' => 0, - ' ън' => 0, - ' ъо' => 0, - ' ъп' => 0, - ' ър' => 0, - ' ъс' => 0, - ' ът' => 0, - ' ъу' => 0, - ' ъф' => 0, - ' ъх' => 0, - ' ъц' => 0, - ' ъч' => 0, - ' ъш' => 0, - ' ъщ' => 0, - ' ъъ' => 0, - ' ъы' => 0, - ' ъь' => 0, - ' ъэ' => 0, - ' ъю' => 0, - ' ъя' => 0, - ' ыё' => 0, - ' ыа' => 0, - ' ыб' => 0, - ' ыв' => 0, - ' ыг' => 0, - ' ыд' => 0, - ' ые' => 0, - ' ыж' => 0, - ' ыз' => 0, - ' ыи' => 0, - ' ый' => 0, - ' ык' => 0, - ' ыл' => 0, - ' ын' => 0, - ' ыо' => 0, - ' ып' => 0, - ' ыр' => 0, - ' ыс' => 0, - ' ыт' => 0, - ' ыу' => 0, - ' ыф' => 0, - ' ых' => 0, - ' ыц' => 0, - ' ыч' => 0, - ' ыш' => 0, - ' ыщ' => 0, - ' ыъ' => 0, - ' ыы' => 0, - ' ыь' => 0, - ' ыэ' => 0, - ' ыю' => 0, - ' ыя' => 0, - ' ьё' => 0, - ' ьа' => 0, - ' ьб' => 0, - ' ьв' => 0, - ' ьг' => 0, - ' ьд' => 0, - ' ье' => 0, - ' ьж' => 0, - ' ьз' => 0, - ' ьи' => 0, - ' ьй' => 0, - ' ьк' => 0, - ' ьл' => 0, - ' ьм' => 0, - ' ьн' => 0, - ' ьо' => 0, - ' ьп' => 0, - ' ьр' => 0, - ' ьс' => 0, - ' ьт' => 0, - ' ьу' => 0, - ' ьф' => 0, - ' ьх' => 0, - ' ьц' => 0, - ' ьч' => 0, - ' ьш' => 0, - ' ьщ' => 0, - ' ьъ' => 0, - ' ьы' => 0, - ' ьь' => 0, - ' ьэ' => 0, - ' ью' => 0, - ' ья' => 0, - ' эё' => 0, - ' эа' => 0, - ' эе' => 0, - ' эи' => 0, - ' эц' => 0, - ' эч' => 0, - ' эщ' => 0, - ' эъ' => 0, - ' эы' => 0, - ' эь' => 0, - ' ээ' => 0, - ' эю' => 0, - ' юё' => 0, - ' юе' => 0, - ' юи' => 0, - ' юй' => 0, - ' юо' => 0, - ' юу' => 0, - ' юц' => 0, - ' юш' => 0, - ' ющ' => 0, - ' юъ' => 0, - ' юы' => 0, - ' юь' => 0, - ' юэ' => 0, - ' юя' => 0, - ' яё' => 0, - ' яа' => 0, - ' яе' => 0, - ' яж' => 0, - ' яо' => 0, - ' яу' => 0, - ' яф' => 0, - ' яц' => 0, - ' яъ' => 0, - ' яы' => 0, - ' яь' => 0, - ' яэ' => 0, - ' яю' => 0, - ' яя' => 0, - 'ёё' => 0, - 'ёё ' => 0, - 'ёа' => 0, - 'ёа ' => 0, - 'ёг ' => 0, - 'ёе' => 0, - 'ёе ' => 0, - 'ёи' => 0, - 'ёи ' => 0, - 'ёй' => 0, - 'ёо' => 0, - 'ёо ' => 0, - 'ёу' => 0, - 'ёу ' => 0, - 'ёф' => 0, - 'ёф ' => 0, - 'ёц ' => 0, - 'ёч ' => 0, - 'ёщ ' => 0, - 'ёъ' => 0, - 'ёъ ' => 0, - 'ёы' => 0, - 'ёы ' => 0, - 'ёь' => 0, - 'ёь ' => 0, - 'ёэ' => 0, - 'ёэ ' => 0, - 'ёю' => 0, - 'ёя' => 0, - 'ёя ' => 0, - 'аё ' => 0, - 'аа ' => 0, - 'аъ' => 0, - 'аъ ' => 0, - 'аы' => 0, - 'аы ' => 0, - 'аь' => 0, - 'аь ' => 0, - 'аэ ' => 0, - 'бё ' => 0, - 'бб ' => 0, - 'бв ' => 0, - 'бг ' => 0, - 'бд ' => 0, - 'бж ' => 0, - 'бз ' => 0, - 'бй' => 0, - 'бй ' => 0, - 'бк ' => 0, - 'бм ' => 0, - 'бн ' => 0, - 'бп ' => 0, - 'бт ' => 0, - 'бф ' => 0, - 'бх ' => 0, - 'бц ' => 0, - 'бч ' => 0, - 'бш ' => 0, - 'бщ ' => 0, - 'бъ ' => 0, - 'бэ ' => 0, - 'вё ' => 0, - 'вб ' => 0, - 'вв ' => 0, - 'вд ' => 0, - 'вж' => 0, - 'вж ' => 0, - 'вз ' => 0, - 'вй' => 0, - 'вй ' => 0, - 'вл ' => 0, - 'вп ' => 0, - 'вф ' => 0, - 'вц ' => 0, - 'вч ' => 0, - 'вщ ' => 0, - 'въ' => 0, - 'въ ' => 0, - 'вэ ' => 0, - 'гё' => 0, - 'гё ' => 0, - 'гб ' => 0, - 'гг ' => 0, - 'гж' => 0, - 'гж ' => 0, - 'гз ' => 0, - 'гй' => 0, - 'гй ' => 0, - 'гк ' => 0, - 'гн ' => 0, - 'гп ' => 0, - 'гф ' => 0, - 'гх' => 0, - 'гх ' => 0, - 'гц' => 0, - 'гц ' => 0, - 'гч ' => 0, - 'гш ' => 0, - 'гщ ' => 0, - 'гъ' => 0, - 'гъ ' => 0, - 'гы ' => 0, - 'гь' => 0, - 'гь ' => 0, - 'гэ ' => 0, - 'гю' => 0, - 'гю ' => 0, - 'гя' => 0, - 'гя ' => 0, - 'дё ' => 0, - 'дб ' => 0, - 'дг ' => 0, - 'дд ' => 0, - 'дй' => 0, - 'дй ' => 0, - 'дк ' => 0, - 'дм ' => 0, - 'дн ' => 0, - 'дп ' => 0, - 'дс ' => 0, - 'дф ' => 0, - 'дх ' => 0, - 'дц ' => 0, - 'дч ' => 0, - 'дш ' => 0, - 'дщ ' => 0, - 'дъ ' => 0, - 'еа ' => 0, - 'еу ' => 0, - 'еъ' => 0, - 'еъ ' => 0, - 'еы' => 0, - 'еы ' => 0, - 'еь' => 0, - 'еь ' => 0, - 'еэ ' => 0, - 'жё ' => 0, - 'жв ' => 0, - 'жг ' => 0, - 'жж ' => 0, - 'жз ' => 0, - 'жй' => 0, - 'жй ' => 0, - 'жк ' => 0, - 'жл ' => 0, - 'жн ' => 0, - 'жп ' => 0, - 'жр ' => 0, - 'жс ' => 0, - 'жт ' => 0, - 'жф ' => 0, - 'жх ' => 0, - 'жц ' => 0, - 'жч ' => 0, - 'жш' => 0, - 'жш ' => 0, - 'жщ' => 0, - 'жщ ' => 0, - 'жъ' => 0, - 'жъ ' => 0, - 'жы ' => 0, - 'жэ ' => 0, - 'жю' => 0, - 'жю ' => 0, - 'жя' => 0, - 'жя ' => 0, - 'зё ' => 0, - 'зж ' => 0, - 'зз ' => 0, - 'зй' => 0, - 'зй ' => 0, - 'зк ' => 0, - 'зп ' => 0, - 'зр ' => 0, - 'зс ' => 0, - 'зт ' => 0, - 'зф' => 0, - 'зф ' => 0, - 'зх' => 0, - 'зх ' => 0, - 'зц ' => 0, - 'зч ' => 0, - 'зш ' => 0, - 'зщ' => 0, - 'зщ ' => 0, - 'зъ ' => 0, - 'зэ ' => 0, - 'иъ' => 0, - 'иъ ' => 0, - 'иы' => 0, - 'иы ' => 0, - 'иь' => 0, - 'иь ' => 0, - 'иэ ' => 0, - 'йё' => 0, - 'йё ' => 0, - 'йа ' => 0, - 'йв ' => 0, - 'йг ' => 0, - 'йж' => 0, - 'йж ' => 0, - 'йз ' => 0, - 'йи ' => 0, - 'йй' => 0, - 'йй ' => 0, - 'йо ' => 0, - 'йу' => 0, - 'йу ' => 0, - 'йч ' => 0, - 'йш ' => 0, - 'йщ ' => 0, - 'йъ' => 0, - 'йъ ' => 0, - 'йы' => 0, - 'йы ' => 0, - 'йь' => 0, - 'йь ' => 0, - 'йэ' => 0, - 'йэ ' => 0, - 'йю' => 0, - 'йю ' => 0, - 'йя' => 0, - 'кё ' => 0, - 'кб ' => 0, - 'кг ' => 0, - 'кд ' => 0, - 'кж ' => 0, - 'кз ' => 0, - 'кй' => 0, - 'кй ' => 0, - 'км ' => 0, - 'кн ' => 0, - 'кф ' => 0, - 'кц ' => 0, - 'кч ' => 0, - 'кш ' => 0, - 'кщ' => 0, - 'кщ ' => 0, - 'къ' => 0, - 'къ ' => 0, - 'кы ' => 0, - 'кь ' => 0, - 'кэ' => 0, - 'кэ ' => 0, - 'кя' => 0, - 'кя ' => 0, - 'лв ' => 0, - 'лж ' => 0, - 'лз ' => 0, - 'лй' => 0, - 'лй ' => 0, - 'лр ' => 0, - 'лф ' => 0, - 'лх ' => 0, - 'лц ' => 0, - 'лч ' => 0, - 'лш ' => 0, - 'лщ ' => 0, - 'лъ' => 0, - 'лъ ' => 0, - 'лэ' => 0, - 'лэ ' => 0, - 'мё ' => 0, - 'мв ' => 0, - 'мг ' => 0, - 'мд ' => 0, - 'мз ' => 0, - 'мй' => 0, - 'мк ' => 0, - 'мл ' => 0, - 'мр ' => 0, - 'мх ' => 0, - 'мц ' => 0, - 'мч ' => 0, - 'мш ' => 0, - 'мщ ' => 0, - 'мъ' => 0, - 'мъ ' => 0, - 'мэ ' => 0, - 'мю ' => 0, - 'нё ' => 0, - 'нб ' => 0, - 'нв ' => 0, - 'нй' => 0, - 'нл ' => 0, - 'нп ' => 0, - 'нщ ' => 0, - 'нъ ' => 0, - 'нэ ' => 0, - 'оъ' => 0, - 'оъ ' => 0, - 'оы' => 0, - 'оы ' => 0, - 'оь' => 0, - 'оь ' => 0, - 'пё ' => 0, - 'пб ' => 0, - 'пв' => 0, - 'пв ' => 0, - 'пг' => 0, - 'пг ' => 0, - 'пд ' => 0, - 'пж' => 0, - 'пж ' => 0, - 'пз' => 0, - 'пз ' => 0, - 'пй' => 0, - 'пй ' => 0, - 'пк ' => 0, - 'пл ' => 0, - 'пм ' => 0, - 'пн ' => 0, - 'пф ' => 0, - 'пх ' => 0, - 'пц ' => 0, - 'пч ' => 0, - 'пш ' => 0, - 'пщ ' => 0, - 'пъ' => 0, - 'пъ ' => 0, - 'пэ' => 0, - 'пэ ' => 0, - 'пю ' => 0, - 'рё ' => 0, - 'рй' => 0, - 'рй ' => 0, - 'ръ' => 0, - 'ръ ' => 0, - 'рэ ' => 0, - 'сб ' => 0, - 'св ' => 0, - 'сг ' => 0, - 'сд ' => 0, - 'сж ' => 0, - 'сз' => 0, - 'сз ' => 0, - 'сй' => 0, - 'сй ' => 0, - 'сн ' => 0, - 'сп ' => 0, - 'сф ' => 0, - 'сц ' => 0, - 'сч ' => 0, - 'сш ' => 0, - 'сщ ' => 0, - 'съ ' => 0, - 'сэ ' => 0, - 'тб ' => 0, - 'тг ' => 0, - 'тд ' => 0, - 'тж ' => 0, - 'тз ' => 0, - 'тй' => 0, - 'тй ' => 0, - 'тк ' => 0, - 'тл ' => 0, - 'тп ' => 0, - 'тф ' => 0, - 'тх ' => 0, - 'тц ' => 0, - 'тш ' => 0, - 'тщ ' => 0, - 'тъ ' => 0, - 'уё ' => 0, - 'уо ' => 0, - 'уу ' => 0, - 'уц ' => 0, - 'уъ' => 0, - 'уъ ' => 0, - 'уы' => 0, - 'уы ' => 0, - 'уь' => 0, - 'уь ' => 0, - 'уэ ' => 0, - 'фё ' => 0, - 'фб ' => 0, - 'фв ' => 0, - 'фг ' => 0, - 'фд ' => 0, - 'фж' => 0, - 'фж ' => 0, - 'фз' => 0, - 'фз ' => 0, - 'фй' => 0, - 'фй ' => 0, - 'фк ' => 0, - 'фл ' => 0, - 'фн ' => 0, - 'фп' => 0, - 'фп ' => 0, - 'фс ' => 0, - 'фх' => 0, - 'фх ' => 0, - 'фц' => 0, - 'фц ' => 0, - 'фч ' => 0, - 'фш ' => 0, - 'фщ ' => 0, - 'фъ' => 0, - 'фъ ' => 0, - 'фэ' => 0, - 'фэ ' => 0, - 'фю ' => 0, - 'хё' => 0, - 'хё ' => 0, - 'хб ' => 0, - 'хг ' => 0, - 'хд ' => 0, - 'хж ' => 0, - 'хз ' => 0, - 'хй' => 0, - 'хй ' => 0, - 'хк ' => 0, - 'хн ' => 0, - 'хп ' => 0, - 'хр ' => 0, - 'хс ' => 0, - 'хф ' => 0, - 'хх ' => 0, - 'хц ' => 0, - 'хч ' => 0, - 'хш ' => 0, - 'хщ' => 0, - 'хщ ' => 0, - 'хъ ' => 0, - 'хы' => 0, - 'хы ' => 0, - 'хь' => 0, - 'хь ' => 0, - 'хэ ' => 0, - 'хю' => 0, - 'хю ' => 0, - 'хя' => 0, - 'хя ' => 0, - 'цё' => 0, - 'цё ' => 0, - 'цб' => 0, - 'цб ' => 0, - 'цв ' => 0, - 'цг ' => 0, - 'цд ' => 0, - 'цж' => 0, - 'цж ' => 0, - 'цз ' => 0, - 'цй' => 0, - 'цй ' => 0, - 'цк ' => 0, - 'цл ' => 0, - 'цм ' => 0, - 'цн ' => 0, - 'цп ' => 0, - 'цр ' => 0, - 'цс ' => 0, - 'цт ' => 0, - 'цф' => 0, - 'цф ' => 0, - 'цх' => 0, - 'цх ' => 0, - 'цц ' => 0, - 'цч' => 0, - 'цч ' => 0, - 'цш ' => 0, - 'цщ' => 0, - 'цщ ' => 0, - 'цъ' => 0, - 'цъ ' => 0, - 'ць' => 0, - 'ць ' => 0, - 'цэ' => 0, - 'цэ ' => 0, - 'цю' => 0, - 'цю ' => 0, - 'ця' => 0, - 'ця ' => 0, - 'чё ' => 0, - 'чб ' => 0, - 'чг' => 0, - 'чг ' => 0, - 'чд' => 0, - 'чд ' => 0, - 'чж ' => 0, - 'чз' => 0, - 'чз ' => 0, - 'чй' => 0, - 'чй ' => 0, - 'чк ' => 0, - 'чл ' => 0, - 'чм ' => 0, - 'чн ' => 0, - 'чп' => 0, - 'чп ' => 0, - 'чр ' => 0, - 'чс ' => 0, - 'чф' => 0, - 'чф ' => 0, - 'чх ' => 0, - 'чц ' => 0, - 'чч ' => 0, - 'чш ' => 0, - 'чщ' => 0, - 'чщ ' => 0, - 'чъ' => 0, - 'чъ ' => 0, - 'чы' => 0, - 'чы ' => 0, - 'чэ' => 0, - 'чэ ' => 0, - 'чю' => 0, - 'чю ' => 0, - 'чя' => 0, - 'чя ' => 0, - 'шё ' => 0, - 'шб ' => 0, - 'шг ' => 0, - 'шд' => 0, - 'шд ' => 0, - 'шж' => 0, - 'шж ' => 0, - 'шз' => 0, - 'шз ' => 0, - 'шй' => 0, - 'шй ' => 0, - 'шк ' => 0, - 'шл ' => 0, - 'шм ' => 0, - 'шн ' => 0, - 'шп ' => 0, - 'шр ' => 0, - 'шс ' => 0, - 'шф ' => 0, - 'шх' => 0, - 'шх ' => 0, - 'шч ' => 0, - 'шш' => 0, - 'шш ' => 0, - 'шщ' => 0, - 'шщ ' => 0, - 'шъ' => 0, - 'шъ ' => 0, - 'шы' => 0, - 'шы ' => 0, - 'шэ' => 0, - 'шэ ' => 0, - 'шя' => 0, - 'шя ' => 0, - 'щб' => 0, - 'щб ' => 0, - 'щв ' => 0, - 'щг' => 0, - 'щг ' => 0, - 'щд' => 0, - 'щд ' => 0, - 'щж' => 0, - 'щж ' => 0, - 'щз' => 0, - 'щз ' => 0, - 'щй' => 0, - 'щй ' => 0, - 'щк' => 0, - 'щк ' => 0, - 'щл' => 0, - 'щл ' => 0, - 'щм ' => 0, - 'щн ' => 0, - 'щп' => 0, - 'щп ' => 0, - 'щр ' => 0, - 'щс' => 0, - 'щс ' => 0, - 'щт' => 0, - 'щт ' => 0, - 'щф' => 0, - 'щф ' => 0, - 'щх' => 0, - 'щх ' => 0, - 'щц' => 0, - 'щц ' => 0, - 'щч' => 0, - 'щч ' => 0, - 'щш' => 0, - 'щш ' => 0, - 'щщ' => 0, - 'щщ ' => 0, - 'щъ' => 0, - 'щъ ' => 0, - 'щы' => 0, - 'щы ' => 0, - 'щэ' => 0, - 'щэ ' => 0, - 'щю' => 0, - 'щю ' => 0, - 'щя' => 0, - 'щя ' => 0, - 'ъё ' => 0, - 'ъа' => 0, - 'ъа ' => 0, - 'ъб' => 0, - 'ъб ' => 0, - 'ъв' => 0, - 'ъв ' => 0, - 'ъг' => 0, - 'ъг ' => 0, - 'ъд' => 0, - 'ъд ' => 0, - 'ъе ' => 0, - 'ъж' => 0, - 'ъж ' => 0, - 'ъз' => 0, - 'ъз ' => 0, - 'ъи' => 0, - 'ъи ' => 0, - 'ъй' => 0, - 'ъй ' => 0, - 'ък' => 0, - 'ък ' => 0, - 'ъл' => 0, - 'ъл ' => 0, - 'ъм' => 0, - 'ъм ' => 0, - 'ън' => 0, - 'ън ' => 0, - 'ъо' => 0, - 'ъо ' => 0, - 'ъп' => 0, - 'ъп ' => 0, - 'ър' => 0, - 'ър ' => 0, - 'ъс' => 0, - 'ъс ' => 0, - 'ът' => 0, - 'ът ' => 0, - 'ъу' => 0, - 'ъу ' => 0, - 'ъф' => 0, - 'ъф ' => 0, - 'ъх' => 0, - 'ъх ' => 0, - 'ъц' => 0, - 'ъц ' => 0, - 'ъч' => 0, - 'ъч ' => 0, - 'ъш' => 0, - 'ъш ' => 0, - 'ъщ' => 0, - 'ъщ ' => 0, - 'ъъ' => 0, - 'ъъ ' => 0, - 'ъы' => 0, - 'ъы ' => 0, - 'ъь' => 0, - 'ъь ' => 0, - 'ъэ' => 0, - 'ъэ ' => 0, - 'ъю ' => 0, - 'ъя ' => 0, - 'ыё' => 0, - 'ыё ' => 0, - 'ыа' => 0, - 'ыа ' => 0, - 'ыи ' => 0, - 'ыо ' => 0, - 'ыу ' => 0, - 'ыф ' => 0, - 'ыъ' => 0, - 'ыъ ' => 0, - 'ыы' => 0, - 'ыы ' => 0, - 'ыь' => 0, - 'ыь ' => 0, - 'ыэ' => 0, - 'ыэ ' => 0, - 'ыю ' => 0, - 'ьа' => 0, - 'ьа ' => 0, - 'ьв ' => 0, - 'ьг ' => 0, - 'ьж ' => 0, - 'ьз ' => 0, - 'ьй' => 0, - 'ьй ' => 0, - 'ьл ' => 0, - 'ьн ' => 0, - 'ьр ' => 0, - 'ьу' => 0, - 'ьу ' => 0, - 'ьх ' => 0, - 'ьщ ' => 0, - 'ьъ' => 0, - 'ьъ ' => 0, - 'ьы ' => 0, - 'ьь' => 0, - 'ьь ' => 0, - 'ьэ ' => 0, - 'эё' => 0, - 'эё ' => 0, - 'эа' => 0, - 'эа ' => 0, - 'эб' => 0, - 'эб ' => 0, - 'эв ' => 0, - 'эг ' => 0, - 'эд ' => 0, - 'эе' => 0, - 'эе ' => 0, - 'эж' => 0, - 'эж ' => 0, - 'эз ' => 0, - 'эи ' => 0, - 'эй ' => 0, - 'эл ' => 0, - 'эм ' => 0, - 'эн ' => 0, - 'эо' => 0, - 'эо ' => 0, - 'эу' => 0, - 'эу ' => 0, - 'эф ' => 0, - 'эх ' => 0, - 'эц' => 0, - 'эц ' => 0, - 'эч' => 0, - 'эч ' => 0, - 'эш ' => 0, - 'эщ' => 0, - 'эщ ' => 0, - 'эъ' => 0, - 'эъ ' => 0, - 'эы' => 0, - 'эы ' => 0, - 'эь' => 0, - 'эь ' => 0, - 'ээ ' => 0, - 'эю' => 0, - 'эю ' => 0, - 'эя' => 0, - 'эя ' => 0, - 'юё' => 0, - 'юё ' => 0, - 'юа ' => 0, - 'юе ' => 0, - 'юж ' => 0, - 'юи ' => 0, - 'юл ' => 0, - 'юо ' => 0, - 'юу' => 0, - 'юу ' => 0, - 'юц ' => 0, - 'юъ' => 0, - 'юъ ' => 0, - 'юы' => 0, - 'юы ' => 0, - 'юь' => 0, - 'юь ' => 0, - 'юэ ' => 0, - 'юя' => 0, - 'яё' => 0, - 'яё ' => 0, - 'яа' => 0, - 'яа ' => 0, - 'яе ' => 0, - 'яо ' => 0, - 'яф' => 0, - 'яф ' => 0, - 'яъ' => 0, - 'яъ ' => 0, - 'яы' => 0, - 'яы ' => 0, - 'яь' => 0, - 'яь ' => 0, - 'яэ' => 0, - 'яэ ' => 0, - #en - ' \'f' => 0, - ' \'p' => 0, - ' \'q' => 0, - ' \'r' => 0, - ' \'x' => 0, - ' \'y' => 0, - ' \'z' => 0, - ' bj' => 0, - ' bq' => 0, - ' bz' => 0, - ' c\'' => 0, - ' cq' => 0, - ' cv' => 0, - ' cx' => 0, - ' dq' => 0, - ' dx' => 0, - ' ez' => 0, - ' f\'' => 0, - ' fh' => 0, - ' fk' => 0, - ' fq' => 0, - ' fv' => 0, - ' fw' => 0, - ' fz' => 0, - ' g\'' => 0, - ' gf' => 0, - ' gg' => 0, - ' gj' => 0, - ' gv' => 0, - ' gx' => 0, - ' gz' => 0, - ' h\'' => 0, - ' hj' => 0, - ' hk' => 0, - ' hn' => 0, - ' hq' => 0, - ' hx' => 0, - ' iq' => 0, - ' iw' => 0, - ' iy' => 0, - ' jb' => 0, - ' jf' => 0, - ' jh' => 0, - ' jj' => 0, - ' jk' => 0, - ' jl' => 0, - ' jm' => 0, - ' jq' => 0, - ' jw' => 0, - ' jx' => 0, - ' jy' => 0, - ' jz' => 0, - ' k\'' => 0, - ' kf' => 0, - ' kj' => 0, - ' kq' => 0, - ' kt' => 0, - ' kx' => 0, - ' kz' => 0, - ' lj' => 0, - ' lk' => 0, - ' lq' => 0, - ' lv' => 0, - ' mj' => 0, - ' mq' => 0, - ' mz' => 0, - ' nj' => 0, - ' nk' => 0, - ' nq' => 0, - ' nz' => 0, - ' oq' => 0, - ' pj' => 0, - ' pz' => 0, - ' qb' => 0, - ' qe' => 0, - ' qf' => 0, - ' qg' => 0, - ' qh' => 0, - ' qj' => 0, - ' qk' => 0, - ' qo' => 0, - ' qp' => 0, - ' qs' => 0, - ' qv' => 0, - ' qx' => 0, - ' qy' => 0, - ' qz' => 0, - ' rb' => 0, - ' rk' => 0, - ' rq' => 0, - ' rv' => 0, - ' rx' => 0, - ' rz' => 0, - ' sz' => 0, - ' tf' => 0, - ' tg' => 0, - ' tj' => 0, - ' tq' => 0, - ' u\'' => 0, - ' ue' => 0, - ' uj' => 0, - ' uo' => 0, - ' uq' => 0, - ' uu' => 0, - ' uy' => 0, - ' vb' => 0, - ' vj' => 0, - ' vk' => 0, - ' vn' => 0, - ' vq' => 0, - ' vr' => 0, - ' vv' => 0, - ' vw' => 0, - ' vx' => 0, - ' vy' => 0, - ' vz' => 0, - ' wj' => 0, - ' wl' => 0, - ' wn' => 0, - ' wq' => 0, - ' wx' => 0, - ' wz' => 0, - ' xb' => 0, - ' xf' => 0, - ' xg' => 0, - ' xh' => 0, - ' xj' => 0, - ' xk' => 0, - ' xq' => 0, - ' xt' => 0, - ' xu' => 0, - ' xz' => 0, - ' yf' => 0, - ' yg' => 0, - ' yh' => 0, - ' yj' => 0, - ' yk' => 0, - ' yl' => 0, - ' yn' => 0, - ' yq' => 0, - ' yv' => 0, - ' yx' => 0, - ' yy' => 0, - ' yz' => 0, - ' z\'' => 0, - ' zb' => 0, - ' zc' => 0, - ' zd' => 0, - ' zf' => 0, - ' zg' => 0, - ' zh' => 0, - ' zj' => 0, - ' zk' => 0, - ' zl' => 0, - ' zm' => 0, - ' zq' => 0, - ' zr' => 0, - ' zv' => 0, - ' zw' => 0, - ' zx' => 0, - ' zz' => 0, - '\'a ' => 0, - '\'b' => 0, - '\'b ' => 0, - '\'c ' => 0, - '\'f' => 0, - '\'f ' => 0, - '\'g' => 0, - '\'g ' => 0, - '\'h ' => 0, - '\'i ' => 0, - '\'j' => 0, - '\'j ' => 0, - '\'k' => 0, - '\'k ' => 0, - '\'l ' => 0, - '\'n ' => 0, - '\'o ' => 0, - '\'p ' => 0, - '\'q' => 0, - '\'q ' => 0, - '\'r ' => 0, - '\'u' => 0, - '\'u ' => 0, - '\'v ' => 0, - '\'w ' => 0, - '\'x' => 0, - '\'x ' => 0, - '\'z' => 0, - '\'z ' => 0, - 'b\' ' => 0, - 'bg ' => 0, - 'bh ' => 0, - 'bp ' => 0, - 'bq' => 0, - 'bq ' => 0, - 'bv ' => 0, - 'bx' => 0, - 'bz' => 0, - 'bz ' => 0, - 'c\' ' => 0, - 'cf ' => 0, - 'cj' => 0, - 'cn ' => 0, - 'cq ' => 0, - 'cv' => 0, - 'cw' => 0, - 'cx' => 0, - 'cx ' => 0, - 'cz ' => 0, - 'db ' => 0, - 'dj ' => 0, - 'dk ' => 0, - 'dw ' => 0, - 'dx' => 0, - 'eh ' => 0, - 'ej ' => 0, - 'f\' ' => 0, - 'fg ' => 0, - 'fh ' => 0, - 'fj' => 0, - 'fj ' => 0, - 'fk' => 0, - 'fk ' => 0, - 'fq' => 0, - 'fq ' => 0, - 'fv ' => 0, - 'fw ' => 0, - 'fx' => 0, - 'fx ' => 0, - 'fz' => 0, - 'fz ' => 0, - 'g\' ' => 0, - 'gc ' => 0, - 'gf ' => 0, - 'gj ' => 0, - 'gk ' => 0, - 'gl ' => 0, - 'gq' => 0, - 'gq ' => 0, - 'gv' => 0, - 'gv ' => 0, - 'gw ' => 0, - 'gx' => 0, - 'gx ' => 0, - 'gz ' => 0, - 'hb ' => 0, - 'hc ' => 0, - 'hg ' => 0, - 'hh ' => 0, - 'hj' => 0, - 'hj ' => 0, - 'hk ' => 0, - 'hv' => 0, - 'hv ' => 0, - 'hw ' => 0, - 'hx' => 0, - 'hx ' => 0, - 'hz' => 0, - 'i\' ' => 0, - 'ih ' => 0, - 'iq ' => 0, - 'iw ' => 0, - 'j\'' => 0, - 'j\' ' => 0, - 'jb' => 0, - 'jb ' => 0, - 'jc' => 0, - 'jc ' => 0, - 'jd' => 0, - 'jf' => 0, - 'jg' => 0, - 'jg ' => 0, - 'jh' => 0, - 'jh ' => 0, - 'jj' => 0, - 'jj ' => 0, - 'jk ' => 0, - 'jl ' => 0, - 'jm' => 0, - 'jm ' => 0, - 'jn' => 0, - 'jn ' => 0, - 'jp ' => 0, - 'jq' => 0, - 'jq ' => 0, - 'jr' => 0, - 'jr ' => 0, - 'js' => 0, - 'js ' => 0, - 'jt' => 0, - 'ju ' => 0, - 'jv' => 0, - 'jv ' => 0, - 'jw' => 0, - 'jw ' => 0, - 'jx' => 0, - 'jx ' => 0, - 'jy' => 0, - 'jy ' => 0, - 'jz' => 0, - 'jz ' => 0, - 'kb ' => 0, - 'kc ' => 0, - 'kd ' => 0, - 'kj ' => 0, - 'km ' => 0, - 'kp ' => 0, - 'kq' => 0, - 'kq ' => 0, - 'kv' => 0, - 'kv ' => 0, - 'kx' => 0, - 'kx ' => 0, - 'kz' => 0, - 'kz ' => 0, - 'lg ' => 0, - 'lh ' => 0, - 'lj ' => 0, - 'lq ' => 0, - 'lr ' => 0, - 'lv ' => 0, - 'lw ' => 0, - 'lx' => 0, - 'lz ' => 0, - 'm\' ' => 0, - 'mg ' => 0, - 'mh ' => 0, - 'mj ' => 0, - 'mk ' => 0, - 'mq' => 0, - 'mq ' => 0, - 'mx' => 0, - 'mx ' => 0, - 'mz' => 0, - 'nb ' => 0, - 'nm ' => 0, - 'pj ' => 0, - 'pk ' => 0, - 'pq' => 0, - 'pq ' => 0, - 'pv' => 0, - 'pw ' => 0, - 'px' => 0, - 'px ' => 0, - 'pz ' => 0, - 'q\'' => 0, - 'q\' ' => 0, - 'qa ' => 0, - 'qb' => 0, - 'qb ' => 0, - 'qc' => 0, - 'qc ' => 0, - 'qd' => 0, - 'qd ' => 0, - 'qe' => 0, - 'qe ' => 0, - 'qf' => 0, - 'qf ' => 0, - 'qg' => 0, - 'qg ' => 0, - 'qh' => 0, - 'qh ' => 0, - 'qi' => 0, - 'qj' => 0, - 'qj ' => 0, - 'qk' => 0, - 'qk ' => 0, - 'ql' => 0, - 'ql ' => 0, - 'qm' => 0, - 'qm ' => 0, - 'qn' => 0, - 'qn ' => 0, - 'qo' => 0, - 'qo ' => 0, - 'qp' => 0, - 'qp ' => 0, - 'qq' => 0, - 'qq ' => 0, - 'qr' => 0, - 'qs' => 0, - 'qs ' => 0, - 'qt' => 0, - 'qt ' => 0, - 'qu ' => 0, - 'qv' => 0, - 'qv ' => 0, - 'qw' => 0, - 'qw ' => 0, - 'qx' => 0, - 'qx ' => 0, - 'qy' => 0, - 'qy ' => 0, - 'qz' => 0, - 'qz ' => 0, - 'rq ' => 0, - 'rz ' => 0, - 'sg ' => 0, - 'sj ' => 0, - 'sx' => 0, - 'sx ' => 0, - 'sz' => 0, - 'sz ' => 0, - 'tg ' => 0, - 'tj ' => 0, - 'tq' => 0, - 'tq ' => 0, - 'tx' => 0, - 'tx ' => 0, - 'uj ' => 0, - 'uq ' => 0, - 'uu ' => 0, - 'uw ' => 0, - 'v\' ' => 0, - 'vb' => 0, - 'vb ' => 0, - 'vc' => 0, - 'vf' => 0, - 'vf ' => 0, - 'vg' => 0, - 'vh' => 0, - 'vh ' => 0, - 'vj' => 0, - 'vj ' => 0, - 'vk' => 0, - 'vk ' => 0, - 'vl ' => 0, - 'vm' => 0, - 'vn ' => 0, - 'vp' => 0, - 'vp ' => 0, - 'vq' => 0, - 'vq ' => 0, - 'vr ' => 0, - 'vv ' => 0, - 'vw' => 0, - 'vw ' => 0, - 'vx' => 0, - 'vz' => 0, - 'vz ' => 0, - 'w\' ' => 0, - 'wb ' => 0, - 'wc ' => 0, - 'wf ' => 0, - 'wg ' => 0, - 'wj' => 0, - 'wj ' => 0, - 'wq' => 0, - 'wq ' => 0, - 'wr ' => 0, - 'wv' => 0, - 'wv ' => 0, - 'wx' => 0, - 'wz ' => 0, - 'x\'' => 0, - 'x\' ' => 0, - 'xa ' => 0, - 'xb ' => 0, - 'xc ' => 0, - 'xd' => 0, - 'xd ' => 0, - 'xf ' => 0, - 'xg ' => 0, - 'xh ' => 0, - 'xj' => 0, - 'xj ' => 0, - 'xk' => 0, - 'xk ' => 0, - 'xl ' => 0, - 'xm ' => 0, - 'xn' => 0, - 'xn ' => 0, - 'xp ' => 0, - 'xq ' => 0, - 'xr' => 0, - 'xr ' => 0, - 'xs ' => 0, - 'xu ' => 0, - 'xv' => 0, - 'xv ' => 0, - 'xw ' => 0, - 'xx' => 0, - 'xz' => 0, - 'xz ' => 0, - 'yb ' => 0, - 'yc ' => 0, - 'yd ' => 0, - 'yf ' => 0, - 'yg ' => 0, - 'yh ' => 0, - 'yj ' => 0, - 'yq' => 0, - 'yq ' => 0, - 'yu ' => 0, - 'yv ' => 0, - 'yw ' => 0, - 'yy' => 0, - 'yy ' => 0, - 'yz ' => 0, - 'z\'' => 0, - 'z\' ' => 0, - 'zb ' => 0, - 'zc' => 0, - 'zc ' => 0, - 'zd' => 0, - 'zd ' => 0, - 'zf' => 0, - 'zf ' => 0, - 'zg ' => 0, - 'zh' => 0, - 'zh ' => 0, - 'zj' => 0, - 'zj ' => 0, - 'zk ' => 0, - 'zl ' => 0, - 'zn' => 0, - 'zn ' => 0, - 'zp ' => 0, - 'zq' => 0, - 'zq ' => 0, - 'zr' => 0, - 'zr ' => 0, - 'zs' => 0, - 'zs ' => 0, - 'zt' => 0, - 'zt ' => 0, - 'zu ' => 0, - 'zv ' => 0, - 'zw ' => 0, - 'zx' => 0, - 'zx ' => 0, - ); + #несуществующие биграммы в начале и конце слов + private $bigrams = array( + #ru + ' ёё' => 0, + ' ёа' => 0, + ' ёб' => 0, + ' ёв' => 0, + ' ёг' => 0, + ' ёд' => 0, + ' ёе' => 0, + ' ёз' => 0, + ' ёи' => 0, + ' ёй' => 0, + ' ён' => 0, + ' ёо' => 0, + ' ёп' => 0, + ' ёс' => 0, + ' ёт' => 0, + ' ёу' => 0, + ' ёф' => 0, + ' ёц' => 0, + ' ёч' => 0, + ' ёщ' => 0, + ' ёъ' => 0, + ' ёы' => 0, + ' ёь' => 0, + ' ёэ' => 0, + ' ёю' => 0, + ' ёя' => 0, + ' аё' => 0, + ' аа' => 0, + ' ае' => 0, + ' ач' => 0, + ' аъ' => 0, + ' аы' => 0, + ' аь' => 0, + ' аю' => 0, + ' ая' => 0, + ' бб' => 0, + ' бв' => 0, + ' бг' => 0, + ' бж' => 0, + ' бй' => 0, + ' бк' => 0, + ' бм' => 0, + ' бн' => 0, + ' бп' => 0, + ' бс' => 0, + ' бт' => 0, + ' бф' => 0, + ' бх' => 0, + ' бц' => 0, + ' бч' => 0, + ' бш' => 0, + ' бщ' => 0, + ' бъ' => 0, + ' вй' => 0, + ' вф' => 0, + ' вщ' => 0, + ' вэ' => 0, + ' вю' => 0, + ' гё' => 0, + ' гб' => 0, + ' гз' => 0, + ' гй' => 0, + ' гк' => 0, + ' гп' => 0, + ' гс' => 0, + ' гт' => 0, + ' гф' => 0, + ' гх' => 0, + ' гц' => 0, + ' гч' => 0, + ' гш' => 0, + ' гщ' => 0, + ' гъ' => 0, + ' гь' => 0, + ' гэ' => 0, + ' дб' => 0, + ' дг' => 0, + ' дд' => 0, + ' дй' => 0, + ' дк' => 0, + ' дп' => 0, + ' дс' => 0, + ' дт' => 0, + ' дф' => 0, + ' дх' => 0, + ' дц' => 0, + ' дч' => 0, + ' дш' => 0, + ' дъ' => 0, + ' дэ' => 0, + ' еа' => 0, + ' еб' => 0, + ' еи' => 0, + ' ео' => 0, + ' ет' => 0, + ' еу' => 0, + ' ец' => 0, + #' еш' => 0, + ' еъ' => 0, + ' еы' => 0, + ' еь' => 0, + ' еэ' => 0, + ' ея' => 0, + ' жз' => 0, + ' жй' => 0, + ' жк' => 0, + ' жл' => 0, + ' жп' => 0, + ' жс' => 0, + ' жт' => 0, + ' жф' => 0, + ' жх' => 0, + ' жц' => 0, + ' жч' => 0, + ' жш' => 0, + ' жщ' => 0, + ' жъ' => 0, + ' жы' => 0, + ' жь' => 0, + ' жэ' => 0, + #' жю' => 0, + ' жя' => 0, + ' зб' => 0, + ' зж' => 0, + ' зз' => 0, + ' зй' => 0, + ' зк' => 0, + ' зп' => 0, + ' зс' => 0, + ' зт' => 0, + ' зф' => 0, + ' зх' => 0, + ' зц' => 0, + ' зч' => 0, + ' зш' => 0, + ' зщ' => 0, + ' зъ' => 0, + ' зь' => 0, + ' зэ' => 0, + ' иё' => 0, + ' иа' => 0, + ' иф' => 0, + ' иц' => 0, + ' иъ' => 0, + ' иы' => 0, + ' иь' => 0, + ' иэ' => 0, + ' ия' => 0, + ' йё' => 0, + ' йа' => 0, + ' йб' => 0, + ' йв' => 0, + ' йг' => 0, + ' йд' => 0, + ' йж' => 0, + ' йз' => 0, + ' йи' => 0, + ' йй' => 0, + ' йк' => 0, + ' йл' => 0, + ' йм' => 0, + ' йн' => 0, + ' йп' => 0, + ' йр' => 0, + ' йс' => 0, + ' йт' => 0, + ' йу' => 0, + ' йф' => 0, + ' йх' => 0, + ' йц' => 0, + ' йч' => 0, + ' йш' => 0, + ' йщ' => 0, + ' йъ' => 0, + ' йы' => 0, + ' йь' => 0, + ' йэ' => 0, + ' йю' => 0, + ' йя' => 0, + ' кё' => 0, + ' кб' => 0, + ' кд' => 0, + ' кж' => 0, + ' кй' => 0, + ' кк' => 0, + ' кф' => 0, + ' кц' => 0, + ' кч' => 0, + ' кщ' => 0, + ' къ' => 0, + ' кя' => 0, + ' лв' => 0, + ' лд' => 0, + ' лз' => 0, + ' лй' => 0, + ' лк' => 0, + ' лл' => 0, + ' лм' => 0, + ' лн' => 0, + ' лп' => 0, + ' лр' => 0, + ' лс' => 0, + ' лт' => 0, + ' лф' => 0, + ' лх' => 0, + ' лц' => 0, + ' лч' => 0, + ' лш' => 0, + ' лщ' => 0, + ' лъ' => 0, + ' лэ' => 0, + ' мб' => 0, + ' мв' => 0, + ' мд' => 0, + ' мж' => 0, + ' мй' => 0, + ' мк' => 0, + ' мп' => 0, + ' мт' => 0, + ' мф' => 0, + ' мц' => 0, + ' мъ' => 0, + ' мь' => 0, + ' нб' => 0, + ' нв' => 0, + ' нг' => 0, + ' нд' => 0, + ' нж' => 0, + ' нз' => 0, + ' нй' => 0, + ' нк' => 0, + ' нл' => 0, + ' нм' => 0, + ' нн' => 0, + ' нп' => 0, + ' нс' => 0, + ' нт' => 0, + ' нф' => 0, + ' нх' => 0, + ' нц' => 0, + ' нч' => 0, + ' нш' => 0, + ' нщ' => 0, + ' нъ' => 0, + ' оё' => 0, + ' ои' => 0, + ' оу' => 0, + ' оъ' => 0, + ' оы' => 0, + ' оь' => 0, + ' оэ' => 0, + ' оя' => 0, + ' пб' => 0, + ' пв' => 0, + ' пг' => 0, + ' пд' => 0, + ' пж' => 0, + ' пз' => 0, + ' пй' => 0, + ' пк' => 0, + ' пм' => 0, + ' пп' => 0, + ' пц' => 0, + ' пщ' => 0, + ' пъ' => 0, + ' рб' => 0, + ' рг' => 0, + ' рз' => 0, + ' рй' => 0, + ' рк' => 0, + ' рл' => 0, + ' рм' => 0, + ' рн' => 0, + ' рп' => 0, + ' рр' => 0, + ' рф' => 0, + ' рх' => 0, + ' рч' => 0, + ' рш' => 0, + ' рщ' => 0, + ' ръ' => 0, + ' сй' => 0, + ' сщ' => 0, + ' тб' => 0, + ' тг' => 0, + ' тд' => 0, + ' тж' => 0, + ' тз' => 0, + ' тй' => 0, + ' тн' => 0, + ' тт' => 0, + ' тх' => 0, + ' тц' => 0, + ' тч' => 0, + ' тш' => 0, + ' тъ' => 0, + ' уу' => 0, + ' уъ' => 0, + ' уы' => 0, + ' уь' => 0, + ' фб' => 0, + ' фв' => 0, + ' фг' => 0, + ' фд' => 0, + ' фж' => 0, + ' фз' => 0, + ' фй' => 0, + ' фк' => 0, + ' фм' => 0, + ' фн' => 0, + ' фп' => 0, + ' фс' => 0, + ' фх' => 0, + ' фц' => 0, + ' фч' => 0, + ' фш' => 0, + ' фщ' => 0, + ' фъ' => 0, + ' фэ' => 0, + ' фя' => 0, + ' хё' => 0, + ' хб' => 0, + ' хг' => 0, + ' хд' => 0, + ' хж' => 0, + ' хз' => 0, + ' хй' => 0, + ' хк' => 0, + ' хп' => 0, + ' хс' => 0, + ' хт' => 0, + ' хф' => 0, + ' хц' => 0, + ' хч' => 0, + ' хш' => 0, + ' хщ' => 0, + ' хъ' => 0, + ' хы' => 0, + ' хь' => 0, + #' хэ' => 0, + ' хю' => 0, + ' хя' => 0, + ' цё' => 0, + ' цб' => 0, + ' цг' => 0, + ' цд' => 0, + ' цж' => 0, + ' цй' => 0, + ' цл' => 0, + ' цм' => 0, + ' цн' => 0, + ' цп' => 0, + ' цр' => 0, + ' цс' => 0, + ' цт' => 0, + ' цф' => 0, + ' цх' => 0, + ' цц' => 0, + ' цч' => 0, + ' цш' => 0, + ' цщ' => 0, + ' цъ' => 0, + ' ць' => 0, + ' цэ' => 0, + ' цю' => 0, + ' ця' => 0, + ' чб' => 0, + ' чг' => 0, + ' чд' => 0, + ' чж' => 0, + ' чз' => 0, + ' чй' => 0, + ' чн' => 0, + ' чп' => 0, + ' чс' => 0, + ' чф' => 0, + ' чц' => 0, + ' чч' => 0, + ' чщ' => 0, + ' чъ' => 0, + ' чы' => 0, + ' чэ' => 0, + ' чю' => 0, + ' чя' => 0, + ' шб' => 0, + ' шг' => 0, + ' шд' => 0, + ' шж' => 0, + ' шз' => 0, + ' шй' => 0, + ' шс' => 0, + ' шф' => 0, + ' шц' => 0, + ' шч' => 0, + ' шщ' => 0, + ' шъ' => 0, + ' шы' => 0, + ' шэ' => 0, + ' шю' => 0, + ' шя' => 0, + ' щб' => 0, + ' щв' => 0, + ' щг' => 0, + ' щд' => 0, + ' щж' => 0, + ' щз' => 0, + ' щй' => 0, + ' щк' => 0, + ' щл' => 0, + ' щм' => 0, + ' щн' => 0, + ' що' => 0, + ' щп' => 0, + ' щр' => 0, + ' щс' => 0, + ' щт' => 0, + ' щф' => 0, + ' щх' => 0, + ' щц' => 0, + ' щч' => 0, + ' щш' => 0, + ' щщ' => 0, + ' щъ' => 0, + ' щы' => 0, + ' щь' => 0, + ' щэ' => 0, + ' щю' => 0, + ' щя' => 0, + ' ъё' => 0, + ' ъа' => 0, + ' ъб' => 0, + ' ъв' => 0, + ' ъг' => 0, + ' ъд' => 0, + ' ъе' => 0, + ' ъж' => 0, + ' ъз' => 0, + ' ъи' => 0, + ' ъй' => 0, + ' ък' => 0, + ' ъл' => 0, + ' ъм' => 0, + ' ън' => 0, + ' ъо' => 0, + ' ъп' => 0, + ' ър' => 0, + ' ъс' => 0, + ' ът' => 0, + ' ъу' => 0, + ' ъф' => 0, + ' ъх' => 0, + ' ъц' => 0, + ' ъч' => 0, + ' ъш' => 0, + ' ъщ' => 0, + ' ъъ' => 0, + ' ъы' => 0, + ' ъь' => 0, + ' ъэ' => 0, + ' ъю' => 0, + ' ъя' => 0, + ' ыё' => 0, + ' ыа' => 0, + ' ыб' => 0, + ' ыв' => 0, + ' ыг' => 0, + ' ыд' => 0, + ' ые' => 0, + ' ыж' => 0, + ' ыз' => 0, + ' ыи' => 0, + ' ый' => 0, + ' ык' => 0, + ' ыл' => 0, + ' ын' => 0, + ' ыо' => 0, + ' ып' => 0, + ' ыр' => 0, + ' ыс' => 0, + ' ыт' => 0, + ' ыу' => 0, + ' ыф' => 0, + ' ых' => 0, + ' ыц' => 0, + ' ыч' => 0, + ' ыш' => 0, + ' ыщ' => 0, + ' ыъ' => 0, + ' ыы' => 0, + ' ыь' => 0, + ' ыэ' => 0, + ' ыю' => 0, + ' ыя' => 0, + ' ьё' => 0, + ' ьа' => 0, + ' ьб' => 0, + ' ьв' => 0, + ' ьг' => 0, + ' ьд' => 0, + ' ье' => 0, + ' ьж' => 0, + ' ьз' => 0, + ' ьи' => 0, + ' ьй' => 0, + ' ьк' => 0, + ' ьл' => 0, + ' ьм' => 0, + ' ьн' => 0, + ' ьо' => 0, + ' ьп' => 0, + ' ьр' => 0, + ' ьс' => 0, + ' ьт' => 0, + ' ьу' => 0, + ' ьф' => 0, + ' ьх' => 0, + ' ьц' => 0, + ' ьч' => 0, + ' ьш' => 0, + ' ьщ' => 0, + ' ьъ' => 0, + ' ьы' => 0, + ' ьь' => 0, + ' ьэ' => 0, + ' ью' => 0, + ' ья' => 0, + ' эё' => 0, + ' эа' => 0, + ' эе' => 0, + ' эи' => 0, + ' эц' => 0, + ' эч' => 0, + ' эщ' => 0, + ' эъ' => 0, + ' эы' => 0, + ' эь' => 0, + ' ээ' => 0, + ' эю' => 0, + ' юё' => 0, + ' юе' => 0, + ' юи' => 0, + ' юй' => 0, + ' юо' => 0, + ' юу' => 0, + ' юц' => 0, + ' юш' => 0, + ' ющ' => 0, + ' юъ' => 0, + ' юы' => 0, + ' юь' => 0, + ' юэ' => 0, + ' юя' => 0, + ' яё' => 0, + ' яа' => 0, + ' яе' => 0, + ' яж' => 0, + ' яо' => 0, + ' яу' => 0, + ' яф' => 0, + ' яц' => 0, + ' яъ' => 0, + ' яы' => 0, + ' яь' => 0, + ' яэ' => 0, + ' яю' => 0, + ' яя' => 0, + 'ёё' => 0, + 'ёё ' => 0, + 'ёа' => 0, + 'ёа ' => 0, + 'ёг ' => 0, + 'ёе' => 0, + 'ёе ' => 0, + 'ёи' => 0, + 'ёи ' => 0, + 'ёй' => 0, + 'ёо' => 0, + 'ёо ' => 0, + 'ёу' => 0, + 'ёу ' => 0, + 'ёф' => 0, + 'ёф ' => 0, + 'ёц ' => 0, + 'ёч ' => 0, + 'ёщ ' => 0, + 'ёъ' => 0, + 'ёъ ' => 0, + 'ёы' => 0, + 'ёы ' => 0, + 'ёь' => 0, + 'ёь ' => 0, + 'ёэ' => 0, + 'ёэ ' => 0, + 'ёю' => 0, + 'ёя' => 0, + 'ёя ' => 0, + 'аё ' => 0, + 'аа ' => 0, + 'аъ' => 0, + 'аъ ' => 0, + 'аы' => 0, + 'аы ' => 0, + 'аь' => 0, + 'аь ' => 0, + 'аэ ' => 0, + 'бё ' => 0, + 'бб ' => 0, + 'бв ' => 0, + 'бг ' => 0, + 'бд ' => 0, + 'бж ' => 0, + 'бз ' => 0, + 'бй' => 0, + 'бй ' => 0, + 'бк ' => 0, + 'бм ' => 0, + 'бн ' => 0, + 'бп ' => 0, + 'бт ' => 0, + 'бф ' => 0, + 'бх ' => 0, + 'бц ' => 0, + 'бч ' => 0, + 'бш ' => 0, + 'бщ ' => 0, + 'бъ ' => 0, + 'бэ ' => 0, + 'вё ' => 0, + 'вб ' => 0, + 'вв ' => 0, + 'вд ' => 0, + 'вж' => 0, + 'вж ' => 0, + 'вз ' => 0, + 'вй' => 0, + 'вй ' => 0, + 'вл ' => 0, + 'вп ' => 0, + 'вф ' => 0, + 'вц ' => 0, + 'вч ' => 0, + 'вщ ' => 0, + 'въ' => 0, + 'въ ' => 0, + 'вэ ' => 0, + 'гё' => 0, + 'гё ' => 0, + 'гб ' => 0, + 'гг ' => 0, + 'гж' => 0, + 'гж ' => 0, + 'гз ' => 0, + 'гй' => 0, + 'гй ' => 0, + 'гк ' => 0, + 'гн ' => 0, + 'гп ' => 0, + 'гф ' => 0, + 'гх' => 0, + 'гх ' => 0, + 'гц' => 0, + 'гц ' => 0, + 'гч ' => 0, + 'гш ' => 0, + 'гщ ' => 0, + 'гъ' => 0, + 'гъ ' => 0, + 'гы ' => 0, + 'гь' => 0, + 'гь ' => 0, + 'гэ ' => 0, + 'гю' => 0, + 'гю ' => 0, + 'гя' => 0, + 'гя ' => 0, + 'дё ' => 0, + 'дб ' => 0, + 'дг ' => 0, + 'дд ' => 0, + 'дй' => 0, + 'дй ' => 0, + 'дк ' => 0, + 'дм ' => 0, + 'дн ' => 0, + 'дп ' => 0, + 'дс ' => 0, + 'дф ' => 0, + 'дх ' => 0, + 'дц ' => 0, + 'дч ' => 0, + 'дш ' => 0, + 'дщ ' => 0, + 'дъ ' => 0, + 'еа ' => 0, + 'еу ' => 0, + 'еъ' => 0, + 'еъ ' => 0, + 'еы' => 0, + 'еы ' => 0, + 'еь' => 0, + 'еь ' => 0, + 'еэ ' => 0, + 'жё ' => 0, + 'жв ' => 0, + 'жг ' => 0, + 'жж ' => 0, + 'жз ' => 0, + 'жй' => 0, + 'жй ' => 0, + 'жк ' => 0, + 'жл ' => 0, + 'жн ' => 0, + 'жп ' => 0, + 'жр ' => 0, + 'жс ' => 0, + 'жт ' => 0, + 'жф ' => 0, + 'жх ' => 0, + 'жц ' => 0, + 'жч ' => 0, + 'жш' => 0, + 'жш ' => 0, + 'жщ' => 0, + 'жщ ' => 0, + 'жъ' => 0, + 'жъ ' => 0, + 'жы ' => 0, + 'жэ ' => 0, + 'жю' => 0, + 'жю ' => 0, + 'жя' => 0, + 'жя ' => 0, + 'зё ' => 0, + 'зж ' => 0, + 'зз ' => 0, + 'зй' => 0, + 'зй ' => 0, + 'зк ' => 0, + 'зп ' => 0, + 'зр ' => 0, + 'зс ' => 0, + 'зт ' => 0, + 'зф' => 0, + 'зф ' => 0, + 'зх' => 0, + 'зх ' => 0, + 'зц ' => 0, + 'зч ' => 0, + 'зш ' => 0, + 'зщ' => 0, + 'зщ ' => 0, + 'зъ ' => 0, + 'зэ ' => 0, + 'иъ' => 0, + 'иъ ' => 0, + 'иы' => 0, + 'иы ' => 0, + 'иь' => 0, + 'иь ' => 0, + 'иэ ' => 0, + 'йё' => 0, + 'йё ' => 0, + 'йа ' => 0, + 'йв ' => 0, + 'йг ' => 0, + 'йж' => 0, + 'йж ' => 0, + 'йз ' => 0, + 'йи ' => 0, + 'йй' => 0, + 'йй ' => 0, + 'йо ' => 0, + 'йу' => 0, + 'йу ' => 0, + 'йч ' => 0, + 'йш ' => 0, + 'йщ ' => 0, + 'йъ' => 0, + 'йъ ' => 0, + 'йы' => 0, + 'йы ' => 0, + 'йь' => 0, + 'йь ' => 0, + 'йэ' => 0, + 'йэ ' => 0, + 'йю' => 0, + 'йю ' => 0, + 'йя' => 0, + 'кё ' => 0, + 'кб ' => 0, + 'кг ' => 0, + 'кд ' => 0, + 'кж ' => 0, + 'кз ' => 0, + 'кй' => 0, + 'кй ' => 0, + 'км ' => 0, + 'кн ' => 0, + 'кф ' => 0, + 'кц ' => 0, + 'кч ' => 0, + 'кш ' => 0, + 'кщ' => 0, + 'кщ ' => 0, + 'къ' => 0, + 'къ ' => 0, + 'кы ' => 0, + 'кь ' => 0, + 'кэ' => 0, + 'кэ ' => 0, + 'кя' => 0, + 'кя ' => 0, + 'лв ' => 0, + 'лж ' => 0, + 'лз ' => 0, + 'лй' => 0, + 'лй ' => 0, + 'лр ' => 0, + 'лф ' => 0, + 'лх ' => 0, + 'лц ' => 0, + 'лч ' => 0, + 'лш ' => 0, + 'лщ ' => 0, + 'лъ' => 0, + 'лъ ' => 0, + 'лэ' => 0, + 'лэ ' => 0, + 'мё ' => 0, + 'мв ' => 0, + 'мг ' => 0, + 'мд ' => 0, + 'мз ' => 0, + 'мй' => 0, + 'мк ' => 0, + 'мл ' => 0, + 'мр ' => 0, + 'мх ' => 0, + 'мц ' => 0, + 'мч ' => 0, + 'мш ' => 0, + 'мщ ' => 0, + 'мъ' => 0, + 'мъ ' => 0, + 'мэ ' => 0, + 'мю ' => 0, + 'нё ' => 0, + 'нб ' => 0, + 'нв ' => 0, + 'нй' => 0, + 'нл ' => 0, + 'нп ' => 0, + 'нщ ' => 0, + 'нъ ' => 0, + 'нэ ' => 0, + 'оъ' => 0, + 'оъ ' => 0, + 'оы' => 0, + 'оы ' => 0, + 'оь' => 0, + 'оь ' => 0, + 'пё ' => 0, + 'пб ' => 0, + 'пв' => 0, + 'пв ' => 0, + 'пг' => 0, + 'пг ' => 0, + 'пд ' => 0, + 'пж' => 0, + 'пж ' => 0, + 'пз' => 0, + 'пз ' => 0, + 'пй' => 0, + 'пй ' => 0, + 'пк ' => 0, + 'пл ' => 0, + 'пм ' => 0, + 'пн ' => 0, + 'пф ' => 0, + 'пх ' => 0, + 'пц ' => 0, + 'пч ' => 0, + 'пш ' => 0, + 'пщ ' => 0, + 'пъ' => 0, + 'пъ ' => 0, + 'пэ' => 0, + 'пэ ' => 0, + 'пю ' => 0, + 'рё ' => 0, + 'рй' => 0, + 'рй ' => 0, + 'ръ' => 0, + 'ръ ' => 0, + 'рэ ' => 0, + 'сб ' => 0, + 'св ' => 0, + 'сг ' => 0, + 'сд ' => 0, + 'сж ' => 0, + 'сз' => 0, + 'сз ' => 0, + 'сй' => 0, + 'сй ' => 0, + 'сн ' => 0, + 'сп ' => 0, + 'сф ' => 0, + 'сц ' => 0, + 'сч ' => 0, + 'сш ' => 0, + 'сщ ' => 0, + 'съ ' => 0, + 'сэ ' => 0, + 'тб ' => 0, + 'тг ' => 0, + 'тд ' => 0, + 'тж ' => 0, + 'тз ' => 0, + 'тй' => 0, + 'тй ' => 0, + 'тк ' => 0, + 'тл ' => 0, + 'тп ' => 0, + 'тф ' => 0, + 'тх ' => 0, + 'тц ' => 0, + 'тш ' => 0, + 'тщ ' => 0, + 'тъ ' => 0, + 'уё ' => 0, + 'уо ' => 0, + 'уу ' => 0, + 'уц ' => 0, + 'уъ' => 0, + 'уъ ' => 0, + 'уы' => 0, + 'уы ' => 0, + 'уь' => 0, + 'уь ' => 0, + 'уэ ' => 0, + 'фё ' => 0, + 'фб ' => 0, + 'фв ' => 0, + 'фг ' => 0, + 'фд ' => 0, + 'фж' => 0, + 'фж ' => 0, + 'фз' => 0, + 'фз ' => 0, + 'фй' => 0, + 'фй ' => 0, + 'фк ' => 0, + 'фл ' => 0, + 'фн ' => 0, + 'фп' => 0, + 'фп ' => 0, + 'фс ' => 0, + 'фх' => 0, + 'фх ' => 0, + 'фц' => 0, + 'фц ' => 0, + 'фч ' => 0, + 'фш ' => 0, + 'фщ ' => 0, + 'фъ' => 0, + 'фъ ' => 0, + 'фэ' => 0, + 'фэ ' => 0, + 'фю ' => 0, + 'хё' => 0, + 'хё ' => 0, + 'хб ' => 0, + 'хг ' => 0, + 'хд ' => 0, + 'хж ' => 0, + 'хз ' => 0, + 'хй' => 0, + 'хй ' => 0, + 'хк ' => 0, + 'хн ' => 0, + 'хп ' => 0, + 'хр ' => 0, + 'хс ' => 0, + 'хф ' => 0, + 'хх ' => 0, + 'хц ' => 0, + 'хч ' => 0, + 'хш ' => 0, + 'хщ' => 0, + 'хщ ' => 0, + 'хъ ' => 0, + 'хы' => 0, + 'хы ' => 0, + 'хь' => 0, + 'хь ' => 0, + 'хэ ' => 0, + 'хю' => 0, + 'хю ' => 0, + 'хя' => 0, + 'хя ' => 0, + 'цё' => 0, + 'цё ' => 0, + 'цб' => 0, + 'цб ' => 0, + 'цв ' => 0, + 'цг ' => 0, + 'цд ' => 0, + 'цж' => 0, + 'цж ' => 0, + 'цз ' => 0, + 'цй' => 0, + 'цй ' => 0, + 'цк ' => 0, + 'цл ' => 0, + 'цм ' => 0, + 'цн ' => 0, + 'цп ' => 0, + 'цр ' => 0, + 'цс ' => 0, + 'цт ' => 0, + 'цф' => 0, + 'цф ' => 0, + 'цх' => 0, + 'цх ' => 0, + 'цц ' => 0, + 'цч' => 0, + 'цч ' => 0, + 'цш ' => 0, + 'цщ' => 0, + 'цщ ' => 0, + 'цъ' => 0, + 'цъ ' => 0, + 'ць' => 0, + 'ць ' => 0, + 'цэ' => 0, + 'цэ ' => 0, + 'цю' => 0, + 'цю ' => 0, + 'ця' => 0, + 'ця ' => 0, + 'чё ' => 0, + 'чб ' => 0, + 'чг' => 0, + 'чг ' => 0, + 'чд' => 0, + 'чд ' => 0, + 'чж ' => 0, + 'чз' => 0, + 'чз ' => 0, + 'чй' => 0, + 'чй ' => 0, + 'чк ' => 0, + 'чл ' => 0, + 'чм ' => 0, + 'чн ' => 0, + 'чп' => 0, + 'чп ' => 0, + 'чр ' => 0, + 'чс ' => 0, + 'чф' => 0, + 'чф ' => 0, + 'чх ' => 0, + 'чц ' => 0, + 'чч ' => 0, + 'чш ' => 0, + 'чщ' => 0, + 'чщ ' => 0, + 'чъ' => 0, + 'чъ ' => 0, + 'чы' => 0, + 'чы ' => 0, + 'чэ' => 0, + 'чэ ' => 0, + 'чю' => 0, + 'чю ' => 0, + 'чя' => 0, + 'чя ' => 0, + 'шё ' => 0, + 'шб ' => 0, + 'шг ' => 0, + 'шд' => 0, + 'шд ' => 0, + 'шж' => 0, + 'шж ' => 0, + 'шз' => 0, + 'шз ' => 0, + 'шй' => 0, + 'шй ' => 0, + 'шк ' => 0, + 'шл ' => 0, + 'шм ' => 0, + 'шн ' => 0, + 'шп ' => 0, + 'шр ' => 0, + 'шс ' => 0, + 'шф ' => 0, + 'шх' => 0, + 'шх ' => 0, + 'шч ' => 0, + 'шш' => 0, + 'шш ' => 0, + 'шщ' => 0, + 'шщ ' => 0, + 'шъ' => 0, + 'шъ ' => 0, + 'шы' => 0, + 'шы ' => 0, + 'шэ' => 0, + 'шэ ' => 0, + 'шя' => 0, + 'шя ' => 0, + 'щб' => 0, + 'щб ' => 0, + 'щв ' => 0, + 'щг' => 0, + 'щг ' => 0, + 'щд' => 0, + 'щд ' => 0, + 'щж' => 0, + 'щж ' => 0, + 'щз' => 0, + 'щз ' => 0, + 'щй' => 0, + 'щй ' => 0, + 'щк' => 0, + 'щк ' => 0, + 'щл' => 0, + 'щл ' => 0, + 'щм ' => 0, + 'щн ' => 0, + 'щп' => 0, + 'щп ' => 0, + 'щр ' => 0, + 'щс' => 0, + 'щс ' => 0, + 'щт' => 0, + 'щт ' => 0, + 'щф' => 0, + 'щф ' => 0, + 'щх' => 0, + 'щх ' => 0, + 'щц' => 0, + 'щц ' => 0, + 'щч' => 0, + 'щч ' => 0, + 'щш' => 0, + 'щш ' => 0, + 'щщ' => 0, + 'щщ ' => 0, + 'щъ' => 0, + 'щъ ' => 0, + 'щы' => 0, + 'щы ' => 0, + 'щэ' => 0, + 'щэ ' => 0, + 'щю' => 0, + 'щю ' => 0, + 'щя' => 0, + 'щя ' => 0, + 'ъё ' => 0, + 'ъа' => 0, + 'ъа ' => 0, + 'ъб' => 0, + 'ъб ' => 0, + 'ъв' => 0, + 'ъв ' => 0, + 'ъг' => 0, + 'ъг ' => 0, + 'ъд' => 0, + 'ъд ' => 0, + 'ъе ' => 0, + 'ъж' => 0, + 'ъж ' => 0, + 'ъз' => 0, + 'ъз ' => 0, + 'ъи' => 0, + 'ъи ' => 0, + 'ъй' => 0, + 'ъй ' => 0, + 'ък' => 0, + 'ък ' => 0, + 'ъл' => 0, + 'ъл ' => 0, + 'ъм' => 0, + 'ъм ' => 0, + 'ън' => 0, + 'ън ' => 0, + 'ъо' => 0, + 'ъо ' => 0, + 'ъп' => 0, + 'ъп ' => 0, + 'ър' => 0, + 'ър ' => 0, + 'ъс' => 0, + 'ъс ' => 0, + 'ът' => 0, + 'ът ' => 0, + 'ъу' => 0, + 'ъу ' => 0, + 'ъф' => 0, + 'ъф ' => 0, + 'ъх' => 0, + 'ъх ' => 0, + 'ъц' => 0, + 'ъц ' => 0, + 'ъч' => 0, + 'ъч ' => 0, + 'ъш' => 0, + 'ъш ' => 0, + 'ъщ' => 0, + 'ъщ ' => 0, + 'ъъ' => 0, + 'ъъ ' => 0, + 'ъы' => 0, + 'ъы ' => 0, + 'ъь' => 0, + 'ъь ' => 0, + 'ъэ' => 0, + 'ъэ ' => 0, + 'ъю ' => 0, + 'ъя ' => 0, + 'ыё' => 0, + 'ыё ' => 0, + 'ыа' => 0, + 'ыа ' => 0, + 'ыи ' => 0, + 'ыо ' => 0, + 'ыу ' => 0, + 'ыф ' => 0, + 'ыъ' => 0, + 'ыъ ' => 0, + 'ыы' => 0, + 'ыы ' => 0, + 'ыь' => 0, + 'ыь ' => 0, + 'ыэ' => 0, + 'ыэ ' => 0, + 'ыю ' => 0, + 'ьа' => 0, + 'ьа ' => 0, + 'ьв ' => 0, + 'ьг ' => 0, + 'ьж ' => 0, + 'ьз ' => 0, + 'ьй' => 0, + 'ьй ' => 0, + 'ьл ' => 0, + 'ьн ' => 0, + 'ьр ' => 0, + 'ьу' => 0, + 'ьу ' => 0, + 'ьх ' => 0, + 'ьщ ' => 0, + 'ьъ' => 0, + 'ьъ ' => 0, + 'ьы ' => 0, + 'ьь' => 0, + 'ьь ' => 0, + 'ьэ ' => 0, + 'эё' => 0, + 'эё ' => 0, + 'эа' => 0, + 'эа ' => 0, + 'эб' => 0, + 'эб ' => 0, + 'эв ' => 0, + 'эг ' => 0, + 'эд ' => 0, + 'эе' => 0, + 'эе ' => 0, + 'эж' => 0, + 'эж ' => 0, + 'эз ' => 0, + 'эи ' => 0, + 'эй ' => 0, + 'эл ' => 0, + 'эм ' => 0, + 'эн ' => 0, + 'эо' => 0, + 'эо ' => 0, + 'эу' => 0, + 'эу ' => 0, + 'эф ' => 0, + 'эх ' => 0, + 'эц' => 0, + 'эц ' => 0, + 'эч' => 0, + 'эч ' => 0, + 'эш ' => 0, + 'эщ' => 0, + 'эщ ' => 0, + 'эъ' => 0, + 'эъ ' => 0, + 'эы' => 0, + 'эы ' => 0, + 'эь' => 0, + 'эь ' => 0, + 'ээ ' => 0, + 'эю' => 0, + 'эю ' => 0, + 'эя' => 0, + 'эя ' => 0, + 'юё' => 0, + 'юё ' => 0, + 'юа ' => 0, + 'юе ' => 0, + 'юж ' => 0, + 'юи ' => 0, + 'юл ' => 0, + 'юо ' => 0, + 'юу' => 0, + 'юу ' => 0, + 'юц ' => 0, + 'юъ' => 0, + 'юъ ' => 0, + 'юы' => 0, + 'юы ' => 0, + 'юь' => 0, + 'юь ' => 0, + 'юэ ' => 0, + 'юя' => 0, + 'яё' => 0, + 'яё ' => 0, + 'яа' => 0, + 'яа ' => 0, + 'яе ' => 0, + 'яо ' => 0, + 'яф' => 0, + 'яф ' => 0, + 'яъ' => 0, + 'яъ ' => 0, + 'яы' => 0, + 'яы ' => 0, + 'яь' => 0, + 'яь ' => 0, + 'яэ' => 0, + 'яэ ' => 0, + #en + ' \'f' => 0, + ' \'p' => 0, + ' \'q' => 0, + ' \'r' => 0, + ' \'x' => 0, + ' \'y' => 0, + ' \'z' => 0, + ' bj' => 0, + ' bq' => 0, + ' bz' => 0, + ' c\'' => 0, + ' cq' => 0, + ' cv' => 0, + ' cx' => 0, + ' dq' => 0, + ' dx' => 0, + ' ez' => 0, + ' f\'' => 0, + ' fh' => 0, + ' fk' => 0, + ' fq' => 0, + ' fv' => 0, + ' fw' => 0, + ' fz' => 0, + ' g\'' => 0, + ' gf' => 0, + ' gg' => 0, + ' gj' => 0, + ' gv' => 0, + ' gx' => 0, + ' gz' => 0, + ' h\'' => 0, + ' hj' => 0, + ' hk' => 0, + ' hn' => 0, + ' hq' => 0, + ' hx' => 0, + ' iq' => 0, + ' iw' => 0, + ' iy' => 0, + ' jb' => 0, + ' jf' => 0, + ' jh' => 0, + ' jj' => 0, + ' jk' => 0, + ' jl' => 0, + ' jm' => 0, + ' jq' => 0, + ' jw' => 0, + ' jx' => 0, + ' jy' => 0, + ' jz' => 0, + ' k\'' => 0, + ' kf' => 0, + ' kj' => 0, + ' kq' => 0, + ' kt' => 0, + ' kx' => 0, + ' kz' => 0, + ' lj' => 0, + ' lk' => 0, + ' lq' => 0, + ' lv' => 0, + ' mj' => 0, + ' mq' => 0, + ' mz' => 0, + ' nj' => 0, + ' nk' => 0, + ' nq' => 0, + ' nz' => 0, + ' oq' => 0, + ' pj' => 0, + ' pz' => 0, + ' qb' => 0, + ' qe' => 0, + ' qf' => 0, + ' qg' => 0, + ' qh' => 0, + ' qj' => 0, + ' qk' => 0, + ' qo' => 0, + ' qp' => 0, + ' qs' => 0, + ' qv' => 0, + ' qx' => 0, + ' qy' => 0, + ' qz' => 0, + ' rb' => 0, + ' rk' => 0, + ' rq' => 0, + ' rv' => 0, + ' rx' => 0, + ' rz' => 0, + ' sz' => 0, + ' tf' => 0, + ' tg' => 0, + ' tj' => 0, + ' tq' => 0, + ' u\'' => 0, + ' ue' => 0, + ' uj' => 0, + ' uo' => 0, + ' uq' => 0, + ' uu' => 0, + ' uy' => 0, + ' vb' => 0, + ' vj' => 0, + ' vk' => 0, + ' vn' => 0, + ' vq' => 0, + ' vr' => 0, + ' vv' => 0, + ' vw' => 0, + ' vx' => 0, + ' vy' => 0, + ' vz' => 0, + ' wj' => 0, + ' wl' => 0, + ' wn' => 0, + ' wq' => 0, + ' wx' => 0, + ' wz' => 0, + ' xb' => 0, + ' xf' => 0, + ' xg' => 0, + ' xh' => 0, + ' xj' => 0, + ' xk' => 0, + ' xq' => 0, + ' xt' => 0, + ' xu' => 0, + ' xz' => 0, + ' yf' => 0, + ' yg' => 0, + ' yh' => 0, + ' yj' => 0, + ' yk' => 0, + ' yl' => 0, + ' yn' => 0, + ' yq' => 0, + ' yv' => 0, + ' yx' => 0, + ' yy' => 0, + ' yz' => 0, + ' z\'' => 0, + ' zb' => 0, + ' zc' => 0, + ' zd' => 0, + ' zf' => 0, + ' zg' => 0, + ' zh' => 0, + ' zj' => 0, + ' zk' => 0, + ' zl' => 0, + ' zm' => 0, + ' zq' => 0, + ' zr' => 0, + ' zv' => 0, + ' zw' => 0, + ' zx' => 0, + ' zz' => 0, + '\'a ' => 0, + '\'b' => 0, + '\'b ' => 0, + '\'c ' => 0, + '\'f' => 0, + '\'f ' => 0, + '\'g' => 0, + '\'g ' => 0, + '\'h ' => 0, + '\'i ' => 0, + '\'j' => 0, + '\'j ' => 0, + '\'k' => 0, + '\'k ' => 0, + '\'l ' => 0, + '\'n ' => 0, + '\'o ' => 0, + '\'p ' => 0, + '\'q' => 0, + '\'q ' => 0, + '\'r ' => 0, + '\'u' => 0, + '\'u ' => 0, + '\'v ' => 0, + '\'w ' => 0, + '\'x' => 0, + '\'x ' => 0, + '\'z' => 0, + '\'z ' => 0, + 'b\' ' => 0, + 'bg ' => 0, + 'bh ' => 0, + 'bp ' => 0, + 'bq' => 0, + 'bq ' => 0, + 'bv ' => 0, + 'bx' => 0, + 'bz' => 0, + 'bz ' => 0, + 'c\' ' => 0, + 'cf ' => 0, + 'cj' => 0, + 'cn ' => 0, + 'cq ' => 0, + 'cv' => 0, + 'cw' => 0, + 'cx' => 0, + 'cx ' => 0, + 'cz ' => 0, + 'db ' => 0, + 'dj ' => 0, + 'dk ' => 0, + 'dw ' => 0, + 'dx' => 0, + 'eh ' => 0, + 'ej ' => 0, + 'f\' ' => 0, + 'fg ' => 0, + 'fh ' => 0, + 'fj' => 0, + 'fj ' => 0, + 'fk' => 0, + 'fk ' => 0, + 'fq' => 0, + 'fq ' => 0, + 'fv ' => 0, + 'fw ' => 0, + 'fx' => 0, + 'fx ' => 0, + 'fz' => 0, + 'fz ' => 0, + 'g\' ' => 0, + 'gc ' => 0, + 'gf ' => 0, + 'gj ' => 0, + 'gk ' => 0, + 'gl ' => 0, + 'gq' => 0, + 'gq ' => 0, + 'gv' => 0, + 'gv ' => 0, + 'gw ' => 0, + 'gx' => 0, + 'gx ' => 0, + 'gz ' => 0, + 'hb ' => 0, + 'hc ' => 0, + 'hg ' => 0, + 'hh ' => 0, + 'hj' => 0, + 'hj ' => 0, + 'hk ' => 0, + 'hv' => 0, + 'hv ' => 0, + 'hw ' => 0, + 'hx' => 0, + 'hx ' => 0, + 'hz' => 0, + 'i\' ' => 0, + 'ih ' => 0, + 'iq ' => 0, + 'iw ' => 0, + 'j\'' => 0, + 'j\' ' => 0, + 'jb' => 0, + 'jb ' => 0, + 'jc' => 0, + 'jc ' => 0, + 'jd' => 0, + 'jf' => 0, + 'jg' => 0, + 'jg ' => 0, + 'jh' => 0, + 'jh ' => 0, + 'jj' => 0, + 'jj ' => 0, + 'jk ' => 0, + 'jl ' => 0, + 'jm' => 0, + 'jm ' => 0, + 'jn' => 0, + 'jn ' => 0, + 'jp ' => 0, + 'jq' => 0, + 'jq ' => 0, + 'jr' => 0, + 'jr ' => 0, + 'js' => 0, + 'js ' => 0, + 'jt' => 0, + 'ju ' => 0, + 'jv' => 0, + 'jv ' => 0, + 'jw' => 0, + 'jw ' => 0, + 'jx' => 0, + 'jx ' => 0, + 'jy' => 0, + 'jy ' => 0, + 'jz' => 0, + 'jz ' => 0, + 'kb ' => 0, + 'kc ' => 0, + 'kd ' => 0, + 'kj ' => 0, + 'km ' => 0, + 'kp ' => 0, + 'kq' => 0, + 'kq ' => 0, + 'kv' => 0, + 'kv ' => 0, + 'kx' => 0, + 'kx ' => 0, + 'kz' => 0, + 'kz ' => 0, + 'lg ' => 0, + 'lh ' => 0, + 'lj ' => 0, + 'lq ' => 0, + 'lr ' => 0, + 'lv ' => 0, + 'lw ' => 0, + 'lx' => 0, + 'lz ' => 0, + 'm\' ' => 0, + 'mg ' => 0, + 'mh ' => 0, + 'mj ' => 0, + 'mk ' => 0, + 'mq' => 0, + 'mq ' => 0, + 'mx' => 0, + 'mx ' => 0, + 'mz' => 0, + 'nb ' => 0, + 'nm ' => 0, + 'pj ' => 0, + 'pk ' => 0, + 'pq' => 0, + 'pq ' => 0, + 'pv' => 0, + 'pw ' => 0, + 'px' => 0, + 'px ' => 0, + 'pz ' => 0, + 'q\'' => 0, + 'q\' ' => 0, + 'qa ' => 0, + 'qb' => 0, + 'qb ' => 0, + 'qc' => 0, + 'qc ' => 0, + 'qd' => 0, + 'qd ' => 0, + 'qe' => 0, + 'qe ' => 0, + 'qf' => 0, + 'qf ' => 0, + 'qg' => 0, + 'qg ' => 0, + 'qh' => 0, + 'qh ' => 0, + 'qi' => 0, + 'qj' => 0, + 'qj ' => 0, + 'qk' => 0, + 'qk ' => 0, + 'ql' => 0, + 'ql ' => 0, + 'qm' => 0, + 'qm ' => 0, + 'qn' => 0, + 'qn ' => 0, + 'qo' => 0, + 'qo ' => 0, + 'qp' => 0, + 'qp ' => 0, + 'qq' => 0, + 'qq ' => 0, + 'qr' => 0, + 'qs' => 0, + 'qs ' => 0, + 'qt' => 0, + 'qt ' => 0, + 'qu ' => 0, + 'qv' => 0, + 'qv ' => 0, + 'qw' => 0, + 'qw ' => 0, + 'qx' => 0, + 'qx ' => 0, + 'qy' => 0, + 'qy ' => 0, + 'qz' => 0, + 'qz ' => 0, + 'rq ' => 0, + 'rz ' => 0, + 'sg ' => 0, + 'sj ' => 0, + 'sx' => 0, + 'sx ' => 0, + 'sz' => 0, + 'sz ' => 0, + 'tg ' => 0, + 'tj ' => 0, + 'tq' => 0, + 'tq ' => 0, + 'tx' => 0, + 'tx ' => 0, + 'uj ' => 0, + 'uq ' => 0, + 'uu ' => 0, + 'uw ' => 0, + 'v\' ' => 0, + 'vb' => 0, + 'vb ' => 0, + 'vc' => 0, + 'vf' => 0, + 'vf ' => 0, + 'vg' => 0, + 'vh' => 0, + 'vh ' => 0, + 'vj' => 0, + 'vj ' => 0, + 'vk' => 0, + 'vk ' => 0, + 'vl ' => 0, + 'vm' => 0, + 'vn ' => 0, + 'vp' => 0, + 'vp ' => 0, + 'vq' => 0, + 'vq ' => 0, + 'vr ' => 0, + 'vv ' => 0, + 'vw' => 0, + 'vw ' => 0, + 'vx' => 0, + 'vz' => 0, + 'vz ' => 0, + 'w\' ' => 0, + 'wb ' => 0, + 'wc ' => 0, + 'wf ' => 0, + 'wg ' => 0, + 'wj' => 0, + 'wj ' => 0, + 'wq' => 0, + 'wq ' => 0, + 'wr ' => 0, + 'wv' => 0, + 'wv ' => 0, + 'wx' => 0, + 'wz ' => 0, + 'x\'' => 0, + 'x\' ' => 0, + 'xa ' => 0, + 'xb ' => 0, + 'xc ' => 0, + 'xd' => 0, + 'xd ' => 0, + 'xf ' => 0, + 'xg ' => 0, + 'xh ' => 0, + 'xj' => 0, + 'xj ' => 0, + 'xk' => 0, + 'xk ' => 0, + 'xl ' => 0, + 'xm ' => 0, + 'xn' => 0, + 'xn ' => 0, + 'xp ' => 0, + 'xq ' => 0, + 'xr' => 0, + 'xr ' => 0, + 'xs ' => 0, + 'xu ' => 0, + 'xv' => 0, + 'xv ' => 0, + 'xw ' => 0, + 'xx' => 0, + 'xz' => 0, + 'xz ' => 0, + 'yb ' => 0, + 'yc ' => 0, + 'yd ' => 0, + 'yf ' => 0, + 'yg ' => 0, + 'yh ' => 0, + 'yj ' => 0, + 'yq' => 0, + 'yq ' => 0, + 'yu ' => 0, + 'yv ' => 0, + 'yw ' => 0, + 'yy' => 0, + 'yy ' => 0, + 'yz ' => 0, + 'z\'' => 0, + 'z\' ' => 0, + 'zb ' => 0, + 'zc' => 0, + 'zc ' => 0, + 'zd' => 0, + 'zd ' => 0, + 'zf' => 0, + 'zf ' => 0, + 'zg ' => 0, + 'zh' => 0, + 'zh ' => 0, + 'zj' => 0, + 'zj ' => 0, + 'zk ' => 0, + 'zl ' => 0, + 'zn' => 0, + 'zn ' => 0, + 'zp ' => 0, + 'zq' => 0, + 'zq ' => 0, + 'zr' => 0, + 'zr ' => 0, + 'zs' => 0, + 'zs ' => 0, + 'zt' => 0, + 'zt ' => 0, + 'zu ' => 0, + 'zv ' => 0, + 'zw ' => 0, + 'zx' => 0, + 'zx ' => 0, + ); - /** - * - * @param array|null $words_exceptions - */ - public function __construct(array $words_exceptions = null) - { - if (! ReflectionTypeHint::isValid()) return false; - #русский --> английский: - $this->en_correct = '/(?: (?:' . $this->tt_f . ') + /** + * + * @param array|null $words_exceptions + */ + public function __construct(array $words_exceptions = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + #русский --> английский: + $this->en_correct = '/(?: (?:' . $this->tt_f . ') (?: (?:' . $this->en_uniq . ') | (?:' . $this->en_sc . '){2} ) | (?:' . $this->en_sc . ') (?:' . $this->tt_f . ') @@ -2807,8 +2833,8 @@ class Text_LangCorrect (?:' . $this->tt_f . ') ) /sxSX'; - #английский --> русский: - $this->tt_correct = '/(?: (?:' . $this->en_sc . ') + #английский --> русский: + $this->tt_correct = '/(?: (?:' . $this->en_sc . ') (?: (?:' . $this->tt_uniq . ') | (?:' . $this->tt_f . '){2} ) | (?:' . $this->tt_f . ') (?:' . $this->en_sc . ') @@ -2817,69 +2843,76 @@ class Text_LangCorrect (?:' . $this->en_sc . ') ) /sxSX'; - $this->table_flip = array( - 0 => array_flip($this->table[0]), - 1 => array_flip($this->table[1]), - ); - if (is_array($words_exceptions)) $this->words_exceptions += $words_exceptions; - } + $this->table_flip = array( + 0 => array_flip($this->table[0]), + 1 => array_flip($this->table[1]), + ); + if (is_array($words_exceptions)) { + $this->words_exceptions += $words_exceptions; + } + } - /** - * Исправляет клавиатурные опечатки в тексте. - * - * @param scalar|null $s Текст в кодировке UTF-8. - * @param int $mode Константы self::SIMILAR_CHARS и/или self::KEYBOARD_LAYOUT, - * (их можно комбинировать). Описание констант см. выше. - * При использовании self::KEYBOARD_LAYOUT время работы увеличивается примерно в 10 раз. - * @param array &$words Ассоц. массив со словами, которые были исправлены: - * в ключах оригиналы, в значениях исправленные слова. - * @return string|bool Returns FALSE if error occured - */ - public function parse($s, $mode = self::SIMILAR_CHARS, array &$words = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; + /** + * Исправляет клавиатурные опечатки в тексте. + * + * @param scalar|null $s Текст в кодировке UTF-8. + * @param int $mode Константы self::SIMILAR_CHARS и/или self::KEYBOARD_LAYOUT, + * (их можно комбинировать). Описание констант см. выше. + * При использовании self::KEYBOARD_LAYOUT время работы увеличивается примерно в 10 раз. + * @param array &$words Ассоц. массив со словами, которые были исправлены: + * в ключах оригиналы, в значениях исправленные слова. + * @return string|bool Returns FALSE if error occured + */ + public function parse($s, $mode = self::SIMILAR_CHARS, array &$words = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (!is_string($s)) { + return $s; + } - if ($mode < self::SIMILAR_CHARS || $mode > (self::SIMILAR_CHARS | self::KEYBOARD_LAYOUT | self::ADD_FIX)) - { - trigger_error('Unknown mode', E_USER_WARNING); - return false; - } + if ($mode < self::SIMILAR_CHARS || $mode > (self::SIMILAR_CHARS | self::KEYBOARD_LAYOUT | self::ADD_FIX)) { + trigger_error('Unknown mode', E_USER_WARNING); + return false; + } - $this->mode = $mode; + $this->mode = $mode; - #вырезаем и заменяем некоторые символы - $additional_chars = array( - "\xc2\xad", #"мягкие" переносы строк (­) - ); - #http://ru.wikipedia.org/wiki/Диакритические_знаки - $s = UTF8::diactrical_remove($s, $additional_chars, $is_can_restored = true, $restore_table); + #вырезаем и заменяем некоторые символы + $additional_chars = array( + "\xc2\xad", #"мягкие" переносы строк (­) + ); + #http://ru.wikipedia.org/wiki/Диакритические_знаки + $s = UTF8::diactrical_remove($s, $additional_chars, $is_can_restored = true, $restore_table); - $this->words = array(); - $s = $this->_parse1($s); - $s = $this->_parse2($s); - $s = UTF8::diactrical_restore($s, $restore_table); - $words = $this->words; - return $s; - } + $this->words = array(); + $s = $this->_parse1($s); + $s = $this->_parse2($s); + $s = UTF8::diactrical_restore($s, $restore_table); + $words = $this->words; + return $s; + } - private function _parse1($s) - { - #заменяем слова из текста, минимальная длина -- 3 символа, меньше нельзя - return preg_replace_callback('/(?> (' . $this->en . ') #1 латинские буквы + private function _parse1($s) + { + #заменяем слова из текста, минимальная длина -- 3 символа, меньше нельзя + return preg_replace_callback('/(?> (' . $this->en . ') #1 латинские буквы | (' . $this->tt . ') #2 русские буквы | (' . $this->sc . ') #3 символы, которые м.б. набраны по ошибке в английской раскладке клавиатуры вместо русских букв ){3,}+ /sxSX', array($this, '_word'), $s); - } + } - private function _parse2($s) - { - #исправляем русские буквы (похожие на латинские) с рядом стоящими цифрами на латинские - #например, это м. б. каталожные номера автозапчастей, в которых есть русские буквы: 1500A023, 52511-60900-H0, K2305, XA527672 - #корректно обрабатываем вхождения '1-ое', 'Ту-134', 'А19-3107/06-43-Ф02-4227/06-С1' - if (version_compare(PHP_VERSION, '5.2.0', '<')) return $s; - return preg_replace_callback('~(?: (?<=[^-_/]|^) + private function _parse2($s) + { + #исправляем русские буквы (похожие на латинские) с рядом стоящими цифрами на латинские + #например, это м. б. каталожные номера автозапчастей, в которых есть русские буквы: 1500A023, 52511-60900-H0, K2305, XA527672 + #корректно обрабатываем вхождения '1-ое', 'Ту-134', 'А19-3107/06-43-Ф02-4227/06-С1' + if (version_compare(PHP_VERSION, '5.2.0', '<')) { + return $s; + } + return preg_replace_callback('~(?: (?<=[^-_/]|^) (?:' . $this->ru_similar . ')++ (?= (?:' . $this->en . '|[-_/])*+ (?<=[^-_/]|' . $this->en . '[-_/]) \d [\d-_/]*+ (?!' . $this->tt_uniq . ') @@ -2891,218 +2924,264 @@ class Text_LangCorrect (?= [\d-_/]*+ (?!' . $this->tt_uniq . ') ) ) ~sxSX', array($this, '_entry'), $s); - } + } - private function _entry(array &$a) - { - $entry =& $a[0]; - $s = strtr($entry, $this->table[0]); - if ($s !== $entry) $this->words[$entry] = $s; - return $s; - } + private function _entry(array &$a) + { + $entry =& $a[0]; + $s = strtr($entry, $this->table[0]); + if ($s !== $entry) { + $this->words[$entry] = $s; + } + return $s; + } - private function _word(array &$a) - { - $word = $a[0]; - #var_export($a); + private function _word(array &$a) + { + $word = $a[0]; + #var_export($a); - $suggestions = array(); + $suggestions = array(); - #если найдено слово из мешанины русских и латинских букв - if (! empty($a[1]) && ! empty($a[2])) - { - if (($this->mode & self::SIMILAR_CHARS) === 0) return $word; - #ВНИМАНИЕ! порядок следования правил преобразования имеет значение! + #если найдено слово из мешанины русских и латинских букв + if (!empty($a[1]) && !empty($a[2])) { + if (($this->mode & self::SIMILAR_CHARS) === 0) { + return $word; + } + #ВНИМАНИЕ! порядок следования правил преобразования имеет значение! - /* + /* Исправляем ошибочно набранные буквы, которые выглядят одинаково в инициалах перед фамилиями (русский <--> английский), например: Т.С.Навка - */ + */ - #0a. английский --> русский: - if (substr($word, 1, 1) === '.' #оптимизация - && preg_match('/^ ( ' . $this->en_similar_uc . '\. #первый инициал + #0a. английский --> русский: + if (substr($word, 1, 1) === '.' #оптимизация + && preg_match('/^ ( ' . $this->en_similar_uc . '\. #первый инициал (?:' . $this->en_similar_uc . '\.)? #второй инициал (необязательно) ) #1 инициалы (' . $this->no_sc . '{2,}+) #2 фамилия (английские и русские буквы) - $/sxSX', $word, $m)) - { - $m[2] = $this->_parse1($m[2]); - #фамилия по-русски? - if (preg_match('/^ (?:' . $this->tt_uc . ') #первая буква д.б. большая - (?:' . $this->tt_f . ')+ #минимальное кол-во букв в фамилии = 2 - $/sxSX', $m[2])) return strtr($m[1], $this->table_flip[0]) . $m[2]; - } + $/sxSX', $word, $m) + ) { + $m[2] = $this->_parse1($m[2]); + #фамилия по-русски? + if (preg_match('/^ (?:' . $this->tt_uc . ') #первая буква д.б. большая + (?:' . $this->tt_f . ')+ #минимальное кол-во букв в фамилии = 2 + $/sxSX', $m[2])) { + return strtr($m[1], $this->table_flip[0]) . $m[2]; + } + } - #0b. русский --> английский: - if (substr($word, 2, 1) === '.' #оптимизация - && preg_match('/^ ( ' . $this->ru_similar_uc . '\. #первый инициал + #0b. русский --> английский: + if (substr($word, 2, 1) === '.' #оптимизация + && preg_match('/^ ( ' . $this->ru_similar_uc . '\. #первый инициал (?:' . $this->ru_similar_uc . '\.)? #второй инициал (необязательно) ) #1 инициалы (' . $this->no_sc . '{2,}+) #2 фамилия (английские и русские буквы) - $/sxSX', $word, $m)) - { - $m[2] = $this->_parse1($m[2]); - #фамилия по-англ.? - if (preg_match('/^ ' . $this->en_uc . ' #первая буква д.б. большая + $/sxSX', $word, $m) + ) { + $m[2] = $this->_parse1($m[2]); + #фамилия по-англ.? + if (preg_match('/^ ' . $this->en_uc . ' #первая буква д.б. большая ' . $this->en . '++ #минимальное кол-во букв в фамилии = 2 - $/sxSX', $m[2])) return strtr($m[1], $this->table[0]) . $m[2]; - } + $/sxSX', $m[2])) { + return strtr($m[1], $this->table[0]) . $m[2]; + } + } - #1. английский --> русский: - $this->method = 0; #буквы, которые выглядят одинаково - $this->is_flip = true; - $s = $this->_replace($word, $this->tt_correct); - if ($word !== $s && ! $this->_is_mixed($s)) $suggestions['tt0'] = $s; + #1. английский --> русский: + $this->method = 0; #буквы, которые выглядят одинаково + $this->is_flip = true; + $s = $this->_replace($word, $this->tt_correct); + if ($word !== $s && !$this->_is_mixed($s)) { + $suggestions['tt0'] = $s; + } - #2. английский --> русский: - $this->method = 1; #буквы в другой раскладке клавиатуры - $this->is_flip = true; - $s = $this->_replace($word, $this->tt_correct); - if ($word !== $s) $suggestions['tt1'] = $s; + #2. английский --> русский: + $this->method = 1; #буквы в другой раскладке клавиатуры + $this->is_flip = true; + $s = $this->_replace($word, $this->tt_correct); + if ($word !== $s) { + $suggestions['tt1'] = $s; + } - #3. русский --> английский: - $this->method = 0; #буквы, которые выглядят одинаково - $this->is_flip = false; - $s = $this->_replace($word, $this->en_correct); - if ($word !== $s && ! $this->_is_mixed($s)) $suggestions['en0'] = $s; + #3. русский --> английский: + $this->method = 0; #буквы, которые выглядят одинаково + $this->is_flip = false; + $s = $this->_replace($word, $this->en_correct); + if ($word !== $s && !$this->_is_mixed($s)) { + $suggestions['en0'] = $s; + } - #4. русский --> английский: - $this->method = 1; #буквы в другой раскладке клавиатуры - $this->is_flip = false; - $s = $this->_replace($word, $this->en_correct); - if ($word !== $s) $suggestions['en1'] = $s; + #4. русский --> английский: + $this->method = 1; #буквы в другой раскладке клавиатуры + $this->is_flip = false; + $s = $this->_replace($word, $this->en_correct); + if ($word !== $s) { + $suggestions['en1'] = $s; + } + } #если найдено слово только из латинских букв; минимальная длина -- 4 буквы! + elseif (!empty($a[1]) && strlen($word) >= 4) { + if (($this->mode & self::KEYBOARD_LAYOUT) === 0) { + return $word; + } - } - #если найдено слово только из латинских букв; минимальная длина -- 4 буквы! - elseif (! empty($a[1]) && strlen($word) >= 4) - { - if (($this->mode & self::KEYBOARD_LAYOUT) === 0) return $word; + #не обрабатываем аббревиатуры, пример: AMPAS + if (preg_match('/^(?:' . $this->en_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) { + return $word; + } - #не обрабатываем аббревиатуры, пример: AMPAS - if (preg_match('/^(?:' . $this->en_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) return $word; + #английский --> русский: + $suggestions['en1'] = $word; + $suggestions['tt1'] = strtr($word, $this->table_flip[1]); + } #если найдено слово только из русских букв; минимальная длина -- 4 буквы! + elseif (!empty($a[2]) && strlen($word) >= 8) { + if (($this->mode & self::KEYBOARD_LAYOUT) === 0) { + return $word; + } - #английский --> русский: - $suggestions['en1'] = $word; - $suggestions['tt1'] = strtr($word, $this->table_flip[1]); - } - #если найдено слово только из русских букв; минимальная длина -- 4 буквы! - elseif (! empty($a[2]) && strlen($word) >= 8) - { - if (($this->mode & self::KEYBOARD_LAYOUT) === 0) return $word; + #не обрабатываем аббревиатуры, пример: ДОСААФ + if (preg_match('/^(?:' . $this->tt_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) { + return $word; + } - #не обрабатываем аббревиатуры, пример: ДОСААФ - if (preg_match('/^(?:' . $this->tt_uc . '|' . $this->sc . '){1,6}+$/sxSX', $word)) return $word; + #русский --> английский: + $suggestions['tt1'] = $word; + $suggestions['en1'] = strtr($word, $this->table[1]); + } #найдены спецсимволы или длина слова слишком мала + else { + return $word; + } - #русский --> английский: - $suggestions['tt1'] = $word; - $suggestions['en1'] = strtr($word, $this->table[1]); - } - #найдены спецсимволы или длина слова слишком мала - else return $word; + $suggestions = array_unique($suggestions); + #var_export($suggestions); - $suggestions = array_unique($suggestions); - #var_export($suggestions); + $c = count($suggestions); + if ($c === 0) { + $s = $word; + } else { + $s = $this->_detect($word, $suggestions, !empty($a[3])); + } + if ($s !== $word) { + $this->words[$word] = $s; + if ($this->mode >= (self::KEYBOARD_LAYOUT | self::ADD_FIX)) { + $s = '(' . $word . '=>' . $s . ')'; + } + } + return $s; + } - $c = count($suggestions); - if ($c === 0) $s = $word; - else $s = $this->_detect($word, $suggestions, ! empty($a[3])); - if ($s !== $word) - { - $this->words[$word] = $s; - if ($this->mode >= (self::KEYBOARD_LAYOUT | self::ADD_FIX)) $s = '(' . $word . '=>' . $s . ')'; - } - return $s; - } + private function _replace($word, $regexp) + { + do { + $word = preg_replace_callback($regexp, array(&$this, '_strtr'), $w = $word); + } while ($w !== $word); + return $word; + } - private function _replace($word, $regexp) - { - do $word = preg_replace_callback($regexp, array(&$this, '_strtr'), $w = $word); - while ($w !== $word); - return $word; - } + private function _strtr(array $a) + { + $word =& $a[0]; + return strtr($word, $this->is_flip ? $this->table_flip[$this->method] : $this->table[$this->method]); + } - private function _strtr(array $a) - { - $word =& $a[0]; - return strtr($word, $this->is_flip ? $this->table_flip[$this->method] : $this->table[$this->method]); - } + private function _is_mixed($word) + { + return preg_match('/(?:' . $this->en . ')/sxSX', $word) && + preg_match('/(?:' . $this->tt_f . ')/sxSX', $word); + } - private function _is_mixed($word) - { - return preg_match('/(?:' . $this->en . ')/sxSX', $word) && - preg_match('/(?:' . $this->tt_f . ')/sxSX', $word); - } + #выбираем из нескольких вариантов один + private function _detect($word, array $suggestions, $is_sc) + { + if (0) { + #DEBUG - #выбираем из нескольких вариантов один - private function _detect($word, array $suggestions, $is_sc) - { - if (0) #DEBUG - { - //$suggestions['?'] = $word; - var_export($suggestions); - } - #не д. б. несуществующих N-грамм - foreach ($suggestions as $type => $w) - { - $lang = substr($type, 0, 2); - if ($this->_bigram_exists($w, $lang)) unset($suggestions[$type]); - } - if (0) #DEBUG - { - //$suggestions['?'] = $word; - var_export($suggestions); - } - if (count($suggestions) === 0) return $word; + //$suggestions['?'] = $word; + var_export($suggestions); + } + #не д. б. несуществующих N-грамм + foreach ($suggestions as $type => $w) { + $lang = substr($type, 0, 2); + if ($this->_bigram_exists($w, $lang)) { + unset($suggestions[$type]); + } + } + if (0) { + #DEBUG - $s = end($suggestions); + //$suggestions['?'] = $word; + var_export($suggestions); + } + if (count($suggestions) === 0) { + return $word; + } - #если в $word были спецсимволы, а в $s их уже нет, возвращаем $s - if ($is_sc && ! preg_match('/' . $this->sc . '/sSX', $s)) return $s; + $s = end($suggestions); - #если в $s спецсимволов больше чем букв, возвращаем $word - $sc_count = 0; - $s = preg_replace('/' . $this->sc . '/sSX', '', $s, -1, $sc_count); - if ($sc_count > 0 && $sc_count > UTF8::strlen($s)) return $word; + #если в $word были спецсимволы, а в $s их уже нет, возвращаем $s + if ($is_sc && !preg_match('/' . $this->sc . '/sSX', $s)) { + return $s; + } - return reset($suggestions); - } + #если в $s спецсимволов больше чем букв, возвращаем $word + $sc_count = 0; + $s = preg_replace('/' . $this->sc . '/sSX', '', $s, -1, $sc_count); + if ($sc_count > 0 && $sc_count > UTF8::strlen($s)) { + return $word; + } - #анализ на основе N-грамм русского и английского языка - private function _bigram_exists($word, $lang) - { - $word = ($lang === 'en') ? strtolower($word) : UTF8::lowercase($word); + return reset($suggestions); + } - #шаг 0. - #проверяем слова в списке слов-исключений - if (array_key_exists($word, $this->words_exceptions[$lang])) return false; + #анализ на основе N-грамм русского и английского языка + private function _bigram_exists($word, $lang) + { + $word = ($lang === 'en') ? strtolower($word) : UTF8::lowercase($word); - #шаг 1. - #проверка на 4 согласные буквы подряд; пример: больши{нств}о, юрисконсу{льтс}тво - if (preg_match('/(?:' . $this->consonant_lc[$lang] . '){4}/sxSX', $word, $m) - #проверяем список исключений - && ! array_key_exists($m[0], $this->consonants4_lc[$lang])) return true; + #шаг 0. + #проверяем слова в списке слов-исключений + if (array_key_exists($word, $this->words_exceptions[$lang])) { + return false; + } - #шаг 2. - #проверка на 3 гласные буквы подряд; пример: длиннош{еее}, зм{еео}бразный - if (preg_match('/(?:' . $this->vowel_lc[$lang] . '){3}/sxSX', $word, $m) - #проверяем список исключений - && ! array_key_exists($m[0], $this->vowels3_lc[$lang])) return true; + #шаг 1. + #проверка на 4 согласные буквы подряд; пример: больши{нств}о, юрисконсу{льтс}тво + if (preg_match('/(?:' . $this->consonant_lc[$lang] . '){4}/sxSX', $word, $m) + #проверяем список исключений + && !array_key_exists($m[0], $this->consonants4_lc[$lang]) + ) { + return true; + } - #шаг 3. - $length = UTF8::strlen($word); - for ($pos = 0, $limit = $length - 1; $pos < $limit; $pos++) - { - /* + #шаг 2. + #проверка на 3 гласные буквы подряд; пример: длиннош{еее}, зм{еео}бразный + if (preg_match('/(?:' . $this->vowel_lc[$lang] . '){3}/sxSX', $word, $m) + #проверяем список исключений + && !array_key_exists($m[0], $this->vowels3_lc[$lang]) + ) { + return true; + } + + #шаг 3. + $length = UTF8::strlen($word); + for ($pos = 0, $limit = $length - 1; $pos < $limit; $pos++) { + /* TODO Качество проверки по несуществующим биграммам можно немного повысить, если учитывать не только начало и конец слова, но и все позиции биграмм в слове. - */ - $ss = UTF8::substr($word, $pos, 2); - if ($pos === 0) $ss = ' ' . $ss; #beginning of word - elseif ($pos === $limit - 1) $ss = $ss . ' '; #ending of word - if (array_key_exists($ss, $this->bigrams)) return true; - } + */ + $ss = UTF8::substr($word, $pos, 2); + if ($pos === 0) { + $ss = ' ' . $ss; + } #beginning of word + elseif ($pos === $limit - 1) { + $ss = $ss . ' '; + } #ending of word + if (array_key_exists($ss, $this->bigrams)) { + return true; + } + } - return false; - } -} \ No newline at end of file + return false; + } +} diff --git a/library/includes/classes/emailer.php b/library/includes/classes/emailer.php index 43ea648a3..dc75409a6 100644 --- a/library/includes/classes/emailer.php +++ b/library/includes/classes/emailer.php @@ -1,244 +1,247 @@ reset(); - $this->from = $bb_cfg['board_email']; - $this->reply_to = $bb_cfg['board_email']; - $this->use_smtp = $use_smtp; /*!empty($bb_cfg['smtp_host']); + $this->reset(); + $this->from = $bb_cfg['board_email']; + $this->reply_to = $bb_cfg['board_email']; + $this->use_smtp = $use_smtp; /*!empty($bb_cfg['smtp_host']); - $this->use_template($tpl_name); - $this->set_subject($sbj); - $this->email_address($to_address);*/ - } + $this->use_template($tpl_name); + $this->set_subject($sbj); + $this->email_address($to_address);*/ + } - public function set_default_vars () - { - global $bb_cfg; + public function set_default_vars() + { + global $bb_cfg; - $this->vars = array( - 'BOARD_EMAIL' => $bb_cfg['board_email'], - 'SITENAME' => $bb_cfg['board_email_sitename'], - 'EMAIL_SIG' => !empty($bb_cfg['board_email_sig']) ? "-- \n{$bb_cfg['board_email_sig']}" : '', - ); - } + $this->vars = array( + 'BOARD_EMAIL' => $bb_cfg['board_email'], + 'SITENAME' => $bb_cfg['board_email_sitename'], + 'EMAIL_SIG' => !empty($bb_cfg['board_email_sig']) ? "-- \n{$bb_cfg['board_email_sig']}" : '', + ); + } - // Resets all the data (address, template file, etc etc to default - public function reset () - { - $this->addresses = array(); - $this->msg = $this->extra_headers = ''; - $this->set_default_vars(); - } + // Resets all the data (address, template file, etc etc to default + public function reset() + { + $this->addresses = array(); + $this->msg = $this->extra_headers = ''; + $this->set_default_vars(); + } - // Sets an email address to send to - public function email_address ($address) - { - $this->addresses['to'] = trim($address); - } + // Sets an email address to send to + public function email_address($address) + { + $this->addresses['to'] = trim($address); + } - public function cc ($address) - { - $this->addresses['cc'][] = trim($address); - } + public function cc($address) + { + $this->addresses['cc'][] = trim($address); + } - public function bcc ($address) - { - $this->addresses['bcc'][] = trim($address); - } + public function bcc($address) + { + $this->addresses['bcc'][] = trim($address); + } - public function replyto ($address) - { - $this->reply_to = trim($address); - } + public function replyto($address) + { + $this->reply_to = trim($address); + } - public function from ($address) - { - $this->from = trim($address); - } + public function from($address) + { + $this->from = trim($address); + } - // set up subject for mail - public function set_subject ($subject = '') - { - $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); - } + // set up subject for mail + public function set_subject($subject = '') + { + $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); + } - // set up extra mail headers - public function extra_headers ($headers) - { - $this->extra_headers .= trim($headers) . "\n"; - } + // set up extra mail headers + public function extra_headers($headers) + { + $this->extra_headers .= trim($headers) . "\n"; + } - public function use_template ($template_file, $template_lang = '') - { - global $bb_cfg; + public function use_template($template_file, $template_lang = '') + { + global $bb_cfg; - if (trim($template_file) == '') - { - bb_die('No template file set'); - } + if (trim($template_file) == '') { + bb_die('No template file set'); + } - if (trim($template_lang) == '') - { - $template_lang = $bb_cfg['default_lang']; - } + if (trim($template_lang) == '') { + $template_lang = $bb_cfg['default_lang']; + } - if (empty($this->tpl_msg[$template_lang . $template_file])) - { - $tpl_file = LANG_ROOT_DIR ."$template_lang/email/$template_file.html"; + if (empty($this->tpl_msg[$template_lang . $template_file])) { + $tpl_file = LANG_ROOT_DIR . "$template_lang/email/$template_file.html"; - if (!@file_exists(@bb_realpath($tpl_file))) - { - $tpl_file = LANG_ROOT_DIR ."{$bb_cfg['default_lang']}/email/$template_file.html"; + if (!@file_exists(@bb_realpath($tpl_file))) { + $tpl_file = LANG_ROOT_DIR . "{$bb_cfg['default_lang']}/email/$template_file.html"; - if (!@file_exists(@bb_realpath($tpl_file))) - { - bb_die('Could not find email template file :: ' . $template_file); - } - } + if (!@file_exists(@bb_realpath($tpl_file))) { + bb_die('Could not find email template file :: ' . $template_file); + } + } - if (!($fd = @fopen($tpl_file, 'r'))) - { - bb_die('Failed opening template file :: ' . $tpl_file); - } + if (!($fd = @fopen($tpl_file, 'r'))) { + bb_die('Failed opening template file :: ' . $tpl_file); + } - $this->tpl_msg[$template_lang . $template_file] = fread($fd, filesize($tpl_file)); - fclose($fd); - } + $this->tpl_msg[$template_lang . $template_file] = fread($fd, filesize($tpl_file)); + fclose($fd); + } - $this->msg = $this->tpl_msg[$template_lang . $template_file]; + $this->msg = $this->tpl_msg[$template_lang . $template_file]; - return true; - } + return true; + } - // assign variables - public function assign_vars ($vars) - { - $this->vars = array_merge($this->vars, $vars); - } + // assign variables + public function assign_vars($vars) + { + $this->vars = array_merge($this->vars, $vars); + } - // Send the mail out to the recipients set previously in var $this->address - public function send ($email_format = 'text') - { - global $bb_cfg, $userdata; + // Send the mail out to the recipients set previously in var $this->address + public function send($email_format = 'text') + { + global $bb_cfg, $userdata; - if ($bb_cfg['emailer_disabled']) - { - return; - } + if ($bb_cfg['emailer_disabled']) { + return; + } - // Escape all quotes - $this->msg = str_replace ("'", "\'", $this->msg); - $this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg); + // Escape all quotes + $this->msg = str_replace("'", "\'", $this->msg); + $this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg); - // Set vars - reset ($this->vars); - while (list($key, $val) = each($this->vars)) - { - $$key = $val; - } + // Set vars + reset($this->vars); + while (list($key, $val) = each($this->vars)) { + $$key = $val; + } - eval("\$this->msg = '$this->msg';"); + eval("\$this->msg = '$this->msg';"); - // Clear vars - reset ($this->vars); - while (list($key, $val) = each($this->vars)) - { - unset($$key); - } + // Clear vars + reset($this->vars); + while (list($key, $val) = each($this->vars)) { + unset($$key); + } - // We now try and pull a subject from the email body ... if it exists, - // do this here because the subject may contain a variable - $drop_header = ''; - $match = array(); - if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) - { - $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject'); - $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); - } - else - { - $this->subject = (($this->subject != '') ? $this->subject : 'No Subject'); - } + // We now try and pull a subject from the email body ... if it exists, + // do this here because the subject may contain a variable + $drop_header = ''; + $match = array(); + if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) { + $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject'); + $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); + } else { + $this->subject = (($this->subject != '') ? $this->subject : 'No Subject'); + } - if (preg_match('#^(Charset:(.*?))$#m', $this->msg, $match)) - { - $this->encoding = (trim($match[2]) != '') ? trim($match[2]) : trim($bb_cfg['lang'][$userdata['user_lang']]['encoding']); - $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); - } - else - { - $this->encoding = trim($bb_cfg['lang'][$userdata['user_lang']]['encoding']); - } - $this->subject = $this->encode($this->subject); + if (preg_match('#^(Charset:(.*?))$#m', $this->msg, $match)) { + $this->encoding = (trim($match[2]) != '') ? trim($match[2]) : trim($bb_cfg['lang'][$userdata['user_lang']]['encoding']); + $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); + } else { + $this->encoding = trim($bb_cfg['lang'][$userdata['user_lang']]['encoding']); + } + $this->subject = $this->encode($this->subject); - if ($drop_header != '') - { - $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg)); - } + if ($drop_header != '') { + $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg)); + } - $to = @$this->addresses['to']; + $to = @$this->addresses['to']; - $cc = (@count($this->addresses['cc'])) ? implode(', ', $this->addresses['cc']) : ''; - $bcc = (@count($this->addresses['bcc'])) ? implode(', ', $this->addresses['bcc']) : ''; + $cc = (@count($this->addresses['cc'])) ? implode(', ', $this->addresses['cc']) : ''; + $bcc = (@count($this->addresses['bcc'])) ? implode(', ', $this->addresses['bcc']) : ''; - // Build header - $type = ($email_format == 'html') ? 'html' : 'plain'; - $this->extra_headers = (($this->reply_to != '') ? "Reply-to: $this->reply_to\n" : '') . (($this->from != '') ? "From: $this->from\n" : "From: " . $bb_cfg['board_email'] . "\n") . "Return-Path: " . $bb_cfg['board_email'] . "\nMessage-ID: <" . md5(uniqid(TIMENOW)) . "@" . $bb_cfg['server_name'] . ">\nMIME-Version: 1.0\nContent-type: text/$type; charset=" . $this->encoding . "\nContent-transfer-encoding: 8bit\nDate: " . date('r', TIMENOW) . "\nX-Priority: 0\nX-MSMail-Priority: Normal\nX-Mailer: Microsoft Office Outlook, Build 11.0.5510\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441\nX-Sender: " . $bb_cfg['board_email'] . "\n" . $this->extra_headers . (($cc != '') ? "Cc: $cc\n" : '') . (($bcc != '') ? "Bcc: $bcc\n" : ''); + // Build header + $type = ($email_format == 'html') ? 'html' : 'plain'; + $this->extra_headers = (($this->reply_to != '') ? "Reply-to: $this->reply_to\n" : '') . (($this->from != '') ? "From: $this->from\n" : "From: " . $bb_cfg['board_email'] . "\n") . "Return-Path: " . $bb_cfg['board_email'] . "\nMessage-ID: <" . md5(uniqid(TIMENOW)) . "@" . $bb_cfg['server_name'] . ">\nMIME-Version: 1.0\nContent-type: text/$type; charset=" . $this->encoding . "\nContent-transfer-encoding: 8bit\nDate: " . date('r', TIMENOW) . "\nX-Priority: 0\nX-MSMail-Priority: Normal\nX-Mailer: Microsoft Office Outlook, Build 11.0.5510\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441\nX-Sender: " . $bb_cfg['board_email'] . "\n" . $this->extra_headers . (($cc != '') ? "Cc: $cc\n" : '') . (($bcc != '') ? "Bcc: $bcc\n" : ''); - // Send message - if ($this->use_smtp) - { - if (!defined('SMTP_INCLUDED')) - { - include(INC_DIR .'smtp.php'); - } + // Send message + if ($this->use_smtp) { + if (!defined('SMTP_INCLUDED')) { + include(INC_DIR . 'smtp.php'); + } - $result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers); - } - else - { - $to = ($to == '') ? ' ' : $to; + $result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers); + } else { + $to = ($to == '') ? ' ' : $to; - $result = @mail($to, $this->subject, preg_replace("#(?msg), $this->extra_headers); - } + $result = @mail($to, $this->subject, preg_replace("#(?msg), $this->extra_headers); + } - // Did it work? - if (!$result) - { - bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result); - } + // Did it work? + if (!$result) { + bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result); + } - return true; - } + return true; + } - public function encode ($str) - { - if ($this->encoding == '') - { - return $str; - } + public function encode($str) + { + if ($this->encoding == '') { + return $str; + } - // define start delimimter, end delimiter and spacer - $start = "=?$this->encoding?B?"; - $end = "?="; + // define start delimimter, end delimiter and spacer + $start = "=?$this->encoding?B?"; + $end = "?="; - // encode the string and split it into chunks with spacers after each chunk - $str = base64_encode($str); + // encode the string and split it into chunks with spacers after each chunk + $str = base64_encode($str); - return $start . $str . $end; - } + return $start . $str . $end; + } } diff --git a/library/includes/classes/recaptcha.php b/library/includes/classes/recaptcha.php index a1f972402..fee71caae 100644 --- a/library/includes/classes/recaptcha.php +++ b/library/includes/classes/recaptcha.php @@ -1,6 +1,31 @@ " . self::$_signupUrl . ""); - } - $this->_secret = $secret; - } + /** + * Constructor. + * + * @param string $secret shared secret between site and ReCAPTCHA server. + */ + public function __construct($secret) + { + if ($secret == null || $secret == "") { + die("To use Google reCAPTCHA you must get an API key from " . self::$_signupUrl . ""); + } + $this->_secret = $secret; + } - /** - * Encodes the given data into a query string format. - * - * @param array $data array of string elements to be encoded. - * - * @return string - encoded request. - */ - private function _encodeQS($data) - { - $req = ""; - foreach ($data as $key => $value) { - $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; - } + /** + * Encodes the given data into a query string format. + * + * @param array $data array of string elements to be encoded. + * + * @return string - encoded request. + */ + private function _encodeQS($data) + { + $req = ""; + foreach ($data as $key => $value) { + $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; + } - // Cut the last '&' - $req = substr($req, 0, strlen($req) - 1); - return $req; - } + // Cut the last '&' + $req = substr($req, 0, strlen($req) - 1); + return $req; + } - /** - * Submits an HTTP GET to a reCAPTCHA server. - * - * @param string $path url path to recaptcha server. - * @param array $data array of parameters to be sent. - * - * @return array response - */ - private function _submitHTTPGet($path, $data) - { - $req = $this->_encodeQS($data); - $response = file_get_contents($path . $req); - return $response; - } + /** + * Submits an HTTP GET to a reCAPTCHA server. + * + * @param string $path url path to recaptcha server. + * @param array $data array of parameters to be sent. + * + * @return array response + */ + private function _submitHTTPGet($path, $data) + { + $req = $this->_encodeQS($data); + $response = file_get_contents($path . $req); + return $response; + } - /** - * Calls the reCAPTCHA siteverify API to verify whether the user passes - * CAPTCHA test. - * - * @param string $remoteIp IP address of end user. - * @param string $response response string from recaptcha verification. - * - * @return ReCaptchaResponse - */ - public function verifyResponse($remoteIp, $response) - { - // Discard empty solution submissions - if ($response == null || strlen($response) == 0) { - $recaptchaResponse = new ReCaptchaResponse(); - $recaptchaResponse->success = false; - $recaptchaResponse->errorCodes = 'missing-input'; - return $recaptchaResponse; - } + /** + * Calls the reCAPTCHA siteverify API to verify whether the user passes + * CAPTCHA test. + * + * @param string $remoteIp IP address of end user. + * @param string $response response string from recaptcha verification. + * + * @return ReCaptchaResponse + */ + public function verifyResponse($remoteIp, $response) + { + // Discard empty solution submissions + if ($response == null || strlen($response) == 0) { + $recaptchaResponse = new ReCaptchaResponse(); + $recaptchaResponse->success = false; + $recaptchaResponse->errorCodes = 'missing-input'; + return $recaptchaResponse; + } - $getResponse = $this->_submitHttpGet( - self::$_siteVerifyUrl, - array( - 'secret' => $this->_secret, - 'remoteip' => $remoteIp, - 'v' => self::$_version, - 'response' => $response - ) - ); - $answers = json_decode($getResponse, true); - $recaptchaResponse = new ReCaptchaResponse(); + $getResponse = $this->_submitHttpGet( + self::$_siteVerifyUrl, + array( + 'secret' => $this->_secret, + 'remoteip' => $remoteIp, + 'v' => self::$_version, + 'response' => $response + ) + ); + $answers = json_decode($getResponse, true); + $recaptchaResponse = new ReCaptchaResponse(); - if (trim($answers['success']) == true) { - $recaptchaResponse->success = true; - } else { - $recaptchaResponse->success = false; - $recaptchaResponse->errorCodes = $answers['error-codes']; - } + if (trim($answers['success']) == true) { + $recaptchaResponse->success = true; + } else { + $recaptchaResponse->success = false; + $recaptchaResponse->errorCodes = $answers['error-codes']; + } - return $recaptchaResponse; - } + return $recaptchaResponse; + } } diff --git a/library/includes/classes/reflection.php b/library/includes/classes/reflection.php index ba0f59059..13e11d4f5 100644 --- a/library/includes/classes/reflection.php +++ b/library/includes/classes/reflection.php @@ -1,6 +1,31 @@ 'is_int', - 'integer' => 'is_int', - 'digit' => 'ctype_digit', - 'number' => 'ctype_digit', - 'float' => 'is_float', - 'double' => 'is_float', - 'real' => 'is_float', - 'numeric' => 'is_numeric', - 'str' => 'is_string', - 'string' => 'is_string', - 'char' => 'is_string', - 'bool' => 'is_bool', - 'boolean' => 'is_bool', - 'null' => 'is_null', - 'array' => 'is_array', - 'obj' => 'is_object', - 'object' => 'is_object', - 'res' => 'is_resource', - 'resource' => 'is_resource', - 'scalar' => 'is_scalar', #integer, float, string or boolean - 'cb' => 'is_callable', - 'callback' => 'is_callable', - ); + protected static $hints = array( + 'int' => 'is_int', + 'integer' => 'is_int', + 'digit' => 'ctype_digit', + 'number' => 'ctype_digit', + 'float' => 'is_float', + 'double' => 'is_float', + 'real' => 'is_float', + 'numeric' => 'is_numeric', + 'str' => 'is_string', + 'string' => 'is_string', + 'char' => 'is_string', + 'bool' => 'is_bool', + 'boolean' => 'is_bool', + 'null' => 'is_null', + 'array' => 'is_array', + 'obj' => 'is_object', + 'object' => 'is_object', + 'res' => 'is_resource', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', #integer, float, string or boolean + 'cb' => 'is_callable', + 'callback' => 'is_callable', + ); - #calling the methods of this class only statically! - private function __construct() {} + #calling the methods of this class only statically! + private function __construct() + { + } - public static function isValid() - { - if (! assert_options(ASSERT_ACTIVE)) return true; - $bt = self::debugBacktrace(null, 1); - extract($bt); //to $file, $line, $function, $class, $object, $type, $args - if (! $args) return true; #speed improve - $r = new ReflectionMethod($class, $function); - $doc = $r->getDocComment(); - $cache_id = $class. $type. $function; - preg_match_all('~ [\r\n]++ [\x20\t]++ \* [\x20\t]++ + public static function isValid() + { + if (!assert_options(ASSERT_ACTIVE)) { + return true; + } + $bt = self::debugBacktrace(null, 1); + extract($bt); //to $file, $line, $function, $class, $object, $type, $args + if (!$args) { + return true; + } #speed improve + $r = new ReflectionMethod($class, $function); + $doc = $r->getDocComment(); + $cache_id = $class . $type . $function; + preg_match_all('~ [\r\n]++ [\x20\t]++ \* [\x20\t]++ @param [\x20\t]++ \K #memory reduce @@ -77,111 +107,119 @@ class ReflectionTypeHint [\x20\t]++ &?+\$([_a-z]++[_a-z\d]*+) #2 name ~sixSX', $doc, $params, PREG_SET_ORDER); - $parameters = $r->getParameters(); - //d($args, $params, $parameters); - if (count($parameters) > count($params)) - { - $message = 'phpDoc %d piece(s) @param description expected in %s%s%s(), %s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, count($parameters), $class, $type, $function, count($params), $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_NOTICE); - } - foreach ($args as $i => $value) - { - if (! isset($params[$i])) return true; - if ($parameters[$i]->name !== $params[$i][2]) - { - $param_num = $i + 1; - $message = 'phpDoc @param %d in %s%s%s() must be named as $%s, $%s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, $param_num, $class, $type, $function, $parameters[$i]->name, $params[$i][2], $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_NOTICE); - } + $parameters = $r->getParameters(); + //d($args, $params, $parameters); + if (count($parameters) > count($params)) { + $message = 'phpDoc %d piece(s) @param description expected in %s%s%s(), %s given, ' . PHP_EOL + . 'called in %s on line %d ' . PHP_EOL + . 'and defined in %s on line %d'; + $message = sprintf($message, count($parameters), $class, $type, $function, count($params), $file, $line, $r->getFileName(), $r->getStartLine()); + trigger_error($message, E_USER_NOTICE); + } + foreach ($args as $i => $value) { + if (!isset($params[$i])) { + return true; + } + if ($parameters[$i]->name !== $params[$i][2]) { + $param_num = $i + 1; + $message = 'phpDoc @param %d in %s%s%s() must be named as $%s, $%s given, ' . PHP_EOL + . 'called in %s on line %d ' . PHP_EOL + . 'and defined in %s on line %d'; + $message = sprintf($message, $param_num, $class, $type, $function, $parameters[$i]->name, $params[$i][2], $file, $line, $r->getFileName(), $r->getStartLine()); + trigger_error($message, E_USER_NOTICE); + } - $hints = preg_split('~[|/,]~sSX', $params[$i][1]); - if (! self::checkValueTypes($hints, $value)) - { - $param_num = $i + 1; - $message = 'Argument %d passed to %s%s%s() must be an %s, %s given, ' . PHP_EOL - . 'called in %s on line %d ' . PHP_EOL - . 'and defined in %s on line %d'; - $message = sprintf($message, $param_num, $class, $type, $function, implode('|', $hints), (is_object($value) ? get_class($value) . ' ' : '') . gettype($value), $file, $line, $r->getFileName(), $r->getStartLine()); - trigger_error($message, E_USER_WARNING); - return false; - } - } - return true; - } + $hints = preg_split('~[|/,]~sSX', $params[$i][1]); + if (!self::checkValueTypes($hints, $value)) { + $param_num = $i + 1; + $message = 'Argument %d passed to %s%s%s() must be an %s, %s given, ' . PHP_EOL + . 'called in %s on line %d ' . PHP_EOL + . 'and defined in %s on line %d'; + $message = sprintf($message, $param_num, $class, $type, $function, implode('|', $hints), (is_object($value) ? get_class($value) . ' ' : '') . gettype($value), $file, $line, $r->getFileName(), $r->getStartLine()); + trigger_error($message, E_USER_WARNING); + return false; + } + } + return true; + } - /** - * Return stacktrace. Correctly work with call_user_func*() - * (totally skip them correcting caller references). - * If $return_frame is present, return only $return_frame matched caller, not all stacktrace. - * - * @param string|null $re_ignore example: '~^' . preg_quote(__CLASS__, '~') . '(?![a-zA-Z\d])~sSX' - * @param int|null $return_frame - * @return array - */ - public static function debugBacktrace($re_ignore = null, $return_frame = null) - { - $trace = debug_backtrace(); + /** + * Return stacktrace. Correctly work with call_user_func*() + * (totally skip them correcting caller references). + * If $return_frame is present, return only $return_frame matched caller, not all stacktrace. + * + * @param string|null $re_ignore example: '~^' . preg_quote(__CLASS__, '~') . '(?![a-zA-Z\d])~sSX' + * @param int|null $return_frame + * @return array + */ + public static function debugBacktrace($re_ignore = null, $return_frame = null) + { + $trace = debug_backtrace(); - $a = array(); - $frames = 0; - for ($i = 0, $n = count($trace); $i < $n; $i++) - { - $t = $trace[$i]; - if (! $t) continue; + $a = array(); + $frames = 0; + for ($i = 0, $n = count($trace); $i < $n; $i++) { + $t = $trace[$i]; + if (!$t) { + continue; + } - // Next frame. - $next = isset($trace[$i+1])? $trace[$i+1] : null; + // Next frame. + $next = isset($trace[$i + 1]) ? $trace[$i + 1] : null; - // Dummy frame before call_user_func*() frames. - if (! isset($t['file']) && $next) - { - $t['over_function'] = $trace[$i+1]['function']; - $t = $t + $trace[$i+1]; - $trace[$i+1] = null; // skip call_user_func on next iteration - } + // Dummy frame before call_user_func*() frames. + if (!isset($t['file']) && $next) { + $t['over_function'] = $trace[$i + 1]['function']; + $t = $t + $trace[$i + 1]; + $trace[$i + 1] = null; // skip call_user_func on next iteration + } - // Skip myself frame. - if (++$frames < 2) continue; + // Skip myself frame. + if (++$frames < 2) { + continue; + } - // 'class' and 'function' field of next frame define where this frame function situated. - // Skip frames for functions situated in ignored places. - if ($re_ignore && $next) - { - // Name of function "inside which" frame was generated. - $frame_caller = (isset($next['class']) ? $next['class'] . $next['type'] : '') - . (isset($next['function']) ? $next['function'] : ''); - if (preg_match($re_ignore, $frame_caller)) continue; - } + // 'class' and 'function' field of next frame define where this frame function situated. + // Skip frames for functions situated in ignored places. + if ($re_ignore && $next) { + // Name of function "inside which" frame was generated. + $frame_caller = (isset($next['class']) ? $next['class'] . $next['type'] : '') + . (isset($next['function']) ? $next['function'] : ''); + if (preg_match($re_ignore, $frame_caller)) { + continue; + } + } - // On each iteration we consider ability to add PREVIOUS frame to $a stack. - if (count($a) === $return_frame) return $t; - $a[] = $t; - } - return $a; - } + // On each iteration we consider ability to add PREVIOUS frame to $a stack. + if (count($a) === $return_frame) { + return $t; + } + $a[] = $t; + } + return $a; + } - /** - * Checks a value to the allowed types - * - * @param array $types - * @param mixed $value - * @return bool - */ - public static function checkValueTypes(array $types, $value) - { - foreach ($types as $type) - { - $type = strtolower($type); - if (array_key_exists($type, self::$hints) && call_user_func(self::$hints[$type], $value)) return true; - if (is_object($value) && @is_a($value, $type)) return true; - if ($type === 'mixed') return true; - } - return false; - } -} \ No newline at end of file + /** + * Checks a value to the allowed types + * + * @param array $types + * @param mixed $value + * @return bool + */ + public static function checkValueTypes(array $types, $value) + { + foreach ($types as $type) { + $type = strtolower($type); + if (array_key_exists($type, self::$hints) && call_user_func(self::$hints[$type], $value)) { + return true; + } + if (is_object($value) && @is_a($value, $type)) { + return true; + } + if ($type === 'mixed') { + return true; + } + } + return false; + } +} diff --git a/library/includes/classes/sitemap.php b/library/includes/classes/sitemap.php index e3b7826a5..34b1ad566 100644 --- a/library/includes/classes/sitemap.php +++ b/library/includes/classes/sitemap.php @@ -1,217 +1,263 @@ home = make_url(); - } + public function __construct() + { + $this->home = make_url(); + } - public function build_map () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= $this->get_topic(); - $map .= ""; + public function build_map() + { + $map = "\n\n"; + $map .= $this->get_static(); + $map .= $this->get_forum(); + $map .= $this->get_topic(); + $map .= ""; - return $map; - } + return $map; + } - public function build_index ($count) { - $lm = date('c'); - $map = "\n\n"; - $map .= "\n{$this->home}internal_data/sitemap/sitemap1.xml\n{$lm}\n\n"; - for ($i = 0; $i < $count; $i++) { - $t = $i + 2; - $map .= "\n{$this->home}internal_data/sitemap/sitemap{$t}.xml\n{$lm}\n\n"; - } - $map .= ""; + public function build_index($count) + { + $lm = date('c'); + $map = "\n\n"; + $map .= "\n{$this->home}internal_data/sitemap/sitemap1.xml\n{$lm}\n\n"; + for ($i = 0; $i < $count; $i++) { + $t = $i + 2; + $map .= "\n{$this->home}internal_data/sitemap/sitemap{$t}.xml\n{$lm}\n\n"; + } + $map .= ""; - return $map; - } + return $map; + } - public function build_stat () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= ""; + public function build_stat() + { + $map = "\n\n"; + $map .= $this->get_static(); + $map .= $this->get_forum(); + $map .= ""; - return $map; - } + return $map; + } - public function build_map_topic ($n) { - $map = "\n\n"; - $map .= $this->get_topic($n); - $map .= ""; + public function build_map_topic($n) + { + $map = "\n\n"; + $map .= $this->get_topic($n); + $map .= ""; - return $map; - } + return $map; + } - public function get_forum () { - global $datastore; + public function get_forum() + { + global $datastore; - $this->priority = $this->cat_priority; - $xml = ''; - $lm = date('c'); + $this->priority = $this->cat_priority; + $xml = ''; + $lm = date('c'); - if (!$forums = $datastore->get('cat_forums')) { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } - $not_forums_id = $forums['not_auth_forums']['guest_view']; - $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; + $not_forums_id = $forums['not_auth_forums']['guest_view']; + $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; - $sql = DB()->sql_query("SELECT forum_id, forum_topics, forum_parent, forum_name FROM " . BB_FORUMS . " " . $ignore_forum_sql . " ORDER BY forum_id ASC"); + $sql = DB()->sql_query("SELECT forum_id, forum_topics, forum_parent, forum_name FROM " . BB_FORUMS . " " . $ignore_forum_sql . " ORDER BY forum_id ASC"); - while ($row = DB()->sql_fetchrow($sql)) { - if (function_exists('seo_url')) $loc = $this->home . seo_url(FORUM_URL . $row['forum_id'], $row['forum_name']); - else $loc = $this->home . FORUM_URL . $row['forum_id']; - $xml .= $this->get_xml($loc, $lm); - } + while ($row = DB()->sql_fetchrow($sql)) { + if (function_exists('seo_url')) { + $loc = $this->home . seo_url(FORUM_URL . $row['forum_id'], $row['forum_name']); + } else { + $loc = $this->home . FORUM_URL . $row['forum_id']; + } + $xml .= $this->get_xml($loc, $lm); + } - return $xml; - } + return $xml; + } - public function get_topic ($page = false) { - global $datastore; + public function get_topic($page = false) + { + global $datastore; - $xml = ''; - $this->priority = $this->topic_priority; + $xml = ''; + $this->priority = $this->topic_priority; - if ($page) { - $page = $page - 1; - $page = $page * 40000; - $this->limit = " LIMIT {$page},40000"; - } else { - if ($this->limit < 1) $this->limit = false; - if ($this->limit) { - $this->limit = " LIMIT 0," . $this->limit; - } else { - $this->limit = ''; - } - } + if ($page) { + $page = $page - 1; + $page = $page * 40000; + $this->limit = " LIMIT {$page},40000"; + } else { + if ($this->limit < 1) { + $this->limit = false; + } + if ($this->limit) { + $this->limit = " LIMIT 0," . $this->limit; + } else { + $this->limit = ''; + } + } - if (!$forums = $datastore->get('cat_forums')) { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } - $not_forums_id = $forums['not_auth_forums']['guest_view']; - $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; + $not_forums_id = $forums['not_auth_forums']['guest_view']; + $ignore_forum_sql = ($not_forums_id) ? "WHERE forum_id NOT IN($not_forums_id)" : ''; - $sql = DB()->sql_query("SELECT topic_id, topic_title, topic_time FROM " . BB_TOPICS . " " . $ignore_forum_sql . " ORDER BY topic_time ASC" . $this->limit); + $sql = DB()->sql_query("SELECT topic_id, topic_title, topic_time FROM " . BB_TOPICS . " " . $ignore_forum_sql . " ORDER BY topic_time ASC" . $this->limit); - while ($row = DB()->sql_fetchrow($sql)) { - if (function_exists('seo_url')) $loc = $this->home . seo_url(TOPIC_URL . $row['topic_id'], $row['topic_title']); - else $loc = $this->home . TOPIC_URL . $row['topic_id']; - $xml .= $this->get_xml($loc, date('c', $row['topic_time'])); - } + while ($row = DB()->sql_fetchrow($sql)) { + if (function_exists('seo_url')) { + $loc = $this->home . seo_url(TOPIC_URL . $row['topic_id'], $row['topic_title']); + } else { + $loc = $this->home . TOPIC_URL . $row['topic_id']; + } + $xml .= $this->get_xml($loc, date('c', $row['topic_time'])); + } - return $xml; - } + return $xml; + } - public function get_static () { - global $bb_cfg; + public function get_static() + { + global $bb_cfg; - $xml = ''; - $lm = date('c'); - $this->priority = $this->stat_priority; + $xml = ''; + $lm = date('c'); + $this->priority = $this->stat_priority; - if (isset($bb_cfg['static_sitemap'])) { - $static_url = preg_replace("/\s/", '', $bb_cfg['static_sitemap']); //вырезаем переносы строк - preg_match_all('#(https?://[\w-]+[\.\w-]+/((?!https?://)[\w- ./?%&=])+)#', $static_url, $out); + if (isset($bb_cfg['static_sitemap'])) { + $static_url = preg_replace("/\s/", '', $bb_cfg['static_sitemap']); //вырезаем переносы строк + preg_match_all('#(https?://[\w-]+[\.\w-]+/((?!https?://)[\w- ./?%&=])+)#', $static_url, $out); - $static_url = count($out['0']); - if ($static_url > 0) { - foreach ($out['0'] as $url) { - $loc = $url; - $xml .= $this->get_xml($loc, $lm); - } - } - } + $static_url = count($out['0']); + if ($static_url > 0) { + foreach ($out['0'] as $url) { + $loc = $url; + $xml .= $this->get_xml($loc, $lm); + } + } + } - return $xml; - } + return $xml; + } - public function get_xml ($loc, $lm) { - $xml = "\t\n"; - $xml .= "\t\t$loc\n"; - $xml .= "\t\t$lm\n"; - $xml .= "\t\t" . $this->priority . "\n"; - $xml .= "\t\n"; + public function get_xml($loc, $lm) + { + $xml = "\t\n"; + $xml .= "\t\t$loc\n"; + $xml .= "\t\t$lm\n"; + $xml .= "\t\t" . $this->priority . "\n"; + $xml .= "\t\n"; - return $xml; - } + return $xml; + } - public function send_url ($url, $map) { - $data = false; - $file = $url.urlencode($map); + public function send_url($url, $map) + { + $data = false; + $file = $url . urlencode($map); - if (function_exists('curl_init')) { - $ch = curl_init(); + if (function_exists('curl_init')) { + $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $file); - curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + curl_setopt($ch, CURLOPT_URL, $file); + curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); - $data = curl_exec($ch); - curl_close($ch); + $data = curl_exec($ch); + curl_close($ch); - return $data; - } else { - return @file_get_contents($file); - } - } + return $data; + } else { + return @file_get_contents($file); + } + } - public function create () { - $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); + public function create() + { + $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); - if (!$this->limit) $this->limit = $row['count']; - if ($this->limit > 40000) { - $pages_count = @ceil($row['count'] / 40000); + if (!$this->limit) { + $this->limit = $row['count']; + } + if ($this->limit > 40000) { + $pages_count = @ceil($row['count'] / 40000); - $sitemap = $this->build_index($pages_count); - $handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); + $sitemap = $this->build_index($pages_count); + $handler = fopen(SITEMAP_DIR . "sitemap.xml", "wb+"); + fwrite($handler, $sitemap); + fclose($handler); + @chmod(SITEMAP_DIR . "sitemap.xml", 0666); - $sitemap = $this->build_stat(); - $handler = fopen(SITEMAP_DIR. "sitemap1.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); + $sitemap = $this->build_stat(); + $handler = fopen(SITEMAP_DIR . "sitemap1.xml", "wb+"); + fwrite($handler, $sitemap); + fclose($handler); + @chmod(SITEMAP_DIR . "sitemap.xml", 0666); - for ($i = 0; $i < $pages_count; $i++) { - $t = $i + 2; - $n = $i + 1; + for ($i = 0; $i < $pages_count; $i++) { + $t = $i + 2; + $n = $i + 1; - $sitemap = $this->build_map_topic($n); - $handler = fopen(SITEMAP_DIR. "sitemap{$t}.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap{$t}.xml", 0666); - } - } else { - $sitemap = $this->build_map(); - $handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); - fwrite($handler, $sitemap); - fclose($handler); - @chmod(SITEMAP_DIR. "sitemap.xml", 0666); - } + $sitemap = $this->build_map_topic($n); + $handler = fopen(SITEMAP_DIR . "sitemap{$t}.xml", "wb+"); + fwrite($handler, $sitemap); + fclose($handler); + @chmod(SITEMAP_DIR . "sitemap{$t}.xml", 0666); + } + } else { + $sitemap = $this->build_map(); + $handler = fopen(SITEMAP_DIR . "sitemap.xml", "wb+"); + fwrite($handler, $sitemap); + fclose($handler); + @chmod(SITEMAP_DIR . "sitemap.xml", 0666); + } - $params['sitemap_time'] = TIMENOW; - bb_update_config($params); - } + $params['sitemap_time'] = TIMENOW; + bb_update_config($params); + } } diff --git a/library/includes/classes/utf8.php b/library/includes/classes/utf8.php index 4a03eac17..30acc68d3 100644 --- a/library/includes/classes/utf8.php +++ b/library/includes/classes/utf8.php @@ -1,6 +1,31 @@ "\x22", #U+0022 ["] " quotation mark = APL quote - '&' => "\x26", #U+0026 [&] & ampersand - '<' => "\x3c", #U+003C [<] < less-than sign - '>' => "\x3e", #U+003E [>] > greater-than sign - ); + /** + * @var array + */ + public static $html_special_chars_table = array( + '"' => "\x22", #U+0022 ["] " quotation mark = APL quote + '&' => "\x26", #U+0026 [&] & ampersand + '<' => "\x3c", #U+003C [<] < less-than sign + '>' => "\x3e", #U+003E [>] > greater-than sign + ); - /** - * @link http://www.fileformat.info/format/w3c/entitytest.htm?sort=Unicode%20Character HTML Entity Browser Test Page - * @var array - */ - public static $html_entity_table = array( - #Latin-1 Entities: - ' ' => "\xc2\xa0", #U+00A0 [ ] no-break space = non-breaking space - '¡' => "\xc2\xa1", #U+00A1 [¡] inverted exclamation mark - '¢' => "\xc2\xa2", #U+00A2 [¢] cent sign - '£' => "\xc2\xa3", #U+00A3 [£] pound sign - '¤' => "\xc2\xa4", #U+00A4 [¤] currency sign - '¥' => "\xc2\xa5", #U+00A5 [¥] yen sign = yuan sign - '¦' => "\xc2\xa6", #U+00A6 [¦] broken bar = broken vertical bar - '§' => "\xc2\xa7", #U+00A7 [§] section sign - '¨' => "\xc2\xa8", #U+00A8 [¨] diaeresis = spacing diaeresis - '©' => "\xc2\xa9", #U+00A9 [©] copyright sign - 'ª' => "\xc2\xaa", #U+00AA [ª] feminine ordinal indicator - '«' => "\xc2\xab", #U+00AB [«] left-pointing double angle quotation mark = left pointing guillemet - '¬' => "\xc2\xac", #U+00AC [¬] not sign - '­' => "\xc2\xad", #U+00AD [ ] soft hyphen = discretionary hyphen - '®' => "\xc2\xae", #U+00AE [®] registered sign = registered trade mark sign - '¯' => "\xc2\xaf", #U+00AF [¯] macron = spacing macron = overline = APL overbar - '°' => "\xc2\xb0", #U+00B0 [°] degree sign - '±' => "\xc2\xb1", #U+00B1 [±] plus-minus sign = plus-or-minus sign - '²' => "\xc2\xb2", #U+00B2 [²] superscript two = superscript digit two = squared - '³' => "\xc2\xb3", #U+00B3 [³] superscript three = superscript digit three = cubed - '´' => "\xc2\xb4", #U+00B4 [´] acute accent = spacing acute - 'µ' => "\xc2\xb5", #U+00B5 [µ] micro sign - '¶' => "\xc2\xb6", #U+00B6 [¶] pilcrow sign = paragraph sign - '·' => "\xc2\xb7", #U+00B7 [·] middle dot = Georgian comma = Greek middle dot - '¸' => "\xc2\xb8", #U+00B8 [¸] cedilla = spacing cedilla - '¹' => "\xc2\xb9", #U+00B9 [¹] superscript one = superscript digit one - 'º' => "\xc2\xba", #U+00BA [º] masculine ordinal indicator - '»' => "\xc2\xbb", #U+00BB [»] right-pointing double angle quotation mark = right pointing guillemet - '¼' => "\xc2\xbc", #U+00BC [¼] vulgar fraction one quarter = fraction one quarter - '½' => "\xc2\xbd", #U+00BD [½] vulgar fraction one half = fraction one half - '¾' => "\xc2\xbe", #U+00BE [¾] vulgar fraction three quarters = fraction three quarters - '¿' => "\xc2\xbf", #U+00BF [¿] inverted question mark = turned question mark - #Latin capital letter - 'À' => "\xc3\x80", #Latin capital letter A with grave = Latin capital letter A grave - 'Á' => "\xc3\x81", #Latin capital letter A with acute - 'Â' => "\xc3\x82", #Latin capital letter A with circumflex - 'Ã' => "\xc3\x83", #Latin capital letter A with tilde - 'Ä' => "\xc3\x84", #Latin capital letter A with diaeresis - 'Å' => "\xc3\x85", #Latin capital letter A with ring above = Latin capital letter A ring - 'Æ' => "\xc3\x86", #Latin capital letter AE = Latin capital ligature AE - 'Ç' => "\xc3\x87", #Latin capital letter C with cedilla - 'È' => "\xc3\x88", #Latin capital letter E with grave - 'É' => "\xc3\x89", #Latin capital letter E with acute - 'Ê' => "\xc3\x8a", #Latin capital letter E with circumflex - 'Ë' => "\xc3\x8b", #Latin capital letter E with diaeresis - 'Ì' => "\xc3\x8c", #Latin capital letter I with grave - 'Í' => "\xc3\x8d", #Latin capital letter I with acute - 'Î' => "\xc3\x8e", #Latin capital letter I with circumflex - 'Ï' => "\xc3\x8f", #Latin capital letter I with diaeresis - 'Ð' => "\xc3\x90", #Latin capital letter ETH - 'Ñ' => "\xc3\x91", #Latin capital letter N with tilde - 'Ò' => "\xc3\x92", #Latin capital letter O with grave - 'Ó' => "\xc3\x93", #Latin capital letter O with acute - 'Ô' => "\xc3\x94", #Latin capital letter O with circumflex - 'Õ' => "\xc3\x95", #Latin capital letter O with tilde - 'Ö' => "\xc3\x96", #Latin capital letter O with diaeresis - '×' => "\xc3\x97", #U+00D7 [×] multiplication sign - 'Ø' => "\xc3\x98", #Latin capital letter O with stroke = Latin capital letter O slash - 'Ù' => "\xc3\x99", #Latin capital letter U with grave - 'Ú' => "\xc3\x9a", #Latin capital letter U with acute - 'Û' => "\xc3\x9b", #Latin capital letter U with circumflex - 'Ü' => "\xc3\x9c", #Latin capital letter U with diaeresis - 'Ý' => "\xc3\x9d", #Latin capital letter Y with acute - 'Þ' => "\xc3\x9e", #Latin capital letter THORN - #Latin small letter - 'ß' => "\xc3\x9f", #Latin small letter sharp s = ess-zed - 'à' => "\xc3\xa0", #Latin small letter a with grave = Latin small letter a grave - 'á' => "\xc3\xa1", #Latin small letter a with acute - 'â' => "\xc3\xa2", #Latin small letter a with circumflex - 'ã' => "\xc3\xa3", #Latin small letter a with tilde - 'ä' => "\xc3\xa4", #Latin small letter a with diaeresis - 'å' => "\xc3\xa5", #Latin small letter a with ring above = Latin small letter a ring - 'æ' => "\xc3\xa6", #Latin small letter ae = Latin small ligature ae - 'ç' => "\xc3\xa7", #Latin small letter c with cedilla - 'è' => "\xc3\xa8", #Latin small letter e with grave - 'é' => "\xc3\xa9", #Latin small letter e with acute - 'ê' => "\xc3\xaa", #Latin small letter e with circumflex - 'ë' => "\xc3\xab", #Latin small letter e with diaeresis - 'ì' => "\xc3\xac", #Latin small letter i with grave - 'í' => "\xc3\xad", #Latin small letter i with acute - 'î' => "\xc3\xae", #Latin small letter i with circumflex - 'ï' => "\xc3\xaf", #Latin small letter i with diaeresis - 'ð' => "\xc3\xb0", #Latin small letter eth - 'ñ' => "\xc3\xb1", #Latin small letter n with tilde - 'ò' => "\xc3\xb2", #Latin small letter o with grave - 'ó' => "\xc3\xb3", #Latin small letter o with acute - 'ô' => "\xc3\xb4", #Latin small letter o with circumflex - 'õ' => "\xc3\xb5", #Latin small letter o with tilde - 'ö' => "\xc3\xb6", #Latin small letter o with diaeresis - '÷' => "\xc3\xb7", #U+00F7 [÷] division sign - 'ø' => "\xc3\xb8", #Latin small letter o with stroke = Latin small letter o slash - 'ù' => "\xc3\xb9", #Latin small letter u with grave - 'ú' => "\xc3\xba", #Latin small letter u with acute - 'û' => "\xc3\xbb", #Latin small letter u with circumflex - 'ü' => "\xc3\xbc", #Latin small letter u with diaeresis - 'ý' => "\xc3\xbd", #Latin small letter y with acute - 'þ' => "\xc3\xbe", #Latin small letter thorn - 'ÿ' => "\xc3\xbf", #Latin small letter y with diaeresis - #Symbols and Greek Letters: - 'ƒ' => "\xc6\x92", #U+0192 [ƒ] Latin small f with hook = function = florin - 'Α' => "\xce\x91", #Greek capital letter alpha - 'Β' => "\xce\x92", #Greek capital letter beta - 'Γ' => "\xce\x93", #Greek capital letter gamma - 'Δ' => "\xce\x94", #Greek capital letter delta - 'Ε' => "\xce\x95", #Greek capital letter epsilon - 'Ζ' => "\xce\x96", #Greek capital letter zeta - 'Η' => "\xce\x97", #Greek capital letter eta - 'Θ' => "\xce\x98", #Greek capital letter theta - 'Ι' => "\xce\x99", #Greek capital letter iota - 'Κ' => "\xce\x9a", #Greek capital letter kappa - 'Λ' => "\xce\x9b", #Greek capital letter lambda - 'Μ' => "\xce\x9c", #Greek capital letter mu - 'Ν' => "\xce\x9d", #Greek capital letter nu - 'Ξ' => "\xce\x9e", #Greek capital letter xi - 'Ο' => "\xce\x9f", #Greek capital letter omicron - 'Π' => "\xce\xa0", #Greek capital letter pi - 'Ρ' => "\xce\xa1", #Greek capital letter rho - 'Σ' => "\xce\xa3", #Greek capital letter sigma - 'Τ' => "\xce\xa4", #Greek capital letter tau - 'Υ' => "\xce\xa5", #Greek capital letter upsilon - 'Φ' => "\xce\xa6", #Greek capital letter phi - 'Χ' => "\xce\xa7", #Greek capital letter chi - 'Ψ' => "\xce\xa8", #Greek capital letter psi - 'Ω' => "\xce\xa9", #Greek capital letter omega - 'α' => "\xce\xb1", #Greek small letter alpha - 'β' => "\xce\xb2", #Greek small letter beta - 'γ' => "\xce\xb3", #Greek small letter gamma - 'δ' => "\xce\xb4", #Greek small letter delta - 'ε' => "\xce\xb5", #Greek small letter epsilon - 'ζ' => "\xce\xb6", #Greek small letter zeta - 'η' => "\xce\xb7", #Greek small letter eta - 'θ' => "\xce\xb8", #Greek small letter theta - 'ι' => "\xce\xb9", #Greek small letter iota - 'κ' => "\xce\xba", #Greek small letter kappa - 'λ' => "\xce\xbb", #Greek small letter lambda - 'μ' => "\xce\xbc", #Greek small letter mu - 'ν' => "\xce\xbd", #Greek small letter nu - 'ξ' => "\xce\xbe", #Greek small letter xi - 'ο' => "\xce\xbf", #Greek small letter omicron - 'π' => "\xcf\x80", #Greek small letter pi - 'ρ' => "\xcf\x81", #Greek small letter rho - 'ς' => "\xcf\x82", #Greek small letter final sigma - 'σ' => "\xcf\x83", #Greek small letter sigma - 'τ' => "\xcf\x84", #Greek small letter tau - 'υ' => "\xcf\x85", #Greek small letter upsilon - 'φ' => "\xcf\x86", #Greek small letter phi - 'χ' => "\xcf\x87", #Greek small letter chi - 'ψ' => "\xcf\x88", #Greek small letter psi - 'ω' => "\xcf\x89", #Greek small letter omega - 'ϑ'=> "\xcf\x91", #Greek small letter theta symbol - 'ϒ' => "\xcf\x92", #Greek upsilon with hook symbol - 'ϖ' => "\xcf\x96", #U+03D6 [ϖ] Greek pi symbol + /** + * @link http://www.fileformat.info/format/w3c/entitytest.htm?sort=Unicode%20Character HTML Entity Browser Test Page + * @var array + */ + public static $html_entity_table = array( + #Latin-1 Entities: + ' ' => "\xc2\xa0", #U+00A0 [ ] no-break space = non-breaking space + '¡' => "\xc2\xa1", #U+00A1 [¡] inverted exclamation mark + '¢' => "\xc2\xa2", #U+00A2 [¢] cent sign + '£' => "\xc2\xa3", #U+00A3 [£] pound sign + '¤' => "\xc2\xa4", #U+00A4 [¤] currency sign + '¥' => "\xc2\xa5", #U+00A5 [¥] yen sign = yuan sign + '¦' => "\xc2\xa6", #U+00A6 [¦] broken bar = broken vertical bar + '§' => "\xc2\xa7", #U+00A7 [§] section sign + '¨' => "\xc2\xa8", #U+00A8 [¨] diaeresis = spacing diaeresis + '©' => "\xc2\xa9", #U+00A9 [©] copyright sign + 'ª' => "\xc2\xaa", #U+00AA [ª] feminine ordinal indicator + '«' => "\xc2\xab", #U+00AB [«] left-pointing double angle quotation mark = left pointing guillemet + '¬' => "\xc2\xac", #U+00AC [¬] not sign + '­' => "\xc2\xad", #U+00AD [ ] soft hyphen = discretionary hyphen + '®' => "\xc2\xae", #U+00AE [®] registered sign = registered trade mark sign + '¯' => "\xc2\xaf", #U+00AF [¯] macron = spacing macron = overline = APL overbar + '°' => "\xc2\xb0", #U+00B0 [°] degree sign + '±' => "\xc2\xb1", #U+00B1 [±] plus-minus sign = plus-or-minus sign + '²' => "\xc2\xb2", #U+00B2 [²] superscript two = superscript digit two = squared + '³' => "\xc2\xb3", #U+00B3 [³] superscript three = superscript digit three = cubed + '´' => "\xc2\xb4", #U+00B4 [´] acute accent = spacing acute + 'µ' => "\xc2\xb5", #U+00B5 [µ] micro sign + '¶' => "\xc2\xb6", #U+00B6 [¶] pilcrow sign = paragraph sign + '·' => "\xc2\xb7", #U+00B7 [·] middle dot = Georgian comma = Greek middle dot + '¸' => "\xc2\xb8", #U+00B8 [¸] cedilla = spacing cedilla + '¹' => "\xc2\xb9", #U+00B9 [¹] superscript one = superscript digit one + 'º' => "\xc2\xba", #U+00BA [º] masculine ordinal indicator + '»' => "\xc2\xbb", #U+00BB [»] right-pointing double angle quotation mark = right pointing guillemet + '¼' => "\xc2\xbc", #U+00BC [¼] vulgar fraction one quarter = fraction one quarter + '½' => "\xc2\xbd", #U+00BD [½] vulgar fraction one half = fraction one half + '¾' => "\xc2\xbe", #U+00BE [¾] vulgar fraction three quarters = fraction three quarters + '¿' => "\xc2\xbf", #U+00BF [¿] inverted question mark = turned question mark + #Latin capital letter + 'À' => "\xc3\x80", #Latin capital letter A with grave = Latin capital letter A grave + 'Á' => "\xc3\x81", #Latin capital letter A with acute + 'Â' => "\xc3\x82", #Latin capital letter A with circumflex + 'Ã' => "\xc3\x83", #Latin capital letter A with tilde + 'Ä' => "\xc3\x84", #Latin capital letter A with diaeresis + 'Å' => "\xc3\x85", #Latin capital letter A with ring above = Latin capital letter A ring + 'Æ' => "\xc3\x86", #Latin capital letter AE = Latin capital ligature AE + 'Ç' => "\xc3\x87", #Latin capital letter C with cedilla + 'È' => "\xc3\x88", #Latin capital letter E with grave + 'É' => "\xc3\x89", #Latin capital letter E with acute + 'Ê' => "\xc3\x8a", #Latin capital letter E with circumflex + 'Ë' => "\xc3\x8b", #Latin capital letter E with diaeresis + 'Ì' => "\xc3\x8c", #Latin capital letter I with grave + 'Í' => "\xc3\x8d", #Latin capital letter I with acute + 'Î' => "\xc3\x8e", #Latin capital letter I with circumflex + 'Ï' => "\xc3\x8f", #Latin capital letter I with diaeresis + 'Ð' => "\xc3\x90", #Latin capital letter ETH + 'Ñ' => "\xc3\x91", #Latin capital letter N with tilde + 'Ò' => "\xc3\x92", #Latin capital letter O with grave + 'Ó' => "\xc3\x93", #Latin capital letter O with acute + 'Ô' => "\xc3\x94", #Latin capital letter O with circumflex + 'Õ' => "\xc3\x95", #Latin capital letter O with tilde + 'Ö' => "\xc3\x96", #Latin capital letter O with diaeresis + '×' => "\xc3\x97", #U+00D7 [×] multiplication sign + 'Ø' => "\xc3\x98", #Latin capital letter O with stroke = Latin capital letter O slash + 'Ù' => "\xc3\x99", #Latin capital letter U with grave + 'Ú' => "\xc3\x9a", #Latin capital letter U with acute + 'Û' => "\xc3\x9b", #Latin capital letter U with circumflex + 'Ü' => "\xc3\x9c", #Latin capital letter U with diaeresis + 'Ý' => "\xc3\x9d", #Latin capital letter Y with acute + 'Þ' => "\xc3\x9e", #Latin capital letter THORN + #Latin small letter + 'ß' => "\xc3\x9f", #Latin small letter sharp s = ess-zed + 'à' => "\xc3\xa0", #Latin small letter a with grave = Latin small letter a grave + 'á' => "\xc3\xa1", #Latin small letter a with acute + 'â' => "\xc3\xa2", #Latin small letter a with circumflex + 'ã' => "\xc3\xa3", #Latin small letter a with tilde + 'ä' => "\xc3\xa4", #Latin small letter a with diaeresis + 'å' => "\xc3\xa5", #Latin small letter a with ring above = Latin small letter a ring + 'æ' => "\xc3\xa6", #Latin small letter ae = Latin small ligature ae + 'ç' => "\xc3\xa7", #Latin small letter c with cedilla + 'è' => "\xc3\xa8", #Latin small letter e with grave + 'é' => "\xc3\xa9", #Latin small letter e with acute + 'ê' => "\xc3\xaa", #Latin small letter e with circumflex + 'ë' => "\xc3\xab", #Latin small letter e with diaeresis + 'ì' => "\xc3\xac", #Latin small letter i with grave + 'í' => "\xc3\xad", #Latin small letter i with acute + 'î' => "\xc3\xae", #Latin small letter i with circumflex + 'ï' => "\xc3\xaf", #Latin small letter i with diaeresis + 'ð' => "\xc3\xb0", #Latin small letter eth + 'ñ' => "\xc3\xb1", #Latin small letter n with tilde + 'ò' => "\xc3\xb2", #Latin small letter o with grave + 'ó' => "\xc3\xb3", #Latin small letter o with acute + 'ô' => "\xc3\xb4", #Latin small letter o with circumflex + 'õ' => "\xc3\xb5", #Latin small letter o with tilde + 'ö' => "\xc3\xb6", #Latin small letter o with diaeresis + '÷' => "\xc3\xb7", #U+00F7 [÷] division sign + 'ø' => "\xc3\xb8", #Latin small letter o with stroke = Latin small letter o slash + 'ù' => "\xc3\xb9", #Latin small letter u with grave + 'ú' => "\xc3\xba", #Latin small letter u with acute + 'û' => "\xc3\xbb", #Latin small letter u with circumflex + 'ü' => "\xc3\xbc", #Latin small letter u with diaeresis + 'ý' => "\xc3\xbd", #Latin small letter y with acute + 'þ' => "\xc3\xbe", #Latin small letter thorn + 'ÿ' => "\xc3\xbf", #Latin small letter y with diaeresis + #Symbols and Greek Letters: + 'ƒ' => "\xc6\x92", #U+0192 [ƒ] Latin small f with hook = function = florin + 'Α' => "\xce\x91", #Greek capital letter alpha + 'Β' => "\xce\x92", #Greek capital letter beta + 'Γ' => "\xce\x93", #Greek capital letter gamma + 'Δ' => "\xce\x94", #Greek capital letter delta + 'Ε' => "\xce\x95", #Greek capital letter epsilon + 'Ζ' => "\xce\x96", #Greek capital letter zeta + 'Η' => "\xce\x97", #Greek capital letter eta + 'Θ' => "\xce\x98", #Greek capital letter theta + 'Ι' => "\xce\x99", #Greek capital letter iota + 'Κ' => "\xce\x9a", #Greek capital letter kappa + 'Λ' => "\xce\x9b", #Greek capital letter lambda + 'Μ' => "\xce\x9c", #Greek capital letter mu + 'Ν' => "\xce\x9d", #Greek capital letter nu + 'Ξ' => "\xce\x9e", #Greek capital letter xi + 'Ο' => "\xce\x9f", #Greek capital letter omicron + 'Π' => "\xce\xa0", #Greek capital letter pi + 'Ρ' => "\xce\xa1", #Greek capital letter rho + 'Σ' => "\xce\xa3", #Greek capital letter sigma + 'Τ' => "\xce\xa4", #Greek capital letter tau + 'Υ' => "\xce\xa5", #Greek capital letter upsilon + 'Φ' => "\xce\xa6", #Greek capital letter phi + 'Χ' => "\xce\xa7", #Greek capital letter chi + 'Ψ' => "\xce\xa8", #Greek capital letter psi + 'Ω' => "\xce\xa9", #Greek capital letter omega + 'α' => "\xce\xb1", #Greek small letter alpha + 'β' => "\xce\xb2", #Greek small letter beta + 'γ' => "\xce\xb3", #Greek small letter gamma + 'δ' => "\xce\xb4", #Greek small letter delta + 'ε' => "\xce\xb5", #Greek small letter epsilon + 'ζ' => "\xce\xb6", #Greek small letter zeta + 'η' => "\xce\xb7", #Greek small letter eta + 'θ' => "\xce\xb8", #Greek small letter theta + 'ι' => "\xce\xb9", #Greek small letter iota + 'κ' => "\xce\xba", #Greek small letter kappa + 'λ' => "\xce\xbb", #Greek small letter lambda + 'μ' => "\xce\xbc", #Greek small letter mu + 'ν' => "\xce\xbd", #Greek small letter nu + 'ξ' => "\xce\xbe", #Greek small letter xi + 'ο' => "\xce\xbf", #Greek small letter omicron + 'π' => "\xcf\x80", #Greek small letter pi + 'ρ' => "\xcf\x81", #Greek small letter rho + 'ς' => "\xcf\x82", #Greek small letter final sigma + 'σ' => "\xcf\x83", #Greek small letter sigma + 'τ' => "\xcf\x84", #Greek small letter tau + 'υ' => "\xcf\x85", #Greek small letter upsilon + 'φ' => "\xcf\x86", #Greek small letter phi + 'χ' => "\xcf\x87", #Greek small letter chi + 'ψ' => "\xcf\x88", #Greek small letter psi + 'ω' => "\xcf\x89", #Greek small letter omega + 'ϑ' => "\xcf\x91", #Greek small letter theta symbol + 'ϒ' => "\xcf\x92", #Greek upsilon with hook symbol + 'ϖ' => "\xcf\x96", #U+03D6 [ϖ] Greek pi symbol - '•' => "\xe2\x80\xa2", #U+2022 [•] bullet = black small circle - '…' => "\xe2\x80\xa6", #U+2026 […] horizontal ellipsis = three dot leader - '′' => "\xe2\x80\xb2", #U+2032 [′] prime = minutes = feet (для обозначения минут и футов) - '″' => "\xe2\x80\xb3", #U+2033 [″] double prime = seconds = inches (для обозначения секунд и дюймов). - '‾' => "\xe2\x80\xbe", #U+203E [‾] overline = spacing overscore - '⁄' => "\xe2\x81\x84", #U+2044 [⁄] fraction slash - '℘' => "\xe2\x84\x98", #U+2118 [℘] script capital P = power set = Weierstrass p - 'ℑ' => "\xe2\x84\x91", #U+2111 [ℑ] blackletter capital I = imaginary part - 'ℜ' => "\xe2\x84\x9c", #U+211C [ℜ] blackletter capital R = real part symbol - '™' => "\xe2\x84\xa2", #U+2122 [™] trade mark sign - 'ℵ' => "\xe2\x84\xb5", #U+2135 [ℵ] alef symbol = first transfinite cardinal - '←' => "\xe2\x86\x90", #U+2190 [←] leftwards arrow - '↑' => "\xe2\x86\x91", #U+2191 [↑] upwards arrow - '→' => "\xe2\x86\x92", #U+2192 [→] rightwards arrow - '↓' => "\xe2\x86\x93", #U+2193 [↓] downwards arrow - '↔' => "\xe2\x86\x94", #U+2194 [↔] left right arrow - '↵' => "\xe2\x86\xb5", #U+21B5 [↵] downwards arrow with corner leftwards = carriage return - '⇐' => "\xe2\x87\x90", #U+21D0 [⇐] leftwards double arrow - '⇑' => "\xe2\x87\x91", #U+21D1 [⇑] upwards double arrow - '⇒' => "\xe2\x87\x92", #U+21D2 [⇒] rightwards double arrow - '⇓' => "\xe2\x87\x93", #U+21D3 [⇓] downwards double arrow - '⇔' => "\xe2\x87\x94", #U+21D4 [⇔] left right double arrow - '∀' => "\xe2\x88\x80", #U+2200 [∀] for all - '∂' => "\xe2\x88\x82", #U+2202 [∂] partial differential - '∃' => "\xe2\x88\x83", #U+2203 [∃] there exists - '∅' => "\xe2\x88\x85", #U+2205 [∅] empty set = null set = diameter - '∇' => "\xe2\x88\x87", #U+2207 [∇] nabla = backward difference - '∈' => "\xe2\x88\x88", #U+2208 [∈] element of - '∉' => "\xe2\x88\x89", #U+2209 [∉] not an element of - '∋' => "\xe2\x88\x8b", #U+220B [∋] contains as member - '∏' => "\xe2\x88\x8f", #U+220F [∏] n-ary product = product sign - '∑' => "\xe2\x88\x91", #U+2211 [∑] n-ary sumation - '−' => "\xe2\x88\x92", #U+2212 [−] minus sign - '∗' => "\xe2\x88\x97", #U+2217 [∗] asterisk operator - '√' => "\xe2\x88\x9a", #U+221A [√] square root = radical sign - '∝' => "\xe2\x88\x9d", #U+221D [∝] proportional to - '∞' => "\xe2\x88\x9e", #U+221E [∞] infinity - '∠' => "\xe2\x88\xa0", #U+2220 [∠] angle - '∧' => "\xe2\x88\xa7", #U+2227 [∧] logical and = wedge - '∨' => "\xe2\x88\xa8", #U+2228 [∨] logical or = vee - '∩' => "\xe2\x88\xa9", #U+2229 [∩] intersection = cap - '∪' => "\xe2\x88\xaa", #U+222A [∪] union = cup - '∫' => "\xe2\x88\xab", #U+222B [∫] integral - '∴' => "\xe2\x88\xb4", #U+2234 [∴] therefore - '∼' => "\xe2\x88\xbc", #U+223C [∼] tilde operator = varies with = similar to - '≅' => "\xe2\x89\x85", #U+2245 [≅] approximately equal to - '≈' => "\xe2\x89\x88", #U+2248 [≈] almost equal to = asymptotic to - '≠' => "\xe2\x89\xa0", #U+2260 [≠] not equal to - '≡' => "\xe2\x89\xa1", #U+2261 [≡] identical to - '≤' => "\xe2\x89\xa4", #U+2264 [≤] less-than or equal to - '≥' => "\xe2\x89\xa5", #U+2265 [≥] greater-than or equal to - '⊂' => "\xe2\x8a\x82", #U+2282 [⊂] subset of - '⊃' => "\xe2\x8a\x83", #U+2283 [⊃] superset of - '⊄' => "\xe2\x8a\x84", #U+2284 [⊄] not a subset of - '⊆' => "\xe2\x8a\x86", #U+2286 [⊆] subset of or equal to - '⊇' => "\xe2\x8a\x87", #U+2287 [⊇] superset of or equal to - '⊕' => "\xe2\x8a\x95", #U+2295 [⊕] circled plus = direct sum - '⊗' => "\xe2\x8a\x97", #U+2297 [⊗] circled times = vector product - '⊥' => "\xe2\x8a\xa5", #U+22A5 [⊥] up tack = orthogonal to = perpendicular - '⋅' => "\xe2\x8b\x85", #U+22C5 [⋅] dot operator - '⌈' => "\xe2\x8c\x88", #U+2308 [⌈] left ceiling = APL upstile - '⌉' => "\xe2\x8c\x89", #U+2309 [⌉] right ceiling - '⌊' => "\xe2\x8c\x8a", #U+230A [⌊] left floor = APL downstile - '⌋' => "\xe2\x8c\x8b", #U+230B [⌋] right floor - '⟨' => "\xe2\x8c\xa9", #U+2329 [〈] left-pointing angle bracket = bra - '⟩' => "\xe2\x8c\xaa", #U+232A [〉] right-pointing angle bracket = ket - '◊' => "\xe2\x97\x8a", #U+25CA [◊] lozenge - '♠' => "\xe2\x99\xa0", #U+2660 [♠] black spade suit - '♣' => "\xe2\x99\xa3", #U+2663 [♣] black club suit = shamrock - '♥' => "\xe2\x99\xa5", #U+2665 [♥] black heart suit = valentine - '♦' => "\xe2\x99\xa6", #U+2666 [♦] black diamond suit - #Other Special Characters: - 'Œ' => "\xc5\x92", #U+0152 [Œ] Latin capital ligature OE - 'œ' => "\xc5\x93", #U+0153 [œ] Latin small ligature oe - 'Š' => "\xc5\xa0", #U+0160 [Š] Latin capital letter S with caron - 'š' => "\xc5\xa1", #U+0161 [š] Latin small letter s with caron - 'Ÿ' => "\xc5\xb8", #U+0178 [Ÿ] Latin capital letter Y with diaeresis - 'ˆ' => "\xcb\x86", #U+02C6 [ˆ] modifier letter circumflex accent - '˜' => "\xcb\x9c", #U+02DC [˜] small tilde - ' ' => "\xe2\x80\x82", #U+2002 [ ] en space - ' ' => "\xe2\x80\x83", #U+2003 [ ] em space - ' ' => "\xe2\x80\x89", #U+2009 [ ] thin space - '‌' => "\xe2\x80\x8c", #U+200C [‌] zero width non-joiner - '‍' => "\xe2\x80\x8d", #U+200D [‍] zero width joiner - '‎' => "\xe2\x80\x8e", #U+200E [‎] left-to-right mark - '‏' => "\xe2\x80\x8f", #U+200F [‏] right-to-left mark - '–' => "\xe2\x80\x93", #U+2013 [–] en dash - '—' => "\xe2\x80\x94", #U+2014 [—] em dash - '‘' => "\xe2\x80\x98", #U+2018 [‘] left single quotation mark - '’' => "\xe2\x80\x99", #U+2019 [’] right single quotation mark (and apostrophe!) - '‚' => "\xe2\x80\x9a", #U+201A [‚] single low-9 quotation mark - '“' => "\xe2\x80\x9c", #U+201C [“] left double quotation mark - '”' => "\xe2\x80\x9d", #U+201D [”] right double quotation mark - '„' => "\xe2\x80\x9e", #U+201E [„] double low-9 quotation mark - '†' => "\xe2\x80\xa0", #U+2020 [†] dagger - '‡' => "\xe2\x80\xa1", #U+2021 [‡] double dagger - '‰' => "\xe2\x80\xb0", #U+2030 [‰] per mille sign - '‹' => "\xe2\x80\xb9", #U+2039 [‹] single left-pointing angle quotation mark - '›' => "\xe2\x80\xba", #U+203A [›] single right-pointing angle quotation mark - '€' => "\xe2\x82\xac", #U+20AC [€] euro sign - ); + '•' => "\xe2\x80\xa2", #U+2022 [•] bullet = black small circle + '…' => "\xe2\x80\xa6", #U+2026 […] horizontal ellipsis = three dot leader + '′' => "\xe2\x80\xb2", #U+2032 [′] prime = minutes = feet (для обозначения минут и футов) + '″' => "\xe2\x80\xb3", #U+2033 [″] double prime = seconds = inches (для обозначения секунд и дюймов). + '‾' => "\xe2\x80\xbe", #U+203E [‾] overline = spacing overscore + '⁄' => "\xe2\x81\x84", #U+2044 [⁄] fraction slash + '℘' => "\xe2\x84\x98", #U+2118 [℘] script capital P = power set = Weierstrass p + 'ℑ' => "\xe2\x84\x91", #U+2111 [ℑ] blackletter capital I = imaginary part + 'ℜ' => "\xe2\x84\x9c", #U+211C [ℜ] blackletter capital R = real part symbol + '™' => "\xe2\x84\xa2", #U+2122 [™] trade mark sign + 'ℵ' => "\xe2\x84\xb5", #U+2135 [ℵ] alef symbol = first transfinite cardinal + '←' => "\xe2\x86\x90", #U+2190 [←] leftwards arrow + '↑' => "\xe2\x86\x91", #U+2191 [↑] upwards arrow + '→' => "\xe2\x86\x92", #U+2192 [→] rightwards arrow + '↓' => "\xe2\x86\x93", #U+2193 [↓] downwards arrow + '↔' => "\xe2\x86\x94", #U+2194 [↔] left right arrow + '↵' => "\xe2\x86\xb5", #U+21B5 [↵] downwards arrow with corner leftwards = carriage return + '⇐' => "\xe2\x87\x90", #U+21D0 [⇐] leftwards double arrow + '⇑' => "\xe2\x87\x91", #U+21D1 [⇑] upwards double arrow + '⇒' => "\xe2\x87\x92", #U+21D2 [⇒] rightwards double arrow + '⇓' => "\xe2\x87\x93", #U+21D3 [⇓] downwards double arrow + '⇔' => "\xe2\x87\x94", #U+21D4 [⇔] left right double arrow + '∀' => "\xe2\x88\x80", #U+2200 [∀] for all + '∂' => "\xe2\x88\x82", #U+2202 [∂] partial differential + '∃' => "\xe2\x88\x83", #U+2203 [∃] there exists + '∅' => "\xe2\x88\x85", #U+2205 [∅] empty set = null set = diameter + '∇' => "\xe2\x88\x87", #U+2207 [∇] nabla = backward difference + '∈' => "\xe2\x88\x88", #U+2208 [∈] element of + '∉' => "\xe2\x88\x89", #U+2209 [∉] not an element of + '∋' => "\xe2\x88\x8b", #U+220B [∋] contains as member + '∏' => "\xe2\x88\x8f", #U+220F [∏] n-ary product = product sign + '∑' => "\xe2\x88\x91", #U+2211 [∑] n-ary sumation + '−' => "\xe2\x88\x92", #U+2212 [−] minus sign + '∗' => "\xe2\x88\x97", #U+2217 [∗] asterisk operator + '√' => "\xe2\x88\x9a", #U+221A [√] square root = radical sign + '∝' => "\xe2\x88\x9d", #U+221D [∝] proportional to + '∞' => "\xe2\x88\x9e", #U+221E [∞] infinity + '∠' => "\xe2\x88\xa0", #U+2220 [∠] angle + '∧' => "\xe2\x88\xa7", #U+2227 [∧] logical and = wedge + '∨' => "\xe2\x88\xa8", #U+2228 [∨] logical or = vee + '∩' => "\xe2\x88\xa9", #U+2229 [∩] intersection = cap + '∪' => "\xe2\x88\xaa", #U+222A [∪] union = cup + '∫' => "\xe2\x88\xab", #U+222B [∫] integral + '∴' => "\xe2\x88\xb4", #U+2234 [∴] therefore + '∼' => "\xe2\x88\xbc", #U+223C [∼] tilde operator = varies with = similar to + '≅' => "\xe2\x89\x85", #U+2245 [≅] approximately equal to + '≈' => "\xe2\x89\x88", #U+2248 [≈] almost equal to = asymptotic to + '≠' => "\xe2\x89\xa0", #U+2260 [≠] not equal to + '≡' => "\xe2\x89\xa1", #U+2261 [≡] identical to + '≤' => "\xe2\x89\xa4", #U+2264 [≤] less-than or equal to + '≥' => "\xe2\x89\xa5", #U+2265 [≥] greater-than or equal to + '⊂' => "\xe2\x8a\x82", #U+2282 [⊂] subset of + '⊃' => "\xe2\x8a\x83", #U+2283 [⊃] superset of + '⊄' => "\xe2\x8a\x84", #U+2284 [⊄] not a subset of + '⊆' => "\xe2\x8a\x86", #U+2286 [⊆] subset of or equal to + '⊇' => "\xe2\x8a\x87", #U+2287 [⊇] superset of or equal to + '⊕' => "\xe2\x8a\x95", #U+2295 [⊕] circled plus = direct sum + '⊗' => "\xe2\x8a\x97", #U+2297 [⊗] circled times = vector product + '⊥' => "\xe2\x8a\xa5", #U+22A5 [⊥] up tack = orthogonal to = perpendicular + '⋅' => "\xe2\x8b\x85", #U+22C5 [⋅] dot operator + '⌈' => "\xe2\x8c\x88", #U+2308 [⌈] left ceiling = APL upstile + '⌉' => "\xe2\x8c\x89", #U+2309 [⌉] right ceiling + '⌊' => "\xe2\x8c\x8a", #U+230A [⌊] left floor = APL downstile + '⌋' => "\xe2\x8c\x8b", #U+230B [⌋] right floor + '⟨' => "\xe2\x8c\xa9", #U+2329 [〈] left-pointing angle bracket = bra + '⟩' => "\xe2\x8c\xaa", #U+232A [〉] right-pointing angle bracket = ket + '◊' => "\xe2\x97\x8a", #U+25CA [◊] lozenge + '♠' => "\xe2\x99\xa0", #U+2660 [♠] black spade suit + '♣' => "\xe2\x99\xa3", #U+2663 [♣] black club suit = shamrock + '♥' => "\xe2\x99\xa5", #U+2665 [♥] black heart suit = valentine + '♦' => "\xe2\x99\xa6", #U+2666 [♦] black diamond suit + #Other Special Characters: + 'Œ' => "\xc5\x92", #U+0152 [Œ] Latin capital ligature OE + 'œ' => "\xc5\x93", #U+0153 [œ] Latin small ligature oe + 'Š' => "\xc5\xa0", #U+0160 [Š] Latin capital letter S with caron + 'š' => "\xc5\xa1", #U+0161 [š] Latin small letter s with caron + 'Ÿ' => "\xc5\xb8", #U+0178 [Ÿ] Latin capital letter Y with diaeresis + 'ˆ' => "\xcb\x86", #U+02C6 [ˆ] modifier letter circumflex accent + '˜' => "\xcb\x9c", #U+02DC [˜] small tilde + ' ' => "\xe2\x80\x82", #U+2002 [ ] en space + ' ' => "\xe2\x80\x83", #U+2003 [ ] em space + ' ' => "\xe2\x80\x89", #U+2009 [ ] thin space + '‌' => "\xe2\x80\x8c", #U+200C [‌] zero width non-joiner + '‍' => "\xe2\x80\x8d", #U+200D [‍] zero width joiner + '‎' => "\xe2\x80\x8e", #U+200E [‎] left-to-right mark + '‏' => "\xe2\x80\x8f", #U+200F [‏] right-to-left mark + '–' => "\xe2\x80\x93", #U+2013 [–] en dash + '—' => "\xe2\x80\x94", #U+2014 [—] em dash + '‘' => "\xe2\x80\x98", #U+2018 [‘] left single quotation mark + '’' => "\xe2\x80\x99", #U+2019 [’] right single quotation mark (and apostrophe!) + '‚' => "\xe2\x80\x9a", #U+201A [‚] single low-9 quotation mark + '“' => "\xe2\x80\x9c", #U+201C [“] left double quotation mark + '”' => "\xe2\x80\x9d", #U+201D [”] right double quotation mark + '„' => "\xe2\x80\x9e", #U+201E [„] double low-9 quotation mark + '†' => "\xe2\x80\xa0", #U+2020 [†] dagger + '‡' => "\xe2\x80\xa1", #U+2021 [‡] double dagger + '‰' => "\xe2\x80\xb0", #U+2030 [‰] per mille sign + '‹' => "\xe2\x80\xb9", #U+2039 [‹] single left-pointing angle quotation mark + '›' => "\xe2\x80\xba", #U+203A [›] single right-pointing angle quotation mark + '€' => "\xe2\x82\xac", #U+20AC [€] euro sign + ); - /** - * This table contains the data on how cp1259 characters map into Unicode (UTF-8). - * The cp1259 map describes standart tatarish cyrillic charset and based on the cp1251 table. - * cp1259 -- this is an outdated one byte encoding of the Tatar language, - * which includes all the Russian letters from cp1251. - * - * @link http://search.cpan.org/CPAN/authors/id/A/AM/AMICHAUER/Lingua-TT-Yanalif-0.08.tar.gz - * @link http://www.unicode.org/charts/PDF/U0400.pdf - */ - public static $cp1259_table = array( - #bytes from 0x00 to 0x7F (ASCII) saved as is - "\x80" => "\xd3\x98", #U+04d8 CYRILLIC CAPITAL LETTER SCHWA - "\x81" => "\xd0\x83", #U+0403 CYRILLIC CAPITAL LETTER GJE - "\x82" => "\xe2\x80\x9a", #U+201a SINGLE LOW-9 QUOTATION MARK - "\x83" => "\xd1\x93", #U+0453 CYRILLIC SMALL LETTER GJE - "\x84" => "\xe2\x80\x9e", #U+201e DOUBLE LOW-9 QUOTATION MARK - "\x85" => "\xe2\x80\xa6", #U+2026 HORIZONTAL ELLIPSIS - "\x86" => "\xe2\x80\xa0", #U+2020 DAGGER - "\x87" => "\xe2\x80\xa1", #U+2021 DOUBLE DAGGER - "\x88" => "\xe2\x82\xac", #U+20ac EURO SIGN - "\x89" => "\xe2\x80\xb0", #U+2030 PER MILLE SIGN - "\x8a" => "\xd3\xa8", #U+04e8 CYRILLIC CAPITAL LETTER BARRED O - "\x8b" => "\xe2\x80\xb9", #U+2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK - "\x8c" => "\xd2\xae", #U+04ae CYRILLIC CAPITAL LETTER STRAIGHT U - "\x8d" => "\xd2\x96", #U+0496 CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER - "\x8e" => "\xd2\xa2", #U+04a2 CYRILLIC CAPITAL LETTER EN WITH HOOK - "\x8f" => "\xd2\xba", #U+04ba CYRILLIC CAPITAL LETTER SHHA - "\x90" => "\xd3\x99", #U+04d9 CYRILLIC SMALL LETTER SCHWA - "\x91" => "\xe2\x80\x98", #U+2018 LEFT SINGLE QUOTATION MARK - "\x92" => "\xe2\x80\x99", #U+2019 RIGHT SINGLE QUOTATION MARK - "\x93" => "\xe2\x80\x9c", #U+201c LEFT DOUBLE QUOTATION MARK - "\x94" => "\xe2\x80\x9d", #U+201d RIGHT DOUBLE QUOTATION MARK - "\x95" => "\xe2\x80\xa2", #U+2022 BULLET - "\x96" => "\xe2\x80\x93", #U+2013 EN DASH - "\x97" => "\xe2\x80\x94", #U+2014 EM DASH - #"\x98" #UNDEFINED - "\x99" => "\xe2\x84\xa2", #U+2122 TRADE MARK SIGN - "\x9a" => "\xd3\xa9", #U+04e9 CYRILLIC SMALL LETTER BARRED O - "\x9b" => "\xe2\x80\xba", #U+203a SINGLE RIGHT-POINTING ANGLE QUOTATION MARK - "\x9c" => "\xd2\xaf", #U+04af CYRILLIC SMALL LETTER STRAIGHT U - "\x9d" => "\xd2\x97", #U+0497 CYRILLIC SMALL LETTER ZHE WITH DESCENDER - "\x9e" => "\xd2\xa3", #U+04a3 CYRILLIC SMALL LETTER EN WITH HOOK - "\x9f" => "\xd2\xbb", #U+04bb CYRILLIC SMALL LETTER SHHA - "\xa0" => "\xc2\xa0", #U+00a0 NO-BREAK SPACE - "\xa1" => "\xd0\x8e", #U+040e CYRILLIC CAPITAL LETTER SHORT U - "\xa2" => "\xd1\x9e", #U+045e CYRILLIC SMALL LETTER SHORT U - "\xa3" => "\xd0\x88", #U+0408 CYRILLIC CAPITAL LETTER JE - "\xa4" => "\xc2\xa4", #U+00a4 CURRENCY SIGN - "\xa5" => "\xd2\x90", #U+0490 CYRILLIC CAPITAL LETTER GHE WITH UPTURN - "\xa6" => "\xc2\xa6", #U+00a6 BROKEN BAR - "\xa7" => "\xc2\xa7", #U+00a7 SECTION SIGN - "\xa8" => "\xd0\x81", #U+0401 CYRILLIC CAPITAL LETTER IO - "\xa9" => "\xc2\xa9", #U+00a9 COPYRIGHT SIGN - "\xaa" => "\xd0\x84", #U+0404 CYRILLIC CAPITAL LETTER UKRAINIAN IE - "\xab" => "\xc2\xab", #U+00ab LEFT-POINTING DOUBLE ANGLE QUOTATION MARK - "\xac" => "\xc2\xac", #U+00ac NOT SIGN - "\xad" => "\xc2\xad", #U+00ad SOFT HYPHEN - "\xae" => "\xc2\xae", #U+00ae REGISTERED SIGN - "\xaf" => "\xd0\x87", #U+0407 CYRILLIC CAPITAL LETTER YI - "\xb0" => "\xc2\xb0", #U+00b0 DEGREE SIGN - "\xb1" => "\xc2\xb1", #U+00b1 PLUS-MINUS SIGN - "\xb2" => "\xd0\x86", #U+0406 CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I - "\xb3" => "\xd1\x96", #U+0456 CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I - "\xb4" => "\xd2\x91", #U+0491 CYRILLIC SMALL LETTER GHE WITH UPTURN - "\xb5" => "\xc2\xb5", #U+00b5 MICRO SIGN - "\xb6" => "\xc2\xb6", #U+00b6 PILCROW SIGN - "\xb7" => "\xc2\xb7", #U+00b7 MIDDLE DOT - "\xb8" => "\xd1\x91", #U+0451 CYRILLIC SMALL LETTER IO - "\xb9" => "\xe2\x84\x96", #U+2116 NUMERO SIGN - "\xba" => "\xd1\x94", #U+0454 CYRILLIC SMALL LETTER UKRAINIAN IE - "\xbb" => "\xc2\xbb", #U+00bb RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK - "\xbc" => "\xd1\x98", #U+0458 CYRILLIC SMALL LETTER JE - "\xbd" => "\xd0\x85", #U+0405 CYRILLIC CAPITAL LETTER DZE - "\xbe" => "\xd1\x95", #U+0455 CYRILLIC SMALL LETTER DZE - "\xbf" => "\xd1\x97", #U+0457 CYRILLIC SMALL LETTER YI - "\xc0" => "\xd0\x90", #U+0410 CYRILLIC CAPITAL LETTER A - "\xc1" => "\xd0\x91", #U+0411 CYRILLIC CAPITAL LETTER BE - "\xc2" => "\xd0\x92", #U+0412 CYRILLIC CAPITAL LETTER VE - "\xc3" => "\xd0\x93", #U+0413 CYRILLIC CAPITAL LETTER GHE - "\xc4" => "\xd0\x94", #U+0414 CYRILLIC CAPITAL LETTER DE - "\xc5" => "\xd0\x95", #U+0415 CYRILLIC CAPITAL LETTER IE - "\xc6" => "\xd0\x96", #U+0416 CYRILLIC CAPITAL LETTER ZHE - "\xc7" => "\xd0\x97", #U+0417 CYRILLIC CAPITAL LETTER ZE - "\xc8" => "\xd0\x98", #U+0418 CYRILLIC CAPITAL LETTER I - "\xc9" => "\xd0\x99", #U+0419 CYRILLIC CAPITAL LETTER SHORT I - "\xca" => "\xd0\x9a", #U+041a CYRILLIC CAPITAL LETTER KA - "\xcb" => "\xd0\x9b", #U+041b CYRILLIC CAPITAL LETTER EL - "\xcc" => "\xd0\x9c", #U+041c CYRILLIC CAPITAL LETTER EM - "\xcd" => "\xd0\x9d", #U+041d CYRILLIC CAPITAL LETTER EN - "\xce" => "\xd0\x9e", #U+041e CYRILLIC CAPITAL LETTER O - "\xcf" => "\xd0\x9f", #U+041f CYRILLIC CAPITAL LETTER PE - "\xd0" => "\xd0\xa0", #U+0420 CYRILLIC CAPITAL LETTER ER - "\xd1" => "\xd0\xa1", #U+0421 CYRILLIC CAPITAL LETTER ES - "\xd2" => "\xd0\xa2", #U+0422 CYRILLIC CAPITAL LETTER TE - "\xd3" => "\xd0\xa3", #U+0423 CYRILLIC CAPITAL LETTER U - "\xd4" => "\xd0\xa4", #U+0424 CYRILLIC CAPITAL LETTER EF - "\xd5" => "\xd0\xa5", #U+0425 CYRILLIC CAPITAL LETTER HA - "\xd6" => "\xd0\xa6", #U+0426 CYRILLIC CAPITAL LETTER TSE - "\xd7" => "\xd0\xa7", #U+0427 CYRILLIC CAPITAL LETTER CHE - "\xd8" => "\xd0\xa8", #U+0428 CYRILLIC CAPITAL LETTER SHA - "\xd9" => "\xd0\xa9", #U+0429 CYRILLIC CAPITAL LETTER SHCHA - "\xda" => "\xd0\xaa", #U+042a CYRILLIC CAPITAL LETTER HARD SIGN - "\xdb" => "\xd0\xab", #U+042b CYRILLIC CAPITAL LETTER YERU - "\xdc" => "\xd0\xac", #U+042c CYRILLIC CAPITAL LETTER SOFT SIGN - "\xdd" => "\xd0\xad", #U+042d CYRILLIC CAPITAL LETTER E - "\xde" => "\xd0\xae", #U+042e CYRILLIC CAPITAL LETTER YU - "\xdf" => "\xd0\xaf", #U+042f CYRILLIC CAPITAL LETTER YA - "\xe0" => "\xd0\xb0", #U+0430 CYRILLIC SMALL LETTER A - "\xe1" => "\xd0\xb1", #U+0431 CYRILLIC SMALL LETTER BE - "\xe2" => "\xd0\xb2", #U+0432 CYRILLIC SMALL LETTER VE - "\xe3" => "\xd0\xb3", #U+0433 CYRILLIC SMALL LETTER GHE - "\xe4" => "\xd0\xb4", #U+0434 CYRILLIC SMALL LETTER DE - "\xe5" => "\xd0\xb5", #U+0435 CYRILLIC SMALL LETTER IE - "\xe6" => "\xd0\xb6", #U+0436 CYRILLIC SMALL LETTER ZHE - "\xe7" => "\xd0\xb7", #U+0437 CYRILLIC SMALL LETTER ZE - "\xe8" => "\xd0\xb8", #U+0438 CYRILLIC SMALL LETTER I - "\xe9" => "\xd0\xb9", #U+0439 CYRILLIC SMALL LETTER SHORT I - "\xea" => "\xd0\xba", #U+043a CYRILLIC SMALL LETTER KA - "\xeb" => "\xd0\xbb", #U+043b CYRILLIC SMALL LETTER EL - "\xec" => "\xd0\xbc", #U+043c CYRILLIC SMALL LETTER EM - "\xed" => "\xd0\xbd", #U+043d CYRILLIC SMALL LETTER EN - "\xee" => "\xd0\xbe", #U+043e CYRILLIC SMALL LETTER O - "\xef" => "\xd0\xbf", #U+043f CYRILLIC SMALL LETTER PE - "\xf0" => "\xd1\x80", #U+0440 CYRILLIC SMALL LETTER ER - "\xf1" => "\xd1\x81", #U+0441 CYRILLIC SMALL LETTER ES - "\xf2" => "\xd1\x82", #U+0442 CYRILLIC SMALL LETTER TE - "\xf3" => "\xd1\x83", #U+0443 CYRILLIC SMALL LETTER U - "\xf4" => "\xd1\x84", #U+0444 CYRILLIC SMALL LETTER EF - "\xf5" => "\xd1\x85", #U+0445 CYRILLIC SMALL LETTER HA - "\xf6" => "\xd1\x86", #U+0446 CYRILLIC SMALL LETTER TSE - "\xf7" => "\xd1\x87", #U+0447 CYRILLIC SMALL LETTER CHE - "\xf8" => "\xd1\x88", #U+0448 CYRILLIC SMALL LETTER SHA - "\xf9" => "\xd1\x89", #U+0449 CYRILLIC SMALL LETTER SHCHA - "\xfa" => "\xd1\x8a", #U+044a CYRILLIC SMALL LETTER HARD SIGN - "\xfb" => "\xd1\x8b", #U+044b CYRILLIC SMALL LETTER YERU - "\xfc" => "\xd1\x8c", #U+044c CYRILLIC SMALL LETTER SOFT SIGN - "\xfd" => "\xd1\x8d", #U+044d CYRILLIC SMALL LETTER E - "\xfe" => "\xd1\x8e", #U+044e CYRILLIC SMALL LETTER YU - "\xff" => "\xd1\x8f", #U+044f CYRILLIC SMALL LETTER YA - ); + /** + * This table contains the data on how cp1259 characters map into Unicode (UTF-8). + * The cp1259 map describes standart tatarish cyrillic charset and based on the cp1251 table. + * cp1259 -- this is an outdated one byte encoding of the Tatar language, + * which includes all the Russian letters from cp1251. + * + * @link http://search.cpan.org/CPAN/authors/id/A/AM/AMICHAUER/Lingua-TT-Yanalif-0.08.tar.gz + * @link http://www.unicode.org/charts/PDF/U0400.pdf + */ + public static $cp1259_table = array( + #bytes from 0x00 to 0x7F (ASCII) saved as is + "\x80" => "\xd3\x98", #U+04d8 CYRILLIC CAPITAL LETTER SCHWA + "\x81" => "\xd0\x83", #U+0403 CYRILLIC CAPITAL LETTER GJE + "\x82" => "\xe2\x80\x9a", #U+201a SINGLE LOW-9 QUOTATION MARK + "\x83" => "\xd1\x93", #U+0453 CYRILLIC SMALL LETTER GJE + "\x84" => "\xe2\x80\x9e", #U+201e DOUBLE LOW-9 QUOTATION MARK + "\x85" => "\xe2\x80\xa6", #U+2026 HORIZONTAL ELLIPSIS + "\x86" => "\xe2\x80\xa0", #U+2020 DAGGER + "\x87" => "\xe2\x80\xa1", #U+2021 DOUBLE DAGGER + "\x88" => "\xe2\x82\xac", #U+20ac EURO SIGN + "\x89" => "\xe2\x80\xb0", #U+2030 PER MILLE SIGN + "\x8a" => "\xd3\xa8", #U+04e8 CYRILLIC CAPITAL LETTER BARRED O + "\x8b" => "\xe2\x80\xb9", #U+2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK + "\x8c" => "\xd2\xae", #U+04ae CYRILLIC CAPITAL LETTER STRAIGHT U + "\x8d" => "\xd2\x96", #U+0496 CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER + "\x8e" => "\xd2\xa2", #U+04a2 CYRILLIC CAPITAL LETTER EN WITH HOOK + "\x8f" => "\xd2\xba", #U+04ba CYRILLIC CAPITAL LETTER SHHA + "\x90" => "\xd3\x99", #U+04d9 CYRILLIC SMALL LETTER SCHWA + "\x91" => "\xe2\x80\x98", #U+2018 LEFT SINGLE QUOTATION MARK + "\x92" => "\xe2\x80\x99", #U+2019 RIGHT SINGLE QUOTATION MARK + "\x93" => "\xe2\x80\x9c", #U+201c LEFT DOUBLE QUOTATION MARK + "\x94" => "\xe2\x80\x9d", #U+201d RIGHT DOUBLE QUOTATION MARK + "\x95" => "\xe2\x80\xa2", #U+2022 BULLET + "\x96" => "\xe2\x80\x93", #U+2013 EN DASH + "\x97" => "\xe2\x80\x94", #U+2014 EM DASH + #"\x98" #UNDEFINED + "\x99" => "\xe2\x84\xa2", #U+2122 TRADE MARK SIGN + "\x9a" => "\xd3\xa9", #U+04e9 CYRILLIC SMALL LETTER BARRED O + "\x9b" => "\xe2\x80\xba", #U+203a SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + "\x9c" => "\xd2\xaf", #U+04af CYRILLIC SMALL LETTER STRAIGHT U + "\x9d" => "\xd2\x97", #U+0497 CYRILLIC SMALL LETTER ZHE WITH DESCENDER + "\x9e" => "\xd2\xa3", #U+04a3 CYRILLIC SMALL LETTER EN WITH HOOK + "\x9f" => "\xd2\xbb", #U+04bb CYRILLIC SMALL LETTER SHHA + "\xa0" => "\xc2\xa0", #U+00a0 NO-BREAK SPACE + "\xa1" => "\xd0\x8e", #U+040e CYRILLIC CAPITAL LETTER SHORT U + "\xa2" => "\xd1\x9e", #U+045e CYRILLIC SMALL LETTER SHORT U + "\xa3" => "\xd0\x88", #U+0408 CYRILLIC CAPITAL LETTER JE + "\xa4" => "\xc2\xa4", #U+00a4 CURRENCY SIGN + "\xa5" => "\xd2\x90", #U+0490 CYRILLIC CAPITAL LETTER GHE WITH UPTURN + "\xa6" => "\xc2\xa6", #U+00a6 BROKEN BAR + "\xa7" => "\xc2\xa7", #U+00a7 SECTION SIGN + "\xa8" => "\xd0\x81", #U+0401 CYRILLIC CAPITAL LETTER IO + "\xa9" => "\xc2\xa9", #U+00a9 COPYRIGHT SIGN + "\xaa" => "\xd0\x84", #U+0404 CYRILLIC CAPITAL LETTER UKRAINIAN IE + "\xab" => "\xc2\xab", #U+00ab LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + "\xac" => "\xc2\xac", #U+00ac NOT SIGN + "\xad" => "\xc2\xad", #U+00ad SOFT HYPHEN + "\xae" => "\xc2\xae", #U+00ae REGISTERED SIGN + "\xaf" => "\xd0\x87", #U+0407 CYRILLIC CAPITAL LETTER YI + "\xb0" => "\xc2\xb0", #U+00b0 DEGREE SIGN + "\xb1" => "\xc2\xb1", #U+00b1 PLUS-MINUS SIGN + "\xb2" => "\xd0\x86", #U+0406 CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I + "\xb3" => "\xd1\x96", #U+0456 CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + "\xb4" => "\xd2\x91", #U+0491 CYRILLIC SMALL LETTER GHE WITH UPTURN + "\xb5" => "\xc2\xb5", #U+00b5 MICRO SIGN + "\xb6" => "\xc2\xb6", #U+00b6 PILCROW SIGN + "\xb7" => "\xc2\xb7", #U+00b7 MIDDLE DOT + "\xb8" => "\xd1\x91", #U+0451 CYRILLIC SMALL LETTER IO + "\xb9" => "\xe2\x84\x96", #U+2116 NUMERO SIGN + "\xba" => "\xd1\x94", #U+0454 CYRILLIC SMALL LETTER UKRAINIAN IE + "\xbb" => "\xc2\xbb", #U+00bb RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + "\xbc" => "\xd1\x98", #U+0458 CYRILLIC SMALL LETTER JE + "\xbd" => "\xd0\x85", #U+0405 CYRILLIC CAPITAL LETTER DZE + "\xbe" => "\xd1\x95", #U+0455 CYRILLIC SMALL LETTER DZE + "\xbf" => "\xd1\x97", #U+0457 CYRILLIC SMALL LETTER YI + "\xc0" => "\xd0\x90", #U+0410 CYRILLIC CAPITAL LETTER A + "\xc1" => "\xd0\x91", #U+0411 CYRILLIC CAPITAL LETTER BE + "\xc2" => "\xd0\x92", #U+0412 CYRILLIC CAPITAL LETTER VE + "\xc3" => "\xd0\x93", #U+0413 CYRILLIC CAPITAL LETTER GHE + "\xc4" => "\xd0\x94", #U+0414 CYRILLIC CAPITAL LETTER DE + "\xc5" => "\xd0\x95", #U+0415 CYRILLIC CAPITAL LETTER IE + "\xc6" => "\xd0\x96", #U+0416 CYRILLIC CAPITAL LETTER ZHE + "\xc7" => "\xd0\x97", #U+0417 CYRILLIC CAPITAL LETTER ZE + "\xc8" => "\xd0\x98", #U+0418 CYRILLIC CAPITAL LETTER I + "\xc9" => "\xd0\x99", #U+0419 CYRILLIC CAPITAL LETTER SHORT I + "\xca" => "\xd0\x9a", #U+041a CYRILLIC CAPITAL LETTER KA + "\xcb" => "\xd0\x9b", #U+041b CYRILLIC CAPITAL LETTER EL + "\xcc" => "\xd0\x9c", #U+041c CYRILLIC CAPITAL LETTER EM + "\xcd" => "\xd0\x9d", #U+041d CYRILLIC CAPITAL LETTER EN + "\xce" => "\xd0\x9e", #U+041e CYRILLIC CAPITAL LETTER O + "\xcf" => "\xd0\x9f", #U+041f CYRILLIC CAPITAL LETTER PE + "\xd0" => "\xd0\xa0", #U+0420 CYRILLIC CAPITAL LETTER ER + "\xd1" => "\xd0\xa1", #U+0421 CYRILLIC CAPITAL LETTER ES + "\xd2" => "\xd0\xa2", #U+0422 CYRILLIC CAPITAL LETTER TE + "\xd3" => "\xd0\xa3", #U+0423 CYRILLIC CAPITAL LETTER U + "\xd4" => "\xd0\xa4", #U+0424 CYRILLIC CAPITAL LETTER EF + "\xd5" => "\xd0\xa5", #U+0425 CYRILLIC CAPITAL LETTER HA + "\xd6" => "\xd0\xa6", #U+0426 CYRILLIC CAPITAL LETTER TSE + "\xd7" => "\xd0\xa7", #U+0427 CYRILLIC CAPITAL LETTER CHE + "\xd8" => "\xd0\xa8", #U+0428 CYRILLIC CAPITAL LETTER SHA + "\xd9" => "\xd0\xa9", #U+0429 CYRILLIC CAPITAL LETTER SHCHA + "\xda" => "\xd0\xaa", #U+042a CYRILLIC CAPITAL LETTER HARD SIGN + "\xdb" => "\xd0\xab", #U+042b CYRILLIC CAPITAL LETTER YERU + "\xdc" => "\xd0\xac", #U+042c CYRILLIC CAPITAL LETTER SOFT SIGN + "\xdd" => "\xd0\xad", #U+042d CYRILLIC CAPITAL LETTER E + "\xde" => "\xd0\xae", #U+042e CYRILLIC CAPITAL LETTER YU + "\xdf" => "\xd0\xaf", #U+042f CYRILLIC CAPITAL LETTER YA + "\xe0" => "\xd0\xb0", #U+0430 CYRILLIC SMALL LETTER A + "\xe1" => "\xd0\xb1", #U+0431 CYRILLIC SMALL LETTER BE + "\xe2" => "\xd0\xb2", #U+0432 CYRILLIC SMALL LETTER VE + "\xe3" => "\xd0\xb3", #U+0433 CYRILLIC SMALL LETTER GHE + "\xe4" => "\xd0\xb4", #U+0434 CYRILLIC SMALL LETTER DE + "\xe5" => "\xd0\xb5", #U+0435 CYRILLIC SMALL LETTER IE + "\xe6" => "\xd0\xb6", #U+0436 CYRILLIC SMALL LETTER ZHE + "\xe7" => "\xd0\xb7", #U+0437 CYRILLIC SMALL LETTER ZE + "\xe8" => "\xd0\xb8", #U+0438 CYRILLIC SMALL LETTER I + "\xe9" => "\xd0\xb9", #U+0439 CYRILLIC SMALL LETTER SHORT I + "\xea" => "\xd0\xba", #U+043a CYRILLIC SMALL LETTER KA + "\xeb" => "\xd0\xbb", #U+043b CYRILLIC SMALL LETTER EL + "\xec" => "\xd0\xbc", #U+043c CYRILLIC SMALL LETTER EM + "\xed" => "\xd0\xbd", #U+043d CYRILLIC SMALL LETTER EN + "\xee" => "\xd0\xbe", #U+043e CYRILLIC SMALL LETTER O + "\xef" => "\xd0\xbf", #U+043f CYRILLIC SMALL LETTER PE + "\xf0" => "\xd1\x80", #U+0440 CYRILLIC SMALL LETTER ER + "\xf1" => "\xd1\x81", #U+0441 CYRILLIC SMALL LETTER ES + "\xf2" => "\xd1\x82", #U+0442 CYRILLIC SMALL LETTER TE + "\xf3" => "\xd1\x83", #U+0443 CYRILLIC SMALL LETTER U + "\xf4" => "\xd1\x84", #U+0444 CYRILLIC SMALL LETTER EF + "\xf5" => "\xd1\x85", #U+0445 CYRILLIC SMALL LETTER HA + "\xf6" => "\xd1\x86", #U+0446 CYRILLIC SMALL LETTER TSE + "\xf7" => "\xd1\x87", #U+0447 CYRILLIC SMALL LETTER CHE + "\xf8" => "\xd1\x88", #U+0448 CYRILLIC SMALL LETTER SHA + "\xf9" => "\xd1\x89", #U+0449 CYRILLIC SMALL LETTER SHCHA + "\xfa" => "\xd1\x8a", #U+044a CYRILLIC SMALL LETTER HARD SIGN + "\xfb" => "\xd1\x8b", #U+044b CYRILLIC SMALL LETTER YERU + "\xfc" => "\xd1\x8c", #U+044c CYRILLIC SMALL LETTER SOFT SIGN + "\xfd" => "\xd1\x8d", #U+044d CYRILLIC SMALL LETTER E + "\xfe" => "\xd1\x8e", #U+044e CYRILLIC SMALL LETTER YU + "\xff" => "\xd1\x8f", #U+044f CYRILLIC SMALL LETTER YA + ); - /** - * UTF-8 Case lookup table - * - * This lookuptable defines the upper case letters to their correspponding - * lower case letter in UTF-8 - * - * @author Andreas Gohr - */ - public static $convert_case_table = array( - #CASE_UPPER => case_lower - "\x41" => "\x61", #A a - "\x42" => "\x62", #B b - "\x43" => "\x63", #C c - "\x44" => "\x64", #D d - "\x45" => "\x65", #E e - "\x46" => "\x66", #F f - "\x47" => "\x67", #G g - "\x48" => "\x68", #H h - "\x49" => "\x69", #I i - "\x4a" => "\x6a", #J j - "\x4b" => "\x6b", #K k - "\x4c" => "\x6c", #L l - "\x4d" => "\x6d", #M m - "\x4e" => "\x6e", #N n - "\x4f" => "\x6f", #O o - "\x50" => "\x70", #P p - "\x51" => "\x71", #Q q - "\x52" => "\x72", #R r - "\x53" => "\x73", #S s - "\x54" => "\x74", #T t - "\x55" => "\x75", #U u - "\x56" => "\x76", #V v - "\x57" => "\x77", #W w - "\x58" => "\x78", #X x - "\x59" => "\x79", #Y y - "\x5a" => "\x7a", #Z z - "\xc3\x80" => "\xc3\xa0", - "\xc3\x81" => "\xc3\xa1", - "\xc3\x82" => "\xc3\xa2", - "\xc3\x83" => "\xc3\xa3", - "\xc3\x84" => "\xc3\xa4", - "\xc3\x85" => "\xc3\xa5", - "\xc3\x86" => "\xc3\xa6", - "\xc3\x87" => "\xc3\xa7", - "\xc3\x88" => "\xc3\xa8", - "\xc3\x89" => "\xc3\xa9", - "\xc3\x8a" => "\xc3\xaa", - "\xc3\x8b" => "\xc3\xab", - "\xc3\x8c" => "\xc3\xac", - "\xc3\x8d" => "\xc3\xad", - "\xc3\x8e" => "\xc3\xae", - "\xc3\x8f" => "\xc3\xaf", - "\xc3\x90" => "\xc3\xb0", - "\xc3\x91" => "\xc3\xb1", - "\xc3\x92" => "\xc3\xb2", - "\xc3\x93" => "\xc3\xb3", - "\xc3\x94" => "\xc3\xb4", - "\xc3\x95" => "\xc3\xb5", - "\xc3\x96" => "\xc3\xb6", - "\xc3\x98" => "\xc3\xb8", - "\xc3\x99" => "\xc3\xb9", - "\xc3\x9a" => "\xc3\xba", - "\xc3\x9b" => "\xc3\xbb", - "\xc3\x9c" => "\xc3\xbc", - "\xc3\x9d" => "\xc3\xbd", - "\xc3\x9e" => "\xc3\xbe", - "\xc4\x80" => "\xc4\x81", - "\xc4\x82" => "\xc4\x83", - "\xc4\x84" => "\xc4\x85", - "\xc4\x86" => "\xc4\x87", - "\xc4\x88" => "\xc4\x89", - "\xc4\x8a" => "\xc4\x8b", - "\xc4\x8c" => "\xc4\x8d", - "\xc4\x8e" => "\xc4\x8f", - "\xc4\x90" => "\xc4\x91", - "\xc4\x92" => "\xc4\x93", - "\xc4\x94" => "\xc4\x95", - "\xc4\x96" => "\xc4\x97", - "\xc4\x98" => "\xc4\x99", - "\xc4\x9a" => "\xc4\x9b", - "\xc4\x9c" => "\xc4\x9d", - "\xc4\x9e" => "\xc4\x9f", - "\xc4\xa0" => "\xc4\xa1", - "\xc4\xa2" => "\xc4\xa3", - "\xc4\xa4" => "\xc4\xa5", - "\xc4\xa6" => "\xc4\xa7", - "\xc4\xa8" => "\xc4\xa9", - "\xc4\xaa" => "\xc4\xab", - "\xc4\xac" => "\xc4\xad", - "\xc4\xae" => "\xc4\xaf", - "\xc4\xb2" => "\xc4\xb3", - "\xc4\xb4" => "\xc4\xb5", - "\xc4\xb6" => "\xc4\xb7", - "\xc4\xb9" => "\xc4\xba", - "\xc4\xbb" => "\xc4\xbc", - "\xc4\xbd" => "\xc4\xbe", - "\xc4\xbf" => "\xc5\x80", - "\xc5\x81" => "\xc5\x82", - "\xc5\x83" => "\xc5\x84", - "\xc5\x85" => "\xc5\x86", - "\xc5\x87" => "\xc5\x88", - "\xc5\x8a" => "\xc5\x8b", - "\xc5\x8c" => "\xc5\x8d", - "\xc5\x8e" => "\xc5\x8f", - "\xc5\x90" => "\xc5\x91", - "\xc5\x92" => "\xc5\x93", - "\xc5\x94" => "\xc5\x95", - "\xc5\x96" => "\xc5\x97", - "\xc5\x98" => "\xc5\x99", - "\xc5\x9a" => "\xc5\x9b", - "\xc5\x9c" => "\xc5\x9d", - "\xc5\x9e" => "\xc5\x9f", - "\xc5\xa0" => "\xc5\xa1", - "\xc5\xa2" => "\xc5\xa3", - "\xc5\xa4" => "\xc5\xa5", - "\xc5\xa6" => "\xc5\xa7", - "\xc5\xa8" => "\xc5\xa9", - "\xc5\xaa" => "\xc5\xab", - "\xc5\xac" => "\xc5\xad", - "\xc5\xae" => "\xc5\xaf", - "\xc5\xb0" => "\xc5\xb1", - "\xc5\xb2" => "\xc5\xb3", - "\xc5\xb4" => "\xc5\xb5", - "\xc5\xb6" => "\xc5\xb7", - "\xc5\xb8" => "\xc3\xbf", - "\xc5\xb9" => "\xc5\xba", - "\xc5\xbb" => "\xc5\xbc", - "\xc5\xbd" => "\xc5\xbe", - "\xc6\x81" => "\xc9\x93", - "\xc6\x82" => "\xc6\x83", - "\xc6\x84" => "\xc6\x85", - "\xc6\x86" => "\xc9\x94", - "\xc6\x87" => "\xc6\x88", - "\xc6\x89" => "\xc9\x96", - "\xc6\x8a" => "\xc9\x97", - "\xc6\x8b" => "\xc6\x8c", - "\xc6\x8e" => "\xc7\x9d", - "\xc6\x8f" => "\xc9\x99", - "\xc6\x90" => "\xc9\x9b", - "\xc6\x91" => "\xc6\x92", - "\xc6\x94" => "\xc9\xa3", - "\xc6\x96" => "\xc9\xa9", - "\xc6\x97" => "\xc9\xa8", - "\xc6\x98" => "\xc6\x99", - "\xc6\x9c" => "\xc9\xaf", - "\xc6\x9d" => "\xc9\xb2", - "\xc6\x9f" => "\xc9\xb5", - "\xc6\xa0" => "\xc6\xa1", - "\xc6\xa2" => "\xc6\xa3", - "\xc6\xa4" => "\xc6\xa5", - "\xc6\xa6" => "\xca\x80", - "\xc6\xa7" => "\xc6\xa8", - "\xc6\xa9" => "\xca\x83", - "\xc6\xac" => "\xc6\xad", - "\xc6\xae" => "\xca\x88", - "\xc6\xaf" => "\xc6\xb0", - "\xc6\xb1" => "\xca\x8a", - "\xc6\xb2" => "\xca\x8b", - "\xc6\xb3" => "\xc6\xb4", - "\xc6\xb5" => "\xc6\xb6", - "\xc6\xb7" => "\xca\x92", - "\xc6\xb8" => "\xc6\xb9", - "\xc6\xbc" => "\xc6\xbd", - "\xc7\x85" => "\xc7\x86", - "\xc7\x88" => "\xc7\x89", - "\xc7\x8b" => "\xc7\x8c", - "\xc7\x8d" => "\xc7\x8e", - "\xc7\x8f" => "\xc7\x90", - "\xc7\x91" => "\xc7\x92", - "\xc7\x93" => "\xc7\x94", - "\xc7\x95" => "\xc7\x96", - "\xc7\x97" => "\xc7\x98", - "\xc7\x99" => "\xc7\x9a", - "\xc7\x9b" => "\xc7\x9c", - "\xc7\x9e" => "\xc7\x9f", - "\xc7\xa0" => "\xc7\xa1", - "\xc7\xa2" => "\xc7\xa3", - "\xc7\xa4" => "\xc7\xa5", - "\xc7\xa6" => "\xc7\xa7", - "\xc7\xa8" => "\xc7\xa9", - "\xc7\xaa" => "\xc7\xab", - "\xc7\xac" => "\xc7\xad", - "\xc7\xae" => "\xc7\xaf", - "\xc7\xb2" => "\xc7\xb3", - "\xc7\xb4" => "\xc7\xb5", - "\xc7\xb6" => "\xc6\x95", - "\xc7\xb7" => "\xc6\xbf", - "\xc7\xb8" => "\xc7\xb9", - "\xc7\xba" => "\xc7\xbb", - "\xc7\xbc" => "\xc7\xbd", - "\xc7\xbe" => "\xc7\xbf", - "\xc8\x80" => "\xc8\x81", - "\xc8\x82" => "\xc8\x83", - "\xc8\x84" => "\xc8\x85", - "\xc8\x86" => "\xc8\x87", - "\xc8\x88" => "\xc8\x89", - "\xc8\x8a" => "\xc8\x8b", - "\xc8\x8c" => "\xc8\x8d", - "\xc8\x8e" => "\xc8\x8f", - "\xc8\x90" => "\xc8\x91", - "\xc8\x92" => "\xc8\x93", - "\xc8\x94" => "\xc8\x95", - "\xc8\x96" => "\xc8\x97", - "\xc8\x98" => "\xc8\x99", - "\xc8\x9a" => "\xc8\x9b", - "\xc8\x9c" => "\xc8\x9d", - "\xc8\x9e" => "\xc8\x9f", - "\xc8\xa0" => "\xc6\x9e", - "\xc8\xa2" => "\xc8\xa3", - "\xc8\xa4" => "\xc8\xa5", - "\xc8\xa6" => "\xc8\xa7", - "\xc8\xa8" => "\xc8\xa9", - "\xc8\xaa" => "\xc8\xab", - "\xc8\xac" => "\xc8\xad", - "\xc8\xae" => "\xc8\xaf", - "\xc8\xb0" => "\xc8\xb1", - "\xc8\xb2" => "\xc8\xb3", - "\xce\x86" => "\xce\xac", - "\xce\x88" => "\xce\xad", - "\xce\x89" => "\xce\xae", - "\xce\x8a" => "\xce\xaf", - "\xce\x8c" => "\xcf\x8c", - "\xce\x8e" => "\xcf\x8d", - "\xce\x8f" => "\xcf\x8e", - "\xce\x91" => "\xce\xb1", - "\xce\x92" => "\xce\xb2", - "\xce\x93" => "\xce\xb3", - "\xce\x94" => "\xce\xb4", - "\xce\x95" => "\xce\xb5", - "\xce\x96" => "\xce\xb6", - "\xce\x97" => "\xce\xb7", - "\xce\x98" => "\xce\xb8", - "\xce\x99" => "\xce\xb9", - "\xce\x9a" => "\xce\xba", - "\xce\x9b" => "\xce\xbb", - "\xce\x9c" => "\xc2\xb5", - "\xce\x9d" => "\xce\xbd", - "\xce\x9e" => "\xce\xbe", - "\xce\x9f" => "\xce\xbf", - "\xce\xa0" => "\xcf\x80", - "\xce\xa1" => "\xcf\x81", - "\xce\xa3" => "\xcf\x82", - "\xce\xa4" => "\xcf\x84", - "\xce\xa5" => "\xcf\x85", - "\xce\xa6" => "\xcf\x86", - "\xce\xa7" => "\xcf\x87", - "\xce\xa8" => "\xcf\x88", - "\xce\xa9" => "\xcf\x89", - "\xce\xaa" => "\xcf\x8a", - "\xce\xab" => "\xcf\x8b", - "\xcf\x98" => "\xcf\x99", - "\xcf\x9a" => "\xcf\x9b", - "\xcf\x9c" => "\xcf\x9d", - "\xcf\x9e" => "\xcf\x9f", - "\xcf\xa0" => "\xcf\xa1", - "\xcf\xa2" => "\xcf\xa3", - "\xcf\xa4" => "\xcf\xa5", - "\xcf\xa6" => "\xcf\xa7", - "\xcf\xa8" => "\xcf\xa9", - "\xcf\xaa" => "\xcf\xab", - "\xcf\xac" => "\xcf\xad", - "\xcf\xae" => "\xcf\xaf", - "\xd0\x80" => "\xd1\x90", - "\xd0\x81" => "\xd1\x91", - "\xd0\x82" => "\xd1\x92", - "\xd0\x83" => "\xd1\x93", - "\xd0\x84" => "\xd1\x94", - "\xd0\x85" => "\xd1\x95", - "\xd0\x86" => "\xd1\x96", - "\xd0\x87" => "\xd1\x97", - "\xd0\x88" => "\xd1\x98", - "\xd0\x89" => "\xd1\x99", - "\xd0\x8a" => "\xd1\x9a", - "\xd0\x8b" => "\xd1\x9b", - "\xd0\x8c" => "\xd1\x9c", - "\xd0\x8d" => "\xd1\x9d", - "\xd0\x8e" => "\xd1\x9e", - "\xd0\x8f" => "\xd1\x9f", - "\xd0\x90" => "\xd0\xb0", - "\xd0\x91" => "\xd0\xb1", - "\xd0\x92" => "\xd0\xb2", - "\xd0\x93" => "\xd0\xb3", - "\xd0\x94" => "\xd0\xb4", - "\xd0\x95" => "\xd0\xb5", - "\xd0\x96" => "\xd0\xb6", - "\xd0\x97" => "\xd0\xb7", - "\xd0\x98" => "\xd0\xb8", - "\xd0\x99" => "\xd0\xb9", - "\xd0\x9a" => "\xd0\xba", - "\xd0\x9b" => "\xd0\xbb", - "\xd0\x9c" => "\xd0\xbc", - "\xd0\x9d" => "\xd0\xbd", - "\xd0\x9e" => "\xd0\xbe", - "\xd0\x9f" => "\xd0\xbf", - "\xd0\xa0" => "\xd1\x80", - "\xd0\xa1" => "\xd1\x81", - "\xd0\xa2" => "\xd1\x82", - "\xd0\xa3" => "\xd1\x83", - "\xd0\xa4" => "\xd1\x84", - "\xd0\xa5" => "\xd1\x85", - "\xd0\xa6" => "\xd1\x86", - "\xd0\xa7" => "\xd1\x87", - "\xd0\xa8" => "\xd1\x88", - "\xd0\xa9" => "\xd1\x89", - "\xd0\xaa" => "\xd1\x8a", - "\xd0\xab" => "\xd1\x8b", - "\xd0\xac" => "\xd1\x8c", - "\xd0\xad" => "\xd1\x8d", - "\xd0\xae" => "\xd1\x8e", - "\xd0\xaf" => "\xd1\x8f", - "\xd1\xa0" => "\xd1\xa1", - "\xd1\xa2" => "\xd1\xa3", - "\xd1\xa4" => "\xd1\xa5", - "\xd1\xa6" => "\xd1\xa7", - "\xd1\xa8" => "\xd1\xa9", - "\xd1\xaa" => "\xd1\xab", - "\xd1\xac" => "\xd1\xad", - "\xd1\xae" => "\xd1\xaf", - "\xd1\xb0" => "\xd1\xb1", - "\xd1\xb2" => "\xd1\xb3", - "\xd1\xb4" => "\xd1\xb5", - "\xd1\xb6" => "\xd1\xb7", - "\xd1\xb8" => "\xd1\xb9", - "\xd1\xba" => "\xd1\xbb", - "\xd1\xbc" => "\xd1\xbd", - "\xd1\xbe" => "\xd1\xbf", - "\xd2\x80" => "\xd2\x81", - "\xd2\x8a" => "\xd2\x8b", - "\xd2\x8c" => "\xd2\x8d", - "\xd2\x8e" => "\xd2\x8f", - "\xd2\x90" => "\xd2\x91", - "\xd2\x92" => "\xd2\x93", - "\xd2\x94" => "\xd2\x95", - "\xd2\x96" => "\xd2\x97", - "\xd2\x98" => "\xd2\x99", - "\xd2\x9a" => "\xd2\x9b", - "\xd2\x9c" => "\xd2\x9d", - "\xd2\x9e" => "\xd2\x9f", - "\xd2\xa0" => "\xd2\xa1", - "\xd2\xa2" => "\xd2\xa3", - "\xd2\xa4" => "\xd2\xa5", - "\xd2\xa6" => "\xd2\xa7", - "\xd2\xa8" => "\xd2\xa9", - "\xd2\xaa" => "\xd2\xab", - "\xd2\xac" => "\xd2\xad", - "\xd2\xae" => "\xd2\xaf", - "\xd2\xb0" => "\xd2\xb1", - "\xd2\xb2" => "\xd2\xb3", - "\xd2\xb4" => "\xd2\xb5", - "\xd2\xb6" => "\xd2\xb7", - "\xd2\xb8" => "\xd2\xb9", - "\xd2\xba" => "\xd2\xbb", - "\xd2\xbc" => "\xd2\xbd", - "\xd2\xbe" => "\xd2\xbf", - "\xd3\x81" => "\xd3\x82", - "\xd3\x83" => "\xd3\x84", - "\xd3\x85" => "\xd3\x86", - "\xd3\x87" => "\xd3\x88", - "\xd3\x89" => "\xd3\x8a", - "\xd3\x8b" => "\xd3\x8c", - "\xd3\x8d" => "\xd3\x8e", - "\xd3\x90" => "\xd3\x91", - "\xd3\x92" => "\xd3\x93", - "\xd3\x94" => "\xd3\x95", - "\xd3\x96" => "\xd3\x97", - "\xd3\x98" => "\xd3\x99", - "\xd3\x9a" => "\xd3\x9b", - "\xd3\x9c" => "\xd3\x9d", - "\xd3\x9e" => "\xd3\x9f", - "\xd3\xa0" => "\xd3\xa1", - "\xd3\xa2" => "\xd3\xa3", - "\xd3\xa4" => "\xd3\xa5", - "\xd3\xa6" => "\xd3\xa7", - "\xd3\xa8" => "\xd3\xa9", - "\xd3\xaa" => "\xd3\xab", - "\xd3\xac" => "\xd3\xad", - "\xd3\xae" => "\xd3\xaf", - "\xd3\xb0" => "\xd3\xb1", - "\xd3\xb2" => "\xd3\xb3", - "\xd3\xb4" => "\xd3\xb5", - "\xd3\xb8" => "\xd3\xb9", - "\xd4\x80" => "\xd4\x81", - "\xd4\x82" => "\xd4\x83", - "\xd4\x84" => "\xd4\x85", - "\xd4\x86" => "\xd4\x87", - "\xd4\x88" => "\xd4\x89", - "\xd4\x8a" => "\xd4\x8b", - "\xd4\x8c" => "\xd4\x8d", - "\xd4\x8e" => "\xd4\x8f", - "\xd4\xb1" => "\xd5\xa1", - "\xd4\xb2" => "\xd5\xa2", - "\xd4\xb3" => "\xd5\xa3", - "\xd4\xb4" => "\xd5\xa4", - "\xd4\xb5" => "\xd5\xa5", - "\xd4\xb6" => "\xd5\xa6", - "\xd4\xb7" => "\xd5\xa7", - "\xd4\xb8" => "\xd5\xa8", - "\xd4\xb9" => "\xd5\xa9", - "\xd4\xba" => "\xd5\xaa", - "\xd4\xbb" => "\xd5\xab", - "\xd4\xbc" => "\xd5\xac", - "\xd4\xbd" => "\xd5\xad", - "\xd4\xbe" => "\xd5\xae", - "\xd4\xbf" => "\xd5\xaf", - "\xd5\x80" => "\xd5\xb0", - "\xd5\x81" => "\xd5\xb1", - "\xd5\x82" => "\xd5\xb2", - "\xd5\x83" => "\xd5\xb3", - "\xd5\x84" => "\xd5\xb4", - "\xd5\x85" => "\xd5\xb5", - "\xd5\x86" => "\xd5\xb6", - "\xd5\x87" => "\xd5\xb7", - "\xd5\x88" => "\xd5\xb8", - "\xd5\x89" => "\xd5\xb9", - "\xd5\x8a" => "\xd5\xba", - "\xd5\x8b" => "\xd5\xbb", - "\xd5\x8c" => "\xd5\xbc", - "\xd5\x8d" => "\xd5\xbd", - "\xd5\x8e" => "\xd5\xbe", - "\xd5\x8f" => "\xd5\xbf", - "\xd5\x90" => "\xd6\x80", - "\xd5\x91" => "\xd6\x81", - "\xd5\x92" => "\xd6\x82", - "\xd5\x93" => "\xd6\x83", - "\xd5\x94" => "\xd6\x84", - "\xd5\x95" => "\xd6\x85", - "\xd5\x96" => "\xd6\x86", - "\xe1\xb8\x80" => "\xe1\xb8\x81", - "\xe1\xb8\x82" => "\xe1\xb8\x83", - "\xe1\xb8\x84" => "\xe1\xb8\x85", - "\xe1\xb8\x86" => "\xe1\xb8\x87", - "\xe1\xb8\x88" => "\xe1\xb8\x89", - "\xe1\xb8\x8a" => "\xe1\xb8\x8b", - "\xe1\xb8\x8c" => "\xe1\xb8\x8d", - "\xe1\xb8\x8e" => "\xe1\xb8\x8f", - "\xe1\xb8\x90" => "\xe1\xb8\x91", - "\xe1\xb8\x92" => "\xe1\xb8\x93", - "\xe1\xb8\x94" => "\xe1\xb8\x95", - "\xe1\xb8\x96" => "\xe1\xb8\x97", - "\xe1\xb8\x98" => "\xe1\xb8\x99", - "\xe1\xb8\x9a" => "\xe1\xb8\x9b", - "\xe1\xb8\x9c" => "\xe1\xb8\x9d", - "\xe1\xb8\x9e" => "\xe1\xb8\x9f", - "\xe1\xb8\xa0" => "\xe1\xb8\xa1", - "\xe1\xb8\xa2" => "\xe1\xb8\xa3", - "\xe1\xb8\xa4" => "\xe1\xb8\xa5", - "\xe1\xb8\xa6" => "\xe1\xb8\xa7", - "\xe1\xb8\xa8" => "\xe1\xb8\xa9", - "\xe1\xb8\xaa" => "\xe1\xb8\xab", - "\xe1\xb8\xac" => "\xe1\xb8\xad", - "\xe1\xb8\xae" => "\xe1\xb8\xaf", - "\xe1\xb8\xb0" => "\xe1\xb8\xb1", - "\xe1\xb8\xb2" => "\xe1\xb8\xb3", - "\xe1\xb8\xb4" => "\xe1\xb8\xb5", - "\xe1\xb8\xb6" => "\xe1\xb8\xb7", - "\xe1\xb8\xb8" => "\xe1\xb8\xb9", - "\xe1\xb8\xba" => "\xe1\xb8\xbb", - "\xe1\xb8\xbc" => "\xe1\xb8\xbd", - "\xe1\xb8\xbe" => "\xe1\xb8\xbf", - "\xe1\xb9\x80" => "\xe1\xb9\x81", - "\xe1\xb9\x82" => "\xe1\xb9\x83", - "\xe1\xb9\x84" => "\xe1\xb9\x85", - "\xe1\xb9\x86" => "\xe1\xb9\x87", - "\xe1\xb9\x88" => "\xe1\xb9\x89", - "\xe1\xb9\x8a" => "\xe1\xb9\x8b", - "\xe1\xb9\x8c" => "\xe1\xb9\x8d", - "\xe1\xb9\x8e" => "\xe1\xb9\x8f", - "\xe1\xb9\x90" => "\xe1\xb9\x91", - "\xe1\xb9\x92" => "\xe1\xb9\x93", - "\xe1\xb9\x94" => "\xe1\xb9\x95", - "\xe1\xb9\x96" => "\xe1\xb9\x97", - "\xe1\xb9\x98" => "\xe1\xb9\x99", - "\xe1\xb9\x9a" => "\xe1\xb9\x9b", - "\xe1\xb9\x9c" => "\xe1\xb9\x9d", - "\xe1\xb9\x9e" => "\xe1\xb9\x9f", - "\xe1\xb9\xa0" => "\xe1\xb9\xa1", - "\xe1\xb9\xa2" => "\xe1\xb9\xa3", - "\xe1\xb9\xa4" => "\xe1\xb9\xa5", - "\xe1\xb9\xa6" => "\xe1\xb9\xa7", - "\xe1\xb9\xa8" => "\xe1\xb9\xa9", - "\xe1\xb9\xaa" => "\xe1\xb9\xab", - "\xe1\xb9\xac" => "\xe1\xb9\xad", - "\xe1\xb9\xae" => "\xe1\xb9\xaf", - "\xe1\xb9\xb0" => "\xe1\xb9\xb1", - "\xe1\xb9\xb2" => "\xe1\xb9\xb3", - "\xe1\xb9\xb4" => "\xe1\xb9\xb5", - "\xe1\xb9\xb6" => "\xe1\xb9\xb7", - "\xe1\xb9\xb8" => "\xe1\xb9\xb9", - "\xe1\xb9\xba" => "\xe1\xb9\xbb", - "\xe1\xb9\xbc" => "\xe1\xb9\xbd", - "\xe1\xb9\xbe" => "\xe1\xb9\xbf", - "\xe1\xba\x80" => "\xe1\xba\x81", - "\xe1\xba\x82" => "\xe1\xba\x83", - "\xe1\xba\x84" => "\xe1\xba\x85", - "\xe1\xba\x86" => "\xe1\xba\x87", - "\xe1\xba\x88" => "\xe1\xba\x89", - "\xe1\xba\x8a" => "\xe1\xba\x8b", - "\xe1\xba\x8c" => "\xe1\xba\x8d", - "\xe1\xba\x8e" => "\xe1\xba\x8f", - "\xe1\xba\x90" => "\xe1\xba\x91", - "\xe1\xba\x92" => "\xe1\xba\x93", - "\xe1\xba\x94" => "\xe1\xba\x95", - "\xe1\xba\xa0" => "\xe1\xba\xa1", - "\xe1\xba\xa2" => "\xe1\xba\xa3", - "\xe1\xba\xa4" => "\xe1\xba\xa5", - "\xe1\xba\xa6" => "\xe1\xba\xa7", - "\xe1\xba\xa8" => "\xe1\xba\xa9", - "\xe1\xba\xaa" => "\xe1\xba\xab", - "\xe1\xba\xac" => "\xe1\xba\xad", - "\xe1\xba\xae" => "\xe1\xba\xaf", - "\xe1\xba\xb0" => "\xe1\xba\xb1", - "\xe1\xba\xb2" => "\xe1\xba\xb3", - "\xe1\xba\xb4" => "\xe1\xba\xb5", - "\xe1\xba\xb6" => "\xe1\xba\xb7", - "\xe1\xba\xb8" => "\xe1\xba\xb9", - "\xe1\xba\xba" => "\xe1\xba\xbb", - "\xe1\xba\xbc" => "\xe1\xba\xbd", - "\xe1\xba\xbe" => "\xe1\xba\xbf", - "\xe1\xbb\x80" => "\xe1\xbb\x81", - "\xe1\xbb\x82" => "\xe1\xbb\x83", - "\xe1\xbb\x84" => "\xe1\xbb\x85", - "\xe1\xbb\x86" => "\xe1\xbb\x87", - "\xe1\xbb\x88" => "\xe1\xbb\x89", - "\xe1\xbb\x8a" => "\xe1\xbb\x8b", - "\xe1\xbb\x8c" => "\xe1\xbb\x8d", - "\xe1\xbb\x8e" => "\xe1\xbb\x8f", - "\xe1\xbb\x90" => "\xe1\xbb\x91", - "\xe1\xbb\x92" => "\xe1\xbb\x93", - "\xe1\xbb\x94" => "\xe1\xbb\x95", - "\xe1\xbb\x96" => "\xe1\xbb\x97", - "\xe1\xbb\x98" => "\xe1\xbb\x99", - "\xe1\xbb\x9a" => "\xe1\xbb\x9b", - "\xe1\xbb\x9c" => "\xe1\xbb\x9d", - "\xe1\xbb\x9e" => "\xe1\xbb\x9f", - "\xe1\xbb\xa0" => "\xe1\xbb\xa1", - "\xe1\xbb\xa2" => "\xe1\xbb\xa3", - "\xe1\xbb\xa4" => "\xe1\xbb\xa5", - "\xe1\xbb\xa6" => "\xe1\xbb\xa7", - "\xe1\xbb\xa8" => "\xe1\xbb\xa9", - "\xe1\xbb\xaa" => "\xe1\xbb\xab", - "\xe1\xbb\xac" => "\xe1\xbb\xad", - "\xe1\xbb\xae" => "\xe1\xbb\xaf", - "\xe1\xbb\xb0" => "\xe1\xbb\xb1", - "\xe1\xbb\xb2" => "\xe1\xbb\xb3", - "\xe1\xbb\xb4" => "\xe1\xbb\xb5", - "\xe1\xbb\xb6" => "\xe1\xbb\xb7", - "\xe1\xbb\xb8" => "\xe1\xbb\xb9", - "\xe1\xbc\x88" => "\xe1\xbc\x80", - "\xe1\xbc\x89" => "\xe1\xbc\x81", - "\xe1\xbc\x8a" => "\xe1\xbc\x82", - "\xe1\xbc\x8b" => "\xe1\xbc\x83", - "\xe1\xbc\x8c" => "\xe1\xbc\x84", - "\xe1\xbc\x8d" => "\xe1\xbc\x85", - "\xe1\xbc\x8e" => "\xe1\xbc\x86", - "\xe1\xbc\x8f" => "\xe1\xbc\x87", - "\xe1\xbc\x98" => "\xe1\xbc\x90", - "\xe1\xbc\x99" => "\xe1\xbc\x91", - "\xe1\xbc\x9a" => "\xe1\xbc\x92", - "\xe1\xbc\x9b" => "\xe1\xbc\x93", - "\xe1\xbc\x9c" => "\xe1\xbc\x94", - "\xe1\xbc\x9d" => "\xe1\xbc\x95", - "\xe1\xbc\xa9" => "\xe1\xbc\xa1", - "\xe1\xbc\xaa" => "\xe1\xbc\xa2", - "\xe1\xbc\xab" => "\xe1\xbc\xa3", - "\xe1\xbc\xac" => "\xe1\xbc\xa4", - "\xe1\xbc\xad" => "\xe1\xbc\xa5", - "\xe1\xbc\xae" => "\xe1\xbc\xa6", - "\xe1\xbc\xaf" => "\xe1\xbc\xa7", - "\xe1\xbc\xb8" => "\xe1\xbc\xb0", - "\xe1\xbc\xb9" => "\xe1\xbc\xb1", - "\xe1\xbc\xba" => "\xe1\xbc\xb2", - "\xe1\xbc\xbb" => "\xe1\xbc\xb3", - "\xe1\xbc\xbc" => "\xe1\xbc\xb4", - "\xe1\xbc\xbd" => "\xe1\xbc\xb5", - "\xe1\xbc\xbe" => "\xe1\xbc\xb6", - "\xe1\xbc\xbf" => "\xe1\xbc\xb7", - "\xe1\xbd\x88" => "\xe1\xbd\x80", - "\xe1\xbd\x89" => "\xe1\xbd\x81", - "\xe1\xbd\x8a" => "\xe1\xbd\x82", - "\xe1\xbd\x8b" => "\xe1\xbd\x83", - "\xe1\xbd\x8c" => "\xe1\xbd\x84", - "\xe1\xbd\x8d" => "\xe1\xbd\x85", - "\xe1\xbd\x99" => "\xe1\xbd\x91", - "\xe1\xbd\x9b" => "\xe1\xbd\x93", - "\xe1\xbd\x9d" => "\xe1\xbd\x95", - "\xe1\xbd\x9f" => "\xe1\xbd\x97", - "\xe1\xbd\xa9" => "\xe1\xbd\xa1", - "\xe1\xbd\xaa" => "\xe1\xbd\xa2", - "\xe1\xbd\xab" => "\xe1\xbd\xa3", - "\xe1\xbd\xac" => "\xe1\xbd\xa4", - "\xe1\xbd\xad" => "\xe1\xbd\xa5", - "\xe1\xbd\xae" => "\xe1\xbd\xa6", - "\xe1\xbd\xaf" => "\xe1\xbd\xa7", - "\xe1\xbe\x88" => "\xe1\xbe\x80", - "\xe1\xbe\x89" => "\xe1\xbe\x81", - "\xe1\xbe\x8a" => "\xe1\xbe\x82", - "\xe1\xbe\x8b" => "\xe1\xbe\x83", - "\xe1\xbe\x8c" => "\xe1\xbe\x84", - "\xe1\xbe\x8d" => "\xe1\xbe\x85", - "\xe1\xbe\x8e" => "\xe1\xbe\x86", - "\xe1\xbe\x8f" => "\xe1\xbe\x87", - "\xe1\xbe\x98" => "\xe1\xbe\x90", - "\xe1\xbe\x99" => "\xe1\xbe\x91", - "\xe1\xbe\x9a" => "\xe1\xbe\x92", - "\xe1\xbe\x9b" => "\xe1\xbe\x93", - "\xe1\xbe\x9c" => "\xe1\xbe\x94", - "\xe1\xbe\x9d" => "\xe1\xbe\x95", - "\xe1\xbe\x9e" => "\xe1\xbe\x96", - "\xe1\xbe\x9f" => "\xe1\xbe\x97", - "\xe1\xbe\xa9" => "\xe1\xbe\xa1", - "\xe1\xbe\xaa" => "\xe1\xbe\xa2", - "\xe1\xbe\xab" => "\xe1\xbe\xa3", - "\xe1\xbe\xac" => "\xe1\xbe\xa4", - "\xe1\xbe\xad" => "\xe1\xbe\xa5", - "\xe1\xbe\xae" => "\xe1\xbe\xa6", - "\xe1\xbe\xaf" => "\xe1\xbe\xa7", - "\xe1\xbe\xb8" => "\xe1\xbe\xb0", - "\xe1\xbe\xb9" => "\xe1\xbe\xb1", - "\xe1\xbe\xba" => "\xe1\xbd\xb0", - "\xe1\xbe\xbb" => "\xe1\xbd\xb1", - "\xe1\xbe\xbc" => "\xe1\xbe\xb3", - "\xe1\xbf\x88" => "\xe1\xbd\xb2", - "\xe1\xbf\x89" => "\xe1\xbd\xb3", - "\xe1\xbf\x8a" => "\xe1\xbd\xb4", - "\xe1\xbf\x8b" => "\xe1\xbd\xb5", - "\xe1\xbf\x8c" => "\xe1\xbf\x83", - "\xe1\xbf\x98" => "\xe1\xbf\x90", - "\xe1\xbf\x99" => "\xe1\xbf\x91", - "\xe1\xbf\x9a" => "\xe1\xbd\xb6", - "\xe1\xbf\x9b" => "\xe1\xbd\xb7", - "\xe1\xbf\xa9" => "\xe1\xbf\xa1", - "\xe1\xbf\xaa" => "\xe1\xbd\xba", - "\xe1\xbf\xab" => "\xe1\xbd\xbb", - "\xe1\xbf\xac" => "\xe1\xbf\xa5", - "\xe1\xbf\xb8" => "\xe1\xbd\xb8", - "\xe1\xbf\xb9" => "\xe1\xbd\xb9", - "\xe1\xbf\xba" => "\xe1\xbd\xbc", - "\xe1\xbf\xbb" => "\xe1\xbd\xbd", - "\xe1\xbf\xbc" => "\xe1\xbf\xb3", - "\xef\xbc\xa1" => "\xef\xbd\x81", - "\xef\xbc\xa2" => "\xef\xbd\x82", - "\xef\xbc\xa3" => "\xef\xbd\x83", - "\xef\xbc\xa4" => "\xef\xbd\x84", - "\xef\xbc\xa5" => "\xef\xbd\x85", - "\xef\xbc\xa6" => "\xef\xbd\x86", - "\xef\xbc\xa7" => "\xef\xbd\x87", - "\xef\xbc\xa8" => "\xef\xbd\x88", - "\xef\xbc\xa9" => "\xef\xbd\x89", - "\xef\xbc\xaa" => "\xef\xbd\x8a", - "\xef\xbc\xab" => "\xef\xbd\x8b", - "\xef\xbc\xac" => "\xef\xbd\x8c", - "\xef\xbc\xad" => "\xef\xbd\x8d", - "\xef\xbc\xae" => "\xef\xbd\x8e", - "\xef\xbc\xaf" => "\xef\xbd\x8f", - "\xef\xbc\xb0" => "\xef\xbd\x90", - "\xef\xbc\xb1" => "\xef\xbd\x91", - "\xef\xbc\xb2" => "\xef\xbd\x92", - "\xef\xbc\xb3" => "\xef\xbd\x93", - "\xef\xbc\xb4" => "\xef\xbd\x94", - "\xef\xbc\xb5" => "\xef\xbd\x95", - "\xef\xbc\xb6" => "\xef\xbd\x96", - "\xef\xbc\xb7" => "\xef\xbd\x97", - "\xef\xbc\xb8" => "\xef\xbd\x98", - "\xef\xbc\xb9" => "\xef\xbd\x99", - "\xef\xbc\xba" => "\xef\xbd\x9a", - ); + /** + * UTF-8 Case lookup table + * + * This lookuptable defines the upper case letters to their correspponding + * lower case letter in UTF-8 + * + * @author Andreas Gohr + */ + public static $convert_case_table = array( + #CASE_UPPER => case_lower + "\x41" => "\x61", #A a + "\x42" => "\x62", #B b + "\x43" => "\x63", #C c + "\x44" => "\x64", #D d + "\x45" => "\x65", #E e + "\x46" => "\x66", #F f + "\x47" => "\x67", #G g + "\x48" => "\x68", #H h + "\x49" => "\x69", #I i + "\x4a" => "\x6a", #J j + "\x4b" => "\x6b", #K k + "\x4c" => "\x6c", #L l + "\x4d" => "\x6d", #M m + "\x4e" => "\x6e", #N n + "\x4f" => "\x6f", #O o + "\x50" => "\x70", #P p + "\x51" => "\x71", #Q q + "\x52" => "\x72", #R r + "\x53" => "\x73", #S s + "\x54" => "\x74", #T t + "\x55" => "\x75", #U u + "\x56" => "\x76", #V v + "\x57" => "\x77", #W w + "\x58" => "\x78", #X x + "\x59" => "\x79", #Y y + "\x5a" => "\x7a", #Z z + "\xc3\x80" => "\xc3\xa0", + "\xc3\x81" => "\xc3\xa1", + "\xc3\x82" => "\xc3\xa2", + "\xc3\x83" => "\xc3\xa3", + "\xc3\x84" => "\xc3\xa4", + "\xc3\x85" => "\xc3\xa5", + "\xc3\x86" => "\xc3\xa6", + "\xc3\x87" => "\xc3\xa7", + "\xc3\x88" => "\xc3\xa8", + "\xc3\x89" => "\xc3\xa9", + "\xc3\x8a" => "\xc3\xaa", + "\xc3\x8b" => "\xc3\xab", + "\xc3\x8c" => "\xc3\xac", + "\xc3\x8d" => "\xc3\xad", + "\xc3\x8e" => "\xc3\xae", + "\xc3\x8f" => "\xc3\xaf", + "\xc3\x90" => "\xc3\xb0", + "\xc3\x91" => "\xc3\xb1", + "\xc3\x92" => "\xc3\xb2", + "\xc3\x93" => "\xc3\xb3", + "\xc3\x94" => "\xc3\xb4", + "\xc3\x95" => "\xc3\xb5", + "\xc3\x96" => "\xc3\xb6", + "\xc3\x98" => "\xc3\xb8", + "\xc3\x99" => "\xc3\xb9", + "\xc3\x9a" => "\xc3\xba", + "\xc3\x9b" => "\xc3\xbb", + "\xc3\x9c" => "\xc3\xbc", + "\xc3\x9d" => "\xc3\xbd", + "\xc3\x9e" => "\xc3\xbe", + "\xc4\x80" => "\xc4\x81", + "\xc4\x82" => "\xc4\x83", + "\xc4\x84" => "\xc4\x85", + "\xc4\x86" => "\xc4\x87", + "\xc4\x88" => "\xc4\x89", + "\xc4\x8a" => "\xc4\x8b", + "\xc4\x8c" => "\xc4\x8d", + "\xc4\x8e" => "\xc4\x8f", + "\xc4\x90" => "\xc4\x91", + "\xc4\x92" => "\xc4\x93", + "\xc4\x94" => "\xc4\x95", + "\xc4\x96" => "\xc4\x97", + "\xc4\x98" => "\xc4\x99", + "\xc4\x9a" => "\xc4\x9b", + "\xc4\x9c" => "\xc4\x9d", + "\xc4\x9e" => "\xc4\x9f", + "\xc4\xa0" => "\xc4\xa1", + "\xc4\xa2" => "\xc4\xa3", + "\xc4\xa4" => "\xc4\xa5", + "\xc4\xa6" => "\xc4\xa7", + "\xc4\xa8" => "\xc4\xa9", + "\xc4\xaa" => "\xc4\xab", + "\xc4\xac" => "\xc4\xad", + "\xc4\xae" => "\xc4\xaf", + "\xc4\xb2" => "\xc4\xb3", + "\xc4\xb4" => "\xc4\xb5", + "\xc4\xb6" => "\xc4\xb7", + "\xc4\xb9" => "\xc4\xba", + "\xc4\xbb" => "\xc4\xbc", + "\xc4\xbd" => "\xc4\xbe", + "\xc4\xbf" => "\xc5\x80", + "\xc5\x81" => "\xc5\x82", + "\xc5\x83" => "\xc5\x84", + "\xc5\x85" => "\xc5\x86", + "\xc5\x87" => "\xc5\x88", + "\xc5\x8a" => "\xc5\x8b", + "\xc5\x8c" => "\xc5\x8d", + "\xc5\x8e" => "\xc5\x8f", + "\xc5\x90" => "\xc5\x91", + "\xc5\x92" => "\xc5\x93", + "\xc5\x94" => "\xc5\x95", + "\xc5\x96" => "\xc5\x97", + "\xc5\x98" => "\xc5\x99", + "\xc5\x9a" => "\xc5\x9b", + "\xc5\x9c" => "\xc5\x9d", + "\xc5\x9e" => "\xc5\x9f", + "\xc5\xa0" => "\xc5\xa1", + "\xc5\xa2" => "\xc5\xa3", + "\xc5\xa4" => "\xc5\xa5", + "\xc5\xa6" => "\xc5\xa7", + "\xc5\xa8" => "\xc5\xa9", + "\xc5\xaa" => "\xc5\xab", + "\xc5\xac" => "\xc5\xad", + "\xc5\xae" => "\xc5\xaf", + "\xc5\xb0" => "\xc5\xb1", + "\xc5\xb2" => "\xc5\xb3", + "\xc5\xb4" => "\xc5\xb5", + "\xc5\xb6" => "\xc5\xb7", + "\xc5\xb8" => "\xc3\xbf", + "\xc5\xb9" => "\xc5\xba", + "\xc5\xbb" => "\xc5\xbc", + "\xc5\xbd" => "\xc5\xbe", + "\xc6\x81" => "\xc9\x93", + "\xc6\x82" => "\xc6\x83", + "\xc6\x84" => "\xc6\x85", + "\xc6\x86" => "\xc9\x94", + "\xc6\x87" => "\xc6\x88", + "\xc6\x89" => "\xc9\x96", + "\xc6\x8a" => "\xc9\x97", + "\xc6\x8b" => "\xc6\x8c", + "\xc6\x8e" => "\xc7\x9d", + "\xc6\x8f" => "\xc9\x99", + "\xc6\x90" => "\xc9\x9b", + "\xc6\x91" => "\xc6\x92", + "\xc6\x94" => "\xc9\xa3", + "\xc6\x96" => "\xc9\xa9", + "\xc6\x97" => "\xc9\xa8", + "\xc6\x98" => "\xc6\x99", + "\xc6\x9c" => "\xc9\xaf", + "\xc6\x9d" => "\xc9\xb2", + "\xc6\x9f" => "\xc9\xb5", + "\xc6\xa0" => "\xc6\xa1", + "\xc6\xa2" => "\xc6\xa3", + "\xc6\xa4" => "\xc6\xa5", + "\xc6\xa6" => "\xca\x80", + "\xc6\xa7" => "\xc6\xa8", + "\xc6\xa9" => "\xca\x83", + "\xc6\xac" => "\xc6\xad", + "\xc6\xae" => "\xca\x88", + "\xc6\xaf" => "\xc6\xb0", + "\xc6\xb1" => "\xca\x8a", + "\xc6\xb2" => "\xca\x8b", + "\xc6\xb3" => "\xc6\xb4", + "\xc6\xb5" => "\xc6\xb6", + "\xc6\xb7" => "\xca\x92", + "\xc6\xb8" => "\xc6\xb9", + "\xc6\xbc" => "\xc6\xbd", + "\xc7\x85" => "\xc7\x86", + "\xc7\x88" => "\xc7\x89", + "\xc7\x8b" => "\xc7\x8c", + "\xc7\x8d" => "\xc7\x8e", + "\xc7\x8f" => "\xc7\x90", + "\xc7\x91" => "\xc7\x92", + "\xc7\x93" => "\xc7\x94", + "\xc7\x95" => "\xc7\x96", + "\xc7\x97" => "\xc7\x98", + "\xc7\x99" => "\xc7\x9a", + "\xc7\x9b" => "\xc7\x9c", + "\xc7\x9e" => "\xc7\x9f", + "\xc7\xa0" => "\xc7\xa1", + "\xc7\xa2" => "\xc7\xa3", + "\xc7\xa4" => "\xc7\xa5", + "\xc7\xa6" => "\xc7\xa7", + "\xc7\xa8" => "\xc7\xa9", + "\xc7\xaa" => "\xc7\xab", + "\xc7\xac" => "\xc7\xad", + "\xc7\xae" => "\xc7\xaf", + "\xc7\xb2" => "\xc7\xb3", + "\xc7\xb4" => "\xc7\xb5", + "\xc7\xb6" => "\xc6\x95", + "\xc7\xb7" => "\xc6\xbf", + "\xc7\xb8" => "\xc7\xb9", + "\xc7\xba" => "\xc7\xbb", + "\xc7\xbc" => "\xc7\xbd", + "\xc7\xbe" => "\xc7\xbf", + "\xc8\x80" => "\xc8\x81", + "\xc8\x82" => "\xc8\x83", + "\xc8\x84" => "\xc8\x85", + "\xc8\x86" => "\xc8\x87", + "\xc8\x88" => "\xc8\x89", + "\xc8\x8a" => "\xc8\x8b", + "\xc8\x8c" => "\xc8\x8d", + "\xc8\x8e" => "\xc8\x8f", + "\xc8\x90" => "\xc8\x91", + "\xc8\x92" => "\xc8\x93", + "\xc8\x94" => "\xc8\x95", + "\xc8\x96" => "\xc8\x97", + "\xc8\x98" => "\xc8\x99", + "\xc8\x9a" => "\xc8\x9b", + "\xc8\x9c" => "\xc8\x9d", + "\xc8\x9e" => "\xc8\x9f", + "\xc8\xa0" => "\xc6\x9e", + "\xc8\xa2" => "\xc8\xa3", + "\xc8\xa4" => "\xc8\xa5", + "\xc8\xa6" => "\xc8\xa7", + "\xc8\xa8" => "\xc8\xa9", + "\xc8\xaa" => "\xc8\xab", + "\xc8\xac" => "\xc8\xad", + "\xc8\xae" => "\xc8\xaf", + "\xc8\xb0" => "\xc8\xb1", + "\xc8\xb2" => "\xc8\xb3", + "\xce\x86" => "\xce\xac", + "\xce\x88" => "\xce\xad", + "\xce\x89" => "\xce\xae", + "\xce\x8a" => "\xce\xaf", + "\xce\x8c" => "\xcf\x8c", + "\xce\x8e" => "\xcf\x8d", + "\xce\x8f" => "\xcf\x8e", + "\xce\x91" => "\xce\xb1", + "\xce\x92" => "\xce\xb2", + "\xce\x93" => "\xce\xb3", + "\xce\x94" => "\xce\xb4", + "\xce\x95" => "\xce\xb5", + "\xce\x96" => "\xce\xb6", + "\xce\x97" => "\xce\xb7", + "\xce\x98" => "\xce\xb8", + "\xce\x99" => "\xce\xb9", + "\xce\x9a" => "\xce\xba", + "\xce\x9b" => "\xce\xbb", + "\xce\x9c" => "\xc2\xb5", + "\xce\x9d" => "\xce\xbd", + "\xce\x9e" => "\xce\xbe", + "\xce\x9f" => "\xce\xbf", + "\xce\xa0" => "\xcf\x80", + "\xce\xa1" => "\xcf\x81", + "\xce\xa3" => "\xcf\x82", + "\xce\xa4" => "\xcf\x84", + "\xce\xa5" => "\xcf\x85", + "\xce\xa6" => "\xcf\x86", + "\xce\xa7" => "\xcf\x87", + "\xce\xa8" => "\xcf\x88", + "\xce\xa9" => "\xcf\x89", + "\xce\xaa" => "\xcf\x8a", + "\xce\xab" => "\xcf\x8b", + "\xcf\x98" => "\xcf\x99", + "\xcf\x9a" => "\xcf\x9b", + "\xcf\x9c" => "\xcf\x9d", + "\xcf\x9e" => "\xcf\x9f", + "\xcf\xa0" => "\xcf\xa1", + "\xcf\xa2" => "\xcf\xa3", + "\xcf\xa4" => "\xcf\xa5", + "\xcf\xa6" => "\xcf\xa7", + "\xcf\xa8" => "\xcf\xa9", + "\xcf\xaa" => "\xcf\xab", + "\xcf\xac" => "\xcf\xad", + "\xcf\xae" => "\xcf\xaf", + "\xd0\x80" => "\xd1\x90", + "\xd0\x81" => "\xd1\x91", + "\xd0\x82" => "\xd1\x92", + "\xd0\x83" => "\xd1\x93", + "\xd0\x84" => "\xd1\x94", + "\xd0\x85" => "\xd1\x95", + "\xd0\x86" => "\xd1\x96", + "\xd0\x87" => "\xd1\x97", + "\xd0\x88" => "\xd1\x98", + "\xd0\x89" => "\xd1\x99", + "\xd0\x8a" => "\xd1\x9a", + "\xd0\x8b" => "\xd1\x9b", + "\xd0\x8c" => "\xd1\x9c", + "\xd0\x8d" => "\xd1\x9d", + "\xd0\x8e" => "\xd1\x9e", + "\xd0\x8f" => "\xd1\x9f", + "\xd0\x90" => "\xd0\xb0", + "\xd0\x91" => "\xd0\xb1", + "\xd0\x92" => "\xd0\xb2", + "\xd0\x93" => "\xd0\xb3", + "\xd0\x94" => "\xd0\xb4", + "\xd0\x95" => "\xd0\xb5", + "\xd0\x96" => "\xd0\xb6", + "\xd0\x97" => "\xd0\xb7", + "\xd0\x98" => "\xd0\xb8", + "\xd0\x99" => "\xd0\xb9", + "\xd0\x9a" => "\xd0\xba", + "\xd0\x9b" => "\xd0\xbb", + "\xd0\x9c" => "\xd0\xbc", + "\xd0\x9d" => "\xd0\xbd", + "\xd0\x9e" => "\xd0\xbe", + "\xd0\x9f" => "\xd0\xbf", + "\xd0\xa0" => "\xd1\x80", + "\xd0\xa1" => "\xd1\x81", + "\xd0\xa2" => "\xd1\x82", + "\xd0\xa3" => "\xd1\x83", + "\xd0\xa4" => "\xd1\x84", + "\xd0\xa5" => "\xd1\x85", + "\xd0\xa6" => "\xd1\x86", + "\xd0\xa7" => "\xd1\x87", + "\xd0\xa8" => "\xd1\x88", + "\xd0\xa9" => "\xd1\x89", + "\xd0\xaa" => "\xd1\x8a", + "\xd0\xab" => "\xd1\x8b", + "\xd0\xac" => "\xd1\x8c", + "\xd0\xad" => "\xd1\x8d", + "\xd0\xae" => "\xd1\x8e", + "\xd0\xaf" => "\xd1\x8f", + "\xd1\xa0" => "\xd1\xa1", + "\xd1\xa2" => "\xd1\xa3", + "\xd1\xa4" => "\xd1\xa5", + "\xd1\xa6" => "\xd1\xa7", + "\xd1\xa8" => "\xd1\xa9", + "\xd1\xaa" => "\xd1\xab", + "\xd1\xac" => "\xd1\xad", + "\xd1\xae" => "\xd1\xaf", + "\xd1\xb0" => "\xd1\xb1", + "\xd1\xb2" => "\xd1\xb3", + "\xd1\xb4" => "\xd1\xb5", + "\xd1\xb6" => "\xd1\xb7", + "\xd1\xb8" => "\xd1\xb9", + "\xd1\xba" => "\xd1\xbb", + "\xd1\xbc" => "\xd1\xbd", + "\xd1\xbe" => "\xd1\xbf", + "\xd2\x80" => "\xd2\x81", + "\xd2\x8a" => "\xd2\x8b", + "\xd2\x8c" => "\xd2\x8d", + "\xd2\x8e" => "\xd2\x8f", + "\xd2\x90" => "\xd2\x91", + "\xd2\x92" => "\xd2\x93", + "\xd2\x94" => "\xd2\x95", + "\xd2\x96" => "\xd2\x97", + "\xd2\x98" => "\xd2\x99", + "\xd2\x9a" => "\xd2\x9b", + "\xd2\x9c" => "\xd2\x9d", + "\xd2\x9e" => "\xd2\x9f", + "\xd2\xa0" => "\xd2\xa1", + "\xd2\xa2" => "\xd2\xa3", + "\xd2\xa4" => "\xd2\xa5", + "\xd2\xa6" => "\xd2\xa7", + "\xd2\xa8" => "\xd2\xa9", + "\xd2\xaa" => "\xd2\xab", + "\xd2\xac" => "\xd2\xad", + "\xd2\xae" => "\xd2\xaf", + "\xd2\xb0" => "\xd2\xb1", + "\xd2\xb2" => "\xd2\xb3", + "\xd2\xb4" => "\xd2\xb5", + "\xd2\xb6" => "\xd2\xb7", + "\xd2\xb8" => "\xd2\xb9", + "\xd2\xba" => "\xd2\xbb", + "\xd2\xbc" => "\xd2\xbd", + "\xd2\xbe" => "\xd2\xbf", + "\xd3\x81" => "\xd3\x82", + "\xd3\x83" => "\xd3\x84", + "\xd3\x85" => "\xd3\x86", + "\xd3\x87" => "\xd3\x88", + "\xd3\x89" => "\xd3\x8a", + "\xd3\x8b" => "\xd3\x8c", + "\xd3\x8d" => "\xd3\x8e", + "\xd3\x90" => "\xd3\x91", + "\xd3\x92" => "\xd3\x93", + "\xd3\x94" => "\xd3\x95", + "\xd3\x96" => "\xd3\x97", + "\xd3\x98" => "\xd3\x99", + "\xd3\x9a" => "\xd3\x9b", + "\xd3\x9c" => "\xd3\x9d", + "\xd3\x9e" => "\xd3\x9f", + "\xd3\xa0" => "\xd3\xa1", + "\xd3\xa2" => "\xd3\xa3", + "\xd3\xa4" => "\xd3\xa5", + "\xd3\xa6" => "\xd3\xa7", + "\xd3\xa8" => "\xd3\xa9", + "\xd3\xaa" => "\xd3\xab", + "\xd3\xac" => "\xd3\xad", + "\xd3\xae" => "\xd3\xaf", + "\xd3\xb0" => "\xd3\xb1", + "\xd3\xb2" => "\xd3\xb3", + "\xd3\xb4" => "\xd3\xb5", + "\xd3\xb8" => "\xd3\xb9", + "\xd4\x80" => "\xd4\x81", + "\xd4\x82" => "\xd4\x83", + "\xd4\x84" => "\xd4\x85", + "\xd4\x86" => "\xd4\x87", + "\xd4\x88" => "\xd4\x89", + "\xd4\x8a" => "\xd4\x8b", + "\xd4\x8c" => "\xd4\x8d", + "\xd4\x8e" => "\xd4\x8f", + "\xd4\xb1" => "\xd5\xa1", + "\xd4\xb2" => "\xd5\xa2", + "\xd4\xb3" => "\xd5\xa3", + "\xd4\xb4" => "\xd5\xa4", + "\xd4\xb5" => "\xd5\xa5", + "\xd4\xb6" => "\xd5\xa6", + "\xd4\xb7" => "\xd5\xa7", + "\xd4\xb8" => "\xd5\xa8", + "\xd4\xb9" => "\xd5\xa9", + "\xd4\xba" => "\xd5\xaa", + "\xd4\xbb" => "\xd5\xab", + "\xd4\xbc" => "\xd5\xac", + "\xd4\xbd" => "\xd5\xad", + "\xd4\xbe" => "\xd5\xae", + "\xd4\xbf" => "\xd5\xaf", + "\xd5\x80" => "\xd5\xb0", + "\xd5\x81" => "\xd5\xb1", + "\xd5\x82" => "\xd5\xb2", + "\xd5\x83" => "\xd5\xb3", + "\xd5\x84" => "\xd5\xb4", + "\xd5\x85" => "\xd5\xb5", + "\xd5\x86" => "\xd5\xb6", + "\xd5\x87" => "\xd5\xb7", + "\xd5\x88" => "\xd5\xb8", + "\xd5\x89" => "\xd5\xb9", + "\xd5\x8a" => "\xd5\xba", + "\xd5\x8b" => "\xd5\xbb", + "\xd5\x8c" => "\xd5\xbc", + "\xd5\x8d" => "\xd5\xbd", + "\xd5\x8e" => "\xd5\xbe", + "\xd5\x8f" => "\xd5\xbf", + "\xd5\x90" => "\xd6\x80", + "\xd5\x91" => "\xd6\x81", + "\xd5\x92" => "\xd6\x82", + "\xd5\x93" => "\xd6\x83", + "\xd5\x94" => "\xd6\x84", + "\xd5\x95" => "\xd6\x85", + "\xd5\x96" => "\xd6\x86", + "\xe1\xb8\x80" => "\xe1\xb8\x81", + "\xe1\xb8\x82" => "\xe1\xb8\x83", + "\xe1\xb8\x84" => "\xe1\xb8\x85", + "\xe1\xb8\x86" => "\xe1\xb8\x87", + "\xe1\xb8\x88" => "\xe1\xb8\x89", + "\xe1\xb8\x8a" => "\xe1\xb8\x8b", + "\xe1\xb8\x8c" => "\xe1\xb8\x8d", + "\xe1\xb8\x8e" => "\xe1\xb8\x8f", + "\xe1\xb8\x90" => "\xe1\xb8\x91", + "\xe1\xb8\x92" => "\xe1\xb8\x93", + "\xe1\xb8\x94" => "\xe1\xb8\x95", + "\xe1\xb8\x96" => "\xe1\xb8\x97", + "\xe1\xb8\x98" => "\xe1\xb8\x99", + "\xe1\xb8\x9a" => "\xe1\xb8\x9b", + "\xe1\xb8\x9c" => "\xe1\xb8\x9d", + "\xe1\xb8\x9e" => "\xe1\xb8\x9f", + "\xe1\xb8\xa0" => "\xe1\xb8\xa1", + "\xe1\xb8\xa2" => "\xe1\xb8\xa3", + "\xe1\xb8\xa4" => "\xe1\xb8\xa5", + "\xe1\xb8\xa6" => "\xe1\xb8\xa7", + "\xe1\xb8\xa8" => "\xe1\xb8\xa9", + "\xe1\xb8\xaa" => "\xe1\xb8\xab", + "\xe1\xb8\xac" => "\xe1\xb8\xad", + "\xe1\xb8\xae" => "\xe1\xb8\xaf", + "\xe1\xb8\xb0" => "\xe1\xb8\xb1", + "\xe1\xb8\xb2" => "\xe1\xb8\xb3", + "\xe1\xb8\xb4" => "\xe1\xb8\xb5", + "\xe1\xb8\xb6" => "\xe1\xb8\xb7", + "\xe1\xb8\xb8" => "\xe1\xb8\xb9", + "\xe1\xb8\xba" => "\xe1\xb8\xbb", + "\xe1\xb8\xbc" => "\xe1\xb8\xbd", + "\xe1\xb8\xbe" => "\xe1\xb8\xbf", + "\xe1\xb9\x80" => "\xe1\xb9\x81", + "\xe1\xb9\x82" => "\xe1\xb9\x83", + "\xe1\xb9\x84" => "\xe1\xb9\x85", + "\xe1\xb9\x86" => "\xe1\xb9\x87", + "\xe1\xb9\x88" => "\xe1\xb9\x89", + "\xe1\xb9\x8a" => "\xe1\xb9\x8b", + "\xe1\xb9\x8c" => "\xe1\xb9\x8d", + "\xe1\xb9\x8e" => "\xe1\xb9\x8f", + "\xe1\xb9\x90" => "\xe1\xb9\x91", + "\xe1\xb9\x92" => "\xe1\xb9\x93", + "\xe1\xb9\x94" => "\xe1\xb9\x95", + "\xe1\xb9\x96" => "\xe1\xb9\x97", + "\xe1\xb9\x98" => "\xe1\xb9\x99", + "\xe1\xb9\x9a" => "\xe1\xb9\x9b", + "\xe1\xb9\x9c" => "\xe1\xb9\x9d", + "\xe1\xb9\x9e" => "\xe1\xb9\x9f", + "\xe1\xb9\xa0" => "\xe1\xb9\xa1", + "\xe1\xb9\xa2" => "\xe1\xb9\xa3", + "\xe1\xb9\xa4" => "\xe1\xb9\xa5", + "\xe1\xb9\xa6" => "\xe1\xb9\xa7", + "\xe1\xb9\xa8" => "\xe1\xb9\xa9", + "\xe1\xb9\xaa" => "\xe1\xb9\xab", + "\xe1\xb9\xac" => "\xe1\xb9\xad", + "\xe1\xb9\xae" => "\xe1\xb9\xaf", + "\xe1\xb9\xb0" => "\xe1\xb9\xb1", + "\xe1\xb9\xb2" => "\xe1\xb9\xb3", + "\xe1\xb9\xb4" => "\xe1\xb9\xb5", + "\xe1\xb9\xb6" => "\xe1\xb9\xb7", + "\xe1\xb9\xb8" => "\xe1\xb9\xb9", + "\xe1\xb9\xba" => "\xe1\xb9\xbb", + "\xe1\xb9\xbc" => "\xe1\xb9\xbd", + "\xe1\xb9\xbe" => "\xe1\xb9\xbf", + "\xe1\xba\x80" => "\xe1\xba\x81", + "\xe1\xba\x82" => "\xe1\xba\x83", + "\xe1\xba\x84" => "\xe1\xba\x85", + "\xe1\xba\x86" => "\xe1\xba\x87", + "\xe1\xba\x88" => "\xe1\xba\x89", + "\xe1\xba\x8a" => "\xe1\xba\x8b", + "\xe1\xba\x8c" => "\xe1\xba\x8d", + "\xe1\xba\x8e" => "\xe1\xba\x8f", + "\xe1\xba\x90" => "\xe1\xba\x91", + "\xe1\xba\x92" => "\xe1\xba\x93", + "\xe1\xba\x94" => "\xe1\xba\x95", + "\xe1\xba\xa0" => "\xe1\xba\xa1", + "\xe1\xba\xa2" => "\xe1\xba\xa3", + "\xe1\xba\xa4" => "\xe1\xba\xa5", + "\xe1\xba\xa6" => "\xe1\xba\xa7", + "\xe1\xba\xa8" => "\xe1\xba\xa9", + "\xe1\xba\xaa" => "\xe1\xba\xab", + "\xe1\xba\xac" => "\xe1\xba\xad", + "\xe1\xba\xae" => "\xe1\xba\xaf", + "\xe1\xba\xb0" => "\xe1\xba\xb1", + "\xe1\xba\xb2" => "\xe1\xba\xb3", + "\xe1\xba\xb4" => "\xe1\xba\xb5", + "\xe1\xba\xb6" => "\xe1\xba\xb7", + "\xe1\xba\xb8" => "\xe1\xba\xb9", + "\xe1\xba\xba" => "\xe1\xba\xbb", + "\xe1\xba\xbc" => "\xe1\xba\xbd", + "\xe1\xba\xbe" => "\xe1\xba\xbf", + "\xe1\xbb\x80" => "\xe1\xbb\x81", + "\xe1\xbb\x82" => "\xe1\xbb\x83", + "\xe1\xbb\x84" => "\xe1\xbb\x85", + "\xe1\xbb\x86" => "\xe1\xbb\x87", + "\xe1\xbb\x88" => "\xe1\xbb\x89", + "\xe1\xbb\x8a" => "\xe1\xbb\x8b", + "\xe1\xbb\x8c" => "\xe1\xbb\x8d", + "\xe1\xbb\x8e" => "\xe1\xbb\x8f", + "\xe1\xbb\x90" => "\xe1\xbb\x91", + "\xe1\xbb\x92" => "\xe1\xbb\x93", + "\xe1\xbb\x94" => "\xe1\xbb\x95", + "\xe1\xbb\x96" => "\xe1\xbb\x97", + "\xe1\xbb\x98" => "\xe1\xbb\x99", + "\xe1\xbb\x9a" => "\xe1\xbb\x9b", + "\xe1\xbb\x9c" => "\xe1\xbb\x9d", + "\xe1\xbb\x9e" => "\xe1\xbb\x9f", + "\xe1\xbb\xa0" => "\xe1\xbb\xa1", + "\xe1\xbb\xa2" => "\xe1\xbb\xa3", + "\xe1\xbb\xa4" => "\xe1\xbb\xa5", + "\xe1\xbb\xa6" => "\xe1\xbb\xa7", + "\xe1\xbb\xa8" => "\xe1\xbb\xa9", + "\xe1\xbb\xaa" => "\xe1\xbb\xab", + "\xe1\xbb\xac" => "\xe1\xbb\xad", + "\xe1\xbb\xae" => "\xe1\xbb\xaf", + "\xe1\xbb\xb0" => "\xe1\xbb\xb1", + "\xe1\xbb\xb2" => "\xe1\xbb\xb3", + "\xe1\xbb\xb4" => "\xe1\xbb\xb5", + "\xe1\xbb\xb6" => "\xe1\xbb\xb7", + "\xe1\xbb\xb8" => "\xe1\xbb\xb9", + "\xe1\xbc\x88" => "\xe1\xbc\x80", + "\xe1\xbc\x89" => "\xe1\xbc\x81", + "\xe1\xbc\x8a" => "\xe1\xbc\x82", + "\xe1\xbc\x8b" => "\xe1\xbc\x83", + "\xe1\xbc\x8c" => "\xe1\xbc\x84", + "\xe1\xbc\x8d" => "\xe1\xbc\x85", + "\xe1\xbc\x8e" => "\xe1\xbc\x86", + "\xe1\xbc\x8f" => "\xe1\xbc\x87", + "\xe1\xbc\x98" => "\xe1\xbc\x90", + "\xe1\xbc\x99" => "\xe1\xbc\x91", + "\xe1\xbc\x9a" => "\xe1\xbc\x92", + "\xe1\xbc\x9b" => "\xe1\xbc\x93", + "\xe1\xbc\x9c" => "\xe1\xbc\x94", + "\xe1\xbc\x9d" => "\xe1\xbc\x95", + "\xe1\xbc\xa9" => "\xe1\xbc\xa1", + "\xe1\xbc\xaa" => "\xe1\xbc\xa2", + "\xe1\xbc\xab" => "\xe1\xbc\xa3", + "\xe1\xbc\xac" => "\xe1\xbc\xa4", + "\xe1\xbc\xad" => "\xe1\xbc\xa5", + "\xe1\xbc\xae" => "\xe1\xbc\xa6", + "\xe1\xbc\xaf" => "\xe1\xbc\xa7", + "\xe1\xbc\xb8" => "\xe1\xbc\xb0", + "\xe1\xbc\xb9" => "\xe1\xbc\xb1", + "\xe1\xbc\xba" => "\xe1\xbc\xb2", + "\xe1\xbc\xbb" => "\xe1\xbc\xb3", + "\xe1\xbc\xbc" => "\xe1\xbc\xb4", + "\xe1\xbc\xbd" => "\xe1\xbc\xb5", + "\xe1\xbc\xbe" => "\xe1\xbc\xb6", + "\xe1\xbc\xbf" => "\xe1\xbc\xb7", + "\xe1\xbd\x88" => "\xe1\xbd\x80", + "\xe1\xbd\x89" => "\xe1\xbd\x81", + "\xe1\xbd\x8a" => "\xe1\xbd\x82", + "\xe1\xbd\x8b" => "\xe1\xbd\x83", + "\xe1\xbd\x8c" => "\xe1\xbd\x84", + "\xe1\xbd\x8d" => "\xe1\xbd\x85", + "\xe1\xbd\x99" => "\xe1\xbd\x91", + "\xe1\xbd\x9b" => "\xe1\xbd\x93", + "\xe1\xbd\x9d" => "\xe1\xbd\x95", + "\xe1\xbd\x9f" => "\xe1\xbd\x97", + "\xe1\xbd\xa9" => "\xe1\xbd\xa1", + "\xe1\xbd\xaa" => "\xe1\xbd\xa2", + "\xe1\xbd\xab" => "\xe1\xbd\xa3", + "\xe1\xbd\xac" => "\xe1\xbd\xa4", + "\xe1\xbd\xad" => "\xe1\xbd\xa5", + "\xe1\xbd\xae" => "\xe1\xbd\xa6", + "\xe1\xbd\xaf" => "\xe1\xbd\xa7", + "\xe1\xbe\x88" => "\xe1\xbe\x80", + "\xe1\xbe\x89" => "\xe1\xbe\x81", + "\xe1\xbe\x8a" => "\xe1\xbe\x82", + "\xe1\xbe\x8b" => "\xe1\xbe\x83", + "\xe1\xbe\x8c" => "\xe1\xbe\x84", + "\xe1\xbe\x8d" => "\xe1\xbe\x85", + "\xe1\xbe\x8e" => "\xe1\xbe\x86", + "\xe1\xbe\x8f" => "\xe1\xbe\x87", + "\xe1\xbe\x98" => "\xe1\xbe\x90", + "\xe1\xbe\x99" => "\xe1\xbe\x91", + "\xe1\xbe\x9a" => "\xe1\xbe\x92", + "\xe1\xbe\x9b" => "\xe1\xbe\x93", + "\xe1\xbe\x9c" => "\xe1\xbe\x94", + "\xe1\xbe\x9d" => "\xe1\xbe\x95", + "\xe1\xbe\x9e" => "\xe1\xbe\x96", + "\xe1\xbe\x9f" => "\xe1\xbe\x97", + "\xe1\xbe\xa9" => "\xe1\xbe\xa1", + "\xe1\xbe\xaa" => "\xe1\xbe\xa2", + "\xe1\xbe\xab" => "\xe1\xbe\xa3", + "\xe1\xbe\xac" => "\xe1\xbe\xa4", + "\xe1\xbe\xad" => "\xe1\xbe\xa5", + "\xe1\xbe\xae" => "\xe1\xbe\xa6", + "\xe1\xbe\xaf" => "\xe1\xbe\xa7", + "\xe1\xbe\xb8" => "\xe1\xbe\xb0", + "\xe1\xbe\xb9" => "\xe1\xbe\xb1", + "\xe1\xbe\xba" => "\xe1\xbd\xb0", + "\xe1\xbe\xbb" => "\xe1\xbd\xb1", + "\xe1\xbe\xbc" => "\xe1\xbe\xb3", + "\xe1\xbf\x88" => "\xe1\xbd\xb2", + "\xe1\xbf\x89" => "\xe1\xbd\xb3", + "\xe1\xbf\x8a" => "\xe1\xbd\xb4", + "\xe1\xbf\x8b" => "\xe1\xbd\xb5", + "\xe1\xbf\x8c" => "\xe1\xbf\x83", + "\xe1\xbf\x98" => "\xe1\xbf\x90", + "\xe1\xbf\x99" => "\xe1\xbf\x91", + "\xe1\xbf\x9a" => "\xe1\xbd\xb6", + "\xe1\xbf\x9b" => "\xe1\xbd\xb7", + "\xe1\xbf\xa9" => "\xe1\xbf\xa1", + "\xe1\xbf\xaa" => "\xe1\xbd\xba", + "\xe1\xbf\xab" => "\xe1\xbd\xbb", + "\xe1\xbf\xac" => "\xe1\xbf\xa5", + "\xe1\xbf\xb8" => "\xe1\xbd\xb8", + "\xe1\xbf\xb9" => "\xe1\xbd\xb9", + "\xe1\xbf\xba" => "\xe1\xbd\xbc", + "\xe1\xbf\xbb" => "\xe1\xbd\xbd", + "\xe1\xbf\xbc" => "\xe1\xbf\xb3", + "\xef\xbc\xa1" => "\xef\xbd\x81", + "\xef\xbc\xa2" => "\xef\xbd\x82", + "\xef\xbc\xa3" => "\xef\xbd\x83", + "\xef\xbc\xa4" => "\xef\xbd\x84", + "\xef\xbc\xa5" => "\xef\xbd\x85", + "\xef\xbc\xa6" => "\xef\xbd\x86", + "\xef\xbc\xa7" => "\xef\xbd\x87", + "\xef\xbc\xa8" => "\xef\xbd\x88", + "\xef\xbc\xa9" => "\xef\xbd\x89", + "\xef\xbc\xaa" => "\xef\xbd\x8a", + "\xef\xbc\xab" => "\xef\xbd\x8b", + "\xef\xbc\xac" => "\xef\xbd\x8c", + "\xef\xbc\xad" => "\xef\xbd\x8d", + "\xef\xbc\xae" => "\xef\xbd\x8e", + "\xef\xbc\xaf" => "\xef\xbd\x8f", + "\xef\xbc\xb0" => "\xef\xbd\x90", + "\xef\xbc\xb1" => "\xef\xbd\x91", + "\xef\xbc\xb2" => "\xef\xbd\x92", + "\xef\xbc\xb3" => "\xef\xbd\x93", + "\xef\xbc\xb4" => "\xef\xbd\x94", + "\xef\xbc\xb5" => "\xef\xbd\x95", + "\xef\xbc\xb6" => "\xef\xbd\x96", + "\xef\xbc\xb7" => "\xef\xbd\x97", + "\xef\xbc\xb8" => "\xef\xbd\x98", + "\xef\xbc\xb9" => "\xef\xbd\x99", + "\xef\xbc\xba" => "\xef\xbd\x9a", + ); - #Unicode Character Database 6.0.0 (2010-06-04) - #autogenerated by unicode_blocks_txt2php() PHP function at 2011-06-04 00:19:39, 209 blocks total - public static $unicode_blocks = array( - 'Basic Latin' => array( - 0 => 0x0000, - 1 => 0x007F, - 2 => 0, - ), - 'Latin-1 Supplement' => array( - 0 => 0x0080, - 1 => 0x00FF, - 2 => 1, - ), - 'Latin Extended-A' => array( - 0 => 0x0100, - 1 => 0x017F, - 2 => 2, - ), - 'Latin Extended-B' => array( - 0 => 0x0180, - 1 => 0x024F, - 2 => 3, - ), - 'IPA Extensions' => array( - 0 => 0x0250, - 1 => 0x02AF, - 2 => 4, - ), - 'Spacing Modifier Letters' => array( - 0 => 0x02B0, - 1 => 0x02FF, - 2 => 5, - ), - 'Combining Diacritical Marks' => array( - 0 => 0x0300, - 1 => 0x036F, - 2 => 6, - ), - 'Greek and Coptic' => array( - 0 => 0x0370, - 1 => 0x03FF, - 2 => 7, - ), - 'Cyrillic' => array( - 0 => 0x0400, - 1 => 0x04FF, - 2 => 8, - ), - 'Cyrillic Supplement' => array( - 0 => 0x0500, - 1 => 0x052F, - 2 => 9, - ), - 'Armenian' => array( - 0 => 0x0530, - 1 => 0x058F, - 2 => 10, - ), - 'Hebrew' => array( - 0 => 0x0590, - 1 => 0x05FF, - 2 => 11, - ), - 'Arabic' => array( - 0 => 0x0600, - 1 => 0x06FF, - 2 => 12, - ), - 'Syriac' => array( - 0 => 0x0700, - 1 => 0x074F, - 2 => 13, - ), - 'Arabic Supplement' => array( - 0 => 0x0750, - 1 => 0x077F, - 2 => 14, - ), - 'Thaana' => array( - 0 => 0x0780, - 1 => 0x07BF, - 2 => 15, - ), - 'NKo' => array( - 0 => 0x07C0, - 1 => 0x07FF, - 2 => 16, - ), - 'Samaritan' => array( - 0 => 0x0800, - 1 => 0x083F, - 2 => 17, - ), - 'Mandaic' => array( - 0 => 0x0840, - 1 => 0x085F, - 2 => 18, - ), - 'Devanagari' => array( - 0 => 0x0900, - 1 => 0x097F, - 2 => 19, - ), - 'Bengali' => array( - 0 => 0x0980, - 1 => 0x09FF, - 2 => 20, - ), - 'Gurmukhi' => array( - 0 => 0x0A00, - 1 => 0x0A7F, - 2 => 21, - ), - 'Gujarati' => array( - 0 => 0x0A80, - 1 => 0x0AFF, - 2 => 22, - ), - 'Oriya' => array( - 0 => 0x0B00, - 1 => 0x0B7F, - 2 => 23, - ), - 'Tamil' => array( - 0 => 0x0B80, - 1 => 0x0BFF, - 2 => 24, - ), - 'Telugu' => array( - 0 => 0x0C00, - 1 => 0x0C7F, - 2 => 25, - ), - 'Kannada' => array( - 0 => 0x0C80, - 1 => 0x0CFF, - 2 => 26, - ), - 'Malayalam' => array( - 0 => 0x0D00, - 1 => 0x0D7F, - 2 => 27, - ), - 'Sinhala' => array( - 0 => 0x0D80, - 1 => 0x0DFF, - 2 => 28, - ), - 'Thai' => array( - 0 => 0x0E00, - 1 => 0x0E7F, - 2 => 29, - ), - 'Lao' => array( - 0 => 0x0E80, - 1 => 0x0EFF, - 2 => 30, - ), - 'Tibetan' => array( - 0 => 0x0F00, - 1 => 0x0FFF, - 2 => 31, - ), - 'Myanmar' => array( - 0 => 0x1000, - 1 => 0x109F, - 2 => 32, - ), - 'Georgian' => array( - 0 => 0x10A0, - 1 => 0x10FF, - 2 => 33, - ), - 'Hangul Jamo' => array( - 0 => 0x1100, - 1 => 0x11FF, - 2 => 34, - ), - 'Ethiopic' => array( - 0 => 0x1200, - 1 => 0x137F, - 2 => 35, - ), - 'Ethiopic Supplement' => array( - 0 => 0x1380, - 1 => 0x139F, - 2 => 36, - ), - 'Cherokee' => array( - 0 => 0x13A0, - 1 => 0x13FF, - 2 => 37, - ), - 'Unified Canadian Aboriginal Syllabics' => array( - 0 => 0x1400, - 1 => 0x167F, - 2 => 38, - ), - 'Ogham' => array( - 0 => 0x1680, - 1 => 0x169F, - 2 => 39, - ), - 'Runic' => array( - 0 => 0x16A0, - 1 => 0x16FF, - 2 => 40, - ), - 'Tagalog' => array( - 0 => 0x1700, - 1 => 0x171F, - 2 => 41, - ), - 'Hanunoo' => array( - 0 => 0x1720, - 1 => 0x173F, - 2 => 42, - ), - 'Buhid' => array( - 0 => 0x1740, - 1 => 0x175F, - 2 => 43, - ), - 'Tagbanwa' => array( - 0 => 0x1760, - 1 => 0x177F, - 2 => 44, - ), - 'Khmer' => array( - 0 => 0x1780, - 1 => 0x17FF, - 2 => 45, - ), - 'Mongolian' => array( - 0 => 0x1800, - 1 => 0x18AF, - 2 => 46, - ), - 'Unified Canadian Aboriginal Syllabics Extended' => array( - 0 => 0x18B0, - 1 => 0x18FF, - 2 => 47, - ), - 'Limbu' => array( - 0 => 0x1900, - 1 => 0x194F, - 2 => 48, - ), - 'Tai Le' => array( - 0 => 0x1950, - 1 => 0x197F, - 2 => 49, - ), - 'New Tai Lue' => array( - 0 => 0x1980, - 1 => 0x19DF, - 2 => 50, - ), - 'Khmer Symbols' => array( - 0 => 0x19E0, - 1 => 0x19FF, - 2 => 51, - ), - 'Buginese' => array( - 0 => 0x1A00, - 1 => 0x1A1F, - 2 => 52, - ), - 'Tai Tham' => array( - 0 => 0x1A20, - 1 => 0x1AAF, - 2 => 53, - ), - 'Balinese' => array( - 0 => 0x1B00, - 1 => 0x1B7F, - 2 => 54, - ), - 'Sundanese' => array( - 0 => 0x1B80, - 1 => 0x1BBF, - 2 => 55, - ), - 'Batak' => array( - 0 => 0x1BC0, - 1 => 0x1BFF, - 2 => 56, - ), - 'Lepcha' => array( - 0 => 0x1C00, - 1 => 0x1C4F, - 2 => 57, - ), - 'Ol Chiki' => array( - 0 => 0x1C50, - 1 => 0x1C7F, - 2 => 58, - ), - 'Vedic Extensions' => array( - 0 => 0x1CD0, - 1 => 0x1CFF, - 2 => 59, - ), - 'Phonetic Extensions' => array( - 0 => 0x1D00, - 1 => 0x1D7F, - 2 => 60, - ), - 'Phonetic Extensions Supplement' => array( - 0 => 0x1D80, - 1 => 0x1DBF, - 2 => 61, - ), - 'Combining Diacritical Marks Supplement' => array( - 0 => 0x1DC0, - 1 => 0x1DFF, - 2 => 62, - ), - 'Latin Extended Additional' => array( - 0 => 0x1E00, - 1 => 0x1EFF, - 2 => 63, - ), - 'Greek Extended' => array( - 0 => 0x1F00, - 1 => 0x1FFF, - 2 => 64, - ), - 'General Punctuation' => array( - 0 => 0x2000, - 1 => 0x206F, - 2 => 65, - ), - 'Superscripts and Subscripts' => array( - 0 => 0x2070, - 1 => 0x209F, - 2 => 66, - ), - 'Currency Symbols' => array( - 0 => 0x20A0, - 1 => 0x20CF, - 2 => 67, - ), - 'Combining Diacritical Marks for Symbols' => array( - 0 => 0x20D0, - 1 => 0x20FF, - 2 => 68, - ), - 'Letterlike Symbols' => array( - 0 => 0x2100, - 1 => 0x214F, - 2 => 69, - ), - 'Number Forms' => array( - 0 => 0x2150, - 1 => 0x218F, - 2 => 70, - ), - 'Arrows' => array( - 0 => 0x2190, - 1 => 0x21FF, - 2 => 71, - ), - 'Mathematical Operators' => array( - 0 => 0x2200, - 1 => 0x22FF, - 2 => 72, - ), - 'Miscellaneous Technical' => array( - 0 => 0x2300, - 1 => 0x23FF, - 2 => 73, - ), - 'Control Pictures' => array( - 0 => 0x2400, - 1 => 0x243F, - 2 => 74, - ), - 'Optical Character Recognition' => array( - 0 => 0x2440, - 1 => 0x245F, - 2 => 75, - ), - 'Enclosed Alphanumerics' => array( - 0 => 0x2460, - 1 => 0x24FF, - 2 => 76, - ), - 'Box Drawing' => array( - 0 => 0x2500, - 1 => 0x257F, - 2 => 77, - ), - 'Block Elements' => array( - 0 => 0x2580, - 1 => 0x259F, - 2 => 78, - ), - 'Geometric Shapes' => array( - 0 => 0x25A0, - 1 => 0x25FF, - 2 => 79, - ), - 'Miscellaneous Symbols' => array( - 0 => 0x2600, - 1 => 0x26FF, - 2 => 80, - ), - 'Dingbats' => array( - 0 => 0x2700, - 1 => 0x27BF, - 2 => 81, - ), - 'Miscellaneous Mathematical Symbols-A' => array( - 0 => 0x27C0, - 1 => 0x27EF, - 2 => 82, - ), - 'Supplemental Arrows-A' => array( - 0 => 0x27F0, - 1 => 0x27FF, - 2 => 83, - ), - 'Braille Patterns' => array( - 0 => 0x2800, - 1 => 0x28FF, - 2 => 84, - ), - 'Supplemental Arrows-B' => array( - 0 => 0x2900, - 1 => 0x297F, - 2 => 85, - ), - 'Miscellaneous Mathematical Symbols-B' => array( - 0 => 0x2980, - 1 => 0x29FF, - 2 => 86, - ), - 'Supplemental Mathematical Operators' => array( - 0 => 0x2A00, - 1 => 0x2AFF, - 2 => 87, - ), - 'Miscellaneous Symbols and Arrows' => array( - 0 => 0x2B00, - 1 => 0x2BFF, - 2 => 88, - ), - 'Glagolitic' => array( - 0 => 0x2C00, - 1 => 0x2C5F, - 2 => 89, - ), - 'Latin Extended-C' => array( - 0 => 0x2C60, - 1 => 0x2C7F, - 2 => 90, - ), - 'Coptic' => array( - 0 => 0x2C80, - 1 => 0x2CFF, - 2 => 91, - ), - 'Georgian Supplement' => array( - 0 => 0x2D00, - 1 => 0x2D2F, - 2 => 92, - ), - 'Tifinagh' => array( - 0 => 0x2D30, - 1 => 0x2D7F, - 2 => 93, - ), - 'Ethiopic Extended' => array( - 0 => 0x2D80, - 1 => 0x2DDF, - 2 => 94, - ), - 'Cyrillic Extended-A' => array( - 0 => 0x2DE0, - 1 => 0x2DFF, - 2 => 95, - ), - 'Supplemental Punctuation' => array( - 0 => 0x2E00, - 1 => 0x2E7F, - 2 => 96, - ), - 'CJK Radicals Supplement' => array( - 0 => 0x2E80, - 1 => 0x2EFF, - 2 => 97, - ), - 'Kangxi Radicals' => array( - 0 => 0x2F00, - 1 => 0x2FDF, - 2 => 98, - ), - 'Ideographic Description Characters' => array( - 0 => 0x2FF0, - 1 => 0x2FFF, - 2 => 99, - ), - 'CJK Symbols and Punctuation' => array( - 0 => 0x3000, - 1 => 0x303F, - 2 => 100, - ), - 'Hiragana' => array( - 0 => 0x3040, - 1 => 0x309F, - 2 => 101, - ), - 'Katakana' => array( - 0 => 0x30A0, - 1 => 0x30FF, - 2 => 102, - ), - 'Bopomofo' => array( - 0 => 0x3100, - 1 => 0x312F, - 2 => 103, - ), - 'Hangul Compatibility Jamo' => array( - 0 => 0x3130, - 1 => 0x318F, - 2 => 104, - ), - 'Kanbun' => array( - 0 => 0x3190, - 1 => 0x319F, - 2 => 105, - ), - 'Bopomofo Extended' => array( - 0 => 0x31A0, - 1 => 0x31BF, - 2 => 106, - ), - 'CJK Strokes' => array( - 0 => 0x31C0, - 1 => 0x31EF, - 2 => 107, - ), - 'Katakana Phonetic Extensions' => array( - 0 => 0x31F0, - 1 => 0x31FF, - 2 => 108, - ), - 'Enclosed CJK Letters and Months' => array( - 0 => 0x3200, - 1 => 0x32FF, - 2 => 109, - ), - 'CJK Compatibility' => array( - 0 => 0x3300, - 1 => 0x33FF, - 2 => 110, - ), - 'CJK Unified Ideographs Extension A' => array( - 0 => 0x3400, - 1 => 0x4DBF, - 2 => 111, - ), - 'Yijing Hexagram Symbols' => array( - 0 => 0x4DC0, - 1 => 0x4DFF, - 2 => 112, - ), - 'CJK Unified Ideographs' => array( - 0 => 0x4E00, - 1 => 0x9FFF, - 2 => 113, - ), - 'Yi Syllables' => array( - 0 => 0xA000, - 1 => 0xA48F, - 2 => 114, - ), - 'Yi Radicals' => array( - 0 => 0xA490, - 1 => 0xA4CF, - 2 => 115, - ), - 'Lisu' => array( - 0 => 0xA4D0, - 1 => 0xA4FF, - 2 => 116, - ), - 'Vai' => array( - 0 => 0xA500, - 1 => 0xA63F, - 2 => 117, - ), - 'Cyrillic Extended-B' => array( - 0 => 0xA640, - 1 => 0xA69F, - 2 => 118, - ), - 'Bamum' => array( - 0 => 0xA6A0, - 1 => 0xA6FF, - 2 => 119, - ), - 'Modifier Tone Letters' => array( - 0 => 0xA700, - 1 => 0xA71F, - 2 => 120, - ), - 'Latin Extended-D' => array( - 0 => 0xA720, - 1 => 0xA7FF, - 2 => 121, - ), - 'Syloti Nagri' => array( - 0 => 0xA800, - 1 => 0xA82F, - 2 => 122, - ), - 'Common Indic Number Forms' => array( - 0 => 0xA830, - 1 => 0xA83F, - 2 => 123, - ), - 'Phags-pa' => array( - 0 => 0xA840, - 1 => 0xA87F, - 2 => 124, - ), - 'Saurashtra' => array( - 0 => 0xA880, - 1 => 0xA8DF, - 2 => 125, - ), - 'Devanagari Extended' => array( - 0 => 0xA8E0, - 1 => 0xA8FF, - 2 => 126, - ), - 'Kayah Li' => array( - 0 => 0xA900, - 1 => 0xA92F, - 2 => 127, - ), - 'Rejang' => array( - 0 => 0xA930, - 1 => 0xA95F, - 2 => 128, - ), - 'Hangul Jamo Extended-A' => array( - 0 => 0xA960, - 1 => 0xA97F, - 2 => 129, - ), - 'Javanese' => array( - 0 => 0xA980, - 1 => 0xA9DF, - 2 => 130, - ), - 'Cham' => array( - 0 => 0xAA00, - 1 => 0xAA5F, - 2 => 131, - ), - 'Myanmar Extended-A' => array( - 0 => 0xAA60, - 1 => 0xAA7F, - 2 => 132, - ), - 'Tai Viet' => array( - 0 => 0xAA80, - 1 => 0xAADF, - 2 => 133, - ), - 'Ethiopic Extended-A' => array( - 0 => 0xAB00, - 1 => 0xAB2F, - 2 => 134, - ), - 'Meetei Mayek' => array( - 0 => 0xABC0, - 1 => 0xABFF, - 2 => 135, - ), - 'Hangul Syllables' => array( - 0 => 0xAC00, - 1 => 0xD7AF, - 2 => 136, - ), - 'Hangul Jamo Extended-B' => array( - 0 => 0xD7B0, - 1 => 0xD7FF, - 2 => 137, - ), - 'High Surrogates' => array( - 0 => 0xD800, - 1 => 0xDB7F, - 2 => 138, - ), - 'High Private Use Surrogates' => array( - 0 => 0xDB80, - 1 => 0xDBFF, - 2 => 139, - ), - 'Low Surrogates' => array( - 0 => 0xDC00, - 1 => 0xDFFF, - 2 => 140, - ), - 'Private Use Area' => array( - 0 => 0xE000, - 1 => 0xF8FF, - 2 => 141, - ), - 'CJK Compatibility Ideographs' => array( - 0 => 0xF900, - 1 => 0xFAFF, - 2 => 142, - ), - 'Alphabetic Presentation Forms' => array( - 0 => 0xFB00, - 1 => 0xFB4F, - 2 => 143, - ), - 'Arabic Presentation Forms-A' => array( - 0 => 0xFB50, - 1 => 0xFDFF, - 2 => 144, - ), - 'Variation Selectors' => array( - 0 => 0xFE00, - 1 => 0xFE0F, - 2 => 145, - ), - 'Vertical Forms' => array( - 0 => 0xFE10, - 1 => 0xFE1F, - 2 => 146, - ), - 'Combining Half Marks' => array( - 0 => 0xFE20, - 1 => 0xFE2F, - 2 => 147, - ), - 'CJK Compatibility Forms' => array( - 0 => 0xFE30, - 1 => 0xFE4F, - 2 => 148, - ), - 'Small Form Variants' => array( - 0 => 0xFE50, - 1 => 0xFE6F, - 2 => 149, - ), - 'Arabic Presentation Forms-B' => array( - 0 => 0xFE70, - 1 => 0xFEFF, - 2 => 150, - ), - 'Halfwidth and Fullwidth Forms' => array( - 0 => 0xFF00, - 1 => 0xFFEF, - 2 => 151, - ), - 'Specials' => array( - 0 => 0xFFF0, - 1 => 0xFFFF, - 2 => 152, - ), - 'Linear B Syllabary' => array( - 0 => 0x10000, - 1 => 0x1007F, - 2 => 153, - ), - 'Linear B Ideograms' => array( - 0 => 0x10080, - 1 => 0x100FF, - 2 => 154, - ), - 'Aegean Numbers' => array( - 0 => 0x10100, - 1 => 0x1013F, - 2 => 155, - ), - 'Ancient Greek Numbers' => array( - 0 => 0x10140, - 1 => 0x1018F, - 2 => 156, - ), - 'Ancient Symbols' => array( - 0 => 0x10190, - 1 => 0x101CF, - 2 => 157, - ), - 'Phaistos Disc' => array( - 0 => 0x101D0, - 1 => 0x101FF, - 2 => 158, - ), - 'Lycian' => array( - 0 => 0x10280, - 1 => 0x1029F, - 2 => 159, - ), - 'Carian' => array( - 0 => 0x102A0, - 1 => 0x102DF, - 2 => 160, - ), - 'Old Italic' => array( - 0 => 0x10300, - 1 => 0x1032F, - 2 => 161, - ), - 'Gothic' => array( - 0 => 0x10330, - 1 => 0x1034F, - 2 => 162, - ), - 'Ugaritic' => array( - 0 => 0x10380, - 1 => 0x1039F, - 2 => 163, - ), - 'Old Persian' => array( - 0 => 0x103A0, - 1 => 0x103DF, - 2 => 164, - ), - 'Deseret' => array( - 0 => 0x10400, - 1 => 0x1044F, - 2 => 165, - ), - 'Shavian' => array( - 0 => 0x10450, - 1 => 0x1047F, - 2 => 166, - ), - 'Osmanya' => array( - 0 => 0x10480, - 1 => 0x104AF, - 2 => 167, - ), - 'Cypriot Syllabary' => array( - 0 => 0x10800, - 1 => 0x1083F, - 2 => 168, - ), - 'Imperial Aramaic' => array( - 0 => 0x10840, - 1 => 0x1085F, - 2 => 169, - ), - 'Phoenician' => array( - 0 => 0x10900, - 1 => 0x1091F, - 2 => 170, - ), - 'Lydian' => array( - 0 => 0x10920, - 1 => 0x1093F, - 2 => 171, - ), - 'Kharoshthi' => array( - 0 => 0x10A00, - 1 => 0x10A5F, - 2 => 172, - ), - 'Old South Arabian' => array( - 0 => 0x10A60, - 1 => 0x10A7F, - 2 => 173, - ), - 'Avestan' => array( - 0 => 0x10B00, - 1 => 0x10B3F, - 2 => 174, - ), - 'Inscriptional Parthian' => array( - 0 => 0x10B40, - 1 => 0x10B5F, - 2 => 175, - ), - 'Inscriptional Pahlavi' => array( - 0 => 0x10B60, - 1 => 0x10B7F, - 2 => 176, - ), - 'Old Turkic' => array( - 0 => 0x10C00, - 1 => 0x10C4F, - 2 => 177, - ), - 'Rumi Numeral Symbols' => array( - 0 => 0x10E60, - 1 => 0x10E7F, - 2 => 178, - ), - 'Brahmi' => array( - 0 => 0x11000, - 1 => 0x1107F, - 2 => 179, - ), - 'Kaithi' => array( - 0 => 0x11080, - 1 => 0x110CF, - 2 => 180, - ), - 'Cuneiform' => array( - 0 => 0x12000, - 1 => 0x123FF, - 2 => 181, - ), - 'Cuneiform Numbers and Punctuation' => array( - 0 => 0x12400, - 1 => 0x1247F, - 2 => 182, - ), - 'Egyptian Hieroglyphs' => array( - 0 => 0x13000, - 1 => 0x1342F, - 2 => 183, - ), - 'Bamum Supplement' => array( - 0 => 0x16800, - 1 => 0x16A3F, - 2 => 184, - ), - 'Kana Supplement' => array( - 0 => 0x1B000, - 1 => 0x1B0FF, - 2 => 185, - ), - 'Byzantine Musical Symbols' => array( - 0 => 0x1D000, - 1 => 0x1D0FF, - 2 => 186, - ), - 'Musical Symbols' => array( - 0 => 0x1D100, - 1 => 0x1D1FF, - 2 => 187, - ), - 'Ancient Greek Musical Notation' => array( - 0 => 0x1D200, - 1 => 0x1D24F, - 2 => 188, - ), - 'Tai Xuan Jing Symbols' => array( - 0 => 0x1D300, - 1 => 0x1D35F, - 2 => 189, - ), - 'Counting Rod Numerals' => array( - 0 => 0x1D360, - 1 => 0x1D37F, - 2 => 190, - ), - 'Mathematical Alphanumeric Symbols' => array( - 0 => 0x1D400, - 1 => 0x1D7FF, - 2 => 191, - ), - 'Mahjong Tiles' => array( - 0 => 0x1F000, - 1 => 0x1F02F, - 2 => 192, - ), - 'Domino Tiles' => array( - 0 => 0x1F030, - 1 => 0x1F09F, - 2 => 193, - ), - 'Playing Cards' => array( - 0 => 0x1F0A0, - 1 => 0x1F0FF, - 2 => 194, - ), - 'Enclosed Alphanumeric Supplement' => array( - 0 => 0x1F100, - 1 => 0x1F1FF, - 2 => 195, - ), - 'Enclosed Ideographic Supplement' => array( - 0 => 0x1F200, - 1 => 0x1F2FF, - 2 => 196, - ), - 'Miscellaneous Symbols And Pictographs' => array( - 0 => 0x1F300, - 1 => 0x1F5FF, - 2 => 197, - ), - 'Emoticons' => array( - 0 => 0x1F600, - 1 => 0x1F64F, - 2 => 198, - ), - 'Transport And Map Symbols' => array( - 0 => 0x1F680, - 1 => 0x1F6FF, - 2 => 199, - ), - 'Alchemical Symbols' => array( - 0 => 0x1F700, - 1 => 0x1F77F, - 2 => 200, - ), - 'CJK Unified Ideographs Extension B' => array( - 0 => 0x20000, - 1 => 0x2A6DF, - 2 => 201, - ), - 'CJK Unified Ideographs Extension C' => array( - 0 => 0x2A700, - 1 => 0x2B73F, - 2 => 202, - ), - 'CJK Unified Ideographs Extension D' => array( - 0 => 0x2B740, - 1 => 0x2B81F, - 2 => 203, - ), - 'CJK Compatibility Ideographs Supplement' => array( - 0 => 0x2F800, - 1 => 0x2FA1F, - 2 => 204, - ), - 'Tags' => array( - 0 => 0xE0000, - 1 => 0xE007F, - 2 => 205, - ), - 'Variation Selectors Supplement' => array( - 0 => 0xE0100, - 1 => 0xE01EF, - 2 => 206, - ), - 'Supplementary Private Use Area-A' => array( - 0 => 0xF0000, - 1 => 0xFFFFF, - 2 => 207, - ), - 'Supplementary Private Use Area-B' => array( - 0 => 0x100000, - 1 => 0x10FFFF, - 2 => 208, - ), - ); + #Unicode Character Database 6.0.0 (2010-06-04) + #autogenerated by unicode_blocks_txt2php() PHP function at 2011-06-04 00:19:39, 209 blocks total + public static $unicode_blocks = array( + 'Basic Latin' => array( + 0 => 0x0000, + 1 => 0x007F, + 2 => 0, + ), + 'Latin-1 Supplement' => array( + 0 => 0x0080, + 1 => 0x00FF, + 2 => 1, + ), + 'Latin Extended-A' => array( + 0 => 0x0100, + 1 => 0x017F, + 2 => 2, + ), + 'Latin Extended-B' => array( + 0 => 0x0180, + 1 => 0x024F, + 2 => 3, + ), + 'IPA Extensions' => array( + 0 => 0x0250, + 1 => 0x02AF, + 2 => 4, + ), + 'Spacing Modifier Letters' => array( + 0 => 0x02B0, + 1 => 0x02FF, + 2 => 5, + ), + 'Combining Diacritical Marks' => array( + 0 => 0x0300, + 1 => 0x036F, + 2 => 6, + ), + 'Greek and Coptic' => array( + 0 => 0x0370, + 1 => 0x03FF, + 2 => 7, + ), + 'Cyrillic' => array( + 0 => 0x0400, + 1 => 0x04FF, + 2 => 8, + ), + 'Cyrillic Supplement' => array( + 0 => 0x0500, + 1 => 0x052F, + 2 => 9, + ), + 'Armenian' => array( + 0 => 0x0530, + 1 => 0x058F, + 2 => 10, + ), + 'Hebrew' => array( + 0 => 0x0590, + 1 => 0x05FF, + 2 => 11, + ), + 'Arabic' => array( + 0 => 0x0600, + 1 => 0x06FF, + 2 => 12, + ), + 'Syriac' => array( + 0 => 0x0700, + 1 => 0x074F, + 2 => 13, + ), + 'Arabic Supplement' => array( + 0 => 0x0750, + 1 => 0x077F, + 2 => 14, + ), + 'Thaana' => array( + 0 => 0x0780, + 1 => 0x07BF, + 2 => 15, + ), + 'NKo' => array( + 0 => 0x07C0, + 1 => 0x07FF, + 2 => 16, + ), + 'Samaritan' => array( + 0 => 0x0800, + 1 => 0x083F, + 2 => 17, + ), + 'Mandaic' => array( + 0 => 0x0840, + 1 => 0x085F, + 2 => 18, + ), + 'Devanagari' => array( + 0 => 0x0900, + 1 => 0x097F, + 2 => 19, + ), + 'Bengali' => array( + 0 => 0x0980, + 1 => 0x09FF, + 2 => 20, + ), + 'Gurmukhi' => array( + 0 => 0x0A00, + 1 => 0x0A7F, + 2 => 21, + ), + 'Gujarati' => array( + 0 => 0x0A80, + 1 => 0x0AFF, + 2 => 22, + ), + 'Oriya' => array( + 0 => 0x0B00, + 1 => 0x0B7F, + 2 => 23, + ), + 'Tamil' => array( + 0 => 0x0B80, + 1 => 0x0BFF, + 2 => 24, + ), + 'Telugu' => array( + 0 => 0x0C00, + 1 => 0x0C7F, + 2 => 25, + ), + 'Kannada' => array( + 0 => 0x0C80, + 1 => 0x0CFF, + 2 => 26, + ), + 'Malayalam' => array( + 0 => 0x0D00, + 1 => 0x0D7F, + 2 => 27, + ), + 'Sinhala' => array( + 0 => 0x0D80, + 1 => 0x0DFF, + 2 => 28, + ), + 'Thai' => array( + 0 => 0x0E00, + 1 => 0x0E7F, + 2 => 29, + ), + 'Lao' => array( + 0 => 0x0E80, + 1 => 0x0EFF, + 2 => 30, + ), + 'Tibetan' => array( + 0 => 0x0F00, + 1 => 0x0FFF, + 2 => 31, + ), + 'Myanmar' => array( + 0 => 0x1000, + 1 => 0x109F, + 2 => 32, + ), + 'Georgian' => array( + 0 => 0x10A0, + 1 => 0x10FF, + 2 => 33, + ), + 'Hangul Jamo' => array( + 0 => 0x1100, + 1 => 0x11FF, + 2 => 34, + ), + 'Ethiopic' => array( + 0 => 0x1200, + 1 => 0x137F, + 2 => 35, + ), + 'Ethiopic Supplement' => array( + 0 => 0x1380, + 1 => 0x139F, + 2 => 36, + ), + 'Cherokee' => array( + 0 => 0x13A0, + 1 => 0x13FF, + 2 => 37, + ), + 'Unified Canadian Aboriginal Syllabics' => array( + 0 => 0x1400, + 1 => 0x167F, + 2 => 38, + ), + 'Ogham' => array( + 0 => 0x1680, + 1 => 0x169F, + 2 => 39, + ), + 'Runic' => array( + 0 => 0x16A0, + 1 => 0x16FF, + 2 => 40, + ), + 'Tagalog' => array( + 0 => 0x1700, + 1 => 0x171F, + 2 => 41, + ), + 'Hanunoo' => array( + 0 => 0x1720, + 1 => 0x173F, + 2 => 42, + ), + 'Buhid' => array( + 0 => 0x1740, + 1 => 0x175F, + 2 => 43, + ), + 'Tagbanwa' => array( + 0 => 0x1760, + 1 => 0x177F, + 2 => 44, + ), + 'Khmer' => array( + 0 => 0x1780, + 1 => 0x17FF, + 2 => 45, + ), + 'Mongolian' => array( + 0 => 0x1800, + 1 => 0x18AF, + 2 => 46, + ), + 'Unified Canadian Aboriginal Syllabics Extended' => array( + 0 => 0x18B0, + 1 => 0x18FF, + 2 => 47, + ), + 'Limbu' => array( + 0 => 0x1900, + 1 => 0x194F, + 2 => 48, + ), + 'Tai Le' => array( + 0 => 0x1950, + 1 => 0x197F, + 2 => 49, + ), + 'New Tai Lue' => array( + 0 => 0x1980, + 1 => 0x19DF, + 2 => 50, + ), + 'Khmer Symbols' => array( + 0 => 0x19E0, + 1 => 0x19FF, + 2 => 51, + ), + 'Buginese' => array( + 0 => 0x1A00, + 1 => 0x1A1F, + 2 => 52, + ), + 'Tai Tham' => array( + 0 => 0x1A20, + 1 => 0x1AAF, + 2 => 53, + ), + 'Balinese' => array( + 0 => 0x1B00, + 1 => 0x1B7F, + 2 => 54, + ), + 'Sundanese' => array( + 0 => 0x1B80, + 1 => 0x1BBF, + 2 => 55, + ), + 'Batak' => array( + 0 => 0x1BC0, + 1 => 0x1BFF, + 2 => 56, + ), + 'Lepcha' => array( + 0 => 0x1C00, + 1 => 0x1C4F, + 2 => 57, + ), + 'Ol Chiki' => array( + 0 => 0x1C50, + 1 => 0x1C7F, + 2 => 58, + ), + 'Vedic Extensions' => array( + 0 => 0x1CD0, + 1 => 0x1CFF, + 2 => 59, + ), + 'Phonetic Extensions' => array( + 0 => 0x1D00, + 1 => 0x1D7F, + 2 => 60, + ), + 'Phonetic Extensions Supplement' => array( + 0 => 0x1D80, + 1 => 0x1DBF, + 2 => 61, + ), + 'Combining Diacritical Marks Supplement' => array( + 0 => 0x1DC0, + 1 => 0x1DFF, + 2 => 62, + ), + 'Latin Extended Additional' => array( + 0 => 0x1E00, + 1 => 0x1EFF, + 2 => 63, + ), + 'Greek Extended' => array( + 0 => 0x1F00, + 1 => 0x1FFF, + 2 => 64, + ), + 'General Punctuation' => array( + 0 => 0x2000, + 1 => 0x206F, + 2 => 65, + ), + 'Superscripts and Subscripts' => array( + 0 => 0x2070, + 1 => 0x209F, + 2 => 66, + ), + 'Currency Symbols' => array( + 0 => 0x20A0, + 1 => 0x20CF, + 2 => 67, + ), + 'Combining Diacritical Marks for Symbols' => array( + 0 => 0x20D0, + 1 => 0x20FF, + 2 => 68, + ), + 'Letterlike Symbols' => array( + 0 => 0x2100, + 1 => 0x214F, + 2 => 69, + ), + 'Number Forms' => array( + 0 => 0x2150, + 1 => 0x218F, + 2 => 70, + ), + 'Arrows' => array( + 0 => 0x2190, + 1 => 0x21FF, + 2 => 71, + ), + 'Mathematical Operators' => array( + 0 => 0x2200, + 1 => 0x22FF, + 2 => 72, + ), + 'Miscellaneous Technical' => array( + 0 => 0x2300, + 1 => 0x23FF, + 2 => 73, + ), + 'Control Pictures' => array( + 0 => 0x2400, + 1 => 0x243F, + 2 => 74, + ), + 'Optical Character Recognition' => array( + 0 => 0x2440, + 1 => 0x245F, + 2 => 75, + ), + 'Enclosed Alphanumerics' => array( + 0 => 0x2460, + 1 => 0x24FF, + 2 => 76, + ), + 'Box Drawing' => array( + 0 => 0x2500, + 1 => 0x257F, + 2 => 77, + ), + 'Block Elements' => array( + 0 => 0x2580, + 1 => 0x259F, + 2 => 78, + ), + 'Geometric Shapes' => array( + 0 => 0x25A0, + 1 => 0x25FF, + 2 => 79, + ), + 'Miscellaneous Symbols' => array( + 0 => 0x2600, + 1 => 0x26FF, + 2 => 80, + ), + 'Dingbats' => array( + 0 => 0x2700, + 1 => 0x27BF, + 2 => 81, + ), + 'Miscellaneous Mathematical Symbols-A' => array( + 0 => 0x27C0, + 1 => 0x27EF, + 2 => 82, + ), + 'Supplemental Arrows-A' => array( + 0 => 0x27F0, + 1 => 0x27FF, + 2 => 83, + ), + 'Braille Patterns' => array( + 0 => 0x2800, + 1 => 0x28FF, + 2 => 84, + ), + 'Supplemental Arrows-B' => array( + 0 => 0x2900, + 1 => 0x297F, + 2 => 85, + ), + 'Miscellaneous Mathematical Symbols-B' => array( + 0 => 0x2980, + 1 => 0x29FF, + 2 => 86, + ), + 'Supplemental Mathematical Operators' => array( + 0 => 0x2A00, + 1 => 0x2AFF, + 2 => 87, + ), + 'Miscellaneous Symbols and Arrows' => array( + 0 => 0x2B00, + 1 => 0x2BFF, + 2 => 88, + ), + 'Glagolitic' => array( + 0 => 0x2C00, + 1 => 0x2C5F, + 2 => 89, + ), + 'Latin Extended-C' => array( + 0 => 0x2C60, + 1 => 0x2C7F, + 2 => 90, + ), + 'Coptic' => array( + 0 => 0x2C80, + 1 => 0x2CFF, + 2 => 91, + ), + 'Georgian Supplement' => array( + 0 => 0x2D00, + 1 => 0x2D2F, + 2 => 92, + ), + 'Tifinagh' => array( + 0 => 0x2D30, + 1 => 0x2D7F, + 2 => 93, + ), + 'Ethiopic Extended' => array( + 0 => 0x2D80, + 1 => 0x2DDF, + 2 => 94, + ), + 'Cyrillic Extended-A' => array( + 0 => 0x2DE0, + 1 => 0x2DFF, + 2 => 95, + ), + 'Supplemental Punctuation' => array( + 0 => 0x2E00, + 1 => 0x2E7F, + 2 => 96, + ), + 'CJK Radicals Supplement' => array( + 0 => 0x2E80, + 1 => 0x2EFF, + 2 => 97, + ), + 'Kangxi Radicals' => array( + 0 => 0x2F00, + 1 => 0x2FDF, + 2 => 98, + ), + 'Ideographic Description Characters' => array( + 0 => 0x2FF0, + 1 => 0x2FFF, + 2 => 99, + ), + 'CJK Symbols and Punctuation' => array( + 0 => 0x3000, + 1 => 0x303F, + 2 => 100, + ), + 'Hiragana' => array( + 0 => 0x3040, + 1 => 0x309F, + 2 => 101, + ), + 'Katakana' => array( + 0 => 0x30A0, + 1 => 0x30FF, + 2 => 102, + ), + 'Bopomofo' => array( + 0 => 0x3100, + 1 => 0x312F, + 2 => 103, + ), + 'Hangul Compatibility Jamo' => array( + 0 => 0x3130, + 1 => 0x318F, + 2 => 104, + ), + 'Kanbun' => array( + 0 => 0x3190, + 1 => 0x319F, + 2 => 105, + ), + 'Bopomofo Extended' => array( + 0 => 0x31A0, + 1 => 0x31BF, + 2 => 106, + ), + 'CJK Strokes' => array( + 0 => 0x31C0, + 1 => 0x31EF, + 2 => 107, + ), + 'Katakana Phonetic Extensions' => array( + 0 => 0x31F0, + 1 => 0x31FF, + 2 => 108, + ), + 'Enclosed CJK Letters and Months' => array( + 0 => 0x3200, + 1 => 0x32FF, + 2 => 109, + ), + 'CJK Compatibility' => array( + 0 => 0x3300, + 1 => 0x33FF, + 2 => 110, + ), + 'CJK Unified Ideographs Extension A' => array( + 0 => 0x3400, + 1 => 0x4DBF, + 2 => 111, + ), + 'Yijing Hexagram Symbols' => array( + 0 => 0x4DC0, + 1 => 0x4DFF, + 2 => 112, + ), + 'CJK Unified Ideographs' => array( + 0 => 0x4E00, + 1 => 0x9FFF, + 2 => 113, + ), + 'Yi Syllables' => array( + 0 => 0xA000, + 1 => 0xA48F, + 2 => 114, + ), + 'Yi Radicals' => array( + 0 => 0xA490, + 1 => 0xA4CF, + 2 => 115, + ), + 'Lisu' => array( + 0 => 0xA4D0, + 1 => 0xA4FF, + 2 => 116, + ), + 'Vai' => array( + 0 => 0xA500, + 1 => 0xA63F, + 2 => 117, + ), + 'Cyrillic Extended-B' => array( + 0 => 0xA640, + 1 => 0xA69F, + 2 => 118, + ), + 'Bamum' => array( + 0 => 0xA6A0, + 1 => 0xA6FF, + 2 => 119, + ), + 'Modifier Tone Letters' => array( + 0 => 0xA700, + 1 => 0xA71F, + 2 => 120, + ), + 'Latin Extended-D' => array( + 0 => 0xA720, + 1 => 0xA7FF, + 2 => 121, + ), + 'Syloti Nagri' => array( + 0 => 0xA800, + 1 => 0xA82F, + 2 => 122, + ), + 'Common Indic Number Forms' => array( + 0 => 0xA830, + 1 => 0xA83F, + 2 => 123, + ), + 'Phags-pa' => array( + 0 => 0xA840, + 1 => 0xA87F, + 2 => 124, + ), + 'Saurashtra' => array( + 0 => 0xA880, + 1 => 0xA8DF, + 2 => 125, + ), + 'Devanagari Extended' => array( + 0 => 0xA8E0, + 1 => 0xA8FF, + 2 => 126, + ), + 'Kayah Li' => array( + 0 => 0xA900, + 1 => 0xA92F, + 2 => 127, + ), + 'Rejang' => array( + 0 => 0xA930, + 1 => 0xA95F, + 2 => 128, + ), + 'Hangul Jamo Extended-A' => array( + 0 => 0xA960, + 1 => 0xA97F, + 2 => 129, + ), + 'Javanese' => array( + 0 => 0xA980, + 1 => 0xA9DF, + 2 => 130, + ), + 'Cham' => array( + 0 => 0xAA00, + 1 => 0xAA5F, + 2 => 131, + ), + 'Myanmar Extended-A' => array( + 0 => 0xAA60, + 1 => 0xAA7F, + 2 => 132, + ), + 'Tai Viet' => array( + 0 => 0xAA80, + 1 => 0xAADF, + 2 => 133, + ), + 'Ethiopic Extended-A' => array( + 0 => 0xAB00, + 1 => 0xAB2F, + 2 => 134, + ), + 'Meetei Mayek' => array( + 0 => 0xABC0, + 1 => 0xABFF, + 2 => 135, + ), + 'Hangul Syllables' => array( + 0 => 0xAC00, + 1 => 0xD7AF, + 2 => 136, + ), + 'Hangul Jamo Extended-B' => array( + 0 => 0xD7B0, + 1 => 0xD7FF, + 2 => 137, + ), + 'High Surrogates' => array( + 0 => 0xD800, + 1 => 0xDB7F, + 2 => 138, + ), + 'High Private Use Surrogates' => array( + 0 => 0xDB80, + 1 => 0xDBFF, + 2 => 139, + ), + 'Low Surrogates' => array( + 0 => 0xDC00, + 1 => 0xDFFF, + 2 => 140, + ), + 'Private Use Area' => array( + 0 => 0xE000, + 1 => 0xF8FF, + 2 => 141, + ), + 'CJK Compatibility Ideographs' => array( + 0 => 0xF900, + 1 => 0xFAFF, + 2 => 142, + ), + 'Alphabetic Presentation Forms' => array( + 0 => 0xFB00, + 1 => 0xFB4F, + 2 => 143, + ), + 'Arabic Presentation Forms-A' => array( + 0 => 0xFB50, + 1 => 0xFDFF, + 2 => 144, + ), + 'Variation Selectors' => array( + 0 => 0xFE00, + 1 => 0xFE0F, + 2 => 145, + ), + 'Vertical Forms' => array( + 0 => 0xFE10, + 1 => 0xFE1F, + 2 => 146, + ), + 'Combining Half Marks' => array( + 0 => 0xFE20, + 1 => 0xFE2F, + 2 => 147, + ), + 'CJK Compatibility Forms' => array( + 0 => 0xFE30, + 1 => 0xFE4F, + 2 => 148, + ), + 'Small Form Variants' => array( + 0 => 0xFE50, + 1 => 0xFE6F, + 2 => 149, + ), + 'Arabic Presentation Forms-B' => array( + 0 => 0xFE70, + 1 => 0xFEFF, + 2 => 150, + ), + 'Halfwidth and Fullwidth Forms' => array( + 0 => 0xFF00, + 1 => 0xFFEF, + 2 => 151, + ), + 'Specials' => array( + 0 => 0xFFF0, + 1 => 0xFFFF, + 2 => 152, + ), + 'Linear B Syllabary' => array( + 0 => 0x10000, + 1 => 0x1007F, + 2 => 153, + ), + 'Linear B Ideograms' => array( + 0 => 0x10080, + 1 => 0x100FF, + 2 => 154, + ), + 'Aegean Numbers' => array( + 0 => 0x10100, + 1 => 0x1013F, + 2 => 155, + ), + 'Ancient Greek Numbers' => array( + 0 => 0x10140, + 1 => 0x1018F, + 2 => 156, + ), + 'Ancient Symbols' => array( + 0 => 0x10190, + 1 => 0x101CF, + 2 => 157, + ), + 'Phaistos Disc' => array( + 0 => 0x101D0, + 1 => 0x101FF, + 2 => 158, + ), + 'Lycian' => array( + 0 => 0x10280, + 1 => 0x1029F, + 2 => 159, + ), + 'Carian' => array( + 0 => 0x102A0, + 1 => 0x102DF, + 2 => 160, + ), + 'Old Italic' => array( + 0 => 0x10300, + 1 => 0x1032F, + 2 => 161, + ), + 'Gothic' => array( + 0 => 0x10330, + 1 => 0x1034F, + 2 => 162, + ), + 'Ugaritic' => array( + 0 => 0x10380, + 1 => 0x1039F, + 2 => 163, + ), + 'Old Persian' => array( + 0 => 0x103A0, + 1 => 0x103DF, + 2 => 164, + ), + 'Deseret' => array( + 0 => 0x10400, + 1 => 0x1044F, + 2 => 165, + ), + 'Shavian' => array( + 0 => 0x10450, + 1 => 0x1047F, + 2 => 166, + ), + 'Osmanya' => array( + 0 => 0x10480, + 1 => 0x104AF, + 2 => 167, + ), + 'Cypriot Syllabary' => array( + 0 => 0x10800, + 1 => 0x1083F, + 2 => 168, + ), + 'Imperial Aramaic' => array( + 0 => 0x10840, + 1 => 0x1085F, + 2 => 169, + ), + 'Phoenician' => array( + 0 => 0x10900, + 1 => 0x1091F, + 2 => 170, + ), + 'Lydian' => array( + 0 => 0x10920, + 1 => 0x1093F, + 2 => 171, + ), + 'Kharoshthi' => array( + 0 => 0x10A00, + 1 => 0x10A5F, + 2 => 172, + ), + 'Old South Arabian' => array( + 0 => 0x10A60, + 1 => 0x10A7F, + 2 => 173, + ), + 'Avestan' => array( + 0 => 0x10B00, + 1 => 0x10B3F, + 2 => 174, + ), + 'Inscriptional Parthian' => array( + 0 => 0x10B40, + 1 => 0x10B5F, + 2 => 175, + ), + 'Inscriptional Pahlavi' => array( + 0 => 0x10B60, + 1 => 0x10B7F, + 2 => 176, + ), + 'Old Turkic' => array( + 0 => 0x10C00, + 1 => 0x10C4F, + 2 => 177, + ), + 'Rumi Numeral Symbols' => array( + 0 => 0x10E60, + 1 => 0x10E7F, + 2 => 178, + ), + 'Brahmi' => array( + 0 => 0x11000, + 1 => 0x1107F, + 2 => 179, + ), + 'Kaithi' => array( + 0 => 0x11080, + 1 => 0x110CF, + 2 => 180, + ), + 'Cuneiform' => array( + 0 => 0x12000, + 1 => 0x123FF, + 2 => 181, + ), + 'Cuneiform Numbers and Punctuation' => array( + 0 => 0x12400, + 1 => 0x1247F, + 2 => 182, + ), + 'Egyptian Hieroglyphs' => array( + 0 => 0x13000, + 1 => 0x1342F, + 2 => 183, + ), + 'Bamum Supplement' => array( + 0 => 0x16800, + 1 => 0x16A3F, + 2 => 184, + ), + 'Kana Supplement' => array( + 0 => 0x1B000, + 1 => 0x1B0FF, + 2 => 185, + ), + 'Byzantine Musical Symbols' => array( + 0 => 0x1D000, + 1 => 0x1D0FF, + 2 => 186, + ), + 'Musical Symbols' => array( + 0 => 0x1D100, + 1 => 0x1D1FF, + 2 => 187, + ), + 'Ancient Greek Musical Notation' => array( + 0 => 0x1D200, + 1 => 0x1D24F, + 2 => 188, + ), + 'Tai Xuan Jing Symbols' => array( + 0 => 0x1D300, + 1 => 0x1D35F, + 2 => 189, + ), + 'Counting Rod Numerals' => array( + 0 => 0x1D360, + 1 => 0x1D37F, + 2 => 190, + ), + 'Mathematical Alphanumeric Symbols' => array( + 0 => 0x1D400, + 1 => 0x1D7FF, + 2 => 191, + ), + 'Mahjong Tiles' => array( + 0 => 0x1F000, + 1 => 0x1F02F, + 2 => 192, + ), + 'Domino Tiles' => array( + 0 => 0x1F030, + 1 => 0x1F09F, + 2 => 193, + ), + 'Playing Cards' => array( + 0 => 0x1F0A0, + 1 => 0x1F0FF, + 2 => 194, + ), + 'Enclosed Alphanumeric Supplement' => array( + 0 => 0x1F100, + 1 => 0x1F1FF, + 2 => 195, + ), + 'Enclosed Ideographic Supplement' => array( + 0 => 0x1F200, + 1 => 0x1F2FF, + 2 => 196, + ), + 'Miscellaneous Symbols And Pictographs' => array( + 0 => 0x1F300, + 1 => 0x1F5FF, + 2 => 197, + ), + 'Emoticons' => array( + 0 => 0x1F600, + 1 => 0x1F64F, + 2 => 198, + ), + 'Transport And Map Symbols' => array( + 0 => 0x1F680, + 1 => 0x1F6FF, + 2 => 199, + ), + 'Alchemical Symbols' => array( + 0 => 0x1F700, + 1 => 0x1F77F, + 2 => 200, + ), + 'CJK Unified Ideographs Extension B' => array( + 0 => 0x20000, + 1 => 0x2A6DF, + 2 => 201, + ), + 'CJK Unified Ideographs Extension C' => array( + 0 => 0x2A700, + 1 => 0x2B73F, + 2 => 202, + ), + 'CJK Unified Ideographs Extension D' => array( + 0 => 0x2B740, + 1 => 0x2B81F, + 2 => 203, + ), + 'CJK Compatibility Ideographs Supplement' => array( + 0 => 0x2F800, + 1 => 0x2FA1F, + 2 => 204, + ), + 'Tags' => array( + 0 => 0xE0000, + 1 => 0xE007F, + 2 => 205, + ), + 'Variation Selectors Supplement' => array( + 0 => 0xE0100, + 1 => 0xE01EF, + 2 => 206, + ), + 'Supplementary Private Use Area-A' => array( + 0 => 0xF0000, + 1 => 0xFFFFF, + 2 => 207, + ), + 'Supplementary Private Use Area-B' => array( + 0 => 0x100000, + 1 => 0x10FFFF, + 2 => 208, + ), + ); - #calling the methods of this class only statically! - private function __construct() {} + #calling the methods of this class only statically! + private function __construct() + { + } - /** - * Remove combining diactrical marks, with possibility of the restore - * Удаляет диакритические знаки в тексте, с возможностью восстановления (опция) - * - * @param string|null $s - * @param array|null $additional_chars for example: "\xc2\xad" #soft hyphen = discretionary hyphen - * @param bool $is_can_restored - * @param array|null &$restore_table - * @return string|bool|null Returns FALSE if error occurred - */ - public static function diactrical_remove($s, $additional_chars = null, $is_can_restored = false, &$restore_table = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Remove combining diactrical marks, with possibility of the restore + * Удаляет диакритические знаки в тексте, с возможностью восстановления (опция) + * + * @param string|null $s + * @param array|null $additional_chars for example: "\xc2\xad" #soft hyphen = discretionary hyphen + * @param bool $is_can_restored + * @param array|null &$restore_table + * @return string|bool|null Returns FALSE if error occurred + */ + public static function diactrical_remove($s, $additional_chars = null, $is_can_restored = false, &$restore_table = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if ($additional_chars) - { - foreach ($additional_chars as $k => &$v) $v = preg_quote($v, '/'); - $re = '/((?>' . self::$diactrical_re . '|' . implode('|', $additional_chars) . ')+)/sxSX'; - } - else $re = '/((?>' . self::$diactrical_re . ')+)/sxSX'; - if (! $is_can_restored) return preg_replace($re, '', $s); + if ($additional_chars) { + foreach ($additional_chars as $k => &$v) { + $v = preg_quote($v, '/'); + } + $re = '/((?>' . self::$diactrical_re . '|' . implode('|', $additional_chars) . ')+)/sxSX'; + } else { + $re = '/((?>' . self::$diactrical_re . ')+)/sxSX'; + } + if (!$is_can_restored) { + return preg_replace($re, '', $s); + } - $restore_table = array(); - $a = preg_split($re, $s, -1, PREG_SPLIT_DELIM_CAPTURE); - $c = count($a); - if ($c === 1) return $s; - $pos = 0; - $s2 = ''; - for ($i = 0; $i < $c - 1; $i += 2) - { - $s2 .= $a[$i]; - #запоминаем символьные (не байтовые!) позиции - $pos += self::strlen($a[$i]); - $restore_table['offsets'][$pos] = $a[$i + 1]; - } - $restore_table['length'] = $pos + self::strlen(end($a)); - return $s2 . end($a); - } + $restore_table = array(); + $a = preg_split($re, $s, -1, PREG_SPLIT_DELIM_CAPTURE); + $c = count($a); + if ($c === 1) { + return $s; + } + $pos = 0; + $s2 = ''; + for ($i = 0; $i < $c - 1; $i += 2) { + $s2 .= $a[$i]; + #запоминаем символьные (не байтовые!) позиции + $pos += self::strlen($a[$i]); + $restore_table['offsets'][$pos] = $a[$i + 1]; + } + $restore_table['length'] = $pos + self::strlen(end($a)); + return $s2 . end($a); + } - /** - * Restore combining diactrical marks, removed by self::diactrical_remove() - * In Russian: - * Восстанавливает диакритические знаки в тексте, при условии, что их символьные позиции и кол-во символов не изменились! - * - * @see self::diactrical_remove() - * @param string|null $s - * @param array $restore_table - * @return string|bool|null Returns FALSE if error occurred (broken $restore_table) - */ - public static function diactrical_restore($s, array $restore_table) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Restore combining diactrical marks, removed by self::diactrical_remove() + * In Russian: + * Восстанавливает диакритические знаки в тексте, при условии, что их символьные позиции и кол-во символов не изменились! + * + * @see self::diactrical_remove() + * @param string|null $s + * @param array $restore_table + * @return string|bool|null Returns FALSE if error occurred (broken $restore_table) + */ + public static function diactrical_restore($s, array $restore_table) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if (! $restore_table) return $s; - if (! is_int(@$restore_table['length']) || - ! is_array(@$restore_table['offsets']) || - $restore_table['length'] !== self::strlen($s)) return false; - $a = array(); - $length = $offset = 0; - $s2 = ''; - foreach ($restore_table['offsets'] as $pos => $diactricals) - { - $length = $pos - $offset; - $s2 .= self::substr($s, $offset, $length) . $diactricals; - $offset = $pos; - } - return $s2 . self::substr($s, $offset, strlen($s)); - } + if (!$restore_table) { + return $s; + } + if (!is_int(@$restore_table['length']) || + !is_array(@$restore_table['offsets']) || + $restore_table['length'] !== self::strlen($s) + ) { + return false; + } + $a = array(); + $length = $offset = 0; + $s2 = ''; + foreach ($restore_table['offsets'] as $pos => $diactricals) { + $length = $pos - $offset; + $s2 .= self::substr($s, $offset, $length) . $diactricals; + $offset = $pos; + } + return $s2 . self::substr($s, $offset, strlen($s)); + } - /** - * Encodes data from another character encoding to UTF-8. - * - * @param array|scalar|null $data - * @param string $charset - * @return array|scalar|null Returns FALSE if error occurred - */ - public static function convert_from($data, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - return self::_convert($data, $charset, 'UTF-8'); - } + /** + * Encodes data from another character encoding to UTF-8. + * + * @param array|scalar|null $data + * @param string $charset + * @return array|scalar|null Returns FALSE if error occurred + */ + public static function convert_from($data, $charset = 'cp1251') + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::_convert($data, $charset, 'UTF-8'); + } - /** - * Encodes data from UTF-8 to another character encoding. - * - * @param array|scalar|null $data - * @param string $charset - * @return array|scalar|null Returns FALSE if error occurred - */ - public static function convert_to($data, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - return self::_convert($data, 'UTF-8', $charset); - } + /** + * Encodes data from UTF-8 to another character encoding. + * + * @param array|scalar|null $data + * @param string $charset + * @return array|scalar|null Returns FALSE if error occurred + */ + public static function convert_to($data, $charset = 'cp1251') + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::_convert($data, 'UTF-8', $charset); + } - /** - * Recoding the data of any structure to/from UTF-8. - * Arrays traversed recursively, recoded keys and values. - * - * @see mb_encoding_aliases() - * @param array|scalar|null $data - * @param string $charset_from - * @param string $charset_to - * @return array|scalar|null Returns FALSE if error occurred - */ - private static function _convert($data, $charset_from, $charset_to) - { - if (! ReflectionTypeHint::isValid()) return false; #for recursive calls - if ($charset_from === $charset_to) return $data; - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::_convert($k, $charset_from, $charset_to); - if ($k === false) return false; - $d[$k] = self::_convert($v, $charset_from, $charset_to); - if ($d[$k] === false && ! is_bool($v)) return false; - } - return $d; - } - if (is_string($data)) - { - #smart behaviour for errors protected + speed improve - if ($charset_from === 'UTF-8' && ! self::is_utf8($data)) return $data; - if ($charset_to === 'UTF-8' && self::is_utf8($data)) return $data; + /** + * Recoding the data of any structure to/from UTF-8. + * Arrays traversed recursively, recoded keys and values. + * + * @see mb_encoding_aliases() + * @param array|scalar|null $data + * @param string $charset_from + * @param string $charset_to + * @return array|scalar|null Returns FALSE if error occurred + */ + private static function _convert($data, $charset_from, $charset_to) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } #for recursive calls + if ($charset_from === $charset_to) { + return $data; + } + if (is_array($data)) { + $d = array(); + foreach ($data as $k => &$v) { + $k = self::_convert($k, $charset_from, $charset_to); + if ($k === false) { + return false; + } + $d[$k] = self::_convert($v, $charset_from, $charset_to); + if ($d[$k] === false && !is_bool($v)) { + return false; + } + } + return $d; + } + if (is_string($data)) { + #smart behaviour for errors protected + speed improve + if ($charset_from === 'UTF-8' && !self::is_utf8($data)) { + return $data; + } + if ($charset_to === 'UTF-8' && self::is_utf8($data)) { + return $data; + } - #since PHP-5.3.x iconv() faster then mb_convert_encoding() - if (function_exists('iconv')) return iconv($charset_from, $charset_to . '//IGNORE//TRANSLIT', $data); - if (function_exists('mb_convert_encoding')) return mb_convert_encoding($data, $charset_to, $charset_from); + #since PHP-5.3.x iconv() faster then mb_convert_encoding() + if (function_exists('iconv')) { + return iconv($charset_from, $charset_to . '//IGNORE//TRANSLIT', $data); + } + if (function_exists('mb_convert_encoding')) { + return mb_convert_encoding($data, $charset_to, $charset_from); + } - #charset_from - if ($charset_from === 'UTF-16' || $charset_from === 'UCS-2') return self::_convert_from_utf16($data); - if ($charset_from === 'cp1251' || $charset_from === 'cp1259') return strtr($data, self::$cp1259_table); - if ($charset_from === 'koi8-r' || $charset_from === 'KOI8-R') return strtr(convert_cyr_string($data, 'k', 'w'), self::$cp1259_table); - if ($charset_from === 'iso8859-5') return strtr(convert_cyr_string($data, 'i', 'w'), self::$cp1259_table); - if ($charset_from === 'cp866') return strtr(convert_cyr_string($data, 'a', 'w'), self::$cp1259_table); - if ($charset_from === 'mac-cyrillic') return strtr(convert_cyr_string($data, 'm', 'w'), self::$cp1259_table); + #charset_from + if ($charset_from === 'UTF-16' || $charset_from === 'UCS-2') { + return self::_convert_from_utf16($data); + } + if ($charset_from === 'cp1251' || $charset_from === 'cp1259') { + return strtr($data, self::$cp1259_table); + } + if ($charset_from === 'koi8-r' || $charset_from === 'KOI8-R') { + return strtr(convert_cyr_string($data, 'k', 'w'), self::$cp1259_table); + } + if ($charset_from === 'iso8859-5') { + return strtr(convert_cyr_string($data, 'i', 'w'), self::$cp1259_table); + } + if ($charset_from === 'cp866') { + return strtr(convert_cyr_string($data, 'a', 'w'), self::$cp1259_table); + } + if ($charset_from === 'mac-cyrillic') { + return strtr(convert_cyr_string($data, 'm', 'w'), self::$cp1259_table); + } - #charset_to - if ($charset_to === 'cp1251' || $charset_to === 'cp1259') return strtr($data, array_flip(self::$cp1259_table)); + #charset_to + if ($charset_to === 'cp1251' || $charset_to === 'cp1259') { + return strtr($data, array_flip(self::$cp1259_table)); + } - #last trying - if (function_exists('recode_string')) - { - $s = @recode_string($charset_from . '..' . $charset_to, $data); - if (is_string($s)) return $s; - } + #last trying + if (function_exists('recode_string')) { + $s = @recode_string($charset_from . '..' . $charset_to, $data); + if (is_string($s)) { + return $s; + } + } - trigger_error('Convert "' . $charset_from . '" --> "' . $charset_to . '" is not supported native, "iconv" or "mbstring" extension required', E_USER_WARNING); - return false; - } - return $data; - } + trigger_error('Convert "' . $charset_from . '" --> "' . $charset_to . '" is not supported native, "iconv" or "mbstring" extension required', E_USER_WARNING); + return false; + } + return $data; + } - /** - * Convert UTF-16 / UCS-2 encoding string to UTF-8. - * Surrogates UTF-16 are supported! - * - * In Russian: - * Преобразует строку из кодировки UTF-16 / UCS-2 в UTF-8. - * Суррогаты UTF-16 поддерживаются! - * - * @param string $s - * @param string $type 'BE' -- big endian byte order - * 'LE' -- little endian byte order - * @param bool $to_array returns array chars instead whole string? - * @return string|array|bool UTF-8 string, array chars or FALSE if error occurred - */ - private static function _convert_from_utf16($s, $type = 'BE', $to_array = false) - { - static $types = array( - 'BE' => 'n', #unsigned short (always 16 bit, big endian byte order) - 'LE' => 'v', #unsigned short (always 16 bit, little endian byte order) - ); - if (! array_key_exists($type, $types)) - { - trigger_error('Unexpected value in 2-nd parameter, "' . $type . '" given!', E_USER_WARNING); - return false; - } - #the fastest way: - if (function_exists('iconv') || function_exists('mb_convert_encoding')) - { - if (function_exists('iconv')) $s = iconv('UTF-16' . $type, 'UTF-8', $s); - elseif (function_exists('mb_convert_encoding')) $s = mb_convert_encoding($s, 'UTF-8', 'UTF-16' . $type); - if (! $to_array) return $s; - return self::str_split($s); - } + /** + * Convert UTF-16 / UCS-2 encoding string to UTF-8. + * Surrogates UTF-16 are supported! + * + * In Russian: + * Преобразует строку из кодировки UTF-16 / UCS-2 в UTF-8. + * Суррогаты UTF-16 поддерживаются! + * + * @param string $s + * @param string $type 'BE' -- big endian byte order + * 'LE' -- little endian byte order + * @param bool $to_array returns array chars instead whole string? + * @return string|array|bool UTF-8 string, array chars or FALSE if error occurred + */ + private static function _convert_from_utf16($s, $type = 'BE', $to_array = false) + { + static $types = array( + 'BE' => 'n', #unsigned short (always 16 bit, big endian byte order) + 'LE' => 'v', #unsigned short (always 16 bit, little endian byte order) + ); + if (!array_key_exists($type, $types)) { + trigger_error('Unexpected value in 2-nd parameter, "' . $type . '" given!', E_USER_WARNING); + return false; + } + #the fastest way: + if (function_exists('iconv') || function_exists('mb_convert_encoding')) { + if (function_exists('iconv')) { + $s = iconv('UTF-16' . $type, 'UTF-8', $s); + } elseif (function_exists('mb_convert_encoding')) { + $s = mb_convert_encoding($s, 'UTF-8', 'UTF-16' . $type); + } + if (!$to_array) { + return $s; + } + return self::str_split($s); + } - /* + /* http://en.wikipedia.org/wiki/UTF-16 The improvement that UTF-16 made over UCS-2 is its ability to encode @@ -2454,848 +2532,1041 @@ class UTF8 L = ((S - 0x10000) % 0x400) + 0xDC00; The conversion of a surrogate pair to a scalar value: N = ((H - 0xD800) * 0x400) + (L - 0xDC00) + 0x10000; - */ - $a = array(); - $hi = false; - foreach (unpack($types[$type] . '*', $s) as $codepoint) - { - #surrogate process - if ($hi !== false) - { - $lo = $codepoint; - if ($lo < 0xDC00 || $lo > 0xDFFF) $a[] = "\xEF\xBF\xBD"; #U+FFFD REPLACEMENT CHARACTER (for broken char) - else - { - $codepoint = (($hi - 0xD800) * 0x400) + ($lo - 0xDC00) + 0x10000; - $a[] = self::chr($codepoint); - } - $hi = false; - } - elseif ($codepoint < 0xD800 || $codepoint > 0xDBFF) $a[] = self::chr($codepoint); #not surrogate - else $hi = $codepoint; #surrogate was found - } - return $to_array ? $a : implode('', $a); - } + */ + $a = array(); + $hi = false; + foreach (unpack($types[$type] . '*', $s) as $codepoint) { + #surrogate process + if ($hi !== false) { + $lo = $codepoint; + if ($lo < 0xDC00 || $lo > 0xDFFF) { + $a[] = "\xEF\xBF\xBD"; + } #U+FFFD REPLACEMENT CHARACTER (for broken char) + else { + $codepoint = (($hi - 0xD800) * 0x400) + ($lo - 0xDC00) + 0x10000; + $a[] = self::chr($codepoint); + } + $hi = false; + } elseif ($codepoint < 0xD800 || $codepoint > 0xDBFF) { + $a[] = self::chr($codepoint); + } #not surrogate + else { + $hi = $codepoint; + } #surrogate was found + } + return $to_array ? $a : implode('', $a); + } - /** - * Strips out device control codes in the ASCII range. - * - * @param string|null String to clean - * @return string|bool|null Returns FALSE if error occurred - */ - public static function strict($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; - return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]+/sSX', '', $s); - } + /** + * Strips out device control codes in the ASCII range. + * + * @param string|null String to clean + * @return string|bool|null Returns FALSE if error occurred + */ + public static function strict($s) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } + return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]+/sSX', '', $s); + } - /** - * Check the data accessory to the class of characters ASCII. - * For null, integer, float, boolean returns TRUE. - * - * Массивы обходятся рекурсивно, если в хотябы одном элементе массива - * его значение не ASCII, возвращается FALSE. - * - * @param array|scalar|null $data - * @return bool - */ - public static function is_ascii($data) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::is_ascii($k) || ! self::is_ascii($v)) return false; - } - return true; - } - #ltrim() little faster then preg_match() - #if (is_string($data)) return preg_match('/^[\x00-\x7f]*$/sSX', $data); #deprecated - if (is_string($data)) return ltrim($data, "\x00..\x7f") === ''; - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } + /** + * Check the data accessory to the class of characters ASCII. + * For null, integer, float, boolean returns TRUE. + * + * Массивы обходятся рекурсивно, если в хотябы одном элементе массива + * его значение не ASCII, возвращается FALSE. + * + * @param array|scalar|null $data + * @return bool + */ + public static function is_ascii($data) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_array($data)) { + foreach ($data as $k => &$v) { + if (!self::is_ascii($k) || !self::is_ascii($v)) { + return false; + } + } + return true; + } + #ltrim() little faster then preg_match() + #if (is_string($data)) return preg_match('/^[\x00-\x7f]*$/sSX', $data); #deprecated + if (is_string($data)) { + return ltrim($data, "\x00..\x7f") === ''; + } + if (is_scalar($data) || is_null($data)) { + return true; + } #~ null, integer, float, boolean + return false; #object or resource + } - /** - * Returns true if data is valid UTF-8 and false otherwise. - * For null, integer, float, boolean returns TRUE. - * - * The arrays are traversed recursively, if At least one element of the array - * its value is not in UTF-8, returns FALSE. - * - * @link http://www.w3.org/International/questions/qa-forms-utf-8.html - * @link http://ru3.php.net/mb_detect_encoding - * @link http://webtest.philigon.ru/articles/utf8/ - * @link http://unicode.coeurlumiere.com/ - * @param array|scalar|null $data - * @param bool $is_strict strict the range of ASCII? - * @return bool - */ - public static function is_utf8($data, $is_strict = true) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::is_utf8($k, $is_strict) || ! self::is_utf8($v, $is_strict)) return false; - } - return true; - } - if (is_string($data)) - { - if (! preg_match('~~suSX', $data)) return false; - if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) return false; - #preg_match('~~suSX') much faster (up to 4 times), then mb_check_encoding($data, 'UTF-8')! - #if (function_exists('mb_check_encoding') && ! mb_check_encoding($data, 'UTF-8')) return false; #DEPRECATED - if ($is_strict && preg_match('/[^\x09\x0A\x0D\x20-\xBF\xC2-\xF7]/sSX', $data)) return false; - return true; - } - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } + /** + * Returns true if data is valid UTF-8 and false otherwise. + * For null, integer, float, boolean returns TRUE. + * + * The arrays are traversed recursively, if At least one element of the array + * its value is not in UTF-8, returns FALSE. + * + * @link http://www.w3.org/International/questions/qa-forms-utf-8.html + * @link http://ru3.php.net/mb_detect_encoding + * @link http://webtest.philigon.ru/articles/utf8/ + * @link http://unicode.coeurlumiere.com/ + * @param array|scalar|null $data + * @param bool $is_strict strict the range of ASCII? + * @return bool + */ + public static function is_utf8($data, $is_strict = true) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_array($data)) { + foreach ($data as $k => &$v) { + if (!self::is_utf8($k, $is_strict) || !self::is_utf8($v, $is_strict)) { + return false; + } + } + return true; + } + if (is_string($data)) { + if (!preg_match('~~suSX', $data)) { + return false; + } + if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) { + return false; + } + #preg_match('~~suSX') much faster (up to 4 times), then mb_check_encoding($data, 'UTF-8')! + #if (function_exists('mb_check_encoding') && ! mb_check_encoding($data, 'UTF-8')) return false; #DEPRECATED + if ($is_strict && preg_match('/[^\x09\x0A\x0D\x20-\xBF\xC2-\xF7]/sSX', $data)) { + return false; + } + return true; + } + if (is_scalar($data) || is_null($data)) { + return true; + } #~ null, integer, float, boolean + return false; #object or resource + } - /** - * Tries to detect if a string is in Unicode encoding - * - * @deprecated Slowly, use self::is_utf8() instead - * @see self::is_utf8() - * @param string $s текст - * @param bool $is_strict строгая проверка диапазона ASCII? - * @return bool - */ - public static function check($s, $is_strict = true) - { - if (! ReflectionTypeHint::isValid()) return false; - for ($i = 0, $len = strlen($s); $i < $len; $i++) - { - $c = ord($s[$i]); - if ($c < 0x80) #1 byte 0bbbbbbb - { - if ($is_strict === false || ($c > 0x1F && $c < 0x7F) || $c == 0x09 || $c == 0x0A || $c == 0x0D) continue; - } - if (($c & 0xE0) == 0xC0) $n = 1; #2 bytes 110bbbbb 10bbbbbb - elseif (($c & 0xF0) == 0xE0) $n = 2; #3 bytes 1110bbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xF8) == 0xF0) $n = 3; #4 bytes 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xFC) == 0xF8) $n = 4; #5 bytes 111110bb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb - elseif (($c & 0xFE) == 0xFC) $n = 5; #6 bytes 1111110b 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb - else return false; #does not match any model - #n bytes matching 10bbbbbb follow ? - for ($j = 0; $j < $n; $j++) - { - $i++; - if ($i == $len || ((ord($s[$i]) & 0xC0) != 0x80) ) return false; - } - } - return true; - } + /** + * Tries to detect if a string is in Unicode encoding + * + * @deprecated Slowly, use self::is_utf8() instead + * @see self::is_utf8() + * @param string $s текст + * @param bool $is_strict строгая проверка диапазона ASCII? + * @return bool + */ + public static function check($s, $is_strict = true) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + for ($i = 0, $len = strlen($s); $i < $len; $i++) { + $c = ord($s[$i]); + if ($c < 0x80) { + #1 byte 0bbbbbbb - /** - * Check the data in UTF-8 charset on given ranges of the standard UNICODE. - * The suitable alternative to regular expressions. - * - * For null, integer, float, boolean returns TRUE. - * - * Arrays traversed recursively (keys and values). - * At least if one array element value is not passed checking, it returns FALSE. - * - * @example - * #A simple check the standard named ranges: - * UTF8::blocks_check('поисковые системы Google и Yandex', array('Basic Latin', 'Cyrillic')); - * #You can check the named, direct ranges or codepoints together: - * UTF8::blocks_check('поисковые системы Google и Yandex', array(array(0x20, 0x7E), #[\x20-\x7E] - * array(0x0410, 0x044F), #[A-Яa-я] - * 0x0401, #russian yo (Ё) - * 0x0451, #russian ye (ё) - * 'Arrows', - * )); - * - * @link http://www.unicode.org/charts/ - * @param array|scalar|null $data - * @param array|string $blocks - * @return bool Возвращает TRUE, если все символы из текста принадлежат указанным диапазонам - * и FALSE в противном случае или для разбитого UTF-8. - */ - public static function blocks_check($data, $blocks) - { - if (! ReflectionTypeHint::isValid()) return false; + if ($is_strict === false || ($c > 0x1F && $c < 0x7F) || $c == 0x09 || $c == 0x0A || $c == 0x0D) { + continue; + } + } + if (($c & 0xE0) == 0xC0) { + $n = 1; + } #2 bytes 110bbbbb 10bbbbbb + elseif (($c & 0xF0) == 0xE0) { + $n = 2; + } #3 bytes 1110bbbb 10bbbbbb 10bbbbbb + elseif (($c & 0xF8) == 0xF0) { + $n = 3; + } #4 bytes 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + elseif (($c & 0xFC) == 0xF8) { + $n = 4; + } #5 bytes 111110bb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb + elseif (($c & 0xFE) == 0xFC) { + $n = 5; + } #6 bytes 1111110b 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb 10bbbbbb + else { + return false; + } #does not match any model + #n bytes matching 10bbbbbb follow ? + for ($j = 0; $j < $n; $j++) { + $i++; + if ($i == $len || ((ord($s[$i]) & 0xC0) != 0x80)) { + return false; + } + } + } + return true; + } - if (is_array($data)) - { - foreach ($data as $k => &$v) - { - if (! self::blocks_check($k, $blocks) || ! self::blocks_check($v, $blocks)) return false; - } - return true; - } + /** + * Check the data in UTF-8 charset on given ranges of the standard UNICODE. + * The suitable alternative to regular expressions. + * + * For null, integer, float, boolean returns TRUE. + * + * Arrays traversed recursively (keys and values). + * At least if one array element value is not passed checking, it returns FALSE. + * + * @example + * #A simple check the standard named ranges: + * UTF8::blocks_check('поисковые системы Google и Yandex', array('Basic Latin', 'Cyrillic')); + * #You can check the named, direct ranges or codepoints together: + * UTF8::blocks_check('поисковые системы Google и Yandex', array(array(0x20, 0x7E), #[\x20-\x7E] + * array(0x0410, 0x044F), #[A-Яa-я] + * 0x0401, #russian yo (Ё) + * 0x0451, #russian ye (ё) + * 'Arrows', + * )); + * + * @link http://www.unicode.org/charts/ + * @param array|scalar|null $data + * @param array|string $blocks + * @return bool Возвращает TRUE, если все символы из текста принадлежат указанным диапазонам + * и FALSE в противном случае или для разбитого UTF-8. + */ + public static function blocks_check($data, $blocks) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } - if (is_string($data)) - { - $chars = self::str_split($data); - if ($chars === false) return false; #broken UTF-8 - unset($data); #memory free - $skip = array(); #save to cache already checked symbols - foreach ($chars as $i => $char) - { - if (array_key_exists($char, $skip)) continue; #speed improve - $codepoint = self::ord($char); - if ($codepoint === false) return false; #broken UTF-8 - $is_valid = false; - $blocks = (array)$blocks; - foreach ($blocks as $j => $block) - { - if (is_string($block)) - { - if (! array_key_exists($block, self::$unicode_blocks)) - { - trigger_error('Unknown block "' . $block . '"!', E_USER_WARNING); - return false; - } - list ($min, $max) = self::$unicode_blocks[$block]; - } - elseif (is_array($block)) list ($min, $max) = $block; - elseif (is_int($block)) $min = $max = $block; - else trigger_error('A string/array/int type expected for block[' . $j . ']!', E_USER_ERROR); - if ($codepoint >= $min && $codepoint <= $max) - { - $is_valid = true; - break; - } - }#foreach - if (! $is_valid) return false; - $skip[$char] = null; - }#foreach - return true; - } - if (is_scalar($data) || is_null($data)) return true; #~ null, integer, float, boolean - return false; #object or resource - } + if (is_array($data)) { + foreach ($data as $k => &$v) { + if (!self::blocks_check($k, $blocks) || !self::blocks_check($v, $blocks)) { + return false; + } + } + return true; + } - /** - * Recode $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES from $charset encoding to UTF-8, if necessary. - * A side effect is a positive protection against XSS attacks with non-printable characters on the vulnerable PHP function. - * Thus web forms can be sent to the server in 2-encoding: $charset and UTF-8. - * For example: ?тест[тест]=тест - * - * Алгоритм работы: - * 1) Функция проверяет массивы $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES - * на корректность значений элементов кодировке UTF-8. - * 2) Значения не в UTF-8 принимаются как $charset и конвертируется в UTF-8, - * при этом байты от 0x00 до 0x7F (ASCII) сохраняются как есть. - * 3) Сконвертированные значения снова проверяются. - * Если данные опять не в кодировке UTF-8, то они считаются разбитыми и функция возвращает FALSE. - * - * NOTICE - * Функция должна вызываться после self::unescape_request()! - * - * @see self::unescape_request() - * @param bool $is_hex2bin Декодировать HEX-данные? - * Пример: 0xd09ec2a0d0bad0bed0bcd0bfd0b0d0bdd0b8d0b8 => О компании - * Параметры в URL адресах иногда бывает удобно кодировать не функцией rawurlencode(), - * а использовать следующий механизм (к тому же кодирующий данные более компактно): - * '0x' . bin2hex($string) - * @param string $charset - * @return bool Возвращает TRUE, если все значения элементов массивов в кодировке UTF-8 - * и FALSE + E_USER_WARNING в противном случае. - */ - public static function autoconvert_request($is_hex2bin = false, $charset = 'cp1251') - { - if (! ReflectionTypeHint::isValid()) return false; - $is_converted = false; - $is_broken = false; - foreach (array('_GET', '_POST', '_COOKIE', '_FILES') as $k => $v) - { - if (! array_key_exists($v, $GLOBALS)) continue; - #использовать array_walk_recursive() не предоставляется возможным, - #т.к. его callback функция не поддерживает передачу ключа по ссылке - $GLOBALS[$v] = self::_autoconvert_request_recursive($GLOBALS[$v], $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) - { - trigger_error('Array $' . $v . ' does not have keys/values in UTF-8 charset!', E_USER_WARNING); - return false; - } - } - if ($is_converted) - { - $_REQUEST = - (isset($_COOKIE) ? $_COOKIE : array()) + - (isset($_POST) ? $_POST : array()) + - (isset($_GET) ? $_GET : array()); - } - return true; - } + if (is_string($data)) { + $chars = self::str_split($data); + if ($chars === false) { + return false; + } #broken UTF-8 + unset($data); #memory free + $skip = array(); #save to cache already checked symbols + foreach ($chars as $i => $char) { + if (array_key_exists($char, $skip)) { + continue; + } #speed improve + $codepoint = self::ord($char); + if ($codepoint === false) { + return false; + } #broken UTF-8 + $is_valid = false; + $blocks = (array)$blocks; + foreach ($blocks as $j => $block) { + if (is_string($block)) { + if (!array_key_exists($block, self::$unicode_blocks)) { + trigger_error('Unknown block "' . $block . '"!', E_USER_WARNING); + return false; + } + list($min, $max) = self::$unicode_blocks[$block]; + } elseif (is_array($block)) { + list($min, $max) = $block; + } elseif (is_int($block)) { + $min = $max = $block; + } else { + trigger_error('A string/array/int type expected for block[' . $j . ']!', E_USER_ERROR); + } + if ($codepoint >= $min && $codepoint <= $max) { + $is_valid = true; + break; + } + }#foreach + if (!$is_valid) { + return false; + } + $skip[$char] = null; + }#foreach + return true; + } + if (is_scalar($data) || is_null($data)) { + return true; + } #~ null, integer, float, boolean + return false; #object or resource + } - private static function _autoconvert_request_recursive(&$data, &$is_converted, &$is_broken, $is_hex2bin, $charset) - { - if ($is_broken) return $data; #speed improve - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::_autoconvert_request($k, $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) return $data; #speed improve - $d[$k] = self::_autoconvert_request_recursive($v, $is_converted, $is_broken, $is_hex2bin, $charset); - if ($is_broken) return $data; #speed improve - } - return $d; - } - return self::_autoconvert_request($data, $is_converted, $is_broken, $is_hex2bin, $charset); - } + /** + * Recode $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES from $charset encoding to UTF-8, if necessary. + * A side effect is a positive protection against XSS attacks with non-printable characters on the vulnerable PHP function. + * Thus web forms can be sent to the server in 2-encoding: $charset and UTF-8. + * For example: ?тест[тест]=тест + * + * Алгоритм работы: + * 1) Функция проверяет массивы $_GET, $_POST, $_COOKIE, $_REQUEST, $_FILES + * на корректность значений элементов кодировке UTF-8. + * 2) Значения не в UTF-8 принимаются как $charset и конвертируется в UTF-8, + * при этом байты от 0x00 до 0x7F (ASCII) сохраняются как есть. + * 3) Сконвертированные значения снова проверяются. + * Если данные опять не в кодировке UTF-8, то они считаются разбитыми и функция возвращает FALSE. + * + * NOTICE + * Функция должна вызываться после self::unescape_request()! + * + * @see self::unescape_request() + * @param bool $is_hex2bin Декодировать HEX-данные? + * Пример: 0xd09ec2a0d0bad0bed0bcd0bfd0b0d0bdd0b8d0b8 => О компании + * Параметры в URL адресах иногда бывает удобно кодировать не функцией rawurlencode(), + * а использовать следующий механизм (к тому же кодирующий данные более компактно): + * '0x' . bin2hex($string) + * @param string $charset + * @return bool Возвращает TRUE, если все значения элементов массивов в кодировке UTF-8 + * и FALSE + E_USER_WARNING в противном случае. + */ + public static function autoconvert_request($is_hex2bin = false, $charset = 'cp1251') + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + $is_converted = false; + $is_broken = false; + foreach (array('_GET', '_POST', '_COOKIE', '_FILES') as $k => $v) { + if (!array_key_exists($v, $GLOBALS)) { + continue; + } + #использовать array_walk_recursive() не предоставляется возможным, + #т.к. его callback функция не поддерживает передачу ключа по ссылке + $GLOBALS[$v] = self::_autoconvert_request_recursive($GLOBALS[$v], $is_converted, $is_broken, $is_hex2bin, $charset); + if ($is_broken) { + trigger_error('Array $' . $v . ' does not have keys/values in UTF-8 charset!', E_USER_WARNING); + return false; + } + } + if ($is_converted) { + $_REQUEST = + (isset($_COOKIE) ? $_COOKIE : array()) + + (isset($_POST) ? $_POST : array()) + + (isset($_GET) ? $_GET : array()); + } + return true; + } - private static function _autoconvert_request(&$s, &$is_converted, &$is_broken, $is_hex2bin, $charset) - { - #regexp speed improve by using strpos() - if ($is_hex2bin && strpos($s, '0x') === 0 && preg_match('/^0x((?:[\da-fA-F]{2})+)$/sSX', $s, $m)) - { - $s = pack('H' . strlen($m[1]), $m[1]); #hex2bin() - $is_converted = true; - } - if (! self::is_utf8($s)) - { - $s = self::convert_from($s, $charset); - if ($s === false) $is_broken = true; - elseif (! self::is_utf8($s)) - { - trigger_error('String 0x ' . substr(bin2hex($s), 0, 100) . '... is not UTF-8!', E_USER_WARNING); - $is_broken = true; - } - else $is_converted = true; - } - return $s; - } + private static function _autoconvert_request_recursive(&$data, &$is_converted, &$is_broken, $is_hex2bin, $charset) + { + if ($is_broken) { + return $data; + } #speed improve + if (is_array($data)) { + $d = array(); + foreach ($data as $k => &$v) { + $k = self::_autoconvert_request($k, $is_converted, $is_broken, $is_hex2bin, $charset); + if ($is_broken) { + return $data; + } #speed improve + $d[$k] = self::_autoconvert_request_recursive($v, $is_converted, $is_broken, $is_hex2bin, $charset); + if ($is_broken) { + return $data; + } #speed improve + } + return $d; + } + return self::_autoconvert_request($data, $is_converted, $is_broken, $is_hex2bin, $charset); + } - /** - * Сравнение строк - * - * @param string|null $s1 - * @param string|null $s2 - * @param string $locale For example, 'en_CA', 'ru_RU' - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strcmp($s1, $s2, $locale = '') - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - if (! function_exists('collator_create')) return strcmp($s1, $s2); - # PHP 5 >= 5.3.0, PECL intl >= 1.0.0 - # If empty string ("") or "root" are passed, UCA rules will be used. - $c = new Collator($locale); - if (! $c) - { - # Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened. - trigger_error(intl_get_error_message(), E_USER_WARNING); - return false; - } - return $c->compare($s1, $s2); - } + private static function _autoconvert_request(&$s, &$is_converted, &$is_broken, $is_hex2bin, $charset) + { + #regexp speed improve by using strpos() + if ($is_hex2bin && strpos($s, '0x') === 0 && preg_match('/^0x((?:[\da-fA-F]{2})+)$/sSX', $s, $m)) { + $s = pack('H' . strlen($m[1]), $m[1]); #hex2bin() + $is_converted = true; + } + if (!self::is_utf8($s)) { + $s = self::convert_from($s, $charset); + if ($s === false) { + $is_broken = true; + } elseif (!self::is_utf8($s)) { + trigger_error('String 0x ' . substr(bin2hex($s), 0, 100) . '... is not UTF-8!', E_USER_WARNING); + $is_broken = true; + } else { + $is_converted = true; + } + } + return $s; + } - /** - * Сравнение строк для N первых символов - * - * @param string|null $s1 - * @param string|null $s2 - * @param int $length - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strncmp($s1, $s2, $length) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - return self::strcmp(self::substr($s1, 0, $length), self::substr($s2, 0, $length)); - } + /** + * Сравнение строк + * + * @param string|null $s1 + * @param string|null $s2 + * @param string $locale For example, 'en_CA', 'ru_RU' + * @return int|bool|null Returns FALSE if error occurred + * Returns < 0 if $s1 is less than $s2; + * > 0 if $s1 is greater than $s2; + * 0 if they are equal. + */ + public static function strcmp($s1, $s2, $locale = '') + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s1) || is_null($s2)) { + return null; + } + if (!function_exists('collator_create')) { + return strcmp($s1, $s2); + } + # PHP 5 >= 5.3.0, PECL intl >= 1.0.0 + # If empty string ("") or "root" are passed, UCA rules will be used. + $c = new Collator($locale); + if (!$c) { + # Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened. + trigger_error(intl_get_error_message(), E_USER_WARNING); + return false; + } + return $c->compare($s1, $s2); + } - /** - * Implementation strcasecmp() function for UTF-8 encoding string. - * - * @param string|null $s1 - * @param string|null $s2 - * @return int|bool|null Returns FALSE if error occurred - * Returns < 0 if $s1 is less than $s2; - * > 0 if $s1 is greater than $s2; - * 0 if they are equal. - */ - public static function strcasecmp($s1, $s2) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s1) || is_null($s2)) return null; - return self::strcmp(self::lowercase($s1), self::lowercase($s2)); - } + /** + * Сравнение строк для N первых символов + * + * @param string|null $s1 + * @param string|null $s2 + * @param int $length + * @return int|bool|null Returns FALSE if error occurred + * Returns < 0 if $s1 is less than $s2; + * > 0 if $s1 is greater than $s2; + * 0 if they are equal. + */ + public static function strncmp($s1, $s2, $length) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s1) || is_null($s2)) { + return null; + } + return self::strcmp(self::substr($s1, 0, $length), self::substr($s2, 0, $length)); + } - /** - * Converts a UTF-8 string to a UNICODE codepoints - * - * @param string|null $s UTF-8 string - * @return array|bool|null Unicode codepoints - * Returns FALSE if $s broken (not UTF-8) - */ - public static function to_unicode($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Implementation strcasecmp() function for UTF-8 encoding string. + * + * @param string|null $s1 + * @param string|null $s2 + * @return int|bool|null Returns FALSE if error occurred + * Returns < 0 if $s1 is less than $s2; + * > 0 if $s1 is greater than $s2; + * 0 if they are equal. + */ + public static function strcasecmp($s1, $s2) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s1) || is_null($s2)) { + return null; + } + return self::strcmp(self::lowercase($s1), self::lowercase($s2)); + } - $s2 = null; - #since PHP-5.3.x iconv() little faster then mb_convert_encoding() - if (function_exists('iconv')) $s2 = @iconv('UTF-8', 'UCS-4BE', $s); - elseif (function_exists('mb_convert_encoding')) $s2 = @mb_convert_encoding($s, 'UCS-4BE', 'UTF-8'); - if (is_string($s2)) return array_values(unpack('N*', $s2)); - if ($s2 !== null) return false; + /** + * Converts a UTF-8 string to a UNICODE codepoints + * + * @param string|null $s UTF-8 string + * @return array|bool|null Unicode codepoints + * Returns FALSE if $s broken (not UTF-8) + */ + public static function to_unicode($s) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - $a = self::str_split($s); - if ($a === false) return false; - return array_map(array(__CLASS__, 'ord'), $a); - } + $s2 = null; + #since PHP-5.3.x iconv() little faster then mb_convert_encoding() + if (function_exists('iconv')) { + $s2 = @iconv('UTF-8', 'UCS-4BE', $s); + } elseif (function_exists('mb_convert_encoding')) { + $s2 = @mb_convert_encoding($s, 'UCS-4BE', 'UTF-8'); + } + if (is_string($s2)) { + return array_values(unpack('N*', $s2)); + } + if ($s2 !== null) { + return false; + } - /** - * Converts a UNICODE codepoints to a UTF-8 string - * - * @param array|null $a Unicode codepoints - * @return string|bool|null UTF-8 string - * Returns FALSE if error occurred - */ - public static function from_unicode($a) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($a)) return $a; + $a = self::str_split($s); + if ($a === false) { + return false; + } + return array_map(array(__CLASS__, 'ord'), $a); + } - #since PHP-5.3.x iconv() little faster then mb_convert_encoding() - if (function_exists('iconv')) - { - array_walk($a, function(&$cp) { $cp = pack('N', $cp); }); - $s = @iconv('UCS-4BE', 'UTF-8', implode('', $a)); - if (! is_string($s)) return false; - return $s; - } - if (function_exists('mb_convert_encoding')) - { - array_walk($a, function(&$cp) { $cp = pack('N', $cp); }); - $s = mb_convert_encoding(implode('', $a), 'UTF-8', 'UCS-4BE'); - if (! is_string($s)) return false; - return $s; - } + /** + * Converts a UNICODE codepoints to a UTF-8 string + * + * @param array|null $a Unicode codepoints + * @return string|bool|null UTF-8 string + * Returns FALSE if error occurred + */ + public static function from_unicode($a) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($a)) { + return $a; + } - return implode('', array_map(array(__CLASS__, 'chr'), $a)); - } + #since PHP-5.3.x iconv() little faster then mb_convert_encoding() + if (function_exists('iconv')) { + array_walk($a, function (&$cp) { + $cp = pack('N', $cp); + }); + $s = @iconv('UCS-4BE', 'UTF-8', implode('', $a)); + if (!is_string($s)) { + return false; + } + return $s; + } + if (function_exists('mb_convert_encoding')) { + array_walk($a, function (&$cp) { + $cp = pack('N', $cp); + }); + $s = mb_convert_encoding(implode('', $a), 'UTF-8', 'UCS-4BE'); + if (!is_string($s)) { + return false; + } + return $s; + } - /** - * Converts a UTF-8 character to a UNICODE codepoint - * - * @param string|null $char UTF-8 character - * @return int|bool|null Unicode codepoint - * Returns FALSE if $char broken (not UTF-8) - */ - public static function ord($char) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($char)) return $char; + return implode('', array_map(array(__CLASS__, 'chr'), $a)); + } - static $cache = array(); - if (array_key_exists($char, $cache)) return $cache[$char]; #speed improve + /** + * Converts a UTF-8 character to a UNICODE codepoint + * + * @param string|null $char UTF-8 character + * @return int|bool|null Unicode codepoint + * Returns FALSE if $char broken (not UTF-8) + */ + public static function ord($char) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($char)) { + return $char; + } - switch (strlen($char)) - { - case 1 : return $cache[$char] = ord($char); - case 2 : return $cache[$char] = (ord($char{1}) & 63) | - ((ord($char{0}) & 31) << 6); - case 3 : return $cache[$char] = (ord($char{2}) & 63) | - ((ord($char{1}) & 63) << 6) | - ((ord($char{0}) & 15) << 12); - case 4 : return $cache[$char] = (ord($char{3}) & 63) | - ((ord($char{2}) & 63) << 6) | - ((ord($char{1}) & 63) << 12) | - ((ord($char{0}) & 7) << 18); - default : - trigger_error('Character 0x' . bin2hex($char) . ' is not UTF-8!', E_USER_WARNING); - return false; - } - } + static $cache = array(); + if (array_key_exists($char, $cache)) { + return $cache[$char]; + } #speed improve - /** - * Converts a UNICODE codepoint to a UTF-8 character - * - * @param int|digit|null $cp Unicode codepoint - * @return string|bool|null UTF-8 character - * Returns FALSE if error occurred - */ - public static function chr($cp) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($cp)) return $cp; + switch (strlen($char)) { + case 1 : + return $cache[$char] = ord($char); + case 2 : + return $cache[$char] = (ord($char{1}) & 63) | + ((ord($char{0}) & 31) << 6); + case 3 : + return $cache[$char] = (ord($char{2}) & 63) | + ((ord($char{1}) & 63) << 6) | + ((ord($char{0}) & 15) << 12); + case 4 : + return $cache[$char] = (ord($char{3}) & 63) | + ((ord($char{2}) & 63) << 6) | + ((ord($char{1}) & 63) << 12) | + ((ord($char{0}) & 7) << 18); + default : + trigger_error('Character 0x' . bin2hex($char) . ' is not UTF-8!', E_USER_WARNING); + return false; + } + } - static $cache = array(); - if (array_key_exists($cp, $cache)) return $cache[$cp]; #speed improve + /** + * Converts a UNICODE codepoint to a UTF-8 character + * + * @param int|digit|null $cp Unicode codepoint + * @return string|bool|null UTF-8 character + * Returns FALSE if error occurred + */ + public static function chr($cp) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($cp)) { + return $cp; + } - if ($cp <= 0x7f) return $cache[$cp] = chr($cp); - if ($cp <= 0x7ff) return $cache[$cp] = chr(0xc0 | ($cp >> 6)) . - chr(0x80 | ($cp & 0x3f)); - if ($cp <= 0xffff) return $cache[$cp] = chr(0xe0 | ($cp >> 12)) . - chr(0x80 | (($cp >> 6) & 0x3f)) . - chr(0x80 | ($cp & 0x3f)); - if ($cp <= 0x10ffff) return $cache[$cp] = chr(0xf0 | ($cp >> 18)) . - chr(0x80 | (($cp >> 12) & 0x3f)) . - chr(0x80 | (($cp >> 6) & 0x3f)) . - chr(0x80 | ($cp & 0x3f)); - #U+FFFD REPLACEMENT CHARACTER - return $cache[$cp] = "\xEF\xBF\xBD"; - } + static $cache = array(); + if (array_key_exists($cp, $cache)) { + return $cache[$cp]; + } #speed improve - /** - * Implementation chunk_split() function for UTF-8 encoding string. - * - * @param string|null $s - * @param int|digit|null $length - * @param string|null $glue - * @return string|bool|null Returns FALSE if error occurred - */ - public static function chunk_split($s, $length = null, $glue = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + if ($cp <= 0x7f) { + return $cache[$cp] = chr($cp); + } + if ($cp <= 0x7ff) { + return $cache[$cp] = chr(0xc0 | ($cp >> 6)) . + chr(0x80 | ($cp & 0x3f)); + } + if ($cp <= 0xffff) { + return $cache[$cp] = chr(0xe0 | ($cp >> 12)) . + chr(0x80 | (($cp >> 6) & 0x3f)) . + chr(0x80 | ($cp & 0x3f)); + } + if ($cp <= 0x10ffff) { + return $cache[$cp] = chr(0xf0 | ($cp >> 18)) . + chr(0x80 | (($cp >> 12) & 0x3f)) . + chr(0x80 | (($cp >> 6) & 0x3f)) . + chr(0x80 | ($cp & 0x3f)); + } + #U+FFFD REPLACEMENT CHARACTER + return $cache[$cp] = "\xEF\xBF\xBD"; + } - $length = intval($length); - $glue = strval($glue); - if ($length < 1) $length = 76; - if ($glue === '') $glue = "\r\n"; - if (! is_array($a = self::str_split($s, $length))) return false; - return implode($glue, $a); - } + /** + * Implementation chunk_split() function for UTF-8 encoding string. + * + * @param string|null $s + * @param int|digit|null $length + * @param string|null $glue + * @return string|bool|null Returns FALSE if error occurred + */ + public static function chunk_split($s, $length = null, $glue = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - /** - * Changes all keys in an array - * - * @param array|null $a - * @param int $mode {CASE_LOWER|CASE_UPPER} - * @return array|bool|null Returns FALSE if error occurred - */ - public static function array_change_key_case($a, $mode) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_array($a)) return $a; - $a2 = array(); - foreach ($a as $k => $v) - { - if (is_string($k)) - { - $k = self::convert_case($k, $mode); - if ($k === false) return false; - } - $a2[$k] = $v; - } - return $a2; - } + $length = intval($length); + $glue = strval($glue); + if ($length < 1) { + $length = 76; + } + if ($glue === '') { + $glue = "\r\n"; + } + if (!is_array($a = self::str_split($s, $length))) { + return false; + } + return implode($glue, $a); + } - /** - * Конвертирует регистр букв в данных в кодировке UTF-8. - * Массивы обходятся рекурсивно, при этом конвертируются только значения - * в элементах массива, а ключи остаются без изменений. - * Для конвертирования только ключей используйте метод self::array_change_key_case(). - * - * @see self::array_change_key_case() - * @link http://www.unicode.org/charts/PDF/U0400.pdf - * @link http://ru.wikipedia.org/wiki/ISO_639-1 - * @param array|scalar|null $data Данные произвольной структуры - * @param int $mode {CASE_LOWER|CASE_UPPER} - * @param bool $is_ascii_optimization for speed improve - * @return scalar|bool|null Returns FALSE if error occurred - */ - public static function convert_case($data, $mode, $is_ascii_optimization = true) - { - if (! ReflectionTypeHint::isValid()) return false; + /** + * Changes all keys in an array + * + * @param array|null $a + * @param int $mode {CASE_LOWER|CASE_UPPER} + * @return array|bool|null Returns FALSE if error occurred + */ + public static function array_change_key_case($a, $mode) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (!is_array($a)) { + return $a; + } + $a2 = array(); + foreach ($a as $k => $v) { + if (is_string($k)) { + $k = self::convert_case($k, $mode); + if ($k === false) { + return false; + } + } + $a2[$k] = $v; + } + return $a2; + } - if (is_array($data)) - { - foreach ($data as $k => &$v) $v = self::convert_case($v, $mode); - return $data; - } - if (! is_string($data) || ! $data) return $data; + /** + * Конвертирует регистр букв в данных в кодировке UTF-8. + * Массивы обходятся рекурсивно, при этом конвертируются только значения + * в элементах массива, а ключи остаются без изменений. + * Для конвертирования только ключей используйте метод self::array_change_key_case(). + * + * @see self::array_change_key_case() + * @link http://www.unicode.org/charts/PDF/U0400.pdf + * @link http://ru.wikipedia.org/wiki/ISO_639-1 + * @param array|scalar|null $data Данные произвольной структуры + * @param int $mode {CASE_LOWER|CASE_UPPER} + * @param bool $is_ascii_optimization for speed improve + * @return scalar|bool|null Returns FALSE if error occurred + */ + public static function convert_case($data, $mode, $is_ascii_optimization = true) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } - if ($mode === CASE_UPPER) - { - if ($is_ascii_optimization && self::is_ascii($data)) return strtoupper($data); #speed improve! - #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() - #if (function_exists('mb_strtoupper')) return mb_strtoupper($data, 'utf-8'); - return strtr($data, array_flip(self::$convert_case_table)); - } - if ($mode === CASE_LOWER) - { - if ($is_ascii_optimization && self::is_ascii($data)) return strtolower($data); #speed improve! - #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() - #if (function_exists('mb_strtolower')) return mb_strtolower($data, 'utf-8'); - return strtr($data, self::$convert_case_table); - } - trigger_error('Parameter 2 should be a constant of CASE_LOWER or CASE_UPPER!', E_USER_WARNING); - return $data; - } + if (is_array($data)) { + foreach ($data as $k => &$v) { + $v = self::convert_case($v, $mode); + } + return $data; + } + if (!is_string($data) || !$data) { + return $data; + } - /** - * Convert a data to lower case - * - * @param array|scalar|null $data - * @return scalar|bool|null Returns FALSE if error occurred */ - public static function lowercase($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_LOWER); - } + if ($mode === CASE_UPPER) { + if ($is_ascii_optimization && self::is_ascii($data)) { + return strtoupper($data); + } #speed improve! + #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() + #if (function_exists('mb_strtoupper')) return mb_strtoupper($data, 'utf-8'); + return strtr($data, array_flip(self::$convert_case_table)); + } + if ($mode === CASE_LOWER) { + if ($is_ascii_optimization && self::is_ascii($data)) { + return strtolower($data); + } #speed improve! + #deprecated, since PHP-5.3.x strtr() 2-3 times faster then mb_strtolower() + #if (function_exists('mb_strtolower')) return mb_strtolower($data, 'utf-8'); + return strtr($data, self::$convert_case_table); + } + trigger_error('Parameter 2 should be a constant of CASE_LOWER or CASE_UPPER!', E_USER_WARNING); + return $data; + } - /** - * Convert a data to upper case - * - * @param array|scalar|null $data - * @return scalar|null Returns FALSE if error occurred - */ - public static function uppercase($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_UPPER); - } + /** + * Convert a data to lower case + * + * @param array|scalar|null $data + * @return scalar|bool|null Returns FALSE if error occurred + */ + public static function lowercase($data) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::convert_case($data, CASE_LOWER); + } - /** - * Convert a data to lower case - * - * @param array|scalar|null $data - * @return scalar|bool|null Returns FALSE if error occurred - */ - public static function strtolower($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_LOWER); - } + /** + * Convert a data to upper case + * + * @param array|scalar|null $data + * @return scalar|null Returns FALSE if error occurred + */ + public static function uppercase($data) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::convert_case($data, CASE_UPPER); + } - /** - * Convert a data to upper case - * - * @param array|scalar|null $data - * @return scalar|null Returns FALSE if error occurred - */ - public static function strtoupper($data) - { - if (! ReflectionTypeHint::isValid()) return false; - return self::convert_case($data, CASE_UPPER); - } + /** + * Convert a data to lower case + * + * @param array|scalar|null $data + * @return scalar|bool|null Returns FALSE if error occurred + */ + public static function strtolower($data) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::convert_case($data, CASE_LOWER); + } - /** - * Convert all HTML entities to native UTF-8 characters - * Функция декодирует гораздо больше именованных сущностей, чем стандартная html_entity_decode() - * Все dec и hex сущности так же переводятся в UTF-8. - * - * Example: '"' or '"' or '"' will be converted to '"'. - * - * @link http://www.htmlhelp.com/reference/html40/entities/ - * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true - * - * @param scalar|null $s - * @param bool $is_special_chars Дополнительно обрабатывать специальные html сущности? (< > & ") - * @return scalar|null Returns FALSE if error occurred - */ - public static function html_entity_decode($s, $is_special_chars = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; + /** + * Convert a data to upper case + * + * @param array|scalar|null $data + * @return scalar|null Returns FALSE if error occurred + */ + public static function strtoupper($data) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + return self::convert_case($data, CASE_UPPER); + } - #speed improve - if (strlen($s) < 4 #по минимальной длине сущности - 4 байта: &#d; &xx; - || ($pos = strpos($s, '&') === false) || strpos($s, ';', $pos) === false) return $s; + /** + * Convert all HTML entities to native UTF-8 characters + * Функция декодирует гораздо больше именованных сущностей, чем стандартная html_entity_decode() + * Все dec и hex сущности так же переводятся в UTF-8. + * + * Example: '"' or '"' or '"' will be converted to '"'. + * + * @link http://www.htmlhelp.com/reference/html40/entities/ + * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true + * + * @param scalar|null $s + * @param bool $is_special_chars Дополнительно обрабатывать специальные html сущности? (< > & ") + * @return scalar|null Returns FALSE if error occurred + */ + public static function html_entity_decode($s, $is_special_chars = false) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (!is_string($s)) { + return $s; + } - $table = self::$html_entity_table; - if ($is_special_chars) $table += self::$html_special_chars_table; + #speed improve + if (strlen($s) < 4 #по минимальной длине сущности - 4 байта: &#d; &xx; + || ($pos = strpos($s, '&') === false) || strpos($s, ';', $pos) === false + ) { + return $s; + } - #replace named entities - $s = strtr($s, $table); - #block below deprecated, since PHP-5.3.x strtr() 1.5 times faster - if (0 && preg_match_all('/&[a-zA-Z]++\d*+;/sSX', $s, $m, null, $pos)) - { - foreach (array_unique($m[0]) as $entity) - { - if (array_key_exists($entity, $table)) $s = str_replace($entity, $table[$entity], $s); - } - } + $table = self::$html_entity_table; + if ($is_special_chars) { + $table += self::$html_special_chars_table; + } - #заменяем числовые dec и hex сущности: - if (strpos($s, '&#') !== false) #speed improve - { - $class = __CLASS__; - $html_special_chars_table_flipped = array_flip(self::$html_special_chars_table); - $s = preg_replace_callback('/&#((x)[\da-fA-F]{1,6}+|\d{1,7}+);/sSX', - function (array $m) use ($class, $html_special_chars_table_flipped, $is_special_chars) - { - $codepoint = isset($m[2]) && $m[2] === 'x' ? hexdec($m[1]) : $m[1]; - if (! $is_special_chars) - { - $char = pack('C', $codepoint); - if (array_key_exists($char, $html_special_chars_table_flipped)) return $html_special_chars_table_flipped[$char]; - } - return $class::chr($codepoint); - }, $s); - } - return $s; - } + #replace named entities + $s = strtr($s, $table); + #block below deprecated, since PHP-5.3.x strtr() 1.5 times faster + if (0 && preg_match_all('/&[a-zA-Z]++\d*+;/sSX', $s, $m, null, $pos)) { + foreach (array_unique($m[0]) as $entity) { + if (array_key_exists($entity, $table)) { + $s = str_replace($entity, $table[$entity], $s); + } + } + } - /** - * Convert special UTF-8 characters to HTML entities. - * Функция кодирует гораздо больше именованных сущностей, чем стандартная htmlentities() - * - * @link http://www.htmlhelp.com/reference/html40/entities/ - * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true - * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true - * - * @param scalar|null $s - * @param bool $is_special_chars_only Обрабатывать только специальные html сущности? (< > & ") - * @return scalar|null Returns FALSE if error occurred - */ - public static function html_entity_encode($s, $is_special_chars_only = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (! is_string($s)) return $s; + #заменяем числовые dec и hex сущности: + if (strpos($s, '&#') !== false) { + #speed improve - #if ($is_special_chars_only) return strtr($s, array_flip(self::$html_special_chars_table)); - if ($is_special_chars_only) return htmlspecialchars($s); + $class = __CLASS__; + $html_special_chars_table_flipped = array_flip(self::$html_special_chars_table); + $s = preg_replace_callback('/&#((x)[\da-fA-F]{1,6}+|\d{1,7}+);/sSX', + function (array $m) use ($class, $html_special_chars_table_flipped, $is_special_chars) { + $codepoint = isset($m[2]) && $m[2] === 'x' ? hexdec($m[1]) : $m[1]; + if (!$is_special_chars) { + $char = pack('C', $codepoint); + if (array_key_exists($char, $html_special_chars_table_flipped)) { + return $html_special_chars_table_flipped[$char]; + } + } + return $class::chr($codepoint); + }, $s); + } + return $s; + } - #replace UTF-8 chars to named entities: - $s = strtr($s, array_flip(self::$html_entity_table)); - #block below deprecated, since PHP-5.3.x strtr() 3 times faster - if (0 && preg_match_all('~(?> [\xc2\xc3\xc5\xc6\xcb\xce\xcf][\x80-\xbf] #2 bytes + /** + * Convert special UTF-8 characters to HTML entities. + * Функция кодирует гораздо больше именованных сущностей, чем стандартная htmlentities() + * + * @link http://www.htmlhelp.com/reference/html40/entities/ + * @link http://www.alanwood.net/demos/ent4_frame.html (HTML 4.01 Character Entity References) + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset1.asp?frame=true + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset2.asp?frame=true + * @link http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset3.asp?frame=true + * + * @param scalar|null $s + * @param bool $is_special_chars_only Обрабатывать только специальные html сущности? (< > & ") + * @return scalar|null Returns FALSE if error occurred + */ + public static function html_entity_encode($s, $is_special_chars_only = false) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (!is_string($s)) { + return $s; + } + + #if ($is_special_chars_only) return strtr($s, array_flip(self::$html_special_chars_table)); + if ($is_special_chars_only) { + return htmlspecialchars($s); + } + + #replace UTF-8 chars to named entities: + $s = strtr($s, array_flip(self::$html_entity_table)); + #block below deprecated, since PHP-5.3.x strtr() 3 times faster + if (0 && preg_match_all('~(?> [\xc2\xc3\xc5\xc6\xcb\xce\xcf][\x80-\xbf] #2 bytes | \xe2[\x80-\x99][\x82-\xac] #3 bytes ) - ~sxSX', $s, $m)) - { - $table = array_flip(self::$html_entity_table); - foreach (array_unique($m[0]) as $char) - { - if (array_key_exists($char, $table)) $s = str_replace($char, $table[$char], $s); - } - } + ~sxSX', $s, $m) + ) { + $table = array_flip(self::$html_entity_table); + foreach (array_unique($m[0]) as $char) { + if (array_key_exists($char, $table)) { + $s = str_replace($char, $table[$char], $s); + } + } + } - return $s; - } + return $s; + } - /** - * Make regular expression for case insensitive match - * Example (non ASCII): "123_слово_test" => "123_(с|С)(л|Л)(о|О)(в|В)(о|О)_[tT][eE][sS][tT]" - * Example (only ASCII): "123_test" => "(?i:123_test)" - * - * @param string $s - * @param string|null $delimiter If the optional delimiter is specified, it will also be escaped. - * This is useful for escaping the delimiter that is required by the PCRE functions. - * The / is the most commonly used delimiter. - * @return string|bool|null Returns FALSE if error occurred - */ - public static function preg_quote_case_insensitive($s, $delimiter = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Make regular expression for case insensitive match + * Example (non ASCII): "123_слово_test" => "123_(с|С)(л|Л)(о|О)(в|В)(о|О)_[tT][eE][sS][tT]" + * Example (only ASCII): "123_test" => "(?i:123_test)" + * + * @param string $s + * @param string|null $delimiter If the optional delimiter is specified, it will also be escaped. + * This is useful for escaping the delimiter that is required by the PCRE functions. + * The / is the most commonly used delimiter. + * @return string|bool|null Returns FALSE if error occurred + */ + public static function preg_quote_case_insensitive($s, $delimiter = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if (self::is_ascii($s)) return '(?i:' . preg_quote($s, $delimiter) . ')'; #speed improve + if (self::is_ascii($s)) { + return '(?i:' . preg_quote($s, $delimiter) . ')'; + } #speed improve - $s_re = ''; - $s_lc = UTF8::lowercase($s); if ($s_lc === false) return false; - $s_uc = UTF8::uppercase($s); if ($s_uc === false) return false; + $s_re = ''; + $s_lc = UTF8::lowercase($s); + if ($s_lc === false) { + return false; + } + $s_uc = UTF8::uppercase($s); + if ($s_uc === false) { + return false; + } - $chars_lc = UTF8::str_split($s_lc); if ($chars_lc === false) return false; - $chars_uc = UTF8::str_split($s_uc); if ($chars_uc === false) return false; + $chars_lc = UTF8::str_split($s_lc); + if ($chars_lc === false) { + return false; + } + $chars_uc = UTF8::str_split($s_uc); + if ($chars_uc === false) { + return false; + } - foreach ($chars_lc as $i => $char) - { - if ($chars_lc[$i] === $chars_uc[$i]) - $s_re .= preg_quote($chars_lc[$i], $delimiter); - elseif (self::is_ascii($chars_lc[$i])) - $s_re .= '[' . preg_quote($chars_lc[$i] . $chars_uc[$i], $delimiter) . ']'; - else - $s_re .= '(' . preg_quote($chars_lc[$i], $delimiter) . '|' - . preg_quote($chars_uc[$i], $delimiter) . ')'; - } - return $s_re; - } + foreach ($chars_lc as $i => $char) { + if ($chars_lc[$i] === $chars_uc[$i]) { + $s_re .= preg_quote($chars_lc[$i], $delimiter); + } elseif (self::is_ascii($chars_lc[$i])) { + $s_re .= '[' . preg_quote($chars_lc[$i] . $chars_uc[$i], $delimiter) . ']'; + } else { + $s_re .= '(' . preg_quote($chars_lc[$i], $delimiter) . '|' + . preg_quote($chars_uc[$i], $delimiter) . ')'; + } + } + return $s_re; + } - /** - * Call preg_match_all() and convert byte offsets into character offsets for PREG_OFFSET_CAPTURE flag. - * This is regardless of whether you use /u modifier. - * - * @link http://bolknote.ru/2010/09/08/~2704 - * - * @param string $pattern - * @param string|null $subject - * @param array $matches - * @param int $flags - * @param int $char_offset - * @return array|bool|null Returns FALSE if error occurred - */ - public static function preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $char_offset = 0) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($subject)) return null; + /** + * Call preg_match_all() and convert byte offsets into character offsets for PREG_OFFSET_CAPTURE flag. + * This is regardless of whether you use /u modifier. + * + * @link http://bolknote.ru/2010/09/08/~2704 + * + * @param string $pattern + * @param string|null $subject + * @param array $matches + * @param int $flags + * @param int $char_offset + * @return array|bool|null Returns FALSE if error occurred + */ + public static function preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $char_offset = 0) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($subject)) { + return null; + } - $byte_offset = ($char_offset > 0) ? strlen(self::substr($subject, 0, $char_offset)) : $char_offset; + $byte_offset = ($char_offset > 0) ? strlen(self::substr($subject, 0, $char_offset)) : $char_offset; - $return = preg_match_all($pattern, $subject, $matches, $flags, $byte_offset); - if ($return === false) return false; + $return = preg_match_all($pattern, $subject, $matches, $flags, $byte_offset); + if ($return === false) { + return false; + } - if ($flags & PREG_OFFSET_CAPTURE) - { - foreach ($matches as &$match) - { - foreach ($match as &$a) $a[1] = self::strlen(substr($subject, 0, $a[1])); - } - } + if ($flags & PREG_OFFSET_CAPTURE) { + foreach ($matches as &$match) { + foreach ($match as &$a) { + $a[1] = self::strlen(substr($subject, 0, $a[1])); + } + } + } - return $return; - } + return $return; + } - #alias for self::str_limit() - public static function truncate($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) - { - return self::str_limit($s, $maxlength, $continue, $is_cutted, $tail_min_length); - } + #alias for self::str_limit() + public static function truncate($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) + { + return self::str_limit($s, $maxlength, $continue, $is_cutted, $tail_min_length); + } - /** - * Обрезает текст в кодировке UTF-8 до заданной длины, - * причём последнее слово показывается целиком, а не обрывается на середине. - * Html сущности корректно обрабатываются. - * - * @param string|null $s Текст в кодировке UTF-8 - * @param int|null|digit $maxlength Ограничение длины текста - * @param string $continue Завершающая строка, которая будет вставлена после текста, если он обрежется - * @param bool|null &$is_cutted Текст был обрезан? - * @param int|digit $tail_min_length Если длина "хвоста", оставшегося после обрезки текста, меньше $tail_min_length, - * то текст возвращается без изменений - * @return string|bool|null Returns FALSE if error occurred - */ - public static function str_limit($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) #"\xe2\x80\xa6" = "…" - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Обрезает текст в кодировке UTF-8 до заданной длины, + * причём последнее слово показывается целиком, а не обрывается на середине. + * Html сущности корректно обрабатываются. + * + * @param string|null $s Текст в кодировке UTF-8 + * @param int|null|digit $maxlength Ограничение длины текста + * @param string $continue Завершающая строка, которая будет вставлена после текста, если он обрежется + * @param bool|null &$is_cutted Текст был обрезан? + * @param int|digit $tail_min_length Если длина "хвоста", оставшегося после обрезки текста, меньше $tail_min_length, + * то текст возвращается без изменений + * @return string|bool|null Returns FALSE if error occurred + */ + public static function str_limit($s, $maxlength = null, $continue = "\xe2\x80\xa6", &$is_cutted = null, $tail_min_length = 20) #"\xe2\x80\xa6" = "…" + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - $is_cutted = false; - if ($continue === null) $continue = "\xe2\x80\xa6"; - if (! $maxlength) $maxlength = 256; + $is_cutted = false; + if ($continue === null) { + $continue = "\xe2\x80\xa6"; + } + if (!$maxlength) { + $maxlength = 256; + } - #speed improve block - #{{{ - if (strlen($s) <= $maxlength) return $s; - $s2 = str_replace("\r\n", '?', $s); - $s2 = preg_replace('/&(?> [a-zA-Z][a-zA-Z\d]+ + #speed improve block + #{{{ + if (strlen($s) <= $maxlength) { + return $s; + } + $s2 = str_replace("\r\n", '?', $s); + $s2 = preg_replace('/&(?> [a-zA-Z][a-zA-Z\d]+ | \#(?> \d{1,4} | x[\da-fA-F]{2,4} ) ); # html сущности (< > & ") /sxSX', '?', $s2); - if (strlen($s2) <= $maxlength || self::strlen($s2) <= $maxlength) return $s; - #}}} + if (strlen($s2) <= $maxlength || self::strlen($s2) <= $maxlength) { + return $s; + } + #}}} - $r = preg_match_all('/(?> \r\n # переносы строк + $r = preg_match_all('/(?> \r\n # переносы строк | &(?> [a-zA-Z][a-zA-Z\d]+ | \#(?> \d{1,4} | x[\da-fA-F]{2,4} @@ -3304,21 +3575,25 @@ class UTF8 | . ) /sxuSX', $s, $m); - if ($r === false) return false; + if ($r === false) { + return false; + } - #d($m); - if (count($m[0]) <= $maxlength) return $s; + #d($m); + if (count($m[0]) <= $maxlength) { + return $s; + } - $left = implode('', array_slice($m[0], 0, $maxlength)); - #из диапазона ASCII исключаем буквы, цифры, открывающие парные символы [a-zA-Z\d\(\{\[] и некоторые др. символы - #нельзя вырезать в конце строки символ ";", т.к. он используются в сущностях &xxx; - $left2 = rtrim($left, "\x00..\x28\x2A..\x2F\x3A\x3C..\x3E\x40\x5B\x5C\x5E..\x60\x7B\x7C\x7E\x7F"); - if (strlen($left) !== strlen($left2)) $return = $left2 . $continue; - else - { - #добавляем остаток к обрезанному слову - $right = implode('', array_slice($m[0], $maxlength)); - preg_match('/^(?> [\d\)\]\}\-\.:]+ #цифры, закрывающие парные символы, дефис для составных слов, дата, время, IP-адреса, URL типа www.ya.ru:80! + $left = implode('', array_slice($m[0], 0, $maxlength)); + #из диапазона ASCII исключаем буквы, цифры, открывающие парные символы [a-zA-Z\d\(\{\[] и некоторые др. символы + #нельзя вырезать в конце строки символ ";", т.к. он используются в сущностях &xxx; + $left2 = rtrim($left, "\x00..\x28\x2A..\x2F\x3A\x3C..\x3E\x40\x5B\x5C\x5E..\x60\x7B\x7C\x7E\x7F"); + if (strlen($left) !== strlen($left2)) { + $return = $left2 . $continue; + } else { + #добавляем остаток к обрезанному слову + $right = implode('', array_slice($m[0], $maxlength)); + preg_match('/^(?> [\d\)\]\}\-\.:]+ #цифры, закрывающие парные символы, дефис для составных слов, дата, время, IP-адреса, URL типа www.ya.ru:80! | \p{L}+ #буквы | \xe2\x80\x9d #закрывающие кавычки | \xe2\x80\x99 #закрывающие кавычки @@ -3326,65 +3601,87 @@ class UTF8 | \xc2\xbb #закрывающие кавычки )+ /suxSX', $right, $m); - #d($m); - $right = isset($m[0]) ? rtrim($m[0], '.-') : ''; - $return = $left . $right; - if (strlen($return) !== strlen($s)) $return .= $continue; - } - if (self::strlen($s) - self::strlen($return) < $tail_min_length) return $s; + #d($m); + $right = isset($m[0]) ? rtrim($m[0], '.-') : ''; + $return = $left . $right; + if (strlen($return) !== strlen($s)) { + $return .= $continue; + } + } + if (self::strlen($s) - self::strlen($return) < $tail_min_length) { + return $s; + } - $is_cutted = true; - return $return; - } + $is_cutted = true; + return $return; + } - /** - * Implementation str_split() function for UTF-8 encoding string. - * - * @param string|null $s - * @param int|null|digit $length - * @return array|bool|null Returns FALSE if error occurred - */ - public static function str_split($s, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Implementation str_split() function for UTF-8 encoding string. + * + * @param string|null $s + * @param int|null|digit $length + * @return array|bool|null Returns FALSE if error occurred + */ + public static function str_split($s, $length = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - $length = ($length === null) ? 1 : intval($length); - if ($length < 1) return false; - #there are limits in regexp for {min,max}! - if (preg_match_all('~.~suSX', $s, $m) === false) return false; - if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) return false; - if ($length === 1) $a = $m[0]; - else - { - $a = array(); - for ($i = 0, $c = count($m[0]); $i < $c; $i += $length) $a[] = implode('', array_slice($m[0], $i, $length)); - } - return $a; - } + $length = ($length === null) ? 1 : intval($length); + if ($length < 1) { + return false; + } + #there are limits in regexp for {min,max}! + if (preg_match_all('~.~suSX', $s, $m) === false) { + return false; + } + if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) { + return false; + } + if ($length === 1) { + $a = $m[0]; + } else { + $a = array(); + for ($i = 0, $c = count($m[0]); $i < $c; $i += $length) { + $a[] = implode('', array_slice($m[0], $i, $length)); + } + } + return $a; + } - /** - * Implementation strlen() function for UTF-8 encoding string. - * - * @param string|null $s - * @return int|bool|null Returns FALSE if error occurred - */ - public static function strlen($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Implementation strlen() function for UTF-8 encoding string. + * + * @param string|null $s + * @return int|bool|null Returns FALSE if error occurred + */ + public static function strlen($s) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - //since PHP-5.3.x mb_strlen() faster then strlen(utf8_decode()) - if (function_exists('mb_strlen')) return mb_strlen($s, 'utf-8'); + //since PHP-5.3.x mb_strlen() faster then strlen(utf8_decode()) + if (function_exists('mb_strlen')) { + return mb_strlen($s, 'utf-8'); + } - /* + /* utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright. It's much faster than iconv_strlen() Note: this function does not count bad UTF-8 bytes in the string - these are simply ignored - */ - return strlen(utf8_decode($s)); + */ + return strlen(utf8_decode($s)); - /* + /* #slowly then strlen(utf8_decode()) if (function_exists('iconv_strlen')) return iconv_strlen($s, 'utf-8'); @@ -3404,672 +3701,813 @@ class UTF8 elseif (($c & 0xC0) == 0xC0) $n++; #multi-byte starting byte (11xxxxxx) } return $n; - */ - } + */ + } - /** - * Implementation strpos() function for UTF-8 encoding string - * - * @param string|null $s The entire string - * @param string|int $needle The searched substring - * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed - * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. - * If needle is not found, will return FALSE. - */ - public static function strpos($s, $needle, $offset = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Implementation strpos() function for UTF-8 encoding string + * + * @param string|null $s The entire string + * @param string|int $needle The searched substring + * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed + * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. + * If needle is not found, will return FALSE. + */ + public static function strpos($s, $needle, $offset = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if ($offset === null || $offset < 0) $offset = 0; - if (function_exists('mb_strpos')) return mb_strpos($s, $needle, $offset, 'utf-8'); - #iconv_strpos() deprecated, because slowly than self::strlen(substr()) - #if (function_exists('iconv_strpos')) return iconv_strpos($s, $needle, $offset, 'utf-8'); - $byte_pos = $offset; - do if (($byte_pos = strpos($s, $needle, $byte_pos)) === false) return false; - while (($char_pos = self::strlen(substr($s, 0, $byte_pos++))) < $offset); - return $char_pos; - } + if ($offset === null || $offset < 0) { + $offset = 0; + } + if (function_exists('mb_strpos')) { + return mb_strpos($s, $needle, $offset, 'utf-8'); + } + #iconv_strpos() deprecated, because slowly than self::strlen(substr()) + #if (function_exists('iconv_strpos')) return iconv_strpos($s, $needle, $offset, 'utf-8'); + $byte_pos = $offset; + do { + if (($byte_pos = strpos($s, $needle, $byte_pos)) === false) { + return false; + } + } while (($char_pos = self::strlen(substr($s, 0, $byte_pos++))) < $offset); + return $char_pos; + } - /** - * Find position of first occurrence of a case-insensitive string. - * - * @param string|null $s The entire string - * @param string|int $needle The searched substring - * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed - * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. - * If needle is not found, will return FALSE. - */ - public static function stripos($s, $needle, $offset = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Find position of first occurrence of a case-insensitive string. + * + * @param string|null $s The entire string + * @param string|int $needle The searched substring + * @param int|null $offset The optional offset parameter specifies the position from which the search should be performed + * @return int|bool|null Returns the numeric position of the first occurrence of needle in haystack. + * If needle is not found, will return FALSE. + */ + public static function stripos($s, $needle, $offset = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if ($offset === null || $offset < 0) $offset = 0; - if (function_exists('mb_stripos')) return mb_stripos($s, $needle, $offset, 'utf-8'); + if ($offset === null || $offset < 0) { + $offset = 0; + } + if (function_exists('mb_stripos')) { + return mb_stripos($s, $needle, $offset, 'utf-8'); + } - #optimization block (speed improve) - #{{{ - $ascii_int = intval(self::is_ascii($s)) + intval(self::is_ascii($needle)); - if ($ascii_int === 1) return false; - if ($ascii_int === 2) return stripos($s, $needle, $offset); - #}}} + #optimization block (speed improve) + #{{{ + $ascii_int = intval(self::is_ascii($s)) + intval(self::is_ascii($needle)); + if ($ascii_int === 1) { + return false; + } + if ($ascii_int === 2) { + return stripos($s, $needle, $offset); + } + #}}} - $s = self::convert_case($s, CASE_LOWER, false); - if ($s === false) return false; - $needle = self::convert_case($needle, CASE_LOWER, false); - if ($needle === false) return false; - return self::strpos($s, $needle, $offset); - } + $s = self::convert_case($s, CASE_LOWER, false); + if ($s === false) { + return false; + } + $needle = self::convert_case($needle, CASE_LOWER, false); + if ($needle === false) { + return false; + } + return self::strpos($s, $needle, $offset); + } - /** - * Implementation strrev() function for UTF-8 encoding string - * - * @param string|null $s - * @return string|bool|null Returns FALSE if error occurred - */ - public static function strrev($s) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + /** + * Implementation strrev() function for UTF-8 encoding string + * + * @param string|null $s + * @return string|bool|null Returns FALSE if error occurred + */ + public static function strrev($s) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - if (0) #TODO test speed - { - $s = self::_convert($s, 'UTF-8', 'UTF-32'); - if (! is_string($s)) return false; - $s = implode('', array_reverse(str_split($s, 4))); - return self::_convert($s, 'UTF-32', 'UTF-8'); - } + if (0) { + #TODO test speed - if (! is_array($a = self::str_split($s))) return false; - return implode('', array_reverse($a)); - } + $s = self::_convert($s, 'UTF-8', 'UTF-32'); + if (!is_string($s)) { + return false; + } + $s = implode('', array_reverse(str_split($s, 4))); + return self::_convert($s, 'UTF-32', 'UTF-8'); + } - /** - * Implementation substr() function for UTF-8 encoding string. - * - * @link http://www.w3.org/International/questions/qa-forms-utf-8.html - * @param string|null $s - * @param int|digit $offset - * @param int|null|digit $length - * @return string|bool|null Returns FALSE if error occurred - */ - public static function substr($s, $offset, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + if (!is_array($a = self::str_split($s))) { + return false; + } + return implode('', array_reverse($a)); + } - #since PHP-5.3.x mb_substr() faster then iconv_substr() - if (function_exists('mb_substr')) - { - if ($length === null) $length = self::strlen($s); - return mb_substr($s, $offset, $length, 'utf-8'); - } - if (function_exists('iconv_substr')) - { - if ($length === null) $length = self::strlen($s); - return iconv_substr($s, $offset, $length, 'utf-8'); - } + /** + * Implementation substr() function for UTF-8 encoding string. + * + * @link http://www.w3.org/International/questions/qa-forms-utf-8.html + * @param string|null $s + * @param int|digit $offset + * @param int|null|digit $length + * @return string|bool|null Returns FALSE if error occurred + */ + public static function substr($s, $offset, $length = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - static $_s = null; - static $_a = null; + #since PHP-5.3.x mb_substr() faster then iconv_substr() + if (function_exists('mb_substr')) { + if ($length === null) { + $length = self::strlen($s); + } + return mb_substr($s, $offset, $length, 'utf-8'); + } + if (function_exists('iconv_substr')) { + if ($length === null) { + $length = self::strlen($s); + } + return iconv_substr($s, $offset, $length, 'utf-8'); + } - if ($_s !== $s) $_a = self::str_split($_s = $s); - if (! is_array($_a)) return false; - if ($length !== null) $a = array_slice($_a, $offset, $length); - else $a = array_slice($_a, $offset); - return implode('', $a); - } + static $_s = null; + static $_a = null; - /** - * Implementation substr_replace() function for UTF-8 encoding string. - * - * @param string|null $s - * @param string|int $replacement - * @param int|digit $start - * @param int|null $length - * @return string|bool|null Returns FALSE if error occurred - */ - public static function substr_replace($s, $replacement, $start, $length = null) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + if ($_s !== $s) { + $_a = self::str_split($_s = $s); + } + if (!is_array($_a)) { + return false; + } + if ($length !== null) { + $a = array_slice($_a, $offset, $length); + } else { + $a = array_slice($_a, $offset); + } + return implode('', $a); + } - if (! is_array($a = self::str_split($s))) return false; - array_splice($a, $start, $length, $replacement); - return implode('', $a); - } + /** + * Implementation substr_replace() function for UTF-8 encoding string. + * + * @param string|null $s + * @param string|int $replacement + * @param int|digit $start + * @param int|null $length + * @return string|bool|null Returns FALSE if error occurred + */ + public static function substr_replace($s, $replacement, $start, $length = null) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - /** - * Implementation ucfirst() function for UTF-8 encoding string. - * Преобразует первый символ строки в кодировке UTF-8 в верхний регистр. - * - * @param string|null $s - * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? - * @return string|bool|null Returns FALSE if error occurred - */ - public static function ucfirst($s, $is_other_to_lowercase = true) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + if (!is_array($a = self::str_split($s))) { + return false; + } + array_splice($a, $start, $length, $replacement); + return implode('', $a); + } - if ($s === '' || ! is_string($s)) return $s; - if (! preg_match('/^(.)(.*)$/suSX', $s, $m)) return false; - return self::uppercase($m[1]) . ($is_other_to_lowercase ? self::lowercase($m[2]) : $m[2]); - } + /** + * Implementation ucfirst() function for UTF-8 encoding string. + * Преобразует первый символ строки в кодировке UTF-8 в верхний регистр. + * + * @param string|null $s + * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? + * @return string|bool|null Returns FALSE if error occurred + */ + public static function ucfirst($s, $is_other_to_lowercase = true) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - /** - * Implementation ucwords() function for UTF-8 encoding string. - * Преобразует в верхний регистр первый символ каждого слова в строке в кодировке UTF-8, - * остальные символы каждого слова преобразуются в нижний регистр. - * - * @param string|null $s - * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? - * @param string $spaces_re - * @return string|bool|null Returns FALSE if error occurred - */ - public static function ucwords($s, $is_other_to_lowercase = true, $spaces_re = '~([\pZ\s]+)~suSX') #\pXps is POSIX space: property Z or tab, NL, VT, FF, CR - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_null($s)) return $s; + if ($s === '' || !is_string($s)) { + return $s; + } + if (!preg_match('/^(.)(.*)$/suSX', $s, $m)) { + return false; + } + return self::uppercase($m[1]) . ($is_other_to_lowercase ? self::lowercase($m[2]) : $m[2]); + } - $words = preg_split($spaces_re, $s, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - foreach ($words as $k => $word) - { - $words[$k] = self::ucfirst($word, $is_other_to_lowercase = true); - if ($words[$k] === false) return false; - } - return implode('', $words); - } + /** + * Implementation ucwords() function for UTF-8 encoding string. + * Преобразует в верхний регистр первый символ каждого слова в строке в кодировке UTF-8, + * остальные символы каждого слова преобразуются в нижний регистр. + * + * @param string|null $s + * @param bool $is_other_to_lowercase остальные символы преобразуются в нижний регистр? + * @param string $spaces_re + * @return string|bool|null Returns FALSE if error occurred + */ + public static function ucwords($s, $is_other_to_lowercase = true, $spaces_re = '~([\pZ\s]+)~suSX') #\pXps is POSIX space: property Z or tab, NL, VT, FF, CR + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_null($s)) { + return $s; + } - /** - * Decodes a string in the format %uXXXX or %u{XXXXXX} in the UTF-8 string. - * - * Используется для декодирования данных типа "%u0442%u0435%u0441%u0442", - * закодированных устаревшей функцией javascript://encode(). - * Рекомендуется использовать функцию javascript://encodeURIComponent(). - * - * NOTICE - * Устаревший формат %uXXXX позволяет использовать юникод только из диапазона UCS-2, т.е. от U+0 до U+FFFF - * - * @param scalar|array|null $data - * @param bool $is_rawurlencode - * @return scalar|array|null Returns FALSE if error occurred - */ - public static function unescape($data, $is_rawurlencode = false) - { - if (! ReflectionTypeHint::isValid()) return false; - if (is_array($data)) - { - $d = array(); - foreach ($data as $k => &$v) - { - $k = self::unescape($k, $is_rawurlencode); - if ($k === false) return false; - $d[$k] = self::unescape($v, $is_rawurlencode); - if ($d[$k] === false && ! is_bool($v)) return false; - } - return $d; - } - if (is_string($data)) - { - if (strpos($data, '%u') === false) return $data; #use strpos() for speed improving - return preg_replace_callback('/%u( [\da-fA-F]{4}+ #%uXXXX only UCS-2 + $words = preg_split($spaces_re, $s, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); + foreach ($words as $k => $word) { + $words[$k] = self::ucfirst($word, $is_other_to_lowercase = true); + if ($words[$k] === false) { + return false; + } + } + return implode('', $words); + } + + /** + * Decodes a string in the format %uXXXX or %u{XXXXXX} in the UTF-8 string. + * + * Используется для декодирования данных типа "%u0442%u0435%u0441%u0442", + * закодированных устаревшей функцией javascript://encode(). + * Рекомендуется использовать функцию javascript://encodeURIComponent(). + * + * NOTICE + * Устаревший формат %uXXXX позволяет использовать юникод только из диапазона UCS-2, т.е. от U+0 до U+FFFF + * + * @param scalar|array|null $data + * @param bool $is_rawurlencode + * @return scalar|array|null Returns FALSE if error occurred + */ + public static function unescape($data, $is_rawurlencode = false) + { + if (!ReflectionTypeHint::isValid()) { + return false; + } + if (is_array($data)) { + $d = array(); + foreach ($data as $k => &$v) { + $k = self::unescape($k, $is_rawurlencode); + if ($k === false) { + return false; + } + $d[$k] = self::unescape($v, $is_rawurlencode); + if ($d[$k] === false && !is_bool($v)) { + return false; + } + } + return $d; + } + if (is_string($data)) { + if (strpos($data, '%u') === false) { + return $data; + } #use strpos() for speed improving + return preg_replace_callback('/%u( [\da-fA-F]{4}+ #%uXXXX only UCS-2 | \{ [\da-fA-F]{1,6}+ \} #%u{XXXXXX} extended form for all UNICODE charts ) /sxSX', - function (array $m) use ($is_rawurlencode) - { - $codepoint = hexdec(trim($m[1], '{}')); - $char = self::chr($codepoint); - return $is_rawurlencode ? rawurlencode($char) : $char; - }, - $data); - } - if (is_scalar($data) || is_null($data)) return $data; #~ null, integer, float, boolean - return false; #object or resource - } + function (array $m) use ($is_rawurlencode) { + $codepoint = hexdec(trim($m[1], '{}')); + $char = self::chr($codepoint); + return $is_rawurlencode ? rawurlencode($char) : $char; + }, + $data); + } + if (is_scalar($data) || is_null($data)) { + return $data; + } #~ null, integer, float, boolean + return false; #object or resource + } - /** - * 1) Corrects the global arrays $_GET, $_POST, $_COOKIE, $_REQUEST - * decoded values ​​in the format %uXXXX and %u{XXXXXX}, encoded, - * for example, through an outdated javascript function escape(). - * Standard PHP5 cannot do it. - * 2) If in the HTTP_COOKIE there are parameters with the same name, - * takes the last value, not the first, as in the QUERY_STRING. - * 3) Creates an array of $_POST for non-standard Content-Type, for example, "Content-Type: application/octet-stream". - * Standard PHP5 creates an array for "Content-Type: application/x-www-form-urlencoded" and "Content-Type: multipart/form-data". - * - * Сессии, куки и независимая авторизация на поддоменах. - * - * ПРИМЕР 1 - * У рабочего сайта http://domain.com появились поддомены. - * Для кроссдоменной авторизации через механизм сессий имя хоста для COOKIE было изменено с "domain.com" на ".domain.com" - * В результате авторизация не работает. - * Помогает очистка COOKIE, но их принудительная очистка на тысячах пользовательских компьютеров проблематична. - * Проблема в следующем: если в HTTP_COOKIE есть параметры с одинаковым именем, то берётся последнее значение, - * а не первое, как в QUERY_STRING. - * Более подробное описание: - * PHP не правильно (?) обрабатывает заголовок HTTP_COOKIE, если там встречаются параметры с одинаковым именем, но разными значениями. - * Пример запроса HTTP-заголовка клиентом: "Cookie: sid=chpgs2fiak-330mzqza; sid=cmz5tnp5zz-xlbbgqp" - * В этом случае сервер берёт первое значение, а не последнее. - * Хотя если в QUERY_STRING есть такая ситуация, всегда берётся последний параметр. - * В HTTP_COOKIE два параметра с одинаковым именем могут появиться, если отправить клиенту следующие HTTP-заголовки: - * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=domain.com" (только domain.com) - * "Set-Cookie: sid=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (domain.com и все его поддомены) - * Решение: поменять имя сессии. - * - * ПРИМЕР 2 - * Есть рабочие сайты: http://domain.com (основной), http://admin.domain.com (админка), - * http://sub1.domain.com (подпроект 1), http://sub2.domain.com, (подпроект 2). - * Так же имеется сервер разработки http://dev.domain.com, на котором м. б. свои поддомены. - * Требуется сделать независимую кросс-доменную авторизацию для http://*.domain.com и http://*.dev.domain.com. - * Для сохранения статуса авторизации будем использовать сессию, имя и значение которой пишется в COOKIE. - * Т. к. домены http://*.dev.domain.com имеют пересечение с доменами http://*.domain.com, - * для независимой авторизации нужно использовать разные имена сессий. - * Пример HTTP заголовков ответа сервера: - * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (.domain.com и все его поддомены) - * "Set-Cookie: sid.dev=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.dev.domain.com" (dev.domain.com и все его поддомены) - * - * @link http://tools.ietf.org/html/rfc2965 RFC 2965 - HTTP State Management Mechanism - * @return void - */ - public static function unescape_request() - { - $fixed = false; + /** + * 1) Corrects the global arrays $_GET, $_POST, $_COOKIE, $_REQUEST + * decoded values ​​in the format %uXXXX and %u{XXXXXX}, encoded, + * for example, through an outdated javascript function escape(). + * Standard PHP5 cannot do it. + * 2) If in the HTTP_COOKIE there are parameters with the same name, + * takes the last value, not the first, as in the QUERY_STRING. + * 3) Creates an array of $_POST for non-standard Content-Type, for example, "Content-Type: application/octet-stream". + * Standard PHP5 creates an array for "Content-Type: application/x-www-form-urlencoded" and "Content-Type: multipart/form-data". + * + * Сессии, куки и независимая авторизация на поддоменах. + * + * ПРИМЕР 1 + * У рабочего сайта http://domain.com появились поддомены. + * Для кроссдоменной авторизации через механизм сессий имя хоста для COOKIE было изменено с "domain.com" на ".domain.com" + * В результате авторизация не работает. + * Помогает очистка COOKIE, но их принудительная очистка на тысячах пользовательских компьютеров проблематична. + * Проблема в следующем: если в HTTP_COOKIE есть параметры с одинаковым именем, то берётся последнее значение, + * а не первое, как в QUERY_STRING. + * Более подробное описание: + * PHP не правильно (?) обрабатывает заголовок HTTP_COOKIE, если там встречаются параметры с одинаковым именем, но разными значениями. + * Пример запроса HTTP-заголовка клиентом: "Cookie: sid=chpgs2fiak-330mzqza; sid=cmz5tnp5zz-xlbbgqp" + * В этом случае сервер берёт первое значение, а не последнее. + * Хотя если в QUERY_STRING есть такая ситуация, всегда берётся последний параметр. + * В HTTP_COOKIE два параметра с одинаковым именем могут появиться, если отправить клиенту следующие HTTP-заголовки: + * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=domain.com" (только domain.com) + * "Set-Cookie: sid=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (domain.com и все его поддомены) + * Решение: поменять имя сессии. + * + * ПРИМЕР 2 + * Есть рабочие сайты: http://domain.com (основной), http://admin.domain.com (админка), + * http://sub1.domain.com (подпроект 1), http://sub2.domain.com, (подпроект 2). + * Так же имеется сервер разработки http://dev.domain.com, на котором м. б. свои поддомены. + * Требуется сделать независимую кросс-доменную авторизацию для http://*.domain.com и http://*.dev.domain.com. + * Для сохранения статуса авторизации будем использовать сессию, имя и значение которой пишется в COOKIE. + * Т. к. домены http://*.dev.domain.com имеют пересечение с доменами http://*.domain.com, + * для независимой авторизации нужно использовать разные имена сессий. + * Пример HTTP заголовков ответа сервера: + * "Set-Cookie: sid=chpgs2fiak-330mzqza; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.domain.com" (.domain.com и все его поддомены) + * "Set-Cookie: sid.dev=cmz6uqorzv-1bn35110; expires=Thu, 15 Oct 2009 14:23:42 GMT; path=/; domain=.dev.domain.com" (dev.domain.com и все его поддомены) + * + * @link http://tools.ietf.org/html/rfc2965 RFC 2965 - HTTP State Management Mechanism + * @return void + */ + public static function unescape_request() + { + $fixed = false; #ATTENTION! HTTP_RAW_POST_DATA is only accessible when Content-Type of POST request is NOT default "application/x-www-form-urlencoded"! - $HTTP_RAW_POST_DATA = isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' ? (isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents('php://input')) : null; - if (ini_get('always_populate_raw_post_data')) $GLOBALS['HTTP_RAW_POST_DATA'] = $HTTP_RAW_POST_DATA; - foreach (array( '_GET' => isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null, - '_POST' => $HTTP_RAW_POST_DATA, - '_COOKIE' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null, - ) as $k => $v) - { - if (! is_string($v)) continue; - if ($k === '_COOKIE') - { - $v = preg_replace('/; *+/sSX', '&', $v); - unset($_COOKIE); #будем парсить HTTP_COOKIE сами, чтобы сделать обработку как у QUERY_STRING - } - if (strpos($v, '%u') !== false) - { - parse_str(self::unescape($v, $is_rawurlencode = true), $GLOBALS[$k]); - $fixed = true; - continue; - } - if (array_key_exists($k, $GLOBALS)) continue; - parse_str($v, $GLOBALS[$k]); - $fixed = true; - } - if ($fixed) - { - $_REQUEST = - (isset($_COOKIE) ? $_COOKIE : array()) + - (isset($_POST) ? $_POST : array()) + - (isset($_GET) ? $_GET : array()); - } - } + $HTTP_RAW_POST_DATA = isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' ? (isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents('php://input')) : null; + if (ini_get('always_populate_raw_post_data')) { + $GLOBALS['HTTP_RAW_POST_DATA'] = $HTTP_RAW_POST_DATA; + } + foreach (array('_GET' => isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null, + '_POST' => $HTTP_RAW_POST_DATA, + '_COOKIE' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null, + ) as $k => $v) { + if (!is_string($v)) { + continue; + } + if ($k === '_COOKIE') { + $v = preg_replace('/; *+/sSX', '&', $v); + unset($_COOKIE); #будем парсить HTTP_COOKIE сами, чтобы сделать обработку как у QUERY_STRING + } + if (strpos($v, '%u') !== false) { + parse_str(self::unescape($v, $is_rawurlencode = true), $GLOBALS[$k]); + $fixed = true; + continue; + } + if (array_key_exists($k, $GLOBALS)) { + continue; + } + parse_str($v, $GLOBALS[$k]); + $fixed = true; + } + if ($fixed) { + $_REQUEST = + (isset($_COOKIE) ? $_COOKIE : array()) + + (isset($_POST) ? $_POST : array()) + + (isset($_GET) ? $_GET : array()); + } + } - /** - * Calculates the height of the edit text in