From 8776f12e868898c02bc8c51b21fe21c8a9e5da5c Mon Sep 17 00:00:00 2001 From: Yuriy Pikhtarev Date: Tue, 27 Sep 2016 22:36:35 +0300 Subject: [PATCH] Basic reformat all .php files to PSR-2. Requires manual verification. --- admin/admin_board.php | 222 +- admin/admin_bt_forum_cfg.php | 158 +- admin/admin_bt_tracker_cfg.php | 73 +- admin/admin_cron.php | 347 +- admin/admin_disallow.php | 97 +- admin/admin_forum_prune.php | 75 +- admin/admin_forumauth.php | 349 +- admin/admin_forumauth_list.php | 510 ++- admin/admin_forums.php | 1699 ++++---- admin/admin_groups.php | 284 +- admin/admin_log.php | 437 +- admin/admin_mass_email.php | 107 +- admin/admin_phpinfo.php | 9 +- admin/admin_ranks.php | 367 +- admin/admin_rebuild_search.php | 779 ++-- admin/admin_sitemap.php | 25 +- admin/admin_smilies.php | 537 ++- admin/admin_terms.php | 26 +- admin/admin_ug_auth.php | 674 ++-- admin/admin_user_ban.php | 527 ++- admin/admin_user_search.php | 1666 ++++---- admin/admin_words.php | 215 +- admin/index.php | 422 +- admin/pagestart.php | 23 +- admin/stats/tr_stats.php | 43 +- admin/stats/tracker.php | 82 +- ajax.php | 659 ++-- bt/announce.php | 557 ++- bt/includes/init_tr.php | 760 ++-- bt/index.php | 2 +- bt/scrape.php | 40 +- callseed.php | 78 +- common.php | 523 ++- configs/main.php | 22 +- cron.php | 4 +- dl_list.php | 189 +- group.php | 943 ++--- group_edit.php | 147 +- index.php | 505 ++- info.php | 91 +- library/ajax/avatar.php | 35 +- library/ajax/change_tor_status.php | 129 +- library/ajax/change_torrent.php | 95 +- library/ajax/change_user_opt.php | 28 +- library/ajax/change_user_rank.php | 16 +- library/ajax/edit_group_profile.php | 62 +- library/ajax/edit_user_profile.php | 246 +- library/ajax/gen_passkey.php | 26 +- library/ajax/group_membership.php | 94 +- library/ajax/index_data.php | 183 +- library/ajax/manage_admin.php | 119 +- library/ajax/manage_user.php | 91 +- library/ajax/mod_action.php | 167 +- library/ajax/post_mod_comment.php | 68 +- library/ajax/posts.php | 451 +-- library/ajax/sitemap.php | 74 +- library/ajax/topic_tpl.php | 258 +- library/ajax/user_register.php | 96 +- library/ajax/view_post.php | 51 +- library/ajax/view_torrent.php | 247 +- library/config.php | 1140 +++--- library/defines.php | 94 +- library/includes/api/sphinx.php | 2986 +++++++------- library/includes/bbcode.php | 1454 ++++--- library/includes/classes/emailer.php | 368 +- library/includes/classes/sitemap.php | 349 +- library/includes/core/dbs.php | 85 +- library/includes/core/mysql.php | 1775 ++++----- library/includes/cron/cron_check.php | 37 +- library/includes/cron/cron_init.php | 68 +- library/includes/cron/cron_run.php | 118 +- .../includes/cron/jobs/board_maintenance.php | 51 +- library/includes/cron/jobs/clean_dlstat.php | 46 +- library/includes/cron/jobs/clean_log.php | 8 +- .../cron/jobs/clean_search_results.php | 6 +- .../cron/jobs/ds_update_cat_forums.php | 2 +- .../includes/cron/jobs/ds_update_stats.php | 2 +- .../includes/cron/jobs/flash_topic_view.php | 12 +- library/includes/cron/jobs/prune_forums.php | 16 +- .../cron/jobs/prune_inactive_users.php | 63 +- .../includes/cron/jobs/prune_topic_moved.php | 13 +- .../includes/cron/jobs/sessions_cleanup.php | 18 +- library/includes/cron/jobs/sitemap.php | 17 +- .../cron/jobs/tr_cleanup_and_dlstat.php | 132 +- .../includes/cron/jobs/tr_complete_count.php | 37 +- library/includes/cron/jobs/tr_maintenance.php | 33 +- .../includes/cron/jobs/tr_make_snapshot.php | 187 +- library/includes/cron/jobs/tr_seed_bonus.php | 38 +- .../cron/jobs/tr_update_seeder_last_seen.php | 6 +- .../includes/cron/jobs/update_forums_atom.php | 33 +- library/includes/datastore/apc.php | 106 +- .../includes/datastore/build_cat_forums.php | 157 +- .../includes/datastore/build_moderators.php | 70 +- library/includes/datastore/build_ranks.php | 9 +- library/includes/datastore/build_smilies.php | 13 +- library/includes/datastore/build_stats.php | 109 +- library/includes/datastore/common.php | 288 +- library/includes/datastore/file.php | 125 +- library/includes/datastore/memcache.php | 154 +- library/includes/datastore/redis.php | 150 +- library/includes/datastore/sqlite.php | 89 +- library/includes/datastore/xcache.php | 106 +- library/includes/functions.php | 3513 ++++++++--------- library/includes/functions_admin.php | 967 +++-- library/includes/functions_admin_cron.php | 171 +- library/includes/functions_admin_torrent.php | 147 +- library/includes/functions_atom.php | 273 +- library/includes/functions_dev.php | 75 +- library/includes/functions_group.php | 241 +- library/includes/functions_post.php | 639 ++- library/includes/functions_torrent.php | 1125 +++--- library/includes/functions_upload.php | 277 +- library/includes/functions_validate.php | 164 +- library/includes/init_bb.php | 431 +- library/includes/online_userlist.php | 167 +- library/includes/page_footer.php | 107 +- library/includes/page_footer_dev.php | 134 +- library/includes/page_header.php | 335 +- library/includes/posting_tpl.php | 106 +- library/includes/sessions.php | 1341 +++---- library/includes/smtp.php | 263 +- library/includes/template.php | 2036 +++++----- library/includes/torrent_show_dl_list.php | 180 +- library/includes/ucp/activate.php | 51 +- library/includes/ucp/bonus.php | 102 +- library/includes/ucp/email.php | 110 +- library/includes/ucp/register.php | 1218 +++--- library/includes/ucp/sendpasswd.php | 108 +- library/includes/ucp/topic_watch.php | 126 +- library/includes/ucp/viewprofile.php | 295 +- library/includes/ucp/viewtorrent.php | 146 +- library/includes/viewtopic_torrent.php | 769 ++-- library/language/en/main.php | 160 +- library/language/ru/main.php | 158 +- library/language/uk/main.php | 164 +- login.php | 142 +- memberlist.php | 281 +- messages/ru.php | 8 +- modcp.php | 1104 +++--- poll.php | 350 +- posting.php | 906 ++--- privmsg.php | 2276 +++++------ profile.php | 59 +- search.php | 1284 +++--- src/Cache/MemoryAdapter.php | 12 +- src/Config.php | 6 +- .../SphinxServiceProvider.php | 2 +- src/Settings.php | 2 +- tests/src/Cache/AdapterTest.php | 8 +- tests/src/Cache/FileAdapterTest.php | 2 +- tests/src/Db/AdapterTest.php | 4 +- tracker.php | 1402 +++---- viewforum.php | 648 ++- viewtopic.php | 1000 +++-- 154 files changed, 24662 insertions(+), 28312 deletions(-) diff --git a/admin/admin_board.php b/admin/admin_board.php index 2fe20d6c6..0d8970610 100644 --- a/admin/admin_board.php +++ b/admin/admin_board.php @@ -1,148 +1,136 @@ '

'. 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'], - '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'], + '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 bf113b660..40e1143be 100644 --- a/admin/admin_bt_forum_cfg.php +++ b/admin/admin_bt_forum_cfg.php @@ -1,148 +1,140 @@ '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_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_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_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_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 d6388f4cb..b496275e9 100644 --- a/admin/admin_bt_tracker_cfg.php +++ b/admin/admin_bt_tracker_cfg.php @@ -1,9 +1,8 @@ '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' => $di->config->get('ignore_reported_ip'), - 'ANNOUNCE_INTERVAL' => $di->config->get('announce_interval'), - 'PASSKEY_KEY' => $di->config->get('passkey_key'), - 'GOLD_SILVER_ENABLED' => $tr_cfg['gold_silver_enabled'], - 'DISABLE_SUBMIT' => true, + 'IGNORE_REPORTED_IP' => $di->config->get('ignore_reported_ip'), + 'ANNOUNCE_INTERVAL' => $di->config->get('announce_interval'), + 'PASSKEY_KEY' => $di->config->get('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 6c23fa23d..99497625b 100644 --- a/admin/admin_cron.php +++ b/admin/admin_cron.php @@ -1,227 +1,198 @@ session_start(); - redirect('admin/'.basename(__FILE__) . '?mode=list'); -} -else require('./pagestart.php'); +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'); 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), - '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), + '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); + } 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'); - 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..db263f47d 100644 --- a/admin/admin_disallow.php +++ b/admin/admin_disallow.php @@ -1,57 +1,47 @@ 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'], '', ''); + $message .= $lang['DISALLOWED_DELETED'] . '

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

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); - bb_die($message); + bb_die($message); } @@ -60,9 +50,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 +62,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_forum_prune.php b/admin/admin_forum_prune.php index 2a9c7c619..811bb527d 100644 --- a/admin/admin_forum_prune.php +++ b/admin/admin_forum_prune.php @@ -1,9 +1,8 @@ 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 ad2d97294..93a0c1169 100644 --- a/admin/admin_forumauth.php +++ b/admin/admin_forumauth.php @@ -1,134 +1,121 @@ 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; - } + $forum_sql = ''; + $adv = 0; + } - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

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

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); } // End of submit @@ -137,116 +124,102 @@ 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..e9017aa41 100644 --- a/admin/admin_forumauth_list.php +++ b/admin/admin_forumauth_list.php @@ -1,174 +1,151 @@ 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 = ''; - } + $cat_sql = ''; + } - $datastore->update('cat_forums'); - bb_die($lang['FORUM_AUTH_UPDATED'] . '

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

' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '', "")); } // End of submit @@ -182,182 +159,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 6d68ea82c..8e599d97d 100644 --- a/admin/admin_forums.php +++ b/admin/admin_forums.php @@ -1,13 +1,12 @@ 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']; + } + } else if (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'); - // TODO: delete only necessary cache - $cache->flush(); + renumber_order('forum', $cat_id); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - 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'); + } + } 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; + } - $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', @@ -321,902 +294,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'); - // TODO: delete only necessary cache - $cache->flush(); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - $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'); - // TODO: delete only necessary cache - $cache->flush(); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - 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'); - // TODO: delete only necessary cache - $cache->flush(); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - 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'); - // TODO: delete only necessary cache - $cache->flush(); + $cat_forums = get_cat_forums(); + fix_orphan_sf(); + update_user_level('all'); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - 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'); - // TODO: delete only necessary cache - $cache->flush(); + renumber_order('forum', $to_id); + $cat_forums = get_cat_forums(); + $fix = fix_orphan_sf(); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - $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; + } 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; + } - 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 + } else if ($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'); - // TODO: delete only necessary cache - $cache->flush(); + renumber_order('forum', $forum_info['cat_id']); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - $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'); - // TODO: delete only necessary cache - $cache->flush(); + renumber_order('category'); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - $show_main_page = true; - break; + $show_main_page = true; + break; - case 'forum_sync': - sync('forum', intval($_GET['f'])); - $datastore->update('cat_forums'); - // TODO: delete only necessary cache - $cache->flush(); + case 'forum_sync': + sync('forum', intval($_GET['f'])); + $datastore->update('cat_forums'); + // TODO: delete only necessary cache + $cache->flush(); - $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", - )); + '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 + }// 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; - } + 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'); - } + 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; } /** @@ -1226,12 +1109,12 @@ function check_name_dup ($mode, $name, $die_on_error = true) * @param $new_cat_id * @param $order_shear */ -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 8faed407e..8d1377a56 100644 --- a/admin/admin_groups.php +++ b/admin/admin_groups.php @@ -1,186 +1,160 @@ $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()); + } 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'; + } - // 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, + )); +} 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); - $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']); + } else if ($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); + } else if ($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 d98c866d1..047606948 100644 --- a/admin/admin_log.php +++ b/admin/admin_log.php @@ -1,9 +1,8 @@ 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'); @@ -67,10 +65,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']; @@ -83,106 +80,93 @@ $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; } // Sort $sort_val = $def_sort; -if (($var =& $_REQUEST[$sort_key]) && ($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]) && ($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]) && ($var != $def_days)) -{ - $daysback_val = max(intval($var), 1); - $url = url_arg($url, $daysback_key, $daysback_val); +if (($var =& $_REQUEST[$daysback_key]) && ($var != $def_days)) { + $daysback_val = max(intval($var), 1); + $url = url_arg($url, $daysback_key, $daysback_val); } -if (($var =& $_REQUEST[$datetime_key]) && ($var != $def_datetime)) -{ - $tz = TIMENOW + (3600 * $di->config->get('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]) && ($var != $def_datetime)) { + $tz = TIMENOW + (3600 * $di->config->get('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)); + } } // SQL @@ -194,188 +178,173 @@ $where .= ($topic_csv) ? " AND l.log_topic_id IN($topic_csv)" : ''; $where .= ($title_match_sql) ? " AND MATCH (l.log_topic_title) AGAINST ('$title_match_sql' IN BOOLEAN MODE)" : ''; $sql = "SELECT l.*, u.* - FROM ". BB_LOG ." l - LEFT JOIN ". BB_USERS ." u ON(u.user_id = l.log_user_id) + FROM " . BB_LOG . " l + LEFT JOIN " . BB_USERS . " u ON(u.user_id = l.log_user_id) $where ORDER BY l.log_time $sort_val - LIMIT $start, ". ($per_page + 1)." + LIMIT $start, " . ($per_page + 1) . " "; $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' => profile_url($row), - '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' => profile_url($row), + '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'])) - { - $template->assign_block_vars('users', array( - 'USERNAME' => profile_url($row), - )); - $filter['users'] = 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'])) { + $template->assign_block_vars('users', array( + 'USERNAME' => profile_url($row), + )); + $filter['users'] = 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()); } // Select $log_type_select = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_types) + $log_action->log_type_select; $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, - '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 0cb59e4e0..70c17bceb 100644 --- a/admin/admin_mass_email.php +++ b/admin/admin_mass_email.php @@ -1,9 +1,8 @@ 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 . $user_id_sql .") + AND u.user_id NOT IN(" . EXCLUDED_USERS . $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 . $user_id_sql .") + AND user_id NOT IN(" . EXCLUDED_USERS . $user_id_sql . ") "); - } + } - require(CLASS_DIR .'emailer.php'); + require(CLASS_DIR . 'emailer.php'); - foreach ($user_list as $i => $row) - { - $emailer = new emailer($di->config->get('smtp_delivery')); + foreach ($user_list as $i => $row) { + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - $emailer->use_template('admin_send_email'); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('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..f947fa015 100644 --- a/admin/admin_phpinfo.php +++ b/admin/admin_phpinfo.php @@ -1,10 +1,9 @@ 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 6bfb3ea5e..ebf439233 100644 --- a/admin/admin_rebuild_search.php +++ b/admin/admin_rebuild_search.php @@ -1,48 +1,45 @@ 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 +49,358 @@ $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)) && !$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)) && !$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 + { + $form_action = "admin_rebuild_search.php"; + $next_button = $lang['FINISHED']; + $progress_bar_img = $images['progress_bar_full']; - $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']; + $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 ." + // 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 + '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; + // 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 + { + 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 - { - $last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); + $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("start_text_input", array()); - } - } + $template->assign_block_vars("start_text_input", array()); + } + } - $template->assign_block_vars("last_saved_info", array()); - } - else - { - $template->assign_block_vars("start_text_input", array()); - } + $template->assign_block_vars("last_saved_info", array()); + } else { + $template->assign_block_vars("start_text_input", array()); + } - // create the output of page - $template->assign_vars(array( - 'TPL_REBUILD_SEARCH_MAIN' => true, + // create the output of page + $template->assign_vars(array( + 'TPL_REBUILD_SEARCH_MAIN' => true, - 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, + 'L_TIME_LIMIT_EXPLAIN' => $time_limit_explain, - '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, + '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, - 'LAST_SAVED_PROCESSING' => $last_saved_processing, + 'LAST_SAVED_PROCESSING' => $last_saved_processing, - 'SESSION_ID' => $userdata['session_id'], + 'SESSION_ID' => $userdata['session_id'], - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_REBUILD_SEARCH_ACTION' => "admin_rebuild_search.php?mode=submit", - )); + '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 +408,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 +522,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 c397c3267..474efebf8 100644 --- a/admin/admin_sitemap.php +++ b/admin/admin_sitemap.php @@ -1,9 +1,8 @@ cache; if (request_var('submit', '')) { - if (bb_update_config(array('static_sitemap' => request_var('static_sitemap', '')))) { - // TODO: delete only necessary cache - $cache->flush(); - } - bb_die('' . $lang['GO_BACK'] . ''); + if (bb_update_config(array('static_sitemap' => request_var('static_sitemap', '')))) { + // TODO: delete only necessary cache + $cache->flush(); + } + bb_die('' . $lang['GO_BACK'] . ''); } -$s_mess = $lang['SITEMAP_CREATED'].': '. bb_date($di->config->get('sitemap_time'), $di->config->get('post_date_format')) .' '. $lang['SITEMAP_AVAILABLE'] .': '. make_url('sitemap.xml') .''; +$s_mess = $lang['SITEMAP_CREATED'] . ': ' . bb_date($di->config->get('sitemap_time'), $di->config->get('post_date_format')) . ' ' . $lang['SITEMAP_AVAILABLE'] . ': ' . make_url('sitemap.xml') . ''; $template->assign_vars(array( - 'STATIC_SITEMAP' => $di->config->get('static_sitemap'), - 'MESSAGE' => (file_exists(INT_DATA_DIR ."sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED'], + 'STATIC_SITEMAP' => $di->config->get('static_sitemap'), + 'MESSAGE' => (file_exists(INT_DATA_DIR . "sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED'], )); -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 4a5a8d5bc..007256f65 100644 --- a/admin/admin_smilies.php +++ b/admin/admin_smilies.php @@ -1,9 +1,8 @@ config->get('smilies_path')); -while ($file = readdir($dir)) -{ - if (!is_dir(bb_realpath(BB_ROOT . $di->config->get('smilies_path') . '/' . $file))) - { - $img_size = getimagesize(BB_ROOT . $di->config->get('smilies_path') . '/' . $file); +while ($file = readdir($dir)) { + if (!is_dir(bb_realpath(BB_ROOT . $di->config->get('smilies_path') . '/' . $file))) { + $img_size = getimagesize(BB_ROOT . $di->config->get('smilies_path') . '/' . $file); - if ($img_size[0] && $img_size[1]) - { - $smiley_images[] = $file; - } - else if (preg_match('/.pak$/i', $file)) - { - $smiley_paks[] = $file; - } - } + if ($img_size[0] && $img_size[1]) { + $smiley_images[] = $file; + } else if (preg_match('/.pak$/i', $file)) { + $smiley_paks[] = $file; + } + } } closedir($dir); // Select main mode -if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) -{ - $smile_pak = (string) request_var('smile_pak', ''); - $clear_current = (int) request_var('clear_current', ''); - $replace_existing = (int) request_var('replace', ''); +if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) { + $smile_pak = (string)request_var('smile_pak', ''); + $clear_current = (int)request_var('clear_current', ''); + $replace_existing = (int)request_var('replace', ''); - 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'); - } + 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 . $di->config->get('smilies_path') . '/'. $smile_pak); + $fcontents = file(BB_ROOT . $di->config->get('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, + )); + } +} else if (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'], '', '')); +} else if (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 . $di->config->get('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 . $di->config->get('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 . $di->config->get('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 . $di->config->get('smilies_path') + )); +} else if ($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 . $di->config->get('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 . $di->config->get('smilies_path'), - )); + $template->assign_vars(array( + 'TPL_SMILE_EDIT' => true, + 'SMILEY_CODE' => $smile_data['code'], + 'SMILEY_EMOTICON' => $smile_data['emoticon'], + 'SMILEY_IMG' => BB_ROOT . $di->config->get('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 . $di->config->get('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 . $di->config->get('smilies_path') .'/'. $smilies[$i]['smile_url'], - 'CODE' => $smilies[$i]['code'], - 'EMOT' => $smilies[$i]['emoticon'], + 'SMILEY_IMG' => BB_ROOT . $di->config->get('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 c1415bbb5..8a7301d3f 100644 --- a/admin/admin_terms.php +++ b/admin/admin_terms.php @@ -1,28 +1,26 @@ config->get('terms') != $_POST['message']) -{ - bb_update_config(array('terms' => $_POST['message'])); - bb_die($lang['CONFIG_UPDATED']); +if (isset($_POST['post']) && $di->config->get('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' => $di->config->get('ext_link_new_win'), - 'MESSAGE' => ($di->config->get('terms')) ? $di->config->get('terms') : '', - 'PREVIEW_HTML' => (isset($_REQUEST['preview'])) ? bbcode2html($_POST['message']) : '', + 'S_ACTION' => 'admin_terms.php', + 'EXT_LINK_NW' => $di->config->get('ext_link_new_win'), + 'MESSAGE' => ($di->config->get('terms')) ? $di->config->get('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 b098c7075..767fa73cf 100644 --- a/admin/admin_ug_auth.php +++ b/admin/admin_ug_auth.php @@ -1,465 +1,415 @@ 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) + 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"); - 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']); - } +else if ($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']) || !in_array($c, array('all', $c_id)) || empty($c_data['forums'])) - { - continue; - } + if (!($c =& $_REQUEST['c']) || !in_array($c, array('all', $c_id)) || 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['RANK_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['RANK_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, - 'USER_OR_GROUPNAME' => $this_userdata['username'], - 'USER_LEVEL' => $lang['USER_LEVEL'] .' : '. $s_user_type, - '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; + $template->assign_vars(array( + 'TPL_AUTH_UG_MAIN' => true, + 'USER_OR_GROUPNAME' => $this_userdata['username'], + 'USER_LEVEL' => $lang['USER_LEVEL'] . ' : ' . $s_user_type, + '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; - 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']) || !in_array($c, array('all', $c_id)) || empty($c_data['forums'])) - { - continue; - } + if (!($c =& $_REQUEST['c']) || !in_array($c, array('all', $c_id)) || 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['RANK_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['RANK_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, - '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'), - )); - } + $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'), + )); + } - $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, - '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, + '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..1d19adc32 100644 --- a/admin/admin_user_ban.php +++ b/admin/admin_user_ban.php @@ -1,362 +1,295 @@ 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++; + } else if (!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 a1c0c3384..4621ad8fa 100644 --- a/admin/admin_user_search.php +++ b/admin/admin_user_search.php @@ -1,9 +1,8 @@ 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) * $di->config->get('topics_per_page')); - } + if ($page == 1) { + $offset = 0; + } else { + $offset = (($page - 1) * $di->config->get('topics_per_page')); + } - $limit = "LIMIT $offset, ".$di->config->get('topics_per_page'); + $limit = "LIMIT $offset, " . $di->config->get('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'] / $di->config->get('topics_per_page') ) ); + if ($total_pages['total'] == 0) { + bb_die($lang['SEARCH_NO_RESULTS']); + } + } + $num_pages = ceil(($total_pages['total'] / $di->config->get('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 752987788..96d57c257 100644 --- a/admin/admin_words.php +++ b/admin/admin_words.php @@ -1,9 +1,8 @@ cache; -if (!$di->config->get('use_word_censor')) -{ - bb_die('Word censor disabled'); +if (!$di->config->get('use_word_censor')) { + bb_die('Word censor disabled'); } $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'; +} else if (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, + )); + } else if ($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->delete('censored'); - $message .= '

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

' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '', ''); + $cache->delete('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); + } else if ($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->delete('censored'); + $cache->delete('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 2166d5b7e..8c9b21b33 100644 --- a/admin/index.php +++ b/admin/index.php @@ -9,280 +9,242 @@ $di = \TorrentPier\Di::getInstance(); $cache = $di->cache; // Generate relevant output -if (isset($_GET['pane']) && $_GET['pane'] == 'left') -{ - $module = []; - if (!$cache->has('admin_module_' . $user->id)) { - $dir = opendir('.'); - $setmodules = 1; - while ($file = readdir($dir)) { - if (preg_match('/^admin_.*?\.php$/', $file)) { - include('./' . $file); - } - } - unset($setmodules); - closedir($dir); - $cache->set('admin_module_' . $user->id, $module, 600); - } +if (isset($_GET['pane']) && $_GET['pane'] == 'left') { + $module = []; + if (!$cache->has('admin_module_' . $user->id)) { + $dir = opendir('.'); + $setmodules = 1; + while ($file = readdir($dir)) { + if (preg_match('/^admin_.*?\.php$/', $file)) { + include('./' . $file); + } + } + unset($setmodules); + closedir($dir); + $cache->set('admin_module_' . $user->id, $module, 600); + } - $module = $cache->get('admin_module_' . $user->id); + $module = $cache->get('admin_module_' . $user->id); - $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' => ($di->config->get('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' => ($di->config->get('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($di->config->get('board_startdate')); - $boarddays = (TIMENOW - $di->config->get('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($di->config->get('board_startdate')); + $boarddays = (TIMENOW - $di->config->get('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 . $di->config->get('avatar_path'))) - { - while( $file = readdir($avatar_dir) ) - { - if( $file != '.' && $file != '..' ) - { - $avatar_dir_size += filesize(BB_ROOT . $di->config->get('avatar_path') . '/' . $file); - } - } - closedir($avatar_dir); + if ($avatar_dir = opendir(BB_ROOT . $di->config->get('avatar_path'))) { + while ($file = readdir($avatar_dir)) { + if ($file != '.' && $file != '..') { + $avatar_dir_size += filesize(BB_ROOT . $di->config->get('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 ($di->config->get('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 ($di->config->get('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' => ($di->config->get('gzip_compress')) ? $lang['ON'] : $lang['OFF'], - 'TP_VERSION' => $di->config->get('tp_version') . (!empty($di->config->get('tp_release_state')) ? ' :: ' . $di->config->get('tp_release_state') : ''), - 'TP_RELEASE_DATE' => $di->config->get('tp_release_date'), - 'ZF_VERSION' => Zend\Version\Version::VERSION, - )); + $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' => ($di->config->get('gzip_compress')) ? $lang['ON'] : $lang['OFF'], + 'TP_VERSION' => $di->config->get('tp_version') . (!empty($di->config->get('tp_release_state')) ? ' :: ' . $di->config->get('tp_release_state') : ''), + 'TP_RELEASE_DATE' => $di->config->get('tp_release_date'), + 'ZF_VERSION' => Zend\Version\Version::VERSION, + )); - 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' => $di->config->get('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' => $di->config->get('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' => $di->config->get('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' => $di->config->get('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' => $di->config->get('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' => $di->config->get('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'); \ No newline at end of file +print_page('index.tpl', 'admin'); diff --git a/admin/pagestart.php b/admin/pagestart.php index 0a336eaaf..22a37f0a8 100644 --- a/admin/pagestart.php +++ b/admin/pagestart.php @@ -3,23 +3,20 @@ define('BB_ROOT', './../'); define('IN_ADMIN', true); -require(BB_ROOT .'common.php'); -require_once(INC_DIR .'functions_admin.php'); +require(BB_ROOT . 'common.php'); +require_once(INC_DIR . 'functions_admin.php'); $user->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 e8e2ce0c2..13fcfb640 100644 --- a/admin/stats/tr_stats.php +++ b/admin/stats/tr_stats.php @@ -2,47 +2,44 @@ define('IN_ADMIN', true); define('BB_ROOT', './../../'); -require(BB_ROOT .'common.php'); +require(BB_ROOT . 'common.php'); $user->session_start(); 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 = mysql_fetch_row(DB()->query($query)); // TODO: deprecated - echo ""; +foreach ($sql as $i => $query) { + $row = mysql_fetch_row(DB()->query($query)); // TODO: deprecated + 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 ''; \ No newline at end of file +echo ''; diff --git a/admin/stats/tracker.php b/admin/stats/tracker.php index a709bf72a..b9bea4081 100644 --- a/admin/stats/tracker.php +++ b/admin/stats/tracker.php @@ -2,7 +2,7 @@ define('IN_ADMIN', true); define('BB_ROOT', './../../'); -require(BB_ROOT .'common.php'); +require(BB_ROOT . 'common.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -20,7 +20,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', @@ -31,53 +31,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 ''; @@ -95,7 +95,7 @@ echo "\n $stat[tor_all] / $stat[tor_active] / $stat[tor_with_seeder]   - [ ". humn_size($stat['torrents_size']) ." ] + [ " . humn_size($stat['torrents_size']) . " ] \n"; @@ -104,36 +104,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 be55bfcc0..df22bede3 100644 --- a/ajax.php +++ b/ajax.php @@ -15,57 +15,52 @@ $user->session_start(); $di = \TorrentPier\Di::getInstance(); // Exit if board is disabled via ON/OFF trigger or by admin -if ($ajax->action != 'manage_admin') -{ - if ($di->config->get('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 ($di->config->get('board_disable')) { + $ajax->ajax_die($lang['BOARD_DISABLE']); + } else if (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 'change_torrent': - case 'gen_passkey': - require(INC_DIR . 'functions_torrent.php'); - break; + case 'view_torrent': + case 'mod_action': + case 'change_tor_status': + case 'change_torrent': + case 'gen_passkey': + 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'] @@ -78,359 +73,339 @@ $ajax->exec(); // class ajax_common { - var $request = []; - var $response = []; + var $request = []; + var $response = []; - var $valid_actions = [ - // ACTION NAME AJAX_AUTH - 'edit_user_profile' => ['admin'], - 'change_user_rank' => ['admin'], - 'change_user_opt' => ['admin'], - 'manage_user' => ['admin'], - 'manage_admin' => ['admin'], - 'sitemap' => ['admin'], + var $valid_actions = [ + // ACTION NAME AJAX_AUTH + 'edit_user_profile' => ['admin'], + 'change_user_rank' => ['admin'], + 'change_user_opt' => ['admin'], + 'manage_user' => ['admin'], + 'manage_admin' => ['admin'], + 'sitemap' => ['admin'], - 'mod_action' => ['mod'], - 'topic_tpl' => ['mod'], - 'group_membership' => ['mod'], - 'post_mod_comment' => ['mod'], + 'mod_action' => ['mod'], + 'topic_tpl' => ['mod'], + 'group_membership' => ['mod'], + 'post_mod_comment' => ['mod'], - 'avatar' => ['user'], - 'gen_passkey' => ['user'], - 'change_torrent' => ['user'], - 'change_tor_status' => ['user'], - 'manage_group' => ['user'], + 'avatar' => ['user'], + 'gen_passkey' => ['user'], + 'change_torrent' => ['user'], + 'change_tor_status' => ['user'], + 'manage_group' => ['user'], - 'view_post' => ['guest'], - 'view_torrent' => ['guest'], - 'user_register' => ['guest'], - 'posts' => ['guest'], - 'index_data' => ['guest'], - ]; + 'view_post' => ['guest'], + 'view_torrent' => ['guest'], + 'user_register' => ['guest'], + 'posts' => ['guest'], + 'index_data' => ['guest'], + ]; - var $action = null; + var $action = null; - /** - * Constructor - */ - function ajax_common() - { - ob_start([&$this, 'ob_handler']); - header('Content-Type: text/plain'); - } + /** + * Constructor + */ + function ajax_common() + { + ob_start([&$this, 'ob_handler']); + header('Content-Type: text/plain'); + } - /** - * Perform action - */ - function exec() - { - global $lang; + /** + * Perform action + */ + 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 - * - * @param $error_msg - * @param int $error_code - */ - 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 + * + * @param $error_msg + * @param int $error_code + */ + 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 + */ + function init() + { + $this->request = $_POST; + $this->action =& $this->request['action']; + } - /** - * Send data - */ - function send() - { - $this->response['action'] = $this->action; + /** + * Send data + */ + 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 - * - * @param $contents - * - * @return string - */ - function ob_handler($contents) - { - if (DBG_USER) - { - if ($contents) - { - $this->response['raw_output'] = $contents; - } - } + /** + * OB Handler + * + * @param $contents + * + * @return string + */ + 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 + */ + function check_admin_session() + { + global $user; - if (!$user->data['session_admin']) - { - if (empty($this->request['user_password'])) - { - $this->prompt_for_password(); - } - else - { - $login_args = [ - '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 = [ + '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 + */ + function prompt_for_password() + { + $this->response['prompt_password'] = 1; + $this->send(); + } - /** - * Prompt for confirmation - * - * @param $confirm_msg - */ - function prompt_for_confirm($confirm_msg) - { - if (empty($confirm_msg)) $this->ajax_die('false'); + /** + * Prompt for confirmation + * + * @param $confirm_msg + */ + 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 - * - * @param $forum_id - */ - function verify_mod_rights($forum_id) - { - global $userdata, $lang; + /** + * Verify mod rights + * + * @param $forum_id + */ + 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'); - } + function edit_user_profile() + { + require(AJAX_DIR . 'edit_user_profile.php'); + } - function change_user_rank() - { - require(AJAX_DIR . 'change_user_rank.php'); - } + function change_user_rank() + { + require(AJAX_DIR . 'change_user_rank.php'); + } - function change_user_opt() - { - require(AJAX_DIR . 'change_user_opt.php'); - } + function change_user_opt() + { + require(AJAX_DIR . 'change_user_opt.php'); + } - function gen_passkey() - { - require(AJAX_DIR . 'gen_passkey.php'); - } + function gen_passkey() + { + require(AJAX_DIR . 'gen_passkey.php'); + } - function group_membership() - { - require(AJAX_DIR . 'group_membership.php'); - } + function group_membership() + { + require(AJAX_DIR . 'group_membership.php'); + } - function manage_group() - { - require(AJAX_DIR . 'edit_group_profile.php'); - } + function manage_group() + { + require(AJAX_DIR . 'edit_group_profile.php'); + } - function post_mod_comment() - { - require(AJAX_DIR . 'post_mod_comment.php'); - } + function post_mod_comment() + { + require(AJAX_DIR . 'post_mod_comment.php'); + } - function view_post() - { - require(AJAX_DIR . 'view_post.php'); - } + function view_post() + { + require(AJAX_DIR . 'view_post.php'); + } - function change_tor_status() - { - require(AJAX_DIR . 'change_tor_status.php'); - } + function change_tor_status() + { + require(AJAX_DIR . 'change_tor_status.php'); + } - function change_torrent() - { - require(AJAX_DIR . 'change_torrent.php'); - } + function change_torrent() + { + require(AJAX_DIR . 'change_torrent.php'); + } - function view_torrent() - { - require(AJAX_DIR . 'view_torrent.php'); - } + function view_torrent() + { + require(AJAX_DIR . 'view_torrent.php'); + } - function user_register() - { - require(AJAX_DIR . 'user_register.php'); - } + function user_register() + { + require(AJAX_DIR . 'user_register.php'); + } - function mod_action() - { - require(AJAX_DIR . 'mod_action.php'); - } + function mod_action() + { + require(AJAX_DIR . 'mod_action.php'); + } - function posts() - { - require(AJAX_DIR . 'posts.php'); - } + function posts() + { + require(AJAX_DIR . 'posts.php'); + } - function manage_user() - { - require(AJAX_DIR . 'manage_user.php'); - } + function manage_user() + { + require(AJAX_DIR . 'manage_user.php'); + } - function manage_admin() - { - require(AJAX_DIR . 'manage_admin.php'); - } + function manage_admin() + { + require(AJAX_DIR . 'manage_admin.php'); + } - function topic_tpl() - { - require(AJAX_DIR . 'topic_tpl.php'); - } + function topic_tpl() + { + require(AJAX_DIR . 'topic_tpl.php'); + } - function index_data() - { - require(AJAX_DIR . 'index_data.php'); - } + function index_data() + { + require(AJAX_DIR . 'index_data.php'); + } - function avatar() - { - require(AJAX_DIR . 'avatar.php'); - } + function avatar() + { + require(AJAX_DIR . 'avatar.php'); + } - function sitemap() - { - require(AJAX_DIR .'sitemap.php'); - } -} \ No newline at end of file + function sitemap() + { + require(AJAX_DIR . 'sitemap.php'); + } +} diff --git a/bt/announce.php b/bt/announce.php index 269955a25..27ac96547 100644 --- a/bt/announce.php +++ b/bt/announce.php @@ -2,7 +2,7 @@ define('IN_TRACKER', true); define('BB_ROOT', './../'); -require(BB_ROOT .'common.php'); +require(BB_ROOT . 'common.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -10,182 +10,158 @@ $di = \TorrentPier\Di::getInstance(); /** @var \TorrentPier\Cache\Adapter $cache */ $cache = $di->cache; -if (empty($_SERVER['HTTP_USER_AGENT'])) -{ - header('Location: http://127.0.0.1', true, 301); - die; +if (empty($_SERVER['HTTP_USER_AGENT'])) { + header('Location: http://127.0.0.1', true, 301); + die; } // Ignore 'completed' event -if (isset($_GET['event']) && $_GET['event'] === 'completed') -{ - if (DBG_LOG) dbg_log(' ', '!die-event-completed'); - dummy_exit(mt_rand(600, 1200)); +if (isset($_GET['event']) && $_GET['event'] === 'completed') { + if (DBG_LOG) dbg_log(' ', '!die-event-completed'); + dummy_exit(mt_rand(600, 1200)); } $announce_interval = $di->config->get('announce_interval'); $passkey_key = $di->config->get('passkey_key'); -$max_left_val = 536870912000; // 500 GB -$max_up_down_val = 5497558138880; // 5 TB -$max_up_add_val = 85899345920; // 80 GB -$max_down_add_val = 85899345920; // 80 GB +$max_left_val = 536870912000; // 500 GB +$max_up_down_val = 5497558138880; // 5 TB +$max_up_add_val = 85899345920; // 80 GB +$max_down_add_val = 85899345920; // 80 GB // Recover info_hash -if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) -{ - $_GET['info_hash'] = $_GET['?info_hash']; +if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) { + $_GET['info_hash'] = $_GET['?info_hash']; } // Initial request verification -if (strpos($_SERVER['REQUEST_URI'], 'scrape') !== false) -{ - msg_die('Please disable SCRAPE!'); +if (strpos($_SERVER['REQUEST_URI'], 'scrape') !== false) { + msg_die('Please disable SCRAPE!'); } -if (!isset($_GET[$passkey_key]) || !is_string($_GET[$passkey_key]) || strlen($_GET[$passkey_key]) != BT_AUTH_KEY_LENGTH) -{ - msg_die('Please LOG IN and REDOWNLOAD this torrent (passkey not found)'); +if (!isset($_GET[$passkey_key]) || !is_string($_GET[$passkey_key]) || strlen($_GET[$passkey_key]) != BT_AUTH_KEY_LENGTH) { + msg_die('Please LOG IN and REDOWNLOAD this torrent (passkey not found)'); } // Input var names // String $input_vars_str = array( - 'info_hash', - 'peer_id', - 'event', - $passkey_key, + 'info_hash', + 'peer_id', + 'event', + $passkey_key, ); // Numeric $input_vars_num = array( - 'port', - 'uploaded', - 'downloaded', - 'left', - 'numwant', - 'compact', + 'port', + 'uploaded', + 'downloaded', + 'left', + 'numwant', + 'compact', ); // Init received data // String -foreach ($input_vars_str as $var_name) -{ - $$var_name = isset($_GET[$var_name]) ? (string) $_GET[$var_name] : null; +foreach ($input_vars_str as $var_name) { + $$var_name = isset($_GET[$var_name]) ? (string)$_GET[$var_name] : null; } // Numeric -foreach ($input_vars_num as $var_name) -{ - $$var_name = isset($_GET[$var_name]) ? (float) $_GET[$var_name] : null; +foreach ($input_vars_num as $var_name) { + $$var_name = isset($_GET[$var_name]) ? (float)$_GET[$var_name] : null; } // Passkey $passkey = isset($$passkey_key) ? $$passkey_key : null; // Verify request // Required params (info_hash, peer_id, port, uploaded, downloaded, left, passkey) -if (!isset($info_hash) || strlen($info_hash) != 20) -{ - msg_die('Invalid info_hash'); +if (!isset($info_hash) || strlen($info_hash) != 20) { + msg_die('Invalid info_hash'); } -if (!isset($peer_id) || strlen($peer_id) != 20) -{ - msg_die('Invalid peer_id'); +if (!isset($peer_id) || strlen($peer_id) != 20) { + msg_die('Invalid peer_id'); } -if (!isset($port) || $port < 0 || $port > 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 (!$di->config->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_GET['ip']) -{ - if (!$di->config->get('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 (!$di->config->get('allow_internal_ip') && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip)) - { - break; - } - $ip = $x_ip; - break; - } - } - } +if (!$di->config->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_GET['ip']) { + if (!$di->config->get('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 (!$di->config->get('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->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 = \Rych\Bencode\Bencode::encode([ + $output = \Rych\Bencode\Bencode::encode([ # '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'] : '-'; @@ -195,160 +171,133 @@ 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->delete(PEER_HASH_PREFIX . $peer_hash); - if (DBG_LOG) dbg_log(' ', 'stopped'); +if ($stopped) { + $cache->delete(PEER_HASH_PREFIX . $peer_hash); + if (DBG_LOG) dbg_log(' ', 'stopped'); } // Get last peer info from DB -if (!$lp_info) -{ - $lp_info = DB()->fetch_row(" - SELECT * FROM ". BB_BT_TRACKER ." WHERE peer_hash = '$peer_hash' LIMIT 1 +if (!$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 (!$di->config->get('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 (!$di->config->get('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 @@ -356,17 +305,13 @@ $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); + } } // Freeleech @@ -376,61 +321,58 @@ if ($tr_cfg['freeleech'] && $down_add) $down_add = 0; $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->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, PEER_HASH_EXPIRE); @@ -440,75 +382,68 @@ if (DBG_LOG && !$lp_info_cached) dbg_log(' ', '$lp_info-caching-FAIL'); // Get cached output $output = $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->set(PEERS_LIST_PREFIX . $topic_id, $output, PEERS_LIST_EXPIRE); + $peers_list_cached = $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 \Rych\Bencode\Bencode::encode($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 7f3040725..6f6a1ee3a 100644 --- a/bt/includes/init_tr.php +++ b/bt/includes/init_tr.php @@ -8,485 +8,451 @@ if ($tr_cfg['off']) tr_die($tr_cfg['off_reason']); // // Functions // -function tracker_exit () +function tracker_exit() { - global $DBS; + global $DBS; - 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); + 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 \Rych\Bencode\Bencode::encode(array('failure reason' => str_compact($msg))); + echo \Rych\Bencode\Bencode::encode(array('failure reason' => str_compact($msg))); - tracker_exit(); + tracker_exit(); } // Database class sql_db { - var $cfg = array(); - var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); - var $link = null; - var $result = null; - var $db_server = ''; - var $selected_db = null; + var $cfg = array(); + var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); + var $link = null; + var $result = null; + var $db_server = ''; + var $selected_db = null; - var $locked = false; + var $locked = false; - var $num_queries = 0; - var $sql_starttime = 0; - var $sql_inittime = 0; - var $sql_timetotal = 0; - var $sql_last_time = 0; - var $slow_time = 0; + var $num_queries = 0; + var $sql_starttime = 0; + var $sql_inittime = 0; + var $sql_timetotal = 0; + var $sql_last_time = 0; + var $slow_time = 0; - var $dbg = array(); - var $dbg_id = 0; - var $dbg_enabled = false; - var $cur_query = null; + var $dbg = array(); + var $dbg_id = 0; + var $dbg_enabled = false; + var $cur_query = null; - var $DBS = array(); + var $DBS = array(); - /** - * Constructor - */ - function sql_db ($cfg_values) - { - global $DBS; + /** + * Constructor + */ + function sql_db($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 + */ + 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 + */ + 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 + */ + 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 + */ + 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) + */ + 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 + */ + function num_rows($result = false) + { + $num_rows = false; - if ($result || ($result = $this->result)) - { - $num_rows = is_resource($result) ? mysql_num_rows($result) : false; - } + if ($result || ($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 + */ + 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 + */ + 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() + */ + 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) + */ + 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 + */ + 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) + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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) && ($ext = mysql_info($this->link))) - { - $info[] = "$ext"; - } - elseif (!$num && ($aff = $this->affected_rows($this->result))) - { - if ($aff != -1) - { - $info[] = "$aff rows"; - } - } + if (is_resource($this->link) && ($ext = mysql_info($this->link))) { + $info[] = "$ext"; + } elseif (!$num && ($aff = $this->affected_rows($this->result))) { + if ($aff != -1) { + $info[] = "$aff rows"; + } + } - return join(', ', $info); - } + return join(', ', $info); + } - /** - * Store debug info - */ - function debug ($mode) - { - if (!SQL_DEBUG) return; + /** + * Store debug info + */ + 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 + */ + 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 + */ + 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 + */ + 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'); - } -} \ No newline at end of file + $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..45f0319e9 100644 --- a/bt/index.php +++ b/bt/index.php @@ -1,3 +1,3 @@ (int) 1800, - 'failure reason' => (string) $msg, - 'warning message' => (string) $msg, - ]); + $output = \Rych\Bencode\Bencode::encode([ + 'min interval' => (int)1800, + 'failure reason' => (string)$msg, + 'warning message' => (string)$msg, + ]); - die($output); + die($output); } define('TR_ROOT', './'); @@ -39,19 +37,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 \Rych\Bencode\Bencode::encode($output); tracker_exit(); -exit; \ No newline at end of file +exit; diff --git a/callseed.php b/callseed.php index f94063431..c6e32edf9 100644 --- a/callseed.php +++ b/callseed.php @@ -11,39 +11,35 @@ $user->session_start(['req_login' => true]); $topic_id = $di->request->query->getInt('t'); -$t_data = topic_info($topic_id); +$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 = []; -$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 . $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 . $ban_user_id . ") AND u.user_active = 1 GROUP BY dl.user_id "); @@ -51,46 +47,40 @@ $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 . $topic_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.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 df2efb604..ba9d28928 100644 --- a/common.php +++ b/common.php @@ -4,21 +4,20 @@ if (isset($_REQUEST['GLOBALS'])) die(); ignore_user_abort(true); define('TIMESTART', utime()); -define('TIMENOW', time()); +define('TIMENOW', time()); -if (empty($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; +if (empty($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; if (empty($_SERVER['HTTP_USER_AGENT'])) $_SERVER['HTTP_USER_AGENT'] = ''; -if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = ''; -if (empty($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME'] = ''; +if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = ''; +if (empty($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME'] = ''; if (!defined('BB_ROOT')) define('BB_ROOT', './'); header('X-Frame-Options: SAMEORIGIN'); // 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']; } // Get all constants @@ -33,13 +32,13 @@ require_once(BB_ROOT . 'library/config.php'); $di = new \TorrentPier\Di(); // TODO: Need to get locale from settings -$di['settings.locale'] = function($di) { - return 'en'; +$di['settings.locale'] = function ($di) { + return 'en'; }; $di->register(new \TorrentPier\ServiceProviders\ConfigServiceProvider, [ - 'file.system.main' => __DIR__ . '/library/config.php', - 'file.local.main' => __DIR__ . '/library/config.local.php', + 'file.system.main' => __DIR__ . '/library/config.php', + 'file.local.main' => __DIR__ . '/library/config.local.php', ]); $di->register(new \TorrentPier\ServiceProviders\LogServiceProvider()); @@ -52,13 +51,14 @@ $di->register(new \TorrentPier\ServiceProviders\TranslationServiceProvider()); $di->register(new \TorrentPier\ServiceProviders\TwigServiceProvider()); $di->register(new \TorrentPier\ServiceProviders\CaptchaServiceProvider()); -$page_cfg = $di->config->page->toArray(); -$tr_cfg = $di->config->tracker->toArray(); +$page_cfg = $di->config->page->toArray(); +$tr_cfg = $di->config->tracker->toArray(); $rating_limits = $di->config->rating->toArray(); define('BB_CFG_LOADED', true); // Load Zend Framework use Zend\Loader\StandardAutoloader; + $loader = new StandardAutoloader(array('autoregister_zf' => true)); $loader->register(); @@ -72,29 +72,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($di->config->get('announce_interval') * (0.85 * $tr_cfg['expire_factor']))); // sec -define('PEERS_LIST_EXPIRE', round($di->config->get('announce_interval') * 0.7)); // sec +define('PEER_HASH_PREFIX', 'peer_'); +define('PEERS_LIST_PREFIX', 'peers_list_'); +define('PEER_HASH_EXPIRE', round($di->config->get('announce_interval') * (0.85 * $tr_cfg['expire_factor']))); // sec +define('PEERS_LIST_EXPIRE', round($di->config->get('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 @@ -104,26 +104,26 @@ define('BOT_UID', -746); require(CORE_DIR . 'dbs.php'); $DBS = new DBS([ - 'db' => [ - 'db' => [ - $di->config->services->db->hostname, - $di->config->services->db->database, - $di->config->services->db->username, - $di->config->services->db->password, - $di->config->services->db->charset, - false - ] - ], - 'db_alias' => $di->config->get('db_alias') + 'db' => [ + 'db' => [ + $di->config->services->db->hostname, + $di->config->services->db->database, + $di->config->services->db->username, + $di->config->services->db->password, + $di->config->services->db->charset, + false + ] + ], + 'db_alias' => $di->config->get('db_alias') ]); /** * TODO: @deprecated */ -function DB ($db_alias = 'db') +function DB($db_alias = 'db') { - global $DBS; - return $DBS->get_db_obj($db_alias); + global $DBS; + return $DBS->get_db_obj($db_alias); } /** @@ -139,335 +139,304 @@ require(INC_DIR . 'datastore/xcache.php'); require(INC_DIR . 'datastore/file.php'); // Initialize datastore -switch ($di->config->get('datastore_type')) -{ - case 'memcache': - $datastore = new datastore_memcache($di->config->get('cache.memcache'), $di->config->get('cache.prefix')); - break; +switch ($di->config->get('datastore_type')) { + case 'memcache': + $datastore = new datastore_memcache($di->config->get('cache.memcache'), $di->config->get('cache.prefix')); + break; - case 'sqlite': - $default_cfg = array( - 'db_file_path' => $di->config->get('cache.db_dir') .'datastore.sqlite.db', - 'pconnect' => true, - 'con_required' => true, - ); - $datastore = new datastore_sqlite($default_cfg, $di->config->get('cache.prefix')); - break; + case 'sqlite': + $default_cfg = array( + 'db_file_path' => $di->config->get('cache.db_dir') . 'datastore.sqlite.db', + 'pconnect' => true, + 'con_required' => true, + ); + $datastore = new datastore_sqlite($default_cfg, $di->config->get('cache.prefix')); + break; - case 'redis': - $datastore = new datastore_redis($di->config->get('cache.redis'), $di->config->get('cache.prefix')); - break; + case 'redis': + $datastore = new datastore_redis($di->config->get('cache.redis'), $di->config->get('cache.prefix')); + break; - case 'apc': - $datastore = new datastore_apc($di->config->get('cache.prefix')); - break; + case 'apc': + $datastore = new datastore_apc($di->config->get('cache.prefix')); + break; - case 'xcache': - $datastore = new datastore_xcache($di->config->get('cache.prefix')); - break; + case 'xcache': + $datastore = new datastore_xcache($di->config->get('cache.prefix')); + break; - case 'filecache': - default: $datastore = new datastore_file($di->config->get('cache.db_dir') . 'datastore/', $di->config->get('cache.prefix')); + case 'filecache': + default: + $datastore = new datastore_file($di->config->get('cache.db_dir') . 'datastore/', $di->config->get('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 (file_exists($file) && $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 (file_exists($file) && $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); } -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]); + } 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); + } } -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_TRACKER')) -{ - 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 = \Rych\Bencode\Bencode::encode(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_TRACKER')) { + 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 = \Rych\Bencode\Bencode::encode(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/configs/main.php b/configs/main.php index b656b9554..8acf9e66b 100644 --- a/configs/main.php +++ b/configs/main.php @@ -6,13 +6,13 @@ return [ 'services' => [ // Database 'db' => [ - 'debug' => '{self.debug}', - 'driver' => 'Pdo_Mysql', + 'debug' => '{self.debug}', + 'driver' => 'Pdo_Mysql', 'hostname' => '127.0.0.1', 'database' => 'tp_220', 'username' => 'user', 'password' => 'pass', - 'charset' => 'utf8' + 'charset' => 'utf8' ], // Cache @@ -41,18 +41,18 @@ return [ // Twig 'twig' => [ 'dir_templates' => __DIR__ . '/../templates/default', - 'dir_cache' => __DIR__ . '/../internal_data/cache', + 'dir_cache' => __DIR__ . '/../internal_data/cache', ], // Sphinx 'sphinx' => [ - 'debug' => '{self.debug}', - 'driver' => '{self.db.driver}', + 'debug' => '{self.debug}', + 'driver' => '{self.db.driver}', 'hostname' => '{self.db.hostname}', 'username' => 'user', 'password' => 'pass', - 'port' => 9306, - 'charset' => 'utf8' + 'port' => 9306, + 'charset' => 'utf8' ], // Logger @@ -60,7 +60,7 @@ return [ 'handlers' => [ function () { return new \Monolog\Handler\StreamHandler( - __DIR__.'/../internal_data/log/app.log', + __DIR__ . '/../internal_data/log/app.log', \Monolog\Logger::DEBUG ); } @@ -70,10 +70,10 @@ return [ // Captcha // Get a Google reCAPTCHA API Key: https://www.google.com/recaptcha/admin 'captcha' => [ - 'disabled' => false, + 'disabled' => false, 'public_key' => '', // your public key 'secret_key' => '', // your secret key - 'theme' => 'light', // light or dark + 'theme' => 'light', // light or dark ], ] ]; diff --git a/cron.php b/cron.php index d500aeb14..d020e7cc9 100644 --- a/cron.php +++ b/cron.php @@ -1,6 +1,6 @@ request->request->getInt(POST_FORUM_URL, 0); -$topic_id = $di->request->request->getInt(POST_TOPIC_URL, 0); -$mode = $di->request->request->get('mode'); +$forum_id = $di->request->request->getInt(POST_FORUM_URL, 0); +$topic_id = $di->request->request->getInt(POST_TOPIC_URL, 0); +$mode = $di->request->request->get('mode'); $confirmed = $di->request->request->has('confirm'); // Get new DL-status -if ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status') -{ - if ($di->request->request->has('dl_set_will')) - { - $new_dl_status = DL_STATUS_WILL; - $dl_key = 'dlw'; - } - elseif ($di->request->request->has('dl_set_down')) - { - $new_dl_status = DL_STATUS_DOWN; - $dl_key = 'dld'; - } - elseif ($di->request->request->has('dl_set_complete')) - { - $new_dl_status = DL_STATUS_COMPLETE; - $dl_key = 'dlc'; - } - elseif ($di->request->request->has('dl_set_cancel')) - { - $new_dl_status = DL_STATUS_CANCEL; - $dl_key = 'dla'; - } - else - { - bb_die('Invalid download status'); - } +if ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status') { + if ($di->request->request->has('dl_set_will')) { + $new_dl_status = DL_STATUS_WILL; + $dl_key = 'dlw'; + } elseif ($di->request->request->has('dl_set_down')) { + $new_dl_status = DL_STATUS_DOWN; + $dl_key = 'dld'; + } elseif ($di->request->request->has('dl_set_complete')) { + $new_dl_status = DL_STATUS_COMPLETE; + $dl_key = 'dlc'; + } elseif ($di->request->request->has('dl_set_cancel')) { + $new_dl_status = DL_STATUS_CANCEL; + $dl_key = 'dla'; + } else { + bb_die('Invalid download status'); + } } // Define redirect URL $full_url = isset($_POST['full_url']) ? str_replace('&', '&', htmlspecialchars($_POST['full_url'])) : ''; -if (isset($_POST['redirect_type']) && $_POST['redirect_type'] == 'search') -{ - $redirect_type = "search.php"; - $redirect = ($full_url) ? $full_url : "$dl_key=1"; -} -else -{ - $redirect_type = (!$topic_id) ? "viewforum.php" : "viewtopic.php"; - $redirect = ($full_url) ? $full_url : ((!$topic_id) ? POST_FORUM_URL ."=$forum_id" : POST_TOPIC_URL ."=$topic_id"); +if (isset($_POST['redirect_type']) && $_POST['redirect_type'] == 'search') { + $redirect_type = "search.php"; + $redirect = ($full_url) ? $full_url : "$dl_key=1"; +} else { + $redirect_type = (!$topic_id) ? "viewforum.php" : "viewtopic.php"; + $redirect = ($full_url) ? $full_url : ((!$topic_id) ? POST_FORUM_URL . "=$forum_id" : POST_TOPIC_URL . "=$topic_id"); } // Start session management @@ -61,104 +48,88 @@ $user->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/group.php b/group.php index 421343efc..0aa30c7b0 100644 --- a/group.php +++ b/group.php @@ -2,9 +2,9 @@ define('BB_SCRIPT', 'group'); define('BB_ROOT', './'); -require(BB_ROOT .'common.php'); -require(INC_DIR .'bbcode.php'); -require(INC_DIR .'functions_group.php'); +require(BB_ROOT . 'common.php'); +require(INC_DIR . 'bbcode.php'); +require(INC_DIR . 'functions_group.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -16,68 +16,60 @@ $select_sort_mode = $select_sort_order = ''; function generate_user_info(&$row, $date_format, $group_mod, &$from, &$posts, &$joined, &$pm, &$email, &$www, &$user_time, &$avatar) { - global $lang, $images; + global $lang, $images; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $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 = ($di->config->get('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); + $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 = ($di->config->get('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 = ($di->config->get('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 = ($di->config->get('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 = ($di->config->get('text_buttons')) ? ''. $lang['VISIT_WEBSITE_TXTB'] .'' : '' . $lang['VISIT_WEBSITE'] . ''; - } - else $www = ''; + if ($row['user_website']) { + $www = ($di->config->get('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 = $di->config->get('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 = $di->config->get('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, @@ -85,16 +77,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 @@ -105,597 +97,514 @@ 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'; + } 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; + } - $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['GROUPS'], - '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['GROUPS'], + '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']); + } - $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 ($di->config->get('group_send_email')) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + if ($di->config->get('group_send_email')) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($moderator['username'] ." <{$moderator['user_email']}>"); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('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' => $di->config->get('sitename'), - 'GROUP_MODERATOR' => $moderator['username'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'USER' => $userdata['username'], + 'SITENAME' => $di->config->get('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']); +} 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['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 ($di->config->get('group_send_email')) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + if ($di->config->get('group_send_email')) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('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' => $di->config->get('sitename'), - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('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); + } else if (!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']) && $di->config->get('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']) && $di->config->get('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($di->config->get('smtp_delivery')); + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('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' => $di->config->get('sitename'), - 'GROUP_NAME' => $group_info['group_name'], - 'U_GROUP' => make_url(GROUP_URL . $group_id), - )); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('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 = ''; + } 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'); - $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 = ''; + } 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 = ''; + } + } - // 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, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($group_moderator, $di->config->get('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['GROUPS'], - '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['GROUPS'], + '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: проверить на работу с новыми вложениями + switch ($view_mode) { + case 'releases': + // TODO: проверить на работу с новыми вложениями - 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, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($member, $di->config->get('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, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); + generate_user_info($member, $di->config->get('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 edd460c66..a05ccb6a0 100644 --- a/group_edit.php +++ b/group_edit.php @@ -2,8 +2,8 @@ define('BB_SCRIPT', 'group_edit'); define('BB_ROOT', './'); -require(BB_ROOT .'common.php'); -require(INC_DIR .'functions_group.php'); +require(BB_ROOT . 'common.php'); +require(INC_DIR . 'functions_group.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -19,96 +19,79 @@ $is_moderator = false; $submit = !empty($_POST['submit']); -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 ($is_moderator) -{ - // Avatar - if ($submit) - { - if (!empty($_FILES['avatar']['name']) && $di->config->get('group_avatars.up_allowed')) - { - require(INC_DIR .'functions_upload.php'); - $upload = new upload_common(); +if ($is_moderator) { + // Avatar + if ($submit) { + if (!empty($_FILES['avatar']['name']) && $di->config->get('group_avatars.up_allowed')) { + require(INC_DIR . 'functions_upload.php'); + $upload = new upload_common(); - if ($upload->init($di->config->get('group_avatars'), $_FILES['avatar']) && $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($di->config->get('group_avatars'), $_FILES['avatar']) && $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['GROUPS'], - '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['GROUPS'], + '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'], $di->config->get('group_avatars.max_width'), $di->config->get('group_avatars.max_height'), (round($di->config->get('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'], $di->config->get('group_avatars.max_width'), $di->config->get('group_avatars.max_height'), (round($di->config->get('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 80a1c2b9b..03a9811a7 100644 --- a/index.php +++ b/index.php @@ -11,32 +11,30 @@ $di = \TorrentPier\Di::getInstance(); $cache = $di->cache; $page_cfg['load_tpl_vars'] = array( - 'post_icons', + 'post_icons', ); -$show_last_topic = true; +$show_last_topic = true; $last_topic_max_len = 28; -$show_online_users = true; -$show_subforums = true; +$show_online_users = true; +$show_subforums = true; $datastore->enqueue(array( - 'stats', - 'moderators', + 'stats', + 'moderators', )); -if ($di->config->get('show_latest_news')) -{ - $datastore->enqueue('latest_news'); +if ($di->config->get('show_latest_news')) { + $datastore->enqueue('latest_news'); } -if ($di->config->get('show_network_news')) -{ - $datastore->enqueue('network_news'); +if ($di->config->get('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 @@ -46,29 +44,27 @@ $req_page .= ($viewcat) ? "_c{$viewcat}" : ''; define('REQUESTED_PAGE', $req_page); if (IS_GUEST && $cache->has(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'))) { - bb_exit($cache->get(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'))); + bb_exit($cache->get(REQUESTED_PAGE . '_guest_' . $di->config->get('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']; @@ -78,9 +74,8 @@ $excluded_forums_csv = $user->get_excluded_forums(AUTH_VIEW); $only_new = $user->opt_js['only_new']; // Validate requested category id -if ($viewcat && !($viewcat =& $forums['c'][$viewcat]['cat_id'])) -{ - redirect("index.php"); +if ($viewcat && !($viewcat =& $forums['c'][$viewcat]['cat_id'])) { + redirect("index.php"); } // Forums @@ -114,86 +109,80 @@ $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 (!$cache->has($cache_name)) { - $cat_forums = []; - foreach (DB()->fetch_rowset($sql) as $row) { - if (!($cat_id = $row['cat_id']) || !($forum_id = $row['forum_id'])) { - continue; - } + $cat_forums = []; + foreach (DB()->fetch_rowset($sql) as $row) { + if (!($cat_id = $row['cat_id']) || !($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->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->set($cache_name, $cat_forums, 180); + unset($row, $forums); + $datastore->rm('cat_forums'); } $cat_forums = $cache->get($cache_name); // 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); @@ -201,224 +190,198 @@ $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'], $di->config->get('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'], $di->config->get('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' => ($di->config->get('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' => ($di->config->get('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' => ($di->config->get('tor_stats')) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', - 'PEERS_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['PEERS_STAT'], $stats['peers'], $stats['seeders'], $stats['leechers']) : '', - 'SPEED_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['SPEED_STAT'], humn_size($stats['speed']) .'/s') : '', - 'SHOW_MOD_INDEX' => $di->config->get('show_mod_index'), - 'FORUM_IMG' => $images['forum'], - 'FORUM_NEW_IMG' => $images['forum_new'], - 'FORUM_LOCKED_IMG' => $images['forum_locked'], + // Tracker stats + 'TORRENTS_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', + 'PEERS_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['PEERS_STAT'], $stats['peers'], $stats['seeders'], $stats['leechers']) : '', + 'SPEED_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['SPEED_STAT'], humn_size($stats['speed']) . '/s') : '', + 'SHOW_MOD_INDEX' => $di->config->get('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 ($di->config->get('bt_show_dl_stat_on_index') && !IS_GUEST) -{ - show_bt_userdata($userdata['user_id']); +if ($di->config->get('bt_show_dl_stat_on_index') && !IS_GUEST) { + show_bt_userdata($userdata['user_id']); } // Latest news -if ($di->config->get('show_latest_news')) -{ - if (!$latest_news = $datastore->get('latest_news')) - { - $datastore->update('latest_news'); - $latest_news = $datastore->get('latest_news'); - } +if ($di->config->get('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'], $di->config->get('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'], $di->config->get('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 ($di->config->get('show_network_news')) -{ - if (!$network_news = $datastore->get('network_news')) - { - $datastore->update('network_news'); - $network_news = $datastore->get('network_news'); - } +if ($di->config->get('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'], $di->config->get('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'], $di->config->get('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 ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) -{ - $week_list = $today_list = array(); - $week_all = $today_all = false; +if ($di->config->get('birthday_check_day') && $di->config->get('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'], $di->config->get('birthday_check_day'), join(', ', $week_list)) . $week_all; - } - else $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('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'], $di->config->get('birthday_check_day'), join(', ', $week_list)) . $week_all; + } else $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('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 @@ -426,4 +389,4 @@ define('SHOW_ONLINE', $show_online_users); 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..2c03029df 100644 --- a/info.php +++ b/info.php @@ -2,7 +2,7 @@ define('BB_SCRIPT', 'info'); define('BB_ROOT', './'); -require(BB_ROOT .'common.php'); +require(BB_ROOT . 'common.php'); // Start session management $user->session_start(); @@ -11,32 +11,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 +43,40 @@ $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $h ?> - - - + + + -
        +
        -
        - -
        - -
        -
        -

        [ ]

        +
        + +
        + +
        +
        +

        [ ] +

        - \ No newline at end of file + diff --git a/library/ajax/avatar.php b/library/ajax/avatar.php index a31d0d9fa..2caa7e537 100644 --- a/library/ajax/avatar.php +++ b/library/ajax/avatar.php @@ -7,32 +7,29 @@ global $lang, $user; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->request['mode']; -$user_id = (int) $this->request['user_id']; +$mode = (string)$this->request['mode']; +$user_id = (int)$this->request['user_id']; -if (!$user_id || !($u_data = get_userdata($user_id))) -{ - $this->ajax_die('Invalid user_id'); +if (!$user_id || !($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 880aa99ac..20a0a4b32 100644 --- a/library/ajax/change_tor_status.php +++ b/library/ajax/change_tor_status.php @@ -9,101 +9,90 @@ $di = \TorrentPier\Di::getInstance(); if (!isset($this->request['topic_id'])) $this->ajax_die('Invalid topic_id'); -$topic_id = (int) $this->request['topic_id']; -$mode = (string) $this->request['mode']; +$topic_id = (int)$this->request['topic_id']; +$mode = (string)$this->request['mode']; -if ($di->config->get('tor_comment')) -{ - $comment = (string) $this->request['comment']; +if ($di->config->get('tor_comment')) { + $comment = (string)$this->request['comment']; } $tor = DB()->fetch_row(" SELECT tor.poster_id, tor.forum_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.topic_id = $topic_id LIMIT 1 "); if (!$tor) $this->ajax_die($lang['TORRENT_FAILED']); -switch ($mode) -{ - case 'status': - $new_status = (int) $this->request['status']; +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 (!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']); - } + // Тот же статус + 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']); - } + // Запрет на изменение/присвоение 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 = {$topic_id} LIMIT 1"); - } - else - { - $this->verify_mod_rights($tor['forum_id']); - } + // Права на изменение статуса + 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 = {$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); - } - } + // Подтверждение изменения статуса, выставленного другим модератором + 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($topic_id, $new_status); + change_tor_status($topic_id, $new_status); - $this->response['status'] = $di->config->get('tor_icons.' . $new_status) .' '. $lang['TOR_STATUS_NAME'][$new_status]. ' · '. profile_url($userdata) .' · '. delta_time(TIMENOW) . $lang['TOR_BACK']. ''; + $this->response['status'] = $di->config->get('tor_icons.' . $new_status) . ' ' . $lang['TOR_STATUS_NAME'][$new_status] . ' · ' . profile_url($userdata) . ' · ' . delta_time(TIMENOW) . $lang['TOR_BACK'] . ''; - if ($di->config->get('tor_comment') && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $di->config->get('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 . $topic_id), $di->config->get('tor_icons.' . $new_status) .' '.$lang['TOR_STATUS_NAME'][$new_status]); + if ($di->config->get('tor_comment') && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $di->config->get('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 . $topic_id), $di->config->get('tor_icons.' . $new_status) . ' ' . $lang['TOR_STATUS_NAME'][$new_status]); - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; + 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; + send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']); + cache_rm_user_sessions($tor['poster_id']); + } + } + break; - case 'status_reply': - if (!$di->config->get('tor_comment')) $this->ajax_die($lang['MODULE_OFF']); + case 'status_reply': + if (!$di->config->get('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 . $topic_id), $tor['topic_title']); + $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 . $topic_id), $tor['topic_title']); - if ($comment && $comment != $lang['COMMENT']) $message .= "\n\n[b]". $lang['COMMENT'] .'[/b]: '. $comment; + 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; + send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']); + cache_rm_user_sessions($tor['checked_user_id']); + break; } -$this->response['topic_id'] = $topic_id; \ No newline at end of file +$this->response['topic_id'] = $topic_id; diff --git a/library/ajax/change_torrent.php b/library/ajax/change_torrent.php index 8ab3bd125..25bf10164 100644 --- a/library/ajax/change_torrent.php +++ b/library/ajax/change_torrent.php @@ -4,68 +4,59 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $lang; -if (!isset($this->request['t'])) -{ - $this->ajax_die('Invalid AJAX topic'); +if (!isset($this->request['t'])) { + $this->ajax_die('Invalid AJAX topic'); } -if (!isset($this->request['u'])) -{ - //$this->ajax_die('Invalid AJAX user'); +if (!isset($this->request['u'])) { + //$this->ajax_die('Invalid AJAX user'); } -if (!isset($this->request['type'])) -{ - $this->ajax_die('Invalid AJAX type'); +if (!isset($this->request['type'])) { + $this->ajax_die('Invalid AJAX type'); } -$topic_id = (int) $this->request['t']; +$topic_id = (int)$this->request['t']; //$req_uid = (int) $this->request['u']; -$type = (string) $this->request['type']; +$type = (string)$this->request['type']; $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($topic_id, $tor_type); - $url = make_url(TOPIC_URL . $topic_id); - $title = $lang['CHANGE_TOR_TYPE']; - 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($topic_id, $tor_type); + $url = make_url(TOPIC_URL . $topic_id); + $title = $lang['CHANGE_TOR_TYPE']; + break; - case 'reg'; - tracker_register($topic_id); - $url = (TOPIC_URL . $topic_id); - break; + case 'reg'; + tracker_register($topic_id); + $url = (TOPIC_URL . $topic_id); + break; - case 'unreg'; - tracker_unregister($topic_id); - $url = (TOPIC_URL . $topic_id); - break; + case 'unreg'; + tracker_unregister($topic_id); + $url = (TOPIC_URL . $topic_id); + break; - case 'del_torrent'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_TORRENT']); - delete_torrent($topic_id); - $url = make_url(TOPIC_URL . $topic_id); - break; + case 'del_torrent'; + if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_TORRENT']); + delete_torrent($topic_id); + $url = make_url(TOPIC_URL . $topic_id); + break; - case 'del_torrent_move_topic'; - if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); - delete_torrent($topic_id); - $url = make_url("modcp.php?t=$topic_id&mode=move"); - break; + case 'del_torrent_move_topic'; + if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); + delete_torrent($topic_id); + $url = make_url("modcp.php?t=$topic_id&mode=move"); + 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 f6f9be670..e691f1c6a 100644 --- a/library/ajax/change_user_opt.php +++ b/library/ajax/change_user_opt.php @@ -4,30 +4,26 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $bf, $lang; -$user_id = (int) $this->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 || !($u_data = get_userdata($user_id))) -{ - $this->ajax_die('invalid user_id'); +if (!$user_id || !($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 08342b420..fd507256f 100644 --- a/library/ajax/change_user_rank.php +++ b/library/ajax/change_user_rank.php @@ -4,24 +4,22 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $datastore, $lang; -$ranks = $datastore->get('ranks'); +$ranks = $datastore->get('ranks'); $rank_id = intval($this->request['rank_id']); -if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!($user_id = intval($this->request['user_id'])) || !($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 3bbca2615..007cb1d08 100644 --- a/library/ajax/edit_group_profile.php +++ b/library/ajax/edit_group_profile.php @@ -7,49 +7,45 @@ global $userdata, $lang; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if (!($group_id = intval($this->request['group_id'])) || !($group_info = get_group_data($group_id))) -{ - $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); +if (!($group_id = intval($this->request['group_id'])) || !($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 acf351c51..9ab13c53c 100644 --- a/library/ajax/edit_user_profile.php +++ b/library/ajax/edit_user_profile.php @@ -7,165 +7,143 @@ global $lang; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) -{ - $this->ajax_die($lang['NO_USER_ID_SPECIFIED']); +if (!($user_id = intval($this->request['user_id'])) || !($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 (!$di->config->get('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 (!$di->config->get('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 (!$di->config->get('birthday_enabled')) $this->ajax_die($lang['MODULE_OFF']); - $birthday_date = date_parse($value); + case 'user_birthday': + if (!$di->config->get('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'] > $di->config->get('birthday_max_age')) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], $di->config->get('birthday_max_age'))); - } - elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] < $di->config->get('birthday_min_age')) - { - $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $di->config->get('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'] > $di->config->get('birthday_max_age')) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_HIGH'], $di->config->get('birthday_max_age'))); + } elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] < $di->config->get('birthday_min_age')) { + $this->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $di->config->get('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 * $di->config->get('board_timezone')); - if ((($value = strtotime($value, $tz)) < $di->config->get('board_startdate')) || ($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 * $di->config->get('board_timezone')); + if ((($value = strtotime($value, $tz)) < $di->config->get('board_startdate')) || ($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..6bc2edfa6 100644 --- a/library/ajax/gen_passkey.php +++ b/library/ajax/gen_passkey.php @@ -4,22 +4,18 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $userdata, $lang; -$req_uid = (int) $this->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; -} -else $this->ajax_die($lang['NOT_AUTHORISED']); \ No newline at end of file + $this->response['passkey'] = $passkey; +} else $this->ajax_die($lang['NOT_AUTHORISED']); diff --git a/library/ajax/group_membership.php b/library/ajax/group_membership.php index 8457f60fb..2f30eb213 100644 --- a/library/ajax/group_membership.php +++ b/library/ajax/group_membership.php @@ -4,66 +4,54 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $lang, $user; -if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) -{ - $this->ajax_die("invalid user_id: $user_id"); +if (!($user_id = intval($this->request['user_id'])) || !($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 c6aa002e2..ae2683f50 100644 --- a/library/ajax/index_data.php +++ b/library/ajax/index_data.php @@ -7,124 +7,113 @@ global $lang, $userdata, $datastore; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->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'], $di->config->get('birthday_check_day'), join(', ', $html)); - } - else $html = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('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'], $di->config->get('birthday_check_day'), join(', ', $html)); + } else $html = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('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; - DB()->query("UPDATE " . BB_USERS . " SET user_timezone = $tz WHERE user_id = " . $userdata['user_id'] . " LIMIT 1"); - 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; + DB()->query("UPDATE " . BB_USERS . " SET user_timezone = $tz WHERE user_id = " . $userdata['user_id'] . " LIMIT 1"); + 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 .= ($di->config->get('seed_bonus_enabled')) ? ''. $lang['SEED_BONUS'] .'' : ''; - $html .= ' + ' . $lang['DOWNLOADED'] . ' + ' . $lang['UPLOADED'] . ' + ' . $lang['RELEASED'] . ' + ' . $lang['BONUS'] . ''; + $html .= ($di->config->get('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 .= ($di->config->get('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 .= ($di->config->get('seed_bonus_enabled')) ? '' . $profiledata['user_points'] . '' : ''; + $html .= ' - '. $lang['SPEED'] .' - '. $lang['DL_DL_SPEED'] .': '. $speed_down .' - '. $lang['DL_UL_SPEED'] .': '. $speed_up .''; - $html .= ($di->config->get('seed_bonus_enabled')) ? '' : ''; - $html .= ''; + ' . $lang['SPEED'] . ' + ' . $lang['DL_DL_SPEED'] . ': ' . $speed_down . ' + ' . $lang['DL_UL_SPEED'] . ': ' . $speed_up . ''; + $html .= ($di->config->get('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 63069f346..d8e987557 100644 --- a/library/ajax/manage_admin.php +++ b/library/ajax/manage_admin.php @@ -10,106 +10,101 @@ $di = \TorrentPier\Di::getInstance(); /** @var \TorrentPier\Cache\Adapter $cache */ $cache = $di->cache; -$mode = (string) $this->request['mode']; +$mode = (string)$this->request['mode']; -switch ($mode) -{ - case 'clear_cache': +switch ($mode) { + case 'clear_cache': - $cache->flush(); + $cache->flush(); - $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 {$di->config->get('sphinx_config_path')} --all --rotate", $result); + exec("indexer --config {$di->config->get('sphinx_config_path')} --all --rotate", $result); - if (!is_file($di->config->get('sphinx_config_path').".log")) - { - file_put_contents($di->config->get('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($di->config->get('sphinx_config_path') . ".log")) { + file_put_contents($di->config->get('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($di->config->get('sphinx_config_path').".log", "##############################".date("H:i:s", TIMENOW)."##############################\r\n", FILE_APPEND); + file_put_contents($di->config->get('sphinx_config_path') . ".log", "##############################" . date("H:i:s", TIMENOW) . "##############################\r\n", FILE_APPEND); - foreach ($result as $row) - { - file_put_contents($di->config->get('sphinx_config_path').".log", $row."\r\n", FILE_APPEND); - } + foreach ($result as $row) { + file_put_contents($di->config->get('sphinx_config_path') . ".log", $row . "\r\n", FILE_APPEND); + } - file_put_contents($di->config->get('sphinx_config_path').".log", "\r\n", FILE_APPEND); - file_put_contents($di->config->get('sphinx_config_path').".log", "\r\n", FILE_APPEND); + file_put_contents($di->config->get('sphinx_config_path') . ".log", "\r\n", FILE_APPEND); + file_put_contents($di->config->get('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 df31ade5a..ada4b202e 100644 --- a/library/ajax/manage_user.php +++ b/library/ajax/manage_user.php @@ -7,81 +7,74 @@ global $userdata, $lang; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->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 b9d7c9d7b..06526a496 100644 --- a/library/ajax/mod_action.php +++ b/library/ajax/mod_action.php @@ -7,128 +7,117 @@ global $userdata, $lang, $datastore; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->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 = explode(',', $topics); + $topic_ids = explode(',', $topics); - foreach($topic_ids as $topic_id) - { - change_tor_status($topic_id, $status); - } + foreach ($topic_ids as $topic_id) { + change_tor_status($topic_id, $status); + } - $this->response['status'] = $di->config->get('tor_icons.' . $status); - $this->response['topics'] = $topic_ids; - break; + $this->response['status'] = $di->config->get('tor_icons.' . $status); + $this->response['topics'] = $topic_ids; + 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(',', $di->config->get('latest_news_forum_id'))); - if (isset($news_forums[$t_data['forum_id']]) && $di->config->get('show_latest_news')) - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } + // Обновление кеша новостей на главной + $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); + if (isset($news_forums[$t_data['forum_id']]) && $di->config->get('show_latest_news')) { + $datastore->enqueue('latest_news'); + $datastore->update('latest_news'); + } - $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); - if (isset($net_forums[$t_data['forum_id']]) && $di->config->get('show_network_news')) - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } + $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); + if (isset($net_forums[$t_data['forum_id']]) && $di->config->get('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..e62619c98 100644 --- a/library/ajax/post_mod_comment.php +++ b/library/ajax/post_mod_comment.php @@ -4,57 +4,55 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $lang, $userdata; -$post_id = (int) $this->request['post_id']; -$mc_type = (int) $this->request['mc_type']; -$mc_text = (string) $this->request['mc_text']; +$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'); $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 143844e50..31ba4b009 100644 --- a/library/ajax/posts.php +++ b/library/ajax/posts.php @@ -7,209 +7,176 @@ global $lang, $userdata; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if (!isset($this->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['attach_ext_id'] || ($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['attach_ext_id'] || ($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 ($di->config->get('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 ($di->config->get('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)) && $row['last_post_time']) - { - if ($userdata['user_level'] == USER) - { - if (TIMENOW - $row['last_post_time'] < $di->config->get('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)) && $row['last_post_time']) { + if ($userdata['user_level'] == USER) { + if (TIMENOW - $row['last_post_time'] < $di->config->get('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 ($di->config->get('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 ($di->config->get('topic_notify_enabled')) - { - $notify = !empty($this->request['notify']); - user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); - } + if ($di->config->get('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 c6783dff4..84269ef9d 100644 --- a/library/ajax/sitemap.php +++ b/library/ajax/sitemap.php @@ -7,52 +7,50 @@ global $lang; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->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, $di->config->get('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, $di->config->get('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 d5216cee6..27cefc75d 100644 --- a/library/ajax/topic_tpl.php +++ b/library/ajax/topic_tpl.php @@ -8,165 +8,145 @@ 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 66ec1cde7..7b1f382ad 100644 --- a/library/ajax/user_register.php +++ b/library/ajax/user_register.php @@ -7,69 +7,51 @@ global $lang, $userdata; /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$mode = (string) $this->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 336c06d02..833aa7677 100644 --- a/library/ajax/view_post.php +++ b/library/ajax/view_post.php @@ -4,12 +4,11 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $user, $lang; -$post_id = (int) $this->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 +16,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 8373f29d7..0dcdffc6f 100644 --- a/library/ajax/view_torrent.php +++ b/library/ajax/view_torrent.php @@ -4,11 +4,10 @@ if (!defined('IN_AJAX')) die(basename(__FILE__)); global $lang; -if (!isset($this->request['t'])) -{ - $this->ajax_die('empty topic_id'); // TODO: перевести +if (!isset($this->request['t'])) { + $this->ajax_die('empty topic_id'); // TODO: перевести } -$topic_id = (int) $this->request['t']; +$topic_id = (int)$this->request['t']; global $bnc_error; $bnc_error = 0; @@ -16,173 +15,149 @@ $bnc_error = 0; // Получение торрент-файла $file_path = get_attach_path($topic_id, 8); -if (($file_contents = @file_get_contents($file_path)) === false) -{ - if (IS_AM) - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] ."\n\n". htmlCHR($file_path)); - } - else - { - $this->ajax_die($lang['ERROR_NO_ATTACHMENT']); - } +if (($file_contents = @file_get_contents($file_path)) === false) { + if (IS_AM) { + $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] . "\n\n" . htmlCHR($file_path)); + } 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 { - var $tor_decoded = array(); - var $files_ary = array('/' => ''); - var $multiple = null; - var $root_dir = ''; - var $files_html = ''; + var $tor_decoded = array(); + var $files_ary = array('/' => ''); + var $multiple = null; + var $root_dir = ''; + var $files_html = ''; - function torrent ($decoded_file_contents) - { - $this->tor_decoded = $decoded_file_contents; - } + function torrent($decoded_file_contents) + { + $this->tor_decoded = $decoded_file_contents; + } - function get_filelist () - { - $this->build_filelist_array(); + 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['/']); + } + } - function build_filelist_array () - { - $info = $this->tor_decoded['info']; + 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['/']); + } + } - function build_file_item ($name, $length) - { - global $images, $lang; + function build_file_item($name, $length) + { + global $images, $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $magnet_name = $magnet_ext = ''; + $magnet_name = $magnet_ext = ''; - if ($di->config->get('magnet_links_enabled')) - { - $magnet_name = ''; - $magnet_ext = ''; - } + if ($di->config->get('magnet_links_enabled')) { + $magnet_name = ''; + $magnet_ext = ''; + } - return "$name $length $magnet_name $magnet_ext"; - } + return "$name $length $magnet_name $magnet_ext"; + } - function build_filelist_html () - { - global $html; - return $html->array2html($this->files_ary); - } + 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; \ No newline at end of file +$this->response['html'] = $tor_filelist; diff --git a/library/config.php b/library/config.php index 3ce4f4827..1384439e5 100644 --- a/library/config.php +++ b/library/config.php @@ -7,576 +7,576 @@ $domain_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : $do $config = [ - // Debug (twig etc.) - 'debug' => true, - - // Increase number after changing js or css - 'js_ver' => 1, - 'css_ver' => 1, - - // Version info - 'tp_version' => '2.2.0', - 'tp_release_date' => '**/**/2016', - 'tp_release_state' => 'ALPHA', - - 'services' => [ - 'cache' => [ - 'adapter' => \TorrentPier\Cache\FileAdapter::class, - 'options' => [ - 'directory' => __DIR__ . '/../internal_data/cache', - 'prefix' => 'hash string' - ], - ], - /*'cache' => [ - 'adapter' => \TorrentPier\Cache\MemoryAdapter::class, - 'options' => [ - 'servers' => [ - 'host' => '127.0.0.1', - 'port' => 11211, - 'weight' => 100, - ], - ], - ],*/ - - // Database - 'db' => [ - 'debug' => '{self.debug}', - 'driver' => 'Pdo_Mysql', - 'hostname' => '127.0.0.1', - 'database' => 'tp_220', - 'username' => 'user', - 'password' => 'pass', - 'charset' => 'utf8' - ], - - // Sphinx - 'sphinx' => [ - 'debug' => '{self.debug}', - 'driver' => '{self.db.driver}', - 'hostname' => '{self.db.hostname}', - 'username' => 'user', - 'password' => 'pass', - 'port' => 9306, - 'charset' => 'utf8' - ], - - // Twig - 'twig' => [ - 'dir_templates' => __DIR__ . '/../templates/default', - 'dir_cache' => __DIR__ . '/../internal_data/cache', - ], - - // Translation - 'translator' => [ - 'dir_cache' => __DIR__ . '/../internal_data/cache', - 'resources' => [ - [ - 'resource' => __DIR__ . '/../messages/ru.php', - 'locale' => 'ru', - ], - [ - 'resource' => __DIR__ . '/../messages/en.php', - 'locale' => 'en', - ] - ] - ], - - // Log - 'log' => [ - 'handlers' => [ - function () { - return new \Monolog\Handler\StreamHandler( - __DIR__.'/../internal_data/log/app.log', - \Monolog\Logger::DEBUG - ); - } - ] - ], - ], - - // Aliases - // TODO: удалить - 'db_alias' => [ - 'log' => 'db', // BB_LOG - 'search' => 'db', // BB_TOPIC_SEARCH - 'sres' => 'db', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS - 'u_ses' => 'db', // BB_USER_SES, BB_USER_LASTVISIT - 'dls' => 'db', // BB_BT_DLS_* - 'ip' => 'db', // BB_POSTS_IP - 'ut' => 'db', // BB_TOPICS_USER_POSTED - 'pm' => 'db', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT - 'pt' => 'db', // BB_POSTS_TEXT - ], - - // Cache - 'cache' => [ - 'db_dir' => realpath(BB_ROOT) .'/internal_data/cache/filecache/', - 'prefix' => 'tp_', // Префикс кеша ('tp_') - 'memcache' => [ - 'host' => '127.0.0.1', - 'port' => 11211, - 'pconnect' => true, - 'con_required' => true, - ], - 'redis' => [ - 'host' => '127.0.0.1', - 'port' => 6379, - 'con_required' => true, - ] - ], - - // Datastore - // Available datastore types: memcache, sqlite, redis, apc, xcache (default filecache) - // TODO: удалить - 'datastore_type' => 'filecache', - - // Server - 'server_name' => $domain_name, // The domain name from which this board runs - 'server_port' => (!empty($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 80, // The port your server is running on - 'script_path' => '/', // The path where FORUM is located relative to the domain name - - // GZip - 'gzip_compress' => true, // compress output - - // Tracker - 'announce_interval' => 2400, // Announce interval (default: 1800) - 'passkey_key' => 'uk', // Passkey key name in GET request - 'ignore_reported_ip' => false, // Ignore IP reported by client - 'verify_reported_ip' => true, // Verify IP reported by client against $_SERVER['HTTP_X_FORWARDED_FOR'] - 'allow_internal_ip' => false, // Allow internal IP (10.xx.. etc.) - - // Ocelot - 'ocelot' => [ - 'enabled' => false, - 'host' => $domain_name, - 'port' => 2710, - 'url' => "http://$domain_name:2710/", // with '/' - 'secret' => 'some_10_chars', // 10 chars - 'stats' => 'some_10_chars', // 10 chars - ], - - // FAQ url help link - 'how_to_download_url_help' => 'viewtopic.php?t=1', // Как скачивать? - 'what_is_torrent_url_help' => 'viewtopic.php?t=2', // Что такое торрент? - 'ratio_url_help' => 'viewtopic.php?t=3', // Рейтинг и ограничения - 'search_help_url' => 'viewtopic.php?t=4', // Помощь по поиску - - // Torrents - 'bt_min_ratio_allow_dl_tor' => 0.3, // 0 - disable - 'bt_min_ratio_warning' => 0.6, // 0 - disable - - 'show_dl_status_in_search' => true, - 'show_dl_status_in_forum' => true, - 'allow_dl_list_names_mode' => true, - - // Days to keep torrent registered - 'seeder_last_seen_days_keep' => 0, // сколько дней назад был сид последний раз - 'seeder_never_seen_days_keep' => 0, // сколько дней имеется статус "Сида не было никогда" - - // DL-Status (days to keep user's dlstatus records) - 'dl_will_days_keep' => 360, - 'dl_down_days_keep' => 180, - 'dl_complete_days_keep' => 180, - 'dl_cancel_days_keep' => 30, - - // Tor-Stats - 'torstat_days_keep' => 60, // days to keep user's per-torrent stats - - // Tor-Help - 'torhelp_enabled' => false, // find dead torrents (without seeder) that user might help seeding - - // URL's - 'ajax_url' => 'ajax.php', # "http://{$_SERVER['SERVER_NAME']}/ajax.php" - 'dl_url' => 'dl.php?t=', # "http://{$domain_name}/dl.php" - 'login_url' => 'login.php', # "http://{$domain_name}/login.php" - 'posting_url' => 'posting.php', # "http://{$domain_name}/posting.php" - 'pm_url' => 'privmsg.php', # "http://{$domain_name}/privmsg.php" - - // Language - 'charset' => 'utf8', // page charset - 'lang' => [ - 'ru' => [ - 'name' => 'Русский', - 'locale' => 'ru_RU.UTF-8', - 'encoding' => 'UTF-8', - ], - 'uk' => [ - 'name' => 'Український', - 'locale' => 'uk_UA.UTF-8', - 'encoding' => 'UTF-8', - ], - 'en' => [ - 'name' => 'English', - 'locale' => 'en_US.UTF-8', - 'encoding' => 'UTF-8', - ], - ], - - // Templates - 'templates' => [ - // TODO: новый шаблонизатор - 'default' => 'Стандартный', - ], - - 'tpl_name' => 'default', - 'stylesheet' => 'main.css', - - 'show_sidebar1_on_every_page' => false, - 'show_sidebar2_on_every_page' => false, - - // Cookie - 'cookie_domain' => in_array($domain_name, array(getenv('SERVER_ADDR'), 'localhost')) ? '' : ".$domain_name", - 'cookie_secure' => (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') ? 1 : 0, - 'cookie_prefix' => 'bb_', // 'bb_' - - // Sessions - // TODO: заменить + глобальный объект user - 'session_update_intrv' => 180, // sec - 'user_session_duration' => 1800, // sec - 'admin_session_duration' => 6*3600, // sec - 'user_session_gc_ttl' => 1800, // number of seconds that a staled session entry may remain in sessions table - 'session_cache_gc_ttl' => 1200, // sec - 'max_last_visit_days' => 14, // days - 'last_visit_update_intrv' => 3600, // sec - - // Registration - 'invalid_logins' => 5, // Количество неверных попыток ввода пароля, перед выводом проверки капчей - 'new_user_reg_disabled' => false, // Запретить регистрацию новых учетных записей - 'unique_ip' => false, // Запретить регистрацию нескольких учетных записей с одного ip - 'new_user_reg_restricted' => false, // Ограничить регистрацию новых пользователей по времени с 01:00 до 17:00 - 'reg_email_activation' => true, // Требовать активацию учетной записи по email - - // Email - // TODO: заменить - 'emailer_disabled' => false, - 'smtp_delivery' => false, // send email via a named server instead of the local mail function - 'smtp_ssl' => false, // use ssl connect - 'smtp_host' => '', // SMTP server host - 'smtp_port' => 25, // SMTP server port - 'smtp_username' => '', // enter a username if your SMTP server requires it - 'smtp_password' => '', // enter a password if your SMTP server requires it - 'smtp' => [ - 'name' => 'yandex.ru', - 'host' => 'smtp.yandex.ru', - 'port' => 465, - 'connection_class' => 'login', - 'connection_config' => [ - 'username' => '', - 'password' => '', - 'ssl' => 'ssl', - ], - ], - - 'board_email' => "noreply@$domain_name", // admin email address - 'board_email_form' => false, // can users send email to each other via board - 'board_email_sig' => '', // this text will be attached to all emails the board sends - 'board_email_sitename' => $domain_name, // sitename used in all emails header - - 'topic_notify_enabled' => true, - 'pm_notify_enabled' => true, - 'group_send_email' => true, - 'email_change_disabled' => false, // disable changing email by user - - 'tech_admin_email' => "admin@$domain_name", // email for sending error reports - 'abuse_email' => "abuse@$domain_name", - 'adv_email' => "adv@$domain_name", - - // Special users - 'dbg_users' => [ - #user_id => 'name', - 2 => 'admin', - ], - 'unlimited_users' => [ - #user_id => 'name', - 2 => 'admin', - ], - 'super_admins' => [ - #user_id => 'name', - 2 => 'admin', - ], - - // Date format - 'date_format' => 'Y-m-d', - - // Subforums - 'sf_on_first_page_only' => true, - - // Forums - 'allowed_topics_per_page' => [50, 100, 150, 200, 250, 300], - - // Topics - 'show_quick_reply' => true, - 'show_rank_text' => false, - 'show_rank_image' => true, - 'show_poster_joined' => true, - 'show_poster_posts' => true, - 'show_poster_from' => true, - 'show_bot_nick' => false, - 'text_buttons' => false, // replace EDIT, QUOTE... images with text links - 'parse_ed2k_links' => true, // make ed2k links clickable - 'post_date_format' => 'd-M-Y H:i', - 'ext_link_new_win' => true, // open external links in new window - - 'topic_moved_days_keep' => 7, // remove topic moved links after xx days (or FALSE to disable) - 'allowed_posts_per_page' => [15, 30, 50, 100], - 'user_signature_start' => '

        _________________
        ', - 'user_signature_end' => '
        ', // Это позволит использовать html теги, которые требуют закрытия. Например или - - // Posts - 'use_posts_cache' => true, - 'posts_cache_days_keep' => 14, - 'max_post_length' => 120000, - 'use_ajax_posts' => true, - - // Search - 'sphinx_enabled' => false, // if false mysql by default - 'sphinx_topic_titles_host' => '127.0.0.1', - 'sphinx_topic_titles_port' => 3312, - 'sphinx_config_path' => realpath("../install/sphinx/sphinx.conf"), - 'disable_ft_search_in_posts' => false, // disable searching in post bodies - 'disable_search_for_guest' => true, - 'allow_search_in_bool_mode' => true, - 'max_search_words_per_post' => 200, - 'search_min_word_len' => 3, - 'search_max_word_len' => 35, - 'limit_max_search_results' => false, - 'spam_filter_file_path' => '', // BB_PATH .'/misc/spam_filter_words.txt'; - - // Posting - 'prevent_multiposting' => true, // replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster - 'max_smilies' => 10, // Максимальное число смайлов в посте (0 - без ограничения) - - // PM - 'privmsg_disable' => false, // отключить систему личных сообщений на форуме - 'max_outgoing_pm_cnt' => 10, // ограничение на кол. одновременных исходящих лс (для замедления рассылки спама) - 'max_inbox_privmsgs' => 500, // максимальное число сообщений в папке входящие (удалить) - 'max_savebox_privmsgs' => 500, // максимальное число сообщений в папке сохраненные (удалить) - 'max_sentbox_privmsgs' => 500, // максимальное число сообщений в папке отправленные (удалить) - 'pm_days_keep' => 180, // время хранения ЛС - - // Actions log - 'log_days_keep' => 90, - - // Users - 'color_nick' => true, // Окраска ников пользователей по user_rank - 'user_not_activated_days_keep' => 7, // "not activated" == "not finished registration" - 'user_not_active_days_keep' => 180, // inactive users but only with no posts - - // Groups - 'group_members_per_page' => 50, - - // Tidy - 'tidy_post' => (!in_array('tidy', get_loaded_extensions())) ? false : true, - - // Misc - 'mem_on_start' => (MEM_USAGE) ? memory_get_usage() : 0, - 'translate_dates' => true, // in displaying time - 'use_word_censor' => true, - - 'last_visit_date_format' => 'd-M H:i', - 'last_post_date_format' => 'd-M-y H:i', - 'poll_max_days' => 180, // сколько дней с момента создания темы опрос будет активным - - 'allow_change' => [ - 'language' => true, - 'dateformat' => true, - ], - - 'trash_forum_id' => 0, // (int) 7 - - 'first_logon_redirect_url' => 'index.php', - 'terms_and_conditions_url' => 'terms.php', - 'tor_help_links' => 'terms.php', - - 'user_agreement_url' => 'info.php?show=user_agreement', - 'copyright_holders_url' => 'info.php?show=copyright_holders', - 'advert_url' => 'info.php?show=advert', - - // Extensions - 'file_id_ext' => [ - 1 => 'gif', - 2 => 'gz', - 3 => 'jpg', - 4 => 'png', - 5 => 'rar', - 6 => 'tar', - 7 => 'tiff', - 8 => 'torrent', - 9 => 'zip', - ], - - // Attachments - 'attach' => [ - 'upload_path' => DATA_DIR . 'torrent_files', // путь к директории с torrent файлами - 'max_size' => 5 * 1024 * 1024, // максимальный размер файла в байтах - ], - - 'tor_forums_allowed_ext' => ['torrent', 'zip', 'rar'], // для разделов с раздачами - 'gen_forums_allowed_ext' => ['torrent', 'zip', 'rar'], // для обычных разделов - - // Avatars - 'avatars' => [ - 'allowed_ext' => ['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 - 'group_avatars' => [ - 'allowed_ext' => ['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 - 'captcha' => [ - 'disabled' => false, - 'public_key' => '', // your public key - 'secret_key' => '', // your secret key - 'theme' => 'light', // light or dark - ], - - // Atom feed - 'atom' => [ - 'path' => INT_DATA_DIR .'atom', // without ending slash - 'url' => './internal_data/atom',// without ending slash - ], - - // Nofollow - 'nofollow' => [ - 'disabled' => false, - 'allowed_url' => [$domain_name], // 'allowed.site', 'www.allowed.site' - ], - - // Page settings - 'page' => [ - 'show_torhelp' => [ - #BB_SCRIPT => true - 'index' => true, - 'tracker' => true, - ], - 'show_sidebar1' => [ - #BB_SCRIPT => true - 'index' => true, - ], - 'show_sidebar2' => [ - #BB_SCRIPT => true - 'index' => true, - ] - ], - - // Tracker settings - 'tracker' => [ - '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, - 'gold_silver_enabled' => true, - 'retracker' => true, - 'retracker_host' => 'http://retracker.local/announce', - 'freeleech' => false, - 'guest_tracker' => true, - ], - - // Ratio settings - // Don't change the order of ratios (from 0 to 1) - // rating < 0.4 -- allow only 1 torrent for leeching - // rating < 0.5 -- only 2 - // rating < 0.6 -- only 3 - // rating > 0.6 -- depend on your tracker config limits (in "ACP - Tracker Config - Limits") - 'rating' => [ - '0.4' => 1, - '0.5' => 2, - '0.6' => 3, - ], - - // Иконки статусов раздач - 'tor_icons' => [ - TOR_NOT_APPROVED => '*', - TOR_CLOSED => 'x', - TOR_APPROVED => '', - TOR_NEED_EDIT => '?', - TOR_NO_DESC => '!', - TOR_DUP => 'D', - TOR_CLOSED_CPHOLD => '©', - TOR_CONSUMED => '', - TOR_DOUBTFUL => '#', - TOR_CHECKING => '%', - TOR_TMP => 'T', - TOR_PREMOD => '', - ], - - // Запрет на скачивание - 'tor_frozen' => [ - TOR_CHECKING => true, - TOR_CLOSED => true, - TOR_CLOSED_CPHOLD => true, - TOR_CONSUMED => true, - TOR_DUP => true, - TOR_NO_DESC => true, - TOR_PREMOD => true, - ], - - // Разрешение на скачку автором, если закрыто на скачивание. - 'tor_frozen_author_download' => [ - TOR_CHECKING => true, - TOR_NO_DESC => true, - TOR_PREMOD => true, - ], - - // Запрет на редактирование головного сообщения - 'tor_cannot_edit' => [ - TOR_CHECKING => true, - TOR_CLOSED => true, - TOR_CONSUMED => true, - TOR_DUP => true, - ], - - // Запрет на создание новых раздач если стоит статус недооформлено/неоформлено/сомнительно - 'tor_cannot_new' => [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL], - - // Разрешение на ответ релизера, если раздача исправлена. - 'tor_reply' => [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL], - - // Если такой статус у релиза, то статистика раздачи будет скрыта - 'tor_no_tor_act' => [ - TOR_CLOSED => true, - TOR_DUP => true, - TOR_CLOSED_CPHOLD => true, - TOR_CONSUMED => true, - ], - - // Vote graphic length defines the maximum length of a vote result graphic, ie. 100% = this length - 'vote_graphic_length' => 205, - 'privmsg_graphic_length' => 175, - 'topic_left_column_witdh' => 150, - - // Images auto-resize - 'post_img_width_decr' => 52, - 'attach_img_width_decr' => 130, + // Debug (twig etc.) + 'debug' => true, + + // Increase number after changing js or css + 'js_ver' => 1, + 'css_ver' => 1, + + // Version info + 'tp_version' => '2.2.0', + 'tp_release_date' => '**/**/2016', + 'tp_release_state' => 'ALPHA', + + 'services' => [ + 'cache' => [ + 'adapter' => \TorrentPier\Cache\FileAdapter::class, + 'options' => [ + 'directory' => __DIR__ . '/../internal_data/cache', + 'prefix' => 'hash string' + ], + ], + /*'cache' => [ + 'adapter' => \TorrentPier\Cache\MemoryAdapter::class, + 'options' => [ + 'servers' => [ + 'host' => '127.0.0.1', + 'port' => 11211, + 'weight' => 100, + ], + ], + ],*/ + + // Database + 'db' => [ + 'debug' => '{self.debug}', + 'driver' => 'Pdo_Mysql', + 'hostname' => '127.0.0.1', + 'database' => 'tp_220', + 'username' => 'user', + 'password' => 'pass', + 'charset' => 'utf8' + ], + + // Sphinx + 'sphinx' => [ + 'debug' => '{self.debug}', + 'driver' => '{self.db.driver}', + 'hostname' => '{self.db.hostname}', + 'username' => 'user', + 'password' => 'pass', + 'port' => 9306, + 'charset' => 'utf8' + ], + + // Twig + 'twig' => [ + 'dir_templates' => __DIR__ . '/../templates/default', + 'dir_cache' => __DIR__ . '/../internal_data/cache', + ], + + // Translation + 'translator' => [ + 'dir_cache' => __DIR__ . '/../internal_data/cache', + 'resources' => [ + [ + 'resource' => __DIR__ . '/../messages/ru.php', + 'locale' => 'ru', + ], + [ + 'resource' => __DIR__ . '/../messages/en.php', + 'locale' => 'en', + ] + ] + ], + + // Log + 'log' => [ + 'handlers' => [ + function () { + return new \Monolog\Handler\StreamHandler( + __DIR__ . '/../internal_data/log/app.log', + \Monolog\Logger::DEBUG + ); + } + ] + ], + ], + + // Aliases + // TODO: удалить + 'db_alias' => [ + 'log' => 'db', // BB_LOG + 'search' => 'db', // BB_TOPIC_SEARCH + 'sres' => 'db', // BB_BT_USER_SETTINGS, BB_SEARCH_RESULTS + 'u_ses' => 'db', // BB_USER_SES, BB_USER_LASTVISIT + 'dls' => 'db', // BB_BT_DLS_* + 'ip' => 'db', // BB_POSTS_IP + 'ut' => 'db', // BB_TOPICS_USER_POSTED + 'pm' => 'db', // BB_PRIVMSGS, BB_PRIVMSGS_TEXT + 'pt' => 'db', // BB_POSTS_TEXT + ], + + // Cache + 'cache' => [ + 'db_dir' => realpath(BB_ROOT) . '/internal_data/cache/filecache/', + 'prefix' => 'tp_', // Префикс кеша ('tp_') + 'memcache' => [ + 'host' => '127.0.0.1', + 'port' => 11211, + 'pconnect' => true, + 'con_required' => true, + ], + 'redis' => [ + 'host' => '127.0.0.1', + 'port' => 6379, + 'con_required' => true, + ] + ], + + // Datastore + // Available datastore types: memcache, sqlite, redis, apc, xcache (default filecache) + // TODO: удалить + 'datastore_type' => 'filecache', + + // Server + 'server_name' => $domain_name, // The domain name from which this board runs + 'server_port' => (!empty($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 80, // The port your server is running on + 'script_path' => '/', // The path where FORUM is located relative to the domain name + + // GZip + 'gzip_compress' => true, // compress output + + // Tracker + 'announce_interval' => 2400, // Announce interval (default: 1800) + 'passkey_key' => 'uk', // Passkey key name in GET request + 'ignore_reported_ip' => false, // Ignore IP reported by client + 'verify_reported_ip' => true, // Verify IP reported by client against $_SERVER['HTTP_X_FORWARDED_FOR'] + 'allow_internal_ip' => false, // Allow internal IP (10.xx.. etc.) + + // Ocelot + 'ocelot' => [ + 'enabled' => false, + 'host' => $domain_name, + 'port' => 2710, + 'url' => "http://$domain_name:2710/", // with '/' + 'secret' => 'some_10_chars', // 10 chars + 'stats' => 'some_10_chars', // 10 chars + ], + + // FAQ url help link + 'how_to_download_url_help' => 'viewtopic.php?t=1', // Как скачивать? + 'what_is_torrent_url_help' => 'viewtopic.php?t=2', // Что такое торрент? + 'ratio_url_help' => 'viewtopic.php?t=3', // Рейтинг и ограничения + 'search_help_url' => 'viewtopic.php?t=4', // Помощь по поиску + + // Torrents + 'bt_min_ratio_allow_dl_tor' => 0.3, // 0 - disable + 'bt_min_ratio_warning' => 0.6, // 0 - disable + + 'show_dl_status_in_search' => true, + 'show_dl_status_in_forum' => true, + 'allow_dl_list_names_mode' => true, + + // Days to keep torrent registered + 'seeder_last_seen_days_keep' => 0, // сколько дней назад был сид последний раз + 'seeder_never_seen_days_keep' => 0, // сколько дней имеется статус "Сида не было никогда" + + // DL-Status (days to keep user's dlstatus records) + 'dl_will_days_keep' => 360, + 'dl_down_days_keep' => 180, + 'dl_complete_days_keep' => 180, + 'dl_cancel_days_keep' => 30, + + // Tor-Stats + 'torstat_days_keep' => 60, // days to keep user's per-torrent stats + + // Tor-Help + 'torhelp_enabled' => false, // find dead torrents (without seeder) that user might help seeding + + // URL's + 'ajax_url' => 'ajax.php', # "http://{$_SERVER['SERVER_NAME']}/ajax.php" + 'dl_url' => 'dl.php?t=', # "http://{$domain_name}/dl.php" + 'login_url' => 'login.php', # "http://{$domain_name}/login.php" + 'posting_url' => 'posting.php', # "http://{$domain_name}/posting.php" + 'pm_url' => 'privmsg.php', # "http://{$domain_name}/privmsg.php" + + // Language + 'charset' => 'utf8', // page charset + 'lang' => [ + 'ru' => [ + 'name' => 'Русский', + 'locale' => 'ru_RU.UTF-8', + 'encoding' => 'UTF-8', + ], + 'uk' => [ + 'name' => 'Український', + 'locale' => 'uk_UA.UTF-8', + 'encoding' => 'UTF-8', + ], + 'en' => [ + 'name' => 'English', + 'locale' => 'en_US.UTF-8', + 'encoding' => 'UTF-8', + ], + ], + + // Templates + 'templates' => [ + // TODO: новый шаблонизатор + 'default' => 'Стандартный', + ], + + 'tpl_name' => 'default', + 'stylesheet' => 'main.css', + + 'show_sidebar1_on_every_page' => false, + 'show_sidebar2_on_every_page' => false, + + // Cookie + 'cookie_domain' => in_array($domain_name, array(getenv('SERVER_ADDR'), 'localhost')) ? '' : ".$domain_name", + 'cookie_secure' => (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') ? 1 : 0, + 'cookie_prefix' => 'bb_', // 'bb_' + + // Sessions + // TODO: заменить + глобальный объект user + 'session_update_intrv' => 180, // sec + 'user_session_duration' => 1800, // sec + 'admin_session_duration' => 6 * 3600, // sec + 'user_session_gc_ttl' => 1800, // number of seconds that a staled session entry may remain in sessions table + 'session_cache_gc_ttl' => 1200, // sec + 'max_last_visit_days' => 14, // days + 'last_visit_update_intrv' => 3600, // sec + + // Registration + 'invalid_logins' => 5, // Количество неверных попыток ввода пароля, перед выводом проверки капчей + 'new_user_reg_disabled' => false, // Запретить регистрацию новых учетных записей + 'unique_ip' => false, // Запретить регистрацию нескольких учетных записей с одного ip + 'new_user_reg_restricted' => false, // Ограничить регистрацию новых пользователей по времени с 01:00 до 17:00 + 'reg_email_activation' => true, // Требовать активацию учетной записи по email + + // Email + // TODO: заменить + 'emailer_disabled' => false, + 'smtp_delivery' => false, // send email via a named server instead of the local mail function + 'smtp_ssl' => false, // use ssl connect + 'smtp_host' => '', // SMTP server host + 'smtp_port' => 25, // SMTP server port + 'smtp_username' => '', // enter a username if your SMTP server requires it + 'smtp_password' => '', // enter a password if your SMTP server requires it + 'smtp' => [ + 'name' => 'yandex.ru', + 'host' => 'smtp.yandex.ru', + 'port' => 465, + 'connection_class' => 'login', + 'connection_config' => [ + 'username' => '', + 'password' => '', + 'ssl' => 'ssl', + ], + ], + + 'board_email' => "noreply@$domain_name", // admin email address + 'board_email_form' => false, // can users send email to each other via board + 'board_email_sig' => '', // this text will be attached to all emails the board sends + 'board_email_sitename' => $domain_name, // sitename used in all emails header + + 'topic_notify_enabled' => true, + 'pm_notify_enabled' => true, + 'group_send_email' => true, + 'email_change_disabled' => false, // disable changing email by user + + 'tech_admin_email' => "admin@$domain_name", // email for sending error reports + 'abuse_email' => "abuse@$domain_name", + 'adv_email' => "adv@$domain_name", + + // Special users + 'dbg_users' => [ + #user_id => 'name', + 2 => 'admin', + ], + 'unlimited_users' => [ + #user_id => 'name', + 2 => 'admin', + ], + 'super_admins' => [ + #user_id => 'name', + 2 => 'admin', + ], + + // Date format + 'date_format' => 'Y-m-d', + + // Subforums + 'sf_on_first_page_only' => true, + + // Forums + 'allowed_topics_per_page' => [50, 100, 150, 200, 250, 300], + + // Topics + 'show_quick_reply' => true, + 'show_rank_text' => false, + 'show_rank_image' => true, + 'show_poster_joined' => true, + 'show_poster_posts' => true, + 'show_poster_from' => true, + 'show_bot_nick' => false, + 'text_buttons' => false, // replace EDIT, QUOTE... images with text links + 'parse_ed2k_links' => true, // make ed2k links clickable + 'post_date_format' => 'd-M-Y H:i', + 'ext_link_new_win' => true, // open external links in new window + + 'topic_moved_days_keep' => 7, // remove topic moved links after xx days (or FALSE to disable) + 'allowed_posts_per_page' => [15, 30, 50, 100], + 'user_signature_start' => '

        _________________
        ', + 'user_signature_end' => '
        ', // Это позволит использовать html теги, которые требуют закрытия. Например
        или + + // Posts + 'use_posts_cache' => true, + 'posts_cache_days_keep' => 14, + 'max_post_length' => 120000, + 'use_ajax_posts' => true, + + // Search + 'sphinx_enabled' => false, // if false mysql by default + 'sphinx_topic_titles_host' => '127.0.0.1', + 'sphinx_topic_titles_port' => 3312, + 'sphinx_config_path' => realpath("../install/sphinx/sphinx.conf"), + 'disable_ft_search_in_posts' => false, // disable searching in post bodies + 'disable_search_for_guest' => true, + 'allow_search_in_bool_mode' => true, + 'max_search_words_per_post' => 200, + 'search_min_word_len' => 3, + 'search_max_word_len' => 35, + 'limit_max_search_results' => false, + 'spam_filter_file_path' => '', // BB_PATH .'/misc/spam_filter_words.txt'; + + // Posting + 'prevent_multiposting' => true, // replace "reply" with "edit last msg" if user (not admin or mod) is last topic poster + 'max_smilies' => 10, // Максимальное число смайлов в посте (0 - без ограничения) + + // PM + 'privmsg_disable' => false, // отключить систему личных сообщений на форуме + 'max_outgoing_pm_cnt' => 10, // ограничение на кол. одновременных исходящих лс (для замедления рассылки спама) + 'max_inbox_privmsgs' => 500, // максимальное число сообщений в папке входящие (удалить) + 'max_savebox_privmsgs' => 500, // максимальное число сообщений в папке сохраненные (удалить) + 'max_sentbox_privmsgs' => 500, // максимальное число сообщений в папке отправленные (удалить) + 'pm_days_keep' => 180, // время хранения ЛС + + // Actions log + 'log_days_keep' => 90, + + // Users + 'color_nick' => true, // Окраска ников пользователей по user_rank + 'user_not_activated_days_keep' => 7, // "not activated" == "not finished registration" + 'user_not_active_days_keep' => 180, // inactive users but only with no posts + + // Groups + 'group_members_per_page' => 50, + + // Tidy + 'tidy_post' => (!in_array('tidy', get_loaded_extensions())) ? false : true, + + // Misc + 'mem_on_start' => (MEM_USAGE) ? memory_get_usage() : 0, + 'translate_dates' => true, // in displaying time + 'use_word_censor' => true, + + 'last_visit_date_format' => 'd-M H:i', + 'last_post_date_format' => 'd-M-y H:i', + 'poll_max_days' => 180, // сколько дней с момента создания темы опрос будет активным + + 'allow_change' => [ + 'language' => true, + 'dateformat' => true, + ], + + 'trash_forum_id' => 0, // (int) 7 + + 'first_logon_redirect_url' => 'index.php', + 'terms_and_conditions_url' => 'terms.php', + 'tor_help_links' => 'terms.php', + + 'user_agreement_url' => 'info.php?show=user_agreement', + 'copyright_holders_url' => 'info.php?show=copyright_holders', + 'advert_url' => 'info.php?show=advert', + + // Extensions + 'file_id_ext' => [ + 1 => 'gif', + 2 => 'gz', + 3 => 'jpg', + 4 => 'png', + 5 => 'rar', + 6 => 'tar', + 7 => 'tiff', + 8 => 'torrent', + 9 => 'zip', + ], + + // Attachments + 'attach' => [ + 'upload_path' => DATA_DIR . 'torrent_files', // путь к директории с torrent файлами + 'max_size' => 5 * 1024 * 1024, // максимальный размер файла в байтах + ], + + 'tor_forums_allowed_ext' => ['torrent', 'zip', 'rar'], // для разделов с раздачами + 'gen_forums_allowed_ext' => ['torrent', 'zip', 'rar'], // для обычных разделов + + // Avatars + 'avatars' => [ + 'allowed_ext' => ['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 + 'group_avatars' => [ + 'allowed_ext' => ['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 + 'captcha' => [ + 'disabled' => false, + 'public_key' => '', // your public key + 'secret_key' => '', // your secret key + 'theme' => 'light', // light or dark + ], + + // Atom feed + 'atom' => [ + 'path' => INT_DATA_DIR . 'atom', // without ending slash + 'url' => './internal_data/atom',// without ending slash + ], + + // Nofollow + 'nofollow' => [ + 'disabled' => false, + 'allowed_url' => [$domain_name], // 'allowed.site', 'www.allowed.site' + ], + + // Page settings + 'page' => [ + 'show_torhelp' => [ + #BB_SCRIPT => true + 'index' => true, + 'tracker' => true, + ], + 'show_sidebar1' => [ + #BB_SCRIPT => true + 'index' => true, + ], + 'show_sidebar2' => [ + #BB_SCRIPT => true + 'index' => true, + ] + ], + + // Tracker settings + 'tracker' => [ + '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, + 'gold_silver_enabled' => true, + 'retracker' => true, + 'retracker_host' => 'http://retracker.local/announce', + 'freeleech' => false, + 'guest_tracker' => true, + ], + + // Ratio settings + // Don't change the order of ratios (from 0 to 1) + // rating < 0.4 -- allow only 1 torrent for leeching + // rating < 0.5 -- only 2 + // rating < 0.6 -- only 3 + // rating > 0.6 -- depend on your tracker config limits (in "ACP - Tracker Config - Limits") + 'rating' => [ + '0.4' => 1, + '0.5' => 2, + '0.6' => 3, + ], + + // Иконки статусов раздач + 'tor_icons' => [ + TOR_NOT_APPROVED => '*', + TOR_CLOSED => 'x', + TOR_APPROVED => '', + TOR_NEED_EDIT => '?', + TOR_NO_DESC => '!', + TOR_DUP => 'D', + TOR_CLOSED_CPHOLD => '©', + TOR_CONSUMED => '', + TOR_DOUBTFUL => '#', + TOR_CHECKING => '%', + TOR_TMP => 'T', + TOR_PREMOD => '', + ], + + // Запрет на скачивание + 'tor_frozen' => [ + TOR_CHECKING => true, + TOR_CLOSED => true, + TOR_CLOSED_CPHOLD => true, + TOR_CONSUMED => true, + TOR_DUP => true, + TOR_NO_DESC => true, + TOR_PREMOD => true, + ], + + // Разрешение на скачку автором, если закрыто на скачивание. + 'tor_frozen_author_download' => [ + TOR_CHECKING => true, + TOR_NO_DESC => true, + TOR_PREMOD => true, + ], + + // Запрет на редактирование головного сообщения + 'tor_cannot_edit' => [ + TOR_CHECKING => true, + TOR_CLOSED => true, + TOR_CONSUMED => true, + TOR_DUP => true, + ], + + // Запрет на создание новых раздач если стоит статус недооформлено/неоформлено/сомнительно + 'tor_cannot_new' => [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL], + + // Разрешение на ответ релизера, если раздача исправлена. + 'tor_reply' => [TOR_NEED_EDIT, TOR_NO_DESC, TOR_DOUBTFUL], + + // Если такой статус у релиза, то статистика раздачи будет скрыта + 'tor_no_tor_act' => [ + TOR_CLOSED => true, + TOR_DUP => true, + TOR_CLOSED_CPHOLD => true, + TOR_CONSUMED => true, + ], + + // Vote graphic length defines the maximum length of a vote result graphic, ie. 100% = this length + 'vote_graphic_length' => 205, + 'privmsg_graphic_length' => 175, + 'topic_left_column_witdh' => 150, + + // Images auto-resize + 'post_img_width_decr' => 52, + 'attach_img_width_decr' => 130, ]; return $config; diff --git a/library/defines.php b/library/defines.php index 660029f16..d2d29a3b7 100644 --- a/library/defines.php +++ b/library/defines.php @@ -7,56 +7,56 @@ define('TR_RATING_LIMITS', true); // ON/OFF define('MIN_DL_FOR_RATIO', 10737418240); // 10 GB in bytes, 0 - disable // 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('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('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/'); // Templates -define('ADMIN_TPL_DIR', TEMPLATES_DIR .'/admin/'); +define('ADMIN_TPL_DIR', TEMPLATES_DIR . '/admin/'); // 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 // 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'); // 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'); // Misc define('MEM_USAGE', function_exists('memory_get_usage')); @@ -66,15 +66,15 @@ define('GZIP_OUTPUT_ALLOWED', (extension_loaded('zlib') && !ini_get('zlib.output // TODO: temporary, move to another place // Torrents (reserved: -1) -define('TOR_NOT_APPROVED', 0); // не проверено -define('TOR_CLOSED', 1); // закрыто -define('TOR_APPROVED', 2); // проверено -define('TOR_NEED_EDIT', 3); // недооформлено -define('TOR_NO_DESC', 4); // неоформлено -define('TOR_DUP', 5); // повтор +define('TOR_NOT_APPROVED', 0); // не проверено +define('TOR_CLOSED', 1); // закрыто +define('TOR_APPROVED', 2); // проверено +define('TOR_NEED_EDIT', 3); // недооформлено +define('TOR_NO_DESC', 4); // неоформлено +define('TOR_DUP', 5); // повтор define('TOR_CLOSED_CPHOLD', 6); // закрыто правообладателем -define('TOR_CONSUMED', 7); // поглощено -define('TOR_DOUBTFUL', 8); // сомнительно -define('TOR_CHECKING', 9); // проверяется -define('TOR_TMP', 10); // временная -define('TOR_PREMOD', 11); // премодерация \ No newline at end of file +define('TOR_CONSUMED', 7); // поглощено +define('TOR_DOUBTFUL', 8); // сомнительно +define('TOR_CHECKING', 9); // проверяется +define('TOR_TMP', 10); // временная +define('TOR_PREMOD', 11); // премодерация diff --git a/library/includes/api/sphinx.php b/library/includes/api/sphinx.php index 6c1cf4a8f..eb6d153f5 100644 --- a/library/includes/api/sphinx.php +++ b/library/includes/api/sphinx.php @@ -20,75 +20,75 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); ///////////////////////////////////////////////////////////////////////////// /// known searchd commands -define ( "SEARCHD_COMMAND_SEARCH", 0 ); -define ( "SEARCHD_COMMAND_EXCERPT", 1 ); -define ( "SEARCHD_COMMAND_UPDATE", 2 ); -define ( "SEARCHD_COMMAND_KEYWORDS",3 ); -define ( "SEARCHD_COMMAND_PERSIST", 4 ); -define ( "SEARCHD_COMMAND_STATUS", 5 ); -define ( "SEARCHD_COMMAND_QUERY", 6 ); +define("SEARCHD_COMMAND_SEARCH", 0); +define("SEARCHD_COMMAND_EXCERPT", 1); +define("SEARCHD_COMMAND_UPDATE", 2); +define("SEARCHD_COMMAND_KEYWORDS", 3); +define("SEARCHD_COMMAND_PERSIST", 4); +define("SEARCHD_COMMAND_STATUS", 5); +define("SEARCHD_COMMAND_QUERY", 6); /// current client-side command implementation versions -define ( "VER_COMMAND_SEARCH", 0x116 ); -define ( "VER_COMMAND_EXCERPT", 0x100 ); -define ( "VER_COMMAND_UPDATE", 0x102 ); -define ( "VER_COMMAND_KEYWORDS", 0x100 ); -define ( "VER_COMMAND_STATUS", 0x100 ); -define ( "VER_COMMAND_QUERY", 0x100 ); +define("VER_COMMAND_SEARCH", 0x116); +define("VER_COMMAND_EXCERPT", 0x100); +define("VER_COMMAND_UPDATE", 0x102); +define("VER_COMMAND_KEYWORDS", 0x100); +define("VER_COMMAND_STATUS", 0x100); +define("VER_COMMAND_QUERY", 0x100); /// known searchd status codes -define ( "SEARCHD_OK", 0 ); -define ( "SEARCHD_ERROR", 1 ); -define ( "SEARCHD_RETRY", 2 ); -define ( "SEARCHD_WARNING", 3 ); +define("SEARCHD_OK", 0); +define("SEARCHD_ERROR", 1); +define("SEARCHD_RETRY", 2); +define("SEARCHD_WARNING", 3); /// known match modes -define ( "SPH_MATCH_ALL", 0 ); -define ( "SPH_MATCH_ANY", 1 ); -define ( "SPH_MATCH_PHRASE", 2 ); -define ( "SPH_MATCH_BOOLEAN", 3 ); -define ( "SPH_MATCH_EXTENDED", 4 ); -define ( "SPH_MATCH_FULLSCAN", 5 ); -define ( "SPH_MATCH_EXTENDED2", 6 ); // extended engine V2 (TEMPORARY, WILL BE REMOVED) +define("SPH_MATCH_ALL", 0); +define("SPH_MATCH_ANY", 1); +define("SPH_MATCH_PHRASE", 2); +define("SPH_MATCH_BOOLEAN", 3); +define("SPH_MATCH_EXTENDED", 4); +define("SPH_MATCH_FULLSCAN", 5); +define("SPH_MATCH_EXTENDED2", 6); // extended engine V2 (TEMPORARY, WILL BE REMOVED) /// known ranking modes (ext2 only) -define ( "SPH_RANK_PROXIMITY_BM25", 0 ); ///< default mode, phrase proximity major factor and BM25 minor one -define ( "SPH_RANK_BM25", 1 ); ///< statistical mode, BM25 ranking only (faster but worse quality) -define ( "SPH_RANK_NONE", 2 ); ///< no ranking, all matches get a weight of 1 -define ( "SPH_RANK_WORDCOUNT", 3 ); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts -define ( "SPH_RANK_PROXIMITY", 4 ); -define ( "SPH_RANK_MATCHANY", 5 ); -define ( "SPH_RANK_FIELDMASK", 6 ); +define("SPH_RANK_PROXIMITY_BM25", 0); ///< default mode, phrase proximity major factor and BM25 minor one +define("SPH_RANK_BM25", 1); ///< statistical mode, BM25 ranking only (faster but worse quality) +define("SPH_RANK_NONE", 2); ///< no ranking, all matches get a weight of 1 +define("SPH_RANK_WORDCOUNT", 3); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts +define("SPH_RANK_PROXIMITY", 4); +define("SPH_RANK_MATCHANY", 5); +define("SPH_RANK_FIELDMASK", 6); /// known sort modes -define ( "SPH_SORT_RELEVANCE", 0 ); -define ( "SPH_SORT_ATTR_DESC", 1 ); -define ( "SPH_SORT_ATTR_ASC", 2 ); -define ( "SPH_SORT_TIME_SEGMENTS", 3 ); -define ( "SPH_SORT_EXTENDED", 4 ); -define ( "SPH_SORT_EXPR", 5 ); +define("SPH_SORT_RELEVANCE", 0); +define("SPH_SORT_ATTR_DESC", 1); +define("SPH_SORT_ATTR_ASC", 2); +define("SPH_SORT_TIME_SEGMENTS", 3); +define("SPH_SORT_EXTENDED", 4); +define("SPH_SORT_EXPR", 5); /// known filter types -define ( "SPH_FILTER_VALUES", 0 ); -define ( "SPH_FILTER_RANGE", 1 ); -define ( "SPH_FILTER_FLOATRANGE", 2 ); +define("SPH_FILTER_VALUES", 0); +define("SPH_FILTER_RANGE", 1); +define("SPH_FILTER_FLOATRANGE", 2); /// known attribute types -define ( "SPH_ATTR_INTEGER", 1 ); -define ( "SPH_ATTR_TIMESTAMP", 2 ); -define ( "SPH_ATTR_ORDINAL", 3 ); -define ( "SPH_ATTR_BOOL", 4 ); -define ( "SPH_ATTR_FLOAT", 5 ); -define ( "SPH_ATTR_BIGINT", 6 ); -define ( "SPH_ATTR_MULTI", 0x40000000 ); +define("SPH_ATTR_INTEGER", 1); +define("SPH_ATTR_TIMESTAMP", 2); +define("SPH_ATTR_ORDINAL", 3); +define("SPH_ATTR_BOOL", 4); +define("SPH_ATTR_FLOAT", 5); +define("SPH_ATTR_BIGINT", 6); +define("SPH_ATTR_MULTI", 0x40000000); /// known grouping functions -define ( "SPH_GROUPBY_DAY", 0 ); -define ( "SPH_GROUPBY_WEEK", 1 ); -define ( "SPH_GROUPBY_MONTH", 2 ); -define ( "SPH_GROUPBY_YEAR", 3 ); -define ( "SPH_GROUPBY_ATTR", 4 ); -define ( "SPH_GROUPBY_ATTRPAIR", 5 ); +define("SPH_GROUPBY_DAY", 0); +define("SPH_GROUPBY_WEEK", 1); +define("SPH_GROUPBY_MONTH", 2); +define("SPH_GROUPBY_YEAR", 3); +define("SPH_GROUPBY_ATTR", 4); +define("SPH_GROUPBY_ATTRPAIR", 5); // important properties of PHP's integers: // - always signed (one bit short of PHP_INT_SIZE) @@ -117,1537 +117,1483 @@ define ( "SPH_GROUPBY_ATTRPAIR", 5 ); // - otherwise format number into a string /// pack 64-bit signed -function sphPackI64 ( $v ) +function sphPackI64($v) { - assert ( is_numeric($v) ); + assert(is_numeric($v)); - // x64 - if ( PHP_INT_SIZE>=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 { - var $_host; ///< searchd host (default is "localhost") - var $_port; ///< searchd port (default is 9312) - var $_offset; ///< how many records to seek from result-set start (default is 0) - var $_limit; ///< how many records to return from result-set starting at offset (default is 20) - var $_mode; ///< query matching mode (default is SPH_MATCH_ALL) - var $_weights; ///< per-field weights (default is 1 for all fields) - var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) - var $_sortby; ///< attribute to sort by (defualt is "") - var $_min_id; ///< min ID to match (default is 0, which means no limit) - var $_max_id; ///< max ID to match (default is 0, which means no limit) - var $_filters; ///< search filters - var $_groupby; ///< group-by attribute name - var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) - var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) - var $_groupdistinct;///< group-by count-distinct attribute - var $_maxmatches; ///< max matches to retrieve - var $_cutoff; ///< cutoff to stop searching at (default is 0) - var $_retrycount; ///< distributed retries count - var $_retrydelay; ///< distributed retries delay - var $_anchor; ///< geographical anchor point - var $_indexweights; ///< per-index weights - var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) - var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) - var $_fieldweights; ///< per-field-name weights - var $_overrides; ///< per-query attribute values overrides - var $_select; ///< select-list (attributes or expressions, with optional aliases) - - var $_error; ///< last error message - var $_warning; ///< last warning message - var $_connerror; ///< connection error vs remote error flag - - var $_reqs; ///< requests array for multi-query - var $_mbenc; ///< stored mbstring encoding - var $_arrayresult; ///< whether $result["matches"] should be a hash or an array - var $_timeout; ///< connect timeout - - var $bb_queries = array(); - var $bb_indexes = array(); - - ///////////////////////////////////////////////////////////////////////////// - // common stuff - ///////////////////////////////////////////////////////////////////////////// - - /// create a new client object and fill defaults - function SphinxClient () - { - $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; - } - - function __destruct() - { - if ( $this->_socket !== false ) - fclose ( $this->_socket ); - } - - /// get last error message (string) - function GetLastError () - { - return $this->_error; - } - - /// get last warning message (string) - function GetLastWarning () - { - return $this->_warning; - } - - /// get last error flag (to tell network connection errors from searchd errors or broken responses) - function IsConnectError() - { - return $this->_connerror; - } - - /// set searchd host name (string) and port (integer) - 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) - function SetConnectTimeout ( $timeout ) - { - assert ( is_numeric($timeout) ); - $this->_timeout = $timeout; - } - - - 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 - function _MBPush () - { - $this->_mbenc = ""; - if ( ini_get ( "mbstring.func_overload" ) & 2 ) - { - $this->_mbenc = mb_internal_encoding(); - mb_internal_encoding ( "latin1" ); - } - } - - /// leave mbstring workaround mode - function _MBPop () - { - if ( $this->_mbenc ) - mb_internal_encoding ( $this->_mbenc ); - } - - /// connect to searchd server - 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 - 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 - 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" - function SetMaxQueryTime ( $max ) - { - assert ( is_int($max) ); - assert ( $max>=0 ); - $this->_maxquerytime = $max; - } - - /// set matching mode - 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 - 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 - 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 - function SetWeights ( $weights ) - { - assert ( is_array($weights) ); - foreach ( $weights as $weight ) - assert ( is_int($weight) ); - - $this->_weights = $weights; - } - - /// bind per-field weights by name - 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 - 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) - 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 - 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) - 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) - 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 - 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 - 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 - function SetGroupDistinct ( $attribute ) - { - assert ( is_string($attribute) ); - $this->_groupdistinct = $attribute; - } - - /// set distributed retries count and delay - 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 - 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 - 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 - function SetSelect ( $select ) - { - assert ( is_string ( $select ) ); - $this->_select = $select; - } - - ////////////////////////////////////////////////////////////////////////////// - - /// clear all filters (for multi-queries) - function ResetFilters () - { - $this->_filters = array(); - $this->_anchor = array(); - } - - /// clear groupby settings (for multi-queries) - function ResetGroupBy () - { - $this->_groupby = ""; - $this->_groupfunc = SPH_GROUPBY_DAY; - $this->_groupsort = "@group desc"; - $this->_groupdistinct= ""; - } - - /// clear all attribute value overrides (for multi-queries) - function ResetOverrides () + var $_host; ///< searchd host (default is "localhost") + var $_port; ///< searchd port (default is 9312) + var $_offset; ///< how many records to seek from result-set start (default is 0) + var $_limit; ///< how many records to return from result-set starting at offset (default is 20) + var $_mode; ///< query matching mode (default is SPH_MATCH_ALL) + var $_weights; ///< per-field weights (default is 1 for all fields) + var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) + var $_sortby; ///< attribute to sort by (defualt is "") + var $_min_id; ///< min ID to match (default is 0, which means no limit) + var $_max_id; ///< max ID to match (default is 0, which means no limit) + var $_filters; ///< search filters + var $_groupby; ///< group-by attribute name + var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) + var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) + var $_groupdistinct;///< group-by count-distinct attribute + var $_maxmatches; ///< max matches to retrieve + var $_cutoff; ///< cutoff to stop searching at (default is 0) + var $_retrycount; ///< distributed retries count + var $_retrydelay; ///< distributed retries delay + var $_anchor; ///< geographical anchor point + var $_indexweights; ///< per-index weights + var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) + var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) + var $_fieldweights; ///< per-field-name weights + var $_overrides; ///< per-query attribute values overrides + var $_select; ///< select-list (attributes or expressions, with optional aliases) + + var $_error; ///< last error message + var $_warning; ///< last warning message + var $_connerror; ///< connection error vs remote error flag + + var $_reqs; ///< requests array for multi-query + var $_mbenc; ///< stored mbstring encoding + var $_arrayresult; ///< whether $result["matches"] should be a hash or an array + var $_timeout; ///< connect timeout + + var $bb_queries = array(); + var $bb_indexes = array(); + + ///////////////////////////////////////////////////////////////////////////// + // common stuff + ///////////////////////////////////////////////////////////////////////////// + + /// create a new client object and fill defaults + function SphinxClient() { - $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 - 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 - 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 - 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 - 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 - 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 - 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 - 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; - } - - 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 - 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 - ///////////////////////////////////////////////////////////////////////////// - - 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; - } - - function Close() - { - if ( $this->_socket === false ) - { - $this->_error = 'not connected'; - return false; - } - - fclose ( $this->_socket ); - $this->_socket = false; - - return true; - } - - ////////////////////////////////////////////////////////////////////////// - // status - ////////////////////////////////////////////////////////////////////////// - - 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; - } + function __destruct() + { + if ($this->_socket !== false) + fclose($this->_socket); + } + + /// get last error message (string) + function GetLastError() + { + return $this->_error; + } + + /// get last warning message (string) + function GetLastWarning() + { + return $this->_warning; + } + + /// get last error flag (to tell network connection errors from searchd errors or broken responses) + function IsConnectError() + { + return $this->_connerror; + } + + /// set searchd host name (string) and port (integer) + 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) + function SetConnectTimeout($timeout) + { + assert(is_numeric($timeout)); + $this->_timeout = $timeout; + } + + + 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 + function _MBPush() + { + $this->_mbenc = ""; + if (ini_get("mbstring.func_overload") & 2) { + $this->_mbenc = mb_internal_encoding(); + mb_internal_encoding("latin1"); + } + } + + /// leave mbstring workaround mode + function _MBPop() + { + if ($this->_mbenc) + mb_internal_encoding($this->_mbenc); + } + + /// connect to searchd server + 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 + 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 + 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" + function SetMaxQueryTime($max) + { + assert(is_int($max)); + assert($max >= 0); + $this->_maxquerytime = $max; + } + + /// set matching mode + 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 + 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 + 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 + function SetWeights($weights) + { + assert(is_array($weights)); + foreach ($weights as $weight) + assert(is_int($weight)); + + $this->_weights = $weights; + } + + /// bind per-field weights by name + 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 + 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) + 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 + 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) + 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) + 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 + 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 + 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 + function SetGroupDistinct($attribute) + { + assert(is_string($attribute)); + $this->_groupdistinct = $attribute; + } + + /// set distributed retries count and delay + 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 + 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 + 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 + function SetSelect($select) + { + assert(is_string($select)); + $this->_select = $select; + } + + ////////////////////////////////////////////////////////////////////////////// + + /// clear all filters (for multi-queries) + function ResetFilters() + { + $this->_filters = array(); + $this->_anchor = array(); + } + + /// clear groupby settings (for multi-queries) + function ResetGroupBy() + { + $this->_groupby = ""; + $this->_groupfunc = SPH_GROUPBY_DAY; + $this->_groupsort = "@group desc"; + $this->_groupdistinct = ""; + } + + /// clear all attribute value overrides (for multi-queries) + function ResetOverrides() + { + $this->_overrides = array(); + } + + ////////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, run given search query through given indexes, + /// and return the search results + 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 + 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 + 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 + 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 + 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 + 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 + 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; + } + + 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 + 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 + ///////////////////////////////////////////////////////////////////////////// + + 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; + } + + function Close() + { + if ($this->_socket === false) { + $this->_error = 'not connected'; + return false; + } + + fclose($this->_socket); + $this->_socket = false; + + return true; + } + + ////////////////////////////////////////////////////////////////////////// + // status + ////////////////////////////////////////////////////////////////////////// + + 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; + } } // // $Id: sphinxapi.php 2055 2009-11-06 23:09:58Z shodan $ -// \ No newline at end of file +// diff --git a/library/includes/bbcode.php b/library/includes/bbcode.php index 4c23bc89b..caf2dbb51 100644 --- a/library/includes/bbcode.php +++ b/library/includes/bbcode.php @@ -3,7 +3,7 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); $datastore->enqueue(array( - 'smile_replacements', + 'smile_replacements', )); $page_cfg['include_bbcode_js'] = true; @@ -11,276 +11,246 @@ $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 $template, $lang, $datastore; + global $template, $lang, $datastore; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $inline_columns = 4; - $inline_rows = 7; - $window_columns = 8; + $inline_columns = 4; + $inline_rows = 7; + $window_columns = 8; - $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_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; + if ($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' => $di->config->get('smilies_path') . '/' . $smile_url, - 'SMILEY_DESC' => $data['emoticon'], - )); + $template->assign_block_vars('smilies_row.smilies_col', array( + 'SMILEY_CODE' => $data['code'], + 'SMILEY_IMG' => $di->config->get('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'); + } } /** -* 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; } /** @@ -296,473 +266,448 @@ function strip_quotes ($text) * @internal param \If $boolean true, use the fast-and-dirty method rather than the shiny and nice method * */ -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) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $max_words_count = $di->config->get('max_search_words_per_post'); - $min_word_len = max(2, $di->config->get('search_min_word_len') - 1); - $max_word_len = $di->config->get('search_max_word_len'); + $max_words_count = $di->config->get('max_search_words_per_post'); + $min_word_len = max(2, $di->config->get('search_min_word_len') - 1); + $max_word_len = $di->config->get('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) - { + if (sizeof($text) > $max_words_count) { # shuffle($text); - $text = array_splice($text, 0, $max_words_count); - } + $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) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $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 || $di->config->get('sphinx_enabled')) - { - return join("\n", $words); - } - else - { - DB()->query("DELETE FROM ". BB_POSTS_SEARCH ." WHERE post_id = $post_id"); + if ($only_return_words || $di->config->get('sphinx_enabled')) { + 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 { - var $tpl = array(); // шаблоны для замены тегов - var $smilies = null; // смайлы - var $found_spam = null; // найденные спам "слова" - var $del_words = array(); // см. get_words_rate() - var $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, - '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, - ); - var $block_tags = array( - 'align', - 'br', - 'clear', - 'hr', - 'list', - 'pre', - 'quote', - 'spoiler', - ); - var $preg = array(); - var $str = array(); - var $preg_search = array(); - var $preg_repl = array(); - var $str_search = array(); - var $str_repl = array(); + var $tpl = array(); // шаблоны для замены тегов + var $smilies = null; // смайлы + var $found_spam = null; // найденные спам "слова" + var $del_words = array(); // см. get_words_rate() + var $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, + '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, + ); + var $block_tags = array( + 'align', + 'br', + 'clear', + 'hr', + 'list', + 'pre', + 'quote', + 'spoiler', + ); + var $preg = array(); + var $str = array(); + var $preg_search = array(); + var $preg_repl = array(); + var $str_search = array(); + var $str_repl = array(); - /** - * Constructor - */ - function bbcode () - { - $this->tpl = get_bbcode_tpl(); + /** + * Constructor + */ + function bbcode() + { + $this->tpl = get_bbcode_tpl(); - $this->init_replacements(); - } + $this->init_replacements(); + } - /** - * init_replacements - */ - 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 + */ + 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); - * - * @param $text - * - * @return string - */ - function bbcode2html ($text) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * bbcode2html + * $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES); + * + * @param $text + * + * @return string + */ + function bbcode2html($text) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $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 ($di->config->get('tidy_post')) - { - $text = $this->tidy($text); - } + if ($di->config->get('tidy_post')) { + $text = $this->tidy($text); + } - return trim($text); - } + return trim($text); + } - /** - * Clean up - * - * @param $text - * - * @return mixed|string - */ - 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; - } + /** + * Clean up + * + * @param $text + * + * @return mixed|string + */ + 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 - * - * @param $text - * - * @return mixed|string - */ - private function spam_filter ($text) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Spam filter + * + * @param $text + * + * @return mixed|string + */ + private function spam_filter($text) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - static $spam_words = null; - static $spam_replace = ' СПАМ'; + 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 (!$di->config->get('spam_filter_file_path')) - { - return $text; - } - if (is_null($spam_words)) - { - $spam_words = file_get_contents($di->config->get('spam_filter_file_path')); - $spam_words = strtolower($spam_words); - $spam_words = explode("\n", $spam_words); - } + // set $spam_words and $spam_replace + if (!$di->config->get('spam_filter_file_path')) { + return $text; + } + if (is_null($spam_words)) { + $spam_words = file_get_contents($di->config->get('spam_filter_file_path')); + $spam_words = strtolower($spam_words); + $spam_words = explode("\n", $spam_words); + } - $found_spam = array(); + $found_spam = array(); - $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); + } - return $text; - } + return $text; + } - /** - * [code] callback - * - * @param $m - * - * @return string - */ - 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 + * + * @param $m + * + * @return string + */ + 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 - * - * @param $m - * - * @return string - */ - function url_callback ($m) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * [url] callback + * + * @param $m + * + * @return string + */ + function url_callback($m) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $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), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) - { - $link = "$url_name"; - } - else - { - $link = "$url_name"; - } + if (in_array(parse_url($url, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) { + $link = "$url_name"; + } else { + $link = "$url_name"; + } - return $link; - } + return $link; + } - /** - * Escape tags inside tiltes in [quote="tilte"] - * - * @param $m - * - * @return string - */ - 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"] + * + * @param $m + * + * @return string + */ + 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 - * - * @param $text - * - * @return string - */ - function make_clickable ($text) - { - $url_regexp = "# + /** + * make_clickable + * + * @param $text + * + * @return string + */ + 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), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) - { - $link = "$name"; - } - else - { - $link = "$name"; - } + if (in_array(parse_url($href, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) { + $link = "$name"; + } else { + $link = "$name"; + } - return $link; - } + return $link; + } - /** - * smilies_pass - * - * @param $text - * - * @return mixed - */ - function smilies_pass ($text) - { - global $datastore; + /** + * smilies_pass + * + * @param $text + * + * @return mixed + */ + 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 - * - * @param $text - * - * @return mixed - */ - function new_line2html ($text) - { - $text = preg_replace('#\n{2,}#', '
            ', $text); - $text = str_replace("\n", '
            ', $text); - return $text; - } + /** + * new_line2html + * + * @param $text + * + * @return mixed + */ + function new_line2html($text) + { + $text = preg_replace('#\n{2,}#', '
            ', $text); + $text = str_replace("\n", '
            ', $text); + return $text; + } - /** - * tidy - * - * @param $text - * - * @return string - */ - function tidy ($text) - { - $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); - return $text; - } + /** + * tidy + * + * @param $text + * + * @return string + */ + 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 { - var $dbg_mode = false; - var $words_rate = 0; - var $deleted_words = array(); - var $del_text_hl = ''; - var $words_del_exp = ''; - var $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; + var $dbg_mode = false; + var $words_rate = 0; + var $deleted_words = array(); + var $del_text_hl = ''; + var $words_del_exp = ''; + var $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; - function words_rate () - { - // слова начинающиеся на.. - $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'; + function words_rate() + { + // слова начинающиеся на.. + $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; + } - /** - * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. - * - * @param $text - * - * @return int - */ - function get_words_rate ($text) - { - $this->words_rate = 127; // максимальное значение по умолчанию - $this->deleted_words = array(); - $this->del_text_hl = $text; + /** + * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. + * + * @param $text + * + * @return int + */ + 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) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - return preg_replace("#\?{$di->config->get('passkey_key')}=[a-zA-Z0-9]{". BT_AUTH_KEY_LENGTH ."}#", "?{$di->config->get('passkey_key')}=passkey", $str); + return preg_replace("#\?{$di->config->get('passkey_key')}=[a-zA-Z0-9]{" . BT_AUTH_KEY_LENGTH . "}#", "?{$di->config->get('passkey_key')}=passkey", $str); } -function get_parsed_post ($postrow, $mode = 'full', $return_chars = 600) +function get_parsed_post($postrow, $mode = 'full', $return_chars = 600) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if ($di->config->get('use_posts_cache') && !empty($postrow['post_html'])) - { - return $postrow['post_html']; - } + if ($di->config->get('use_posts_cache') && !empty($postrow['post_html'])) { + return $postrow['post_html']; + } - $message = bbcode2html($postrow['post_text']); + $message = bbcode2html($postrow['post_text']); - // Posts cache - if ($di->config->get('use_posts_cache')) - { - DB()->shutdown['post_html'][] = array( - 'post_id' => (int) $postrow['post_id'], - 'post_html' => (string) $message, - ); - } + // Posts cache + if ($di->config->get('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/classes/emailer.php b/library/includes/classes/emailer.php index 86d750938..265d6f0dd 100644 --- a/library/includes/classes/emailer.php +++ b/library/includes/classes/emailer.php @@ -2,247 +2,223 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -use Zend\Mail; - class emailer { - var $msg, $subject, $extra_headers; - var $addresses, $reply_to, $from; - var $use_smtp; + var $msg, $subject, $extra_headers; + var $addresses, $reply_to, $from; + var $use_smtp; - var $tpl_msg = array(); - var $vars = array(); + var $tpl_msg = array(); + var $vars = array(); - function emailer ($use_smtp/*$tpl_name, $sbj, $to_address*/) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function emailer($use_smtp/*$tpl_name, $sbj, $to_address*/) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $this->reset(); - $this->from = $di->config->get('board_email'); - $this->reply_to = $di->config->get('board_email'); - $this->use_smtp = $use_smtp; - } + $this->reset(); + $this->from = $di->config->get('board_email'); + $this->reply_to = $di->config->get('board_email'); + $this->use_smtp = $use_smtp; + } - function set_default_vars () - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function set_default_vars() + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $this->vars = array( - 'BOARD_EMAIL' => $di->config->get('board_email'), - 'SITENAME' => $di->config->get('board_email_sitename'), - 'EMAIL_SIG' => !empty($di->config->get('board_email_sig')) ? "-- \n{$di->config->get('board_email_sig')}" : '', - ); - } + $this->vars = array( + 'BOARD_EMAIL' => $di->config->get('board_email'), + 'SITENAME' => $di->config->get('board_email_sitename'), + 'EMAIL_SIG' => !empty($di->config->get('board_email_sig')) ? "-- \n{$di->config->get('board_email_sig')}" : '', + ); + } - // Resets all the data (address, template file, etc etc to default - 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 + function reset() + { + $this->addresses = array(); + $this->msg = $this->extra_headers = ''; + $this->set_default_vars(); + } - // Sets an email address to send to - function email_address ($address) - { - $this->addresses['to'] = trim($address); - } + // Sets an email address to send to + function email_address($address) + { + $this->addresses['to'] = trim($address); + } - function cc ($address) - { - $this->addresses['cc'][] = trim($address); - } + function cc($address) + { + $this->addresses['cc'][] = trim($address); + } - function bcc ($address) - { - $this->addresses['bcc'][] = trim($address); - } + function bcc($address) + { + $this->addresses['bcc'][] = trim($address); + } - function replyto ($address) - { - $this->reply_to = trim($address); - } + function replyto($address) + { + $this->reply_to = trim($address); + } - function from ($address) - { - $this->from = trim($address); - } + function from($address) + { + $this->from = trim($address); + } - // set up subject for mail - function set_subject ($subject = '') - { - $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); - } + // set up subject for mail + function set_subject($subject = '') + { + $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); + } - // set up extra mail headers - function extra_headers ($headers) - { - $this->extra_headers .= trim($headers) . "\n"; - } + // set up extra mail headers + function extra_headers($headers) + { + $this->extra_headers .= trim($headers) . "\n"; + } - function use_template ($template_file, $template_lang = '') - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function use_template($template_file, $template_lang = '') + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - 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 = $di->config->get('default_lang'); - } + if (trim($template_lang) == '') { + $template_lang = $di->config->get('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 ."{$di->config->get('default_lang')}/email/$template_file.html"; + if (!file_exists(bb_realpath($tpl_file))) { + $tpl_file = LANG_ROOT_DIR . "{$di->config->get('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 - function assign_vars ($vars) - { - $this->vars = array_merge($this->vars, $vars); - } + // assign variables + function assign_vars($vars) + { + $this->vars = array_merge($this->vars, $vars); + } - // Send the mail out to the recipients set previously in var $this->address - function send ($email_format = 'text') - { - global $userdata; + // Send the mail out to the recipients set previously in var $this->address + function send($email_format = 'text') + { + global $userdata; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if ($di->config->get('emailer_disabled')) - { - return false; - } + if ($di->config->get('emailer_disabled')) { + return false; + } - // 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($di->config->get('lang.' . $userdata['user_lang'] . '.encoding')); - $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); - } - else - { - $this->encoding = trim($di->config->get('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($di->config->get('lang.' . $userdata['user_lang'] . '.encoding')); + $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); + } else { + $this->encoding = trim($di->config->get('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: " . $di->config->get('board_email') . "\n") . "Return-Path: " . $di->config->get('board_email') . "\nMessage-ID: <" . md5(uniqid(TIMENOW)) . "@" . $di->config->get('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: " . $di->config->get('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: " . $di->config->get('board_email') . "\n") . "Return-Path: " . $di->config->get('board_email') . "\nMessage-ID: <" . md5(uniqid(TIMENOW)) . "@" . $di->config->get('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: " . $di->config->get('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; + } - function encode ($str) - { - if ($this->encoding == '') - { - return $str; - } + 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; - } -} \ No newline at end of file + return $start . $str . $end; + } +} diff --git a/library/includes/classes/sitemap.php b/library/includes/classes/sitemap.php index e59f522e3..6c8072097 100644 --- a/library/includes/classes/sitemap.php +++ b/library/includes/classes/sitemap.php @@ -4,215 +4,226 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class sitemap { - var $home = ''; - var $limit = 0; - var $topic_priority = '0.5'; - var $stat_priority = '0.5'; - var $priority = '0.6'; - var $cat_priority = '0.7'; + var $home = ''; + var $limit = 0; + var $topic_priority = '0.5'; + var $stat_priority = '0.5'; + var $priority = '0.6'; + var $cat_priority = '0.7'; - function sitemap () { - $this->home = make_url(); - } + function sitemap() + { + $this->home = make_url(); + } - function build_map () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= $this->get_topic(); - $map .= ""; + function build_map() + { + $map = "\n\n"; + $map .= $this->get_static(); + $map .= $this->get_forum(); + $map .= $this->get_topic(); + $map .= ""; - return $map; - } + return $map; + } - 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 .= ""; + 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; + } - function build_stat () { - $map = "\n\n"; - $map .= $this->get_static(); - $map .= $this->get_forum(); - $map .= ""; + function build_stat() + { + $map = "\n\n"; + $map .= $this->get_static(); + $map .= $this->get_forum(); + $map .= ""; - return $map; - } + return $map; + } - function build_map_topic ($n) { - $map = "\n\n"; - $map .= $this->get_topic($n); - $map .= ""; + function build_map_topic($n) + { + $map = "\n\n"; + $map .= $this->get_topic($n); + $map .= ""; - return $map; - } + return $map; + } - function get_forum () { - global $datastore; + 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; + } - function get_topic ($page = false) { - global $datastore; + 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; + } - function get_static () { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function get_static() + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $xml = ''; - $lm = date('c'); - $this->priority = $this->stat_priority; + $xml = ''; + $lm = date('c'); + $this->priority = $this->stat_priority; - if ($di->config->get('static_sitemap')) { - $static_url = preg_replace("/\s/", '', $di->config->get('static_sitemap')); //вырезаем переносы строк - preg_match_all('#(https?://[\w-]+[\.\w-]+/((?!https?://)[\w- ./?%&=])+)#', $static_url, $out); + if ($di->config->get('static_sitemap')) { + $static_url = preg_replace("/\s/", '', $di->config->get('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; + } - 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"; + 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; + } - function send_url ($url, $map) { - $data = false; - $file = $url.urlencode($map); + 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); + } + } - function create () { - $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); + 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); - } -} \ No newline at end of file + $params['sitemap_time'] = TIMENOW; + bb_update_config($params); + } +} diff --git a/library/includes/core/dbs.php b/library/includes/core/dbs.php index a3e9ef913..7ec766746 100644 --- a/library/includes/core/dbs.php +++ b/library/includes/core/dbs.php @@ -4,55 +4,48 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class DBS { - var $cfg = array(); // $srv_name => $srv_cfg - var $srv = array(); // $srv_name => $db_obj - var $alias = array(); // $srv_alias => $srv_name + var $cfg = array(); // $srv_name => $srv_cfg + var $srv = array(); // $srv_name => $db_obj + var $alias = array(); // $srv_alias => $srv_name - var $log_file = 'sql_queries'; - var $log_counter = 0; - var $num_queries = 0; - var $sql_inittime = 0; - var $sql_timetotal = 0; + var $log_file = 'sql_queries'; + var $log_counter = 0; + var $num_queries = 0; + var $sql_inittime = 0; + var $sql_timetotal = 0; - function DBS ($cfg) - { - $this->cfg = $cfg['db']; - $this->alias = $cfg['db_alias']; + function DBS($cfg) + { + $this->cfg = $cfg['db']; + $this->alias = $cfg['db_alias']; - foreach ($this->cfg as $srv_name => $srv_cfg) - { - $this->srv[$srv_name] = null; - } - } + foreach ($this->cfg as $srv_name => $srv_cfg) { + $this->srv[$srv_name] = null; + } + } - // получение/инициализация класса для сервера $srv_name - function get_db_obj ($srv_name_or_alias = 'db1') - { - $srv_name = $this->get_srv_name($srv_name_or_alias); + // получение/инициализация класса для сервера $srv_name + function get_db_obj($srv_name_or_alias = 'db1') + { + $srv_name = $this->get_srv_name($srv_name_or_alias); - if (!is_object($this->srv[$srv_name])) - { - $this->srv[$srv_name] = new sql_db($this->cfg[$srv_name]); - $this->srv[$srv_name]->db_server = $srv_name; - } - return $this->srv[$srv_name]; - } + if (!is_object($this->srv[$srv_name])) { + $this->srv[$srv_name] = new sql_db($this->cfg[$srv_name]); + $this->srv[$srv_name]->db_server = $srv_name; + } + return $this->srv[$srv_name]; + } - // определение имени сервера - function get_srv_name ($name) - { - if (isset($this->alias[$name])) - { - $srv_name = $this->alias[$name]; - } - else if (isset($this->cfg[$name])) - { - $srv_name = $name; - } - else - { - $srv_name = 'db1'; - } - return $srv_name; - } -} \ No newline at end of file + // определение имени сервера + function get_srv_name($name) + { + if (isset($this->alias[$name])) { + $srv_name = $this->alias[$name]; + } else if (isset($this->cfg[$name])) { + $srv_name = $name; + } else { + $srv_name = 'db1'; + } + return $srv_name; + } +} diff --git a/library/includes/core/mysql.php b/library/includes/core/mysql.php index dfdc015e5..eda719d12 100644 --- a/library/includes/core/mysql.php +++ b/library/includes/core/mysql.php @@ -4,993 +4,898 @@ if (!defined('SQL_DEBUG')) die(basename(__FILE__)); class sql_db { - var $cfg = array(); - var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); - var $link = null; - var $result = null; - var $db_server = ''; - var $selected_db = null; - var $inited = false; - - var $locked = false; - var $locks = array(); - - var $num_queries = 0; - var $sql_starttime = 0; - var $sql_inittime = 0; - var $sql_timetotal = 0; - var $cur_query_time = 0; - var $slow_time = 0; - - var $dbg = array(); - var $dbg_id = 0; - var $dbg_enabled = false; - var $cur_query = null; - - var $do_explain = false; - var $explain_hold = ''; - var $explain_out = ''; - - var $shutdown = array(); - - var $DBS = array(); - - /** - * Constructor - */ - function sql_db ($cfg_values) - { - global $DBS; - - $this->cfg = array_combine($this->cfg_keys, $cfg_values); - $this->dbg_enabled = (sql_dbg_enabled() || !empty($_COOKIE['explain'])); - $this->do_explain = ($this->dbg_enabled && !empty($_COOKIE['explain'])); - $this->slow_time = SQL_SLOW_QUERY_TIME; - - // ссылки на глобальные переменные (для включения логов сразу на всех серверах, подсчета общего количества запросов и т.д.) - $this->DBS['log_file'] =& $DBS->log_file; - $this->DBS['log_counter'] =& $DBS->log_counter; - $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(); - - // 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']}")) - { - die("Could not set charset {$this->cfg['charset']}"); - } - } - - $this->inited = true; - $this->num_queries = 0; - $this->sql_inittime = $this->sql_timetotal; - $this->DBS['sql_inittime'] += $this->sql_inittime; - } - - /** - * Open connection - */ - function connect () - { - $this->cur_query = ($this->dbg_enabled) ? ($this->cfg['persist'] ? 'p' : '') . "connect to: {$this->cfg['dbhost']}" : 'connect'; - $this->debug('start'); - - $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; - - if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) - { - $server = (DBG_USER) ? $this->cfg['dbhost'] : ''; - header("HTTP/1.0 503 Service Unavailable"); - bb_log(' ', "db_err/connect_failed_{$this->cfg['dbhost']}"); - die("Could not connect to mysql server $server"); - } - - register_shutdown_function(array(&$this, 'close')); - - $this->debug('stop'); - $this->cur_query = null; - - return $link; - } - - /** - * Select database - */ - function select_db () - { - $this->cur_query = ($this->dbg_enabled) ? "select db: {$this->cfg['dbname']}" : 'select db'; - $this->debug('start'); - - if (!mysql_select_db($this->cfg['dbname'], $this->link)) - { - $database = (DBG_USER) ? $this->cfg['dbhost'] : ''; - die("Could not select database $database"); - } - - $this->debug('stop'); - $this->cur_query = null; - - return $this->cfg['dbname']; - } - - /** - * Base query method - */ - function sql_query ($query) - { - if (!is_resource($this->link)) - { - $this->init(); - } - if (is_array($query)) - { - $query = $this->build_sql($query); - } - if (SQL_PREPEND_SRC_COMM) - { - $query = '/* '. $this->debug_find_source() .' */ '. $query; - } - $this->cur_query = $query; - $this->debug('start'); - - if (!$this->result = mysql_query($query, $this->link)) - { - $this->log_error(); - } - - $this->debug('stop'); - $this->cur_query = null; - - if ($this->inited) - { - $this->num_queries++; - $this->DBS['num_queries']++; - } - - return $this->result; - } - - /** - * Execute query WRAPPER (with error handling) - */ - function query ($query) - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $result; - } - - /** - * Return number of rows - */ - function num_rows ($result = false) - { - $num_rows = false; - - if ($result OR $result = $this->result) - { - $num_rows = is_resource($result) ? mysql_num_rows($result) : false; - } - - return $num_rows; - } - - /** - * Return number of affected rows - */ - function affected_rows () - { - return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; - } - - /** - * Fetch current field - */ - function sql_fetchfield($field, $rownum = -1, $query_id = 0) - { - if(!$query_id) - { - $query_id = $this->query_result; - } - if($query_id) - { - if($rownum > -1) - { - $result = mysql_result($query_id, $rownum, $field); - } - else - { - if(empty($this->row[$query_id]) && empty($this->rowset[$query_id])) - { - if($this->sql_fetchrow()) - { - $result = $this->row[$query_id][$field]; - } - } - else - { - if($this->rowset[$query_id]) - { - $result = $this->rowset[$query_id][0][$field]; - } - else if($this->row[$query_id]) - { - $result = $this->row[$query_id][$field]; - } - } - } - return $result; - } - else - { - return false; - } - } - - /** - * Fetch current row - */ - function sql_fetchrow ($result, $field_name = '') - { - $row = mysql_fetch_assoc($result); - - if ($field_name) - { - return isset($row[$field_name]) ? $row[$field_name] : false; - } - else - { - return $row; - } - } - - /** - * Alias of sql_fetchrow() - */ - function fetch_next ($result) - { - return $this->sql_fetchrow($result); - } - - /** - * Fetch row WRAPPER (with error handling) - */ - function fetch_row ($query, $field_name = '') - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $this->sql_fetchrow($result, $field_name); - } - - /** - * Fetch all rows - */ - function sql_fetchrowset ($result, $field_name = '') - { - $rowset = array(); - - while ($row = mysql_fetch_assoc($result)) - { - $rowset[] = ($field_name) ? $row[$field_name] : $row; - } - - return $rowset; - } - - /** - * Fetch all rows WRAPPER (with error handling) - */ - function fetch_rowset ($query, $field_name = '') - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $this->sql_fetchrowset($result, $field_name); - } - - /** - * Fetch all rows WRAPPER (with error handling) - */ - function fetch_all ($query, $field_name = '') - { - if (!$result = $this->sql_query($query)) - { - $this->trigger_error(); - } - - return $this->sql_fetchrowset($result, $field_name); - } - - /** - * Get last inserted id after insert statement - */ - function sql_nextid () - { - return mysql_insert_id($this->link); - } - - /** - * Free sql result - */ - function sql_freeresult ($result = false) - { - if ($result OR $result = $this->result) - { - $return_value = is_resource($result) ? mysql_free_result($result) : false; - } - - $this->result = null; - } - - /** - * Escape data used in sql query - */ - function escape ($v, $check_type = false, $dont_escape = false) - { - if ($dont_escape) return $v; - if (!$check_type) return $this->escape_string($v); - - switch (true) - { - case is_string ($v): return "'". $this->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'); - } - - /** - * Escape string - */ - function escape_string ($str) - { - if (!is_resource($this->link)) - { - $this->init(); - } - - return mysql_real_escape_string($str, $this->link); - } - - /** - * Build SQL statement from array (based on same method from phpBB3, idea from Ikonboard) - * - * Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT - */ - function build_array ($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true) - { - $fields = $values = $ary = $query = array(); - $dont_escape = $data_already_escaped; - $check_type = $check_data_type_in_escape; - - if (empty($input_ary) || !is_array($input_ary)) - { - $this->trigger_error(__FUNCTION__ .' - wrong params: $input_ary'); - } - - if ($query_type == 'INSERT') - { - foreach ($input_ary as $field => $val) - { - $fields[] = $field; - $values[] = $this->escape($val, $check_type, $dont_escape); - } - $fields = join(', ', $fields); - $values = join(', ', $values); - $query = "($fields)\nVALUES\n($values)"; - } - else if ($query_type == 'INSERT_SELECT') - { - foreach ($input_ary as $field => $val) - { - $fields[] = $field; - $values[] = $this->escape($val, $check_type, $dont_escape); - } - $fields = join(', ', $fields); - $values = join(', ', $values); - $query = "($fields)\nSELECT\n$values"; - } - else if ($query_type == 'MULTI_INSERT') - { - foreach ($input_ary as $id => $sql_ary) - { - foreach ($sql_ary as $field => $val) - { - $values[] = $this->escape($val, $check_type, $dont_escape); - } - $ary[] = '('. join(', ', $values) .')'; - $values = array(); - } - $fields = join(', ', array_keys($input_ary[0])); - $values = join(",\n", $ary); - $query = "($fields)\nVALUES\n$values"; - } - else if ($query_type == 'SELECT' || $query_type == 'UPDATE') - { - foreach ($input_ary as $field => $val) - { - $ary[] = "$field = ". $this->escape($val, $check_type, $dont_escape); - } - $glue = ($query_type == 'SELECT') ? "\nAND " : ",\n"; - $query = join($glue, $ary); - } - - if (!$query) - { - bb_die('
            '. __FUNCTION__ .": Wrong params for $query_type query type\n\n\$input_ary:\n\n". htmlCHR(print_r($input_ary, true)) .'
            '); - } - - return "\n". $query ."\n"; - } - - function get_empty_sql_array () - { - return array( - 'SELECT' => array(), - 'select_options' => array(), - 'FROM' => array(), - 'INNER JOIN' => array(), - 'LEFT JOIN' => array(), - 'WHERE' => array(), - 'GROUP BY' => array(), - 'HAVING' => array(), - 'ORDER BY' => array(), - 'LIMIT' => array(), - ); - } - - function build_sql ($sql_ary) - { - $sql = ''; - array_deep($sql_ary, 'array_unique', false, true); - - foreach ($sql_ary as $clause => $ary) - { - switch ($clause) - { - case 'SELECT': - $sql .= ($ary) ? ' SELECT '. join(' ', $sql_ary['select_options']) .' '. join(', ', $ary) : ''; - break; - case 'FROM': - $sql .= ($ary) ? ' FROM '. join(', ', $ary) : ''; - break; - case 'INNER JOIN': - $sql .= ($ary) ? ' INNER JOIN '. join(' INNER JOIN ', $ary) : ''; - break; - case 'LEFT JOIN': - $sql .= ($ary) ? ' LEFT JOIN '. join(' LEFT JOIN ', $ary) : ''; - break; - case 'WHERE': - $sql .= ($ary) ? ' WHERE '. join(' AND ', $ary) : ''; - break; - case 'GROUP BY': - $sql .= ($ary) ? ' GROUP BY '. join(', ', $ary) : ''; - break; - case 'HAVING': - $sql .= ($ary) ? ' HAVING '. join(' AND ', $ary) : ''; - break; - case 'ORDER BY': - $sql .= ($ary) ? ' ORDER BY '. join(', ', $ary) : ''; - break; - case 'LIMIT': - $sql .= ($ary) ? ' LIMIT '. join(', ', $ary) : ''; - break; - } - } - - return trim($sql); - } - - /** - * Return sql error array - */ - function sql_error () - { - if (is_resource($this->link)) - { - return array('code' => mysql_errno($this->link), 'message' => mysql_error($this->link)); - } - else - { - return array('code' => '', 'message' => 'not connected'); - } - } - - /** - * Close sql connection - */ - function close () - { - if (is_resource($this->link)) - { - $this->unlock(); - - if (!empty($this->locks)) - { - foreach ($this->locks as $name => $void) - { - $this->release_lock($name); - } - } - - $this->exec_shutdown_queries(); - - mysql_close($this->link); - } - - $this->link = $this->selected_db = null; - } - - /** - * Add shutdown query - */ - function add_shutdown_query ($sql) - { - $this->shutdown['__sql'][] = $sql; - } - - /** - * Exec shutdown queries - */ - function exec_shutdown_queries () - { - if (empty($this->shutdown)) return; - - if (!empty($this->shutdown['post_html'])) - { - $post_html_sql = $this->build_array('MULTI_INSERT', $this->shutdown['post_html']); - $this->query("REPLACE INTO ". BB_POSTS_HTML ." $post_html_sql"); - } - - if (!empty($this->shutdown['__sql'])) - { - foreach ($this->shutdown['__sql'] as $sql) - { - $this->query($sql); - } - } - } - - /** - * Lock tables - */ - function lock ($tables, $lock_type = 'WRITE') - { - if ($this->cfg['persist']) - { + var $cfg = array(); + var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); + var $link = null; + var $result = null; + var $db_server = ''; + var $selected_db = null; + var $inited = false; + + var $locked = false; + var $locks = array(); + + var $num_queries = 0; + var $sql_starttime = 0; + var $sql_inittime = 0; + var $sql_timetotal = 0; + var $cur_query_time = 0; + var $slow_time = 0; + + var $dbg = array(); + var $dbg_id = 0; + var $dbg_enabled = false; + var $cur_query = null; + + var $do_explain = false; + var $explain_hold = ''; + var $explain_out = ''; + + var $shutdown = array(); + + var $DBS = array(); + + /** + * Constructor + */ + function sql_db($cfg_values) + { + global $DBS; + + $this->cfg = array_combine($this->cfg_keys, $cfg_values); + $this->dbg_enabled = (sql_dbg_enabled() || !empty($_COOKIE['explain'])); + $this->do_explain = ($this->dbg_enabled && !empty($_COOKIE['explain'])); + $this->slow_time = SQL_SLOW_QUERY_TIME; + + // ссылки на глобальные переменные (для включения логов сразу на всех серверах, подсчета общего количества запросов и т.д.) + $this->DBS['log_file'] =& $DBS->log_file; + $this->DBS['log_counter'] =& $DBS->log_counter; + $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(); + + // 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']}")) { + die("Could not set charset {$this->cfg['charset']}"); + } + } + + $this->inited = true; + $this->num_queries = 0; + $this->sql_inittime = $this->sql_timetotal; + $this->DBS['sql_inittime'] += $this->sql_inittime; + } + + /** + * Open connection + */ + function connect() + { + $this->cur_query = ($this->dbg_enabled) ? ($this->cfg['persist'] ? 'p' : '') . "connect to: {$this->cfg['dbhost']}" : 'connect'; + $this->debug('start'); + + $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; + + if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) { + $server = (DBG_USER) ? $this->cfg['dbhost'] : ''; + header("HTTP/1.0 503 Service Unavailable"); + bb_log(' ', "db_err/connect_failed_{$this->cfg['dbhost']}"); + die("Could not connect to mysql server $server"); + } + + register_shutdown_function(array(&$this, 'close')); + + $this->debug('stop'); + $this->cur_query = null; + + return $link; + } + + /** + * Select database + */ + function select_db() + { + $this->cur_query = ($this->dbg_enabled) ? "select db: {$this->cfg['dbname']}" : 'select db'; + $this->debug('start'); + + if (!mysql_select_db($this->cfg['dbname'], $this->link)) { + $database = (DBG_USER) ? $this->cfg['dbhost'] : ''; + die("Could not select database $database"); + } + + $this->debug('stop'); + $this->cur_query = null; + + return $this->cfg['dbname']; + } + + /** + * Base query method + */ + function sql_query($query) + { + if (!is_resource($this->link)) { + $this->init(); + } + if (is_array($query)) { + $query = $this->build_sql($query); + } + if (SQL_PREPEND_SRC_COMM) { + $query = '/* ' . $this->debug_find_source() . ' */ ' . $query; + } + $this->cur_query = $query; + $this->debug('start'); + + if (!$this->result = mysql_query($query, $this->link)) { + $this->log_error(); + } + + $this->debug('stop'); + $this->cur_query = null; + + if ($this->inited) { + $this->num_queries++; + $this->DBS['num_queries']++; + } + + return $this->result; + } + + /** + * Execute query WRAPPER (with error handling) + */ + function query($query) + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } + + return $result; + } + + /** + * Return number of rows + */ + function num_rows($result = false) + { + $num_rows = false; + + if ($result OR $result = $this->result) { + $num_rows = is_resource($result) ? mysql_num_rows($result) : false; + } + + return $num_rows; + } + + /** + * Return number of affected rows + */ + function affected_rows() + { + return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; + } + + /** + * Fetch current field + */ + function sql_fetchfield($field, $rownum = -1, $query_id = 0) + { + if (!$query_id) { + $query_id = $this->query_result; + } + if ($query_id) { + if ($rownum > -1) { + $result = mysql_result($query_id, $rownum, $field); + } else { + if (empty($this->row[$query_id]) && empty($this->rowset[$query_id])) { + if ($this->sql_fetchrow()) { + $result = $this->row[$query_id][$field]; + } + } else { + if ($this->rowset[$query_id]) { + $result = $this->rowset[$query_id][0][$field]; + } else if ($this->row[$query_id]) { + $result = $this->row[$query_id][$field]; + } + } + } + return $result; + } else { + return false; + } + } + + /** + * Fetch current row + */ + function sql_fetchrow($result, $field_name = '') + { + $row = mysql_fetch_assoc($result); + + if ($field_name) { + return isset($row[$field_name]) ? $row[$field_name] : false; + } else { + return $row; + } + } + + /** + * Alias of sql_fetchrow() + */ + function fetch_next($result) + { + return $this->sql_fetchrow($result); + } + + /** + * Fetch row WRAPPER (with error handling) + */ + function fetch_row($query, $field_name = '') + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } + + return $this->sql_fetchrow($result, $field_name); + } + + /** + * Fetch all rows + */ + function sql_fetchrowset($result, $field_name = '') + { + $rowset = array(); + + while ($row = mysql_fetch_assoc($result)) { + $rowset[] = ($field_name) ? $row[$field_name] : $row; + } + + return $rowset; + } + + /** + * Fetch all rows WRAPPER (with error handling) + */ + function fetch_rowset($query, $field_name = '') + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } + + return $this->sql_fetchrowset($result, $field_name); + } + + /** + * Fetch all rows WRAPPER (with error handling) + */ + function fetch_all($query, $field_name = '') + { + if (!$result = $this->sql_query($query)) { + $this->trigger_error(); + } + + return $this->sql_fetchrowset($result, $field_name); + } + + /** + * Get last inserted id after insert statement + */ + function sql_nextid() + { + return mysql_insert_id($this->link); + } + + /** + * Free sql result + */ + function sql_freeresult($result = false) + { + if ($result OR $result = $this->result) { + $return_value = is_resource($result) ? mysql_free_result($result) : false; + } + + $this->result = null; + } + + /** + * Escape data used in sql query + */ + function escape($v, $check_type = false, $dont_escape = false) + { + if ($dont_escape) return $v; + if (!$check_type) return $this->escape_string($v); + + switch (true) { + case is_string($v): + return "'" . $this->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'); + } + + /** + * Escape string + */ + function escape_string($str) + { + if (!is_resource($this->link)) { + $this->init(); + } + + return mysql_real_escape_string($str, $this->link); + } + + /** + * Build SQL statement from array (based on same method from phpBB3, idea from Ikonboard) + * + * Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT + */ + function build_array($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true) + { + $fields = $values = $ary = $query = array(); + $dont_escape = $data_already_escaped; + $check_type = $check_data_type_in_escape; + + if (empty($input_ary) || !is_array($input_ary)) { + $this->trigger_error(__FUNCTION__ . ' - wrong params: $input_ary'); + } + + if ($query_type == 'INSERT') { + foreach ($input_ary as $field => $val) { + $fields[] = $field; + $values[] = $this->escape($val, $check_type, $dont_escape); + } + $fields = join(', ', $fields); + $values = join(', ', $values); + $query = "($fields)\nVALUES\n($values)"; + } else if ($query_type == 'INSERT_SELECT') { + foreach ($input_ary as $field => $val) { + $fields[] = $field; + $values[] = $this->escape($val, $check_type, $dont_escape); + } + $fields = join(', ', $fields); + $values = join(', ', $values); + $query = "($fields)\nSELECT\n$values"; + } else if ($query_type == 'MULTI_INSERT') { + foreach ($input_ary as $id => $sql_ary) { + foreach ($sql_ary as $field => $val) { + $values[] = $this->escape($val, $check_type, $dont_escape); + } + $ary[] = '(' . join(', ', $values) . ')'; + $values = array(); + } + $fields = join(', ', array_keys($input_ary[0])); + $values = join(",\n", $ary); + $query = "($fields)\nVALUES\n$values"; + } else if ($query_type == 'SELECT' || $query_type == 'UPDATE') { + foreach ($input_ary as $field => $val) { + $ary[] = "$field = " . $this->escape($val, $check_type, $dont_escape); + } + $glue = ($query_type == 'SELECT') ? "\nAND " : ",\n"; + $query = join($glue, $ary); + } + + if (!$query) { + bb_die('
            ' . __FUNCTION__ . ": Wrong params for $query_type query type\n\n\$input_ary:\n\n" . htmlCHR(print_r($input_ary, true)) . '
            '); + } + + return "\n" . $query . "\n"; + } + + function get_empty_sql_array() + { + return array( + 'SELECT' => array(), + 'select_options' => array(), + 'FROM' => array(), + 'INNER JOIN' => array(), + 'LEFT JOIN' => array(), + 'WHERE' => array(), + 'GROUP BY' => array(), + 'HAVING' => array(), + 'ORDER BY' => array(), + 'LIMIT' => array(), + ); + } + + function build_sql($sql_ary) + { + $sql = ''; + array_deep($sql_ary, 'array_unique', false, true); + + foreach ($sql_ary as $clause => $ary) { + switch ($clause) { + case 'SELECT': + $sql .= ($ary) ? ' SELECT ' . join(' ', $sql_ary['select_options']) . ' ' . join(', ', $ary) : ''; + break; + case 'FROM': + $sql .= ($ary) ? ' FROM ' . join(', ', $ary) : ''; + break; + case 'INNER JOIN': + $sql .= ($ary) ? ' INNER JOIN ' . join(' INNER JOIN ', $ary) : ''; + break; + case 'LEFT JOIN': + $sql .= ($ary) ? ' LEFT JOIN ' . join(' LEFT JOIN ', $ary) : ''; + break; + case 'WHERE': + $sql .= ($ary) ? ' WHERE ' . join(' AND ', $ary) : ''; + break; + case 'GROUP BY': + $sql .= ($ary) ? ' GROUP BY ' . join(', ', $ary) : ''; + break; + case 'HAVING': + $sql .= ($ary) ? ' HAVING ' . join(' AND ', $ary) : ''; + break; + case 'ORDER BY': + $sql .= ($ary) ? ' ORDER BY ' . join(', ', $ary) : ''; + break; + case 'LIMIT': + $sql .= ($ary) ? ' LIMIT ' . join(', ', $ary) : ''; + break; + } + } + + return trim($sql); + } + + /** + * Return sql error array + */ + function sql_error() + { + if (is_resource($this->link)) { + return array('code' => mysql_errno($this->link), 'message' => mysql_error($this->link)); + } else { + return array('code' => '', 'message' => 'not connected'); + } + } + + /** + * Close sql connection + */ + function close() + { + if (is_resource($this->link)) { + $this->unlock(); + + if (!empty($this->locks)) { + foreach ($this->locks as $name => $void) { + $this->release_lock($name); + } + } + + $this->exec_shutdown_queries(); + + mysql_close($this->link); + } + + $this->link = $this->selected_db = null; + } + + /** + * Add shutdown query + */ + function add_shutdown_query($sql) + { + $this->shutdown['__sql'][] = $sql; + } + + /** + * Exec shutdown queries + */ + function exec_shutdown_queries() + { + if (empty($this->shutdown)) return; + + if (!empty($this->shutdown['post_html'])) { + $post_html_sql = $this->build_array('MULTI_INSERT', $this->shutdown['post_html']); + $this->query("REPLACE INTO " . BB_POSTS_HTML . " $post_html_sql"); + } + + if (!empty($this->shutdown['__sql'])) { + foreach ($this->shutdown['__sql'] as $sql) { + $this->query($sql); + } + } + } + + /** + * Lock tables + */ + function lock($tables, $lock_type = 'WRITE') + { + if ($this->cfg['persist']) { # return true; - } + } - $tables_sql = array(); + $tables_sql = array(); - foreach ((array) $tables as $table_name) - { - $tables_sql[] = "$table_name $lock_type"; - } - if ($tables_sql = join(', ', $tables_sql)) - { - $this->locked = $this->sql_query("LOCK TABLES $tables_sql"); - } + foreach ((array)$tables as $table_name) { + $tables_sql[] = "$table_name $lock_type"; + } + if ($tables_sql = join(', ', $tables_sql)) { + $this->locked = $this->sql_query("LOCK TABLES $tables_sql"); + } - return $this->locked; - } + return $this->locked; + } - /** - * Unlock tables - */ - function unlock () - { - if ($this->locked && $this->sql_query("UNLOCK TABLES")) - { - $this->locked = false; - } + /** + * Unlock tables + */ + function unlock() + { + if ($this->locked && $this->sql_query("UNLOCK TABLES")) { + $this->locked = false; + } - return !$this->locked; - } + return !$this->locked; + } - /** - * Obtain user level lock - */ - function get_lock ($name, $timeout = 0) - { - $lock_name = $this->get_lock_name($name); - $timeout = (int) $timeout; - $row = $this->fetch_row("SELECT GET_LOCK('$lock_name', $timeout) AS lock_result"); + /** + * Obtain user level lock + */ + function get_lock($name, $timeout = 0) + { + $lock_name = $this->get_lock_name($name); + $timeout = (int)$timeout; + $row = $this->fetch_row("SELECT GET_LOCK('$lock_name', $timeout) AS lock_result"); - if ($row['lock_result']) - { - $this->locks[$name] = true; - } + if ($row['lock_result']) { + $this->locks[$name] = true; + } - return $row['lock_result']; - } + return $row['lock_result']; + } - /** - * Obtain user level lock status - */ - function release_lock ($name) - { - $lock_name = $this->get_lock_name($name); - $row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result"); + /** + * Obtain user level lock status + */ + function release_lock($name) + { + $lock_name = $this->get_lock_name($name); + $row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result"); - if ($row['lock_result']) - { - unset($this->locks[$name]); - } + if ($row['lock_result']) { + unset($this->locks[$name]); + } - return $row['lock_result']; - } + return $row['lock_result']; + } - /** - * Release user level lock - */ - function is_free_lock ($name) - { - $lock_name = $this->get_lock_name($name); - $row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result"); - return $row['lock_result']; - } + /** + * Release user level lock + */ + function is_free_lock($name) + { + $lock_name = $this->get_lock_name($name); + $row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result"); + return $row['lock_result']; + } - /** - * Make per db unique lock name - */ - function get_lock_name ($name) - { - if (!$this->selected_db) - { - $this->init(); - } + /** + * Make per db unique lock name + */ + function get_lock_name($name) + { + if (!$this->selected_db) { + $this->init(); + } - return "{$this->selected_db}_{$name}"; - } + return "{$this->selected_db}_{$name}"; + } - /** - * Get info about last query - */ - function query_info () - { - $info = array(); + /** + * Get info about last query + */ + 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"; - } - else if (!$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"; + } else if (!$num && ($aff = $this->affected_rows($this->result) AND $aff != -1)) { + $info[] = "$aff rows"; + } - return str_compact(join(', ', $info)); - } + return str_compact(join(', ', $info)); + } - /** - * Get server version - */ - function server_version () - { - preg_match('#^(\d+\.\d+\.\d+).*#', mysql_get_server_info(), $m); - return $m[1]; - } + /** + * Get server version + */ + function server_version() + { + preg_match('#^(\d+\.\d+\.\d+).*#', mysql_get_server_info(), $m); + return $m[1]; + } - /** - * Set slow query marker for xx seconds - * This will disable counting other queries as "slow" during this time - */ - function expect_slow_query ($ignoring_time = 60, $new_priority = 10) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Set slow query marker for xx seconds + * This will disable counting other queries as "slow" during this time + */ + function expect_slow_query($ignoring_time = 60, $new_priority = 10) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if ($old_priority = $cache->get('dont_log_slow_query')) - { - if ($old_priority > $new_priority) - { - return; - } - } + if ($old_priority = $cache->get('dont_log_slow_query')) { + if ($old_priority > $new_priority) { + return; + } + } - define('IN_FIRST_SLOW_QUERY', true); + define('IN_FIRST_SLOW_QUERY', true); - $cache->set('dont_log_slow_query', $new_priority, $ignoring_time); - } + $cache->set('dont_log_slow_query', $new_priority, $ignoring_time); + } - /** - * Store debug info - */ - function debug ($mode) - { - if (!SQL_DEBUG) return; + /** + * Store debug info + */ + function debug($mode) + { + if (!SQL_DEBUG) return; - $id =& $this->dbg_id; - $dbg =& $this->dbg[$id]; + $id =& $this->dbg_id; + $dbg =& $this->dbg[$id]; - if ($mode == 'start') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->sql_starttime = utime(); - } - if ($this->dbg_enabled) - { - $dbg['sql'] = preg_replace('#^(\s*)(/\*)(.*)(\*/)(\s*)#', '', $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'] = ''; - $dbg['info'] = ''; - $dbg['mem_before'] = sys('mem'); - } - if ($this->do_explain) - { - $this->explain('start'); - } - } - else if ($mode == 'stop') - { - if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) - { - $this->cur_query_time = utime() - $this->sql_starttime; - $this->sql_timetotal += $this->cur_query_time; - $this->DBS['sql_timetotal'] += $this->cur_query_time; + if ($mode == 'start') { + if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { + $this->sql_starttime = utime(); + } + if ($this->dbg_enabled) { + $dbg['sql'] = preg_replace('#^(\s*)(/\*)(.*)(\*/)(\s*)#', '', $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'] = ''; + $dbg['info'] = ''; + $dbg['mem_before'] = sys('mem'); + } + if ($this->do_explain) { + $this->explain('start'); + } + } else if ($mode == 'stop') { + if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { + $this->cur_query_time = utime() - $this->sql_starttime; + $this->sql_timetotal += $this->cur_query_time; + $this->DBS['sql_timetotal'] += $this->cur_query_time; - if (SQL_LOG_SLOW_QUERIES && $this->cur_query_time > $this->slow_time) - { - $this->log_slow_query(); - } - } - if ($this->dbg_enabled) - { - $dbg['time'] = utime() - $this->sql_starttime; - $dbg['info'] = $this->query_info(); - $dbg['mem_after'] = sys('mem'); - $id++; - } - if ($this->do_explain) - { - $this->explain('stop'); - } - // проверка установки $this->inited - для пропуска инициализационных запросов - if ($this->DBS['log_counter'] && $this->inited) - { - $this->log_query($this->DBS['log_file']); - $this->DBS['log_counter']--; - } - } - } + if (SQL_LOG_SLOW_QUERIES && $this->cur_query_time > $this->slow_time) { + $this->log_slow_query(); + } + } + if ($this->dbg_enabled) { + $dbg['time'] = utime() - $this->sql_starttime; + $dbg['info'] = $this->query_info(); + $dbg['mem_after'] = sys('mem'); + $id++; + } + if ($this->do_explain) { + $this->explain('stop'); + } + // проверка установки $this->inited - для пропуска инициализационных запросов + if ($this->DBS['log_counter'] && $this->inited) { + $this->log_query($this->DBS['log_file']); + $this->DBS['log_counter']--; + } + } + } - /** - * Trigger error - */ - function trigger_error ($msg = 'DB Error') - { - if (error_reporting()) - { - if (DBG_LOG === true) - { - $err = $this->sql_error(); - $msg .= "\n". trim(sprintf('#%06d %s', $err['code'], $err['message'])); - } - else - { - $msg .= " [". $this->debug_find_source() ."]"; - } + /** + * Trigger error + */ + function trigger_error($msg = 'DB Error') + { + if (error_reporting()) { + if (DBG_LOG === true) { + $err = $this->sql_error(); + $msg .= "\n" . trim(sprintf('#%06d %s', $err['code'], $err['message'])); + } else { + $msg .= " [" . $this->debug_find_source() . "]"; + } - trigger_error($msg, E_USER_ERROR); - } - } + trigger_error($msg, E_USER_ERROR); + } + } - /** - * Find caller source - */ - function debug_find_source ($mode = '') - { - foreach (debug_backtrace() as $trace) - { - if (!empty($trace['file']) && $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 ''; - } + /** + * Find caller source + */ + function debug_find_source($mode = '') + { + foreach (debug_backtrace() as $trace) { + if (!empty($trace['file']) && $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 ''; + } - /** - * Prepare for logging - */ - function log_next_query ($queries_count = 1, $log_file = 'sql_queries') - { - $this->DBS['log_file'] = $log_file; - $this->DBS['log_counter'] = $queries_count; - } + /** + * Prepare for logging + */ + function log_next_query($queries_count = 1, $log_file = 'sql_queries') + { + $this->DBS['log_file'] = $log_file; + $this->DBS['log_counter'] = $queries_count; + } - /** - * Log query - */ - function log_query ($log_file = 'sql_queries') - { - $q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time); - $msg = array(); - $msg[] = round($this->sql_starttime); - $msg[] = date('m-d H:i:s', $this->sql_starttime); - $msg[] = sprintf('%-6s', $q_time); - $msg[] = sprintf('%-4s', round(sys('la'), 1)); - $msg[] = sprintf('%05d', getmypid()); - $msg[] = $this->db_server; - $msg[] = short_query($this->cur_query); - $msg = join(LOG_SEPR, $msg); - $msg .= ($info = $this->query_info()) ? ' # '. $info : ''; - $msg .= ' # '. $this->debug_find_source() .' '; - $msg .= defined('IN_CRON') ? 'cron' : basename($_SERVER['REQUEST_URI']); - bb_log($msg . LOG_LF, $log_file); - } + /** + * Log query + */ + function log_query($log_file = 'sql_queries') + { + $q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time); + $msg = array(); + $msg[] = round($this->sql_starttime); + $msg[] = date('m-d H:i:s', $this->sql_starttime); + $msg[] = sprintf('%-6s', $q_time); + $msg[] = sprintf('%-4s', round(sys('la'), 1)); + $msg[] = sprintf('%05d', getmypid()); + $msg[] = $this->db_server; + $msg[] = short_query($this->cur_query); + $msg = join(LOG_SEPR, $msg); + $msg .= ($info = $this->query_info()) ? ' # ' . $info : ''; + $msg .= ' # ' . $this->debug_find_source() . ' '; + $msg .= defined('IN_CRON') ? 'cron' : basename($_SERVER['REQUEST_URI']); + bb_log($msg . LOG_LF, $log_file); + } - /** - * Log slow query - */ - function log_slow_query ($log_file = 'sql_slow_bb') - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Log slow query + */ + function log_slow_query($log_file = 'sql_slow_bb') + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!defined('IN_FIRST_SLOW_QUERY') && $cache->get('dont_log_slow_query')) - { - return; - } - $this->log_query($log_file); - } + if (!defined('IN_FIRST_SLOW_QUERY') && $cache->get('dont_log_slow_query')) { + return; + } + $this->log_query($log_file); + } - /** - * Log error - */ - function log_error () - { - if (!SQL_LOG_ERRORS) return; + /** + * Log error + */ + function log_error() + { + if (!SQL_LOG_ERRORS) 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() ." :: $this->db_server.$this->selected_db"; - $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[] = 'PID : '. sprintf('%05d', getmypid()); - $msg[] = 'Request : '. trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; - $msg[] = ''; - bb_log($msg, 'sql_error_bb'); - } + $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() . " :: $this->db_server.$this->selected_db"; + $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[] = 'PID : ' . sprintf('%05d', getmypid()); + $msg[] = 'Request : ' . trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; + $msg[] = ''; + bb_log($msg, 'sql_error_bb'); + } - /** - * Explain queries (based on code from phpBB3) - */ - function explain ($mode, $html_table = '', $row = '') - { - $query = str_compact($this->cur_query); - // remove comments - $query = preg_replace('#(\s*)(/\*)(.*)(\*/)(\s*)#', '', $query); + /** + * Explain queries (based on code from phpBB3) + */ + function explain($mode, $html_table = '', $row = '') + { + $query = str_compact($this->cur_query); + // remove comments + $query = preg_replace('#(\s*)(/\*)(.*)(\*/)(\s*)#', '', $query); - switch ($mode) - { - case 'start': - $this->explain_hold = ''; - if (preg_match('#UPDATE ([a-z0-9_]+).*?WHERE(.*)/#', $query, $m)) - { - $query = "SELECT * FROM $m[1] WHERE $m[2]"; - } - else if (preg_match('#DELETE FROM ([a-z0-9_]+).*?WHERE(.*)#s', $query, $m)) - { - $query = "SELECT * FROM $m[1] WHERE $m[2]"; - } + switch ($mode) { + case 'start': + $this->explain_hold = ''; + if (preg_match('#UPDATE ([a-z0-9_]+).*?WHERE(.*)/#', $query, $m)) { + $query = "SELECT * FROM $m[1] WHERE $m[2]"; + } else if (preg_match('#DELETE FROM ([a-z0-9_]+).*?WHERE(.*)#s', $query, $m)) { + $query = "SELECT * FROM $m[1] WHERE $m[2]"; + } - if (preg_match('#^SELECT#', $query)) - { - $html_table = false; + if (preg_match('#^SELECT#', $query)) { + $html_table = false; - if ($result = mysql_query("EXPLAIN $query", $this->link)) - { - while ($row = mysql_fetch_assoc($result)) - { - $html_table = $this->explain('add_explain_row', $html_table, $row); - } - } - if ($html_table) - { - $this->explain_hold .= '
        '; - } - } - break; + if ($result = mysql_query("EXPLAIN $query", $this->link)) { + while ($row = mysql_fetch_assoc($result)) { + $html_table = $this->explain('add_explain_row', $html_table, $row); + } + } + if ($html_table) { + $this->explain_hold .= ''; + } + } + break; - case 'stop': - if (!$this->explain_hold) break; + case 'stop': + if (!$this->explain_hold) break; - $id = $this->dbg_id-1; - $htid = 'expl-'. intval($this->link) .'-'. $id; - $dbg = $this->dbg[$id]; + $id = $this->dbg_id - 1; + $htid = 'expl-' . intval($this->link) . '-' . $id; + $dbg = $this->dbg[$id]; - $this->explain_out .= ' + $this->explain_out .= ' - - + + - +
         '. $dbg['src'] .'  ['. sprintf('%.4f', $dbg['time']) .' s]  '. $dbg['info'] .''. "$this->db_server.$this->selected_db" .' :: Query #'. ($this->num_queries+1) .'  ' . $dbg['src'] . '  [' . sprintf('%.4f', $dbg['time']) . ' s]  ' . $dbg['info'] . '' . "$this->db_server.$this->selected_db" . ' :: Query #' . ($this->num_queries + 1) . ' 
        '. $this->explain_hold .'
        ' . $this->explain_hold . '
        -
        '. short_query($dbg['sql'], true) .'  
        +
        ' . short_query($dbg['sql'], true) . '  

        '; - break; + break; - case 'add_explain_row': - if (!$html_table && $row) - { - $html_table = true; - $this->explain_hold .= ''; - foreach (array_keys($row) as $val) - { - $this->explain_hold .= ''; - } - $this->explain_hold .= ''; - } - $this->explain_hold .= ''; - foreach (array_values($row) as $i => $val) - { - $class = !($i % 2) ? 'row1' : 'row2'; - $this->explain_hold .= ''; - } - $this->explain_hold .= ''; + case 'add_explain_row': + if (!$html_table && $row) { + $html_table = true; + $this->explain_hold .= '
        '. $val .'
        '. str_replace(array("{$this->selected_db}.", ',', ';'), array('', ', ', ';
        '), $val) .'
        '; + foreach (array_keys($row) as $val) { + $this->explain_hold .= ''; + } + $this->explain_hold .= ''; + } + $this->explain_hold .= ''; + foreach (array_values($row) as $i => $val) { + $class = !($i % 2) ? 'row1' : 'row2'; + $this->explain_hold .= ''; + } + $this->explain_hold .= ''; - return $html_table; + return $html_table; - break; + break; - case 'display': - echo '
        '. $this->explain_out .'
        '; - break; - } - } -} \ No newline at end of file + case 'display': + echo '
        ' . $this->explain_out . '
        '; + break; + } + } +} diff --git a/library/includes/cron/cron_check.php b/library/includes/cron/cron_check.php index 5c211ff02..900b5aacf 100644 --- a/library/includes/cron/cron_check.php +++ b/library/includes/cron/cron_check.php @@ -2,37 +2,32 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -bb_log(date('H:i:s - ') . getmypid() .' --x- SELECT jobs'. LOG_LF, CRON_LOG_DIR .'cron_check'); +bb_log(date('H:i:s - ') . getmypid() . ' --x- SELECT jobs' . LOG_LF, CRON_LOG_DIR . 'cron_check'); // Get cron jobs $cron_jobs = DB()->fetch_rowset(" - SELECT * FROM ". BB_CRON ." + SELECT * FROM " . BB_CRON . " WHERE cron_active = 1 AND next_run <= NOW() ORDER BY run_order "); // Run cron jobs -if ($cron_jobs) -{ - bb_log(date('H:i:s - ') . getmypid() .' --x- RUN jobs'. LOG_LF, CRON_LOG_DIR .'cron_check'); +if ($cron_jobs) { + bb_log(date('H:i:s - ') . getmypid() . ' --x- RUN jobs' . LOG_LF, CRON_LOG_DIR . 'cron_check'); - foreach ($cron_jobs as $job) - { - if ($job['disable_board']) - { - cron_disable_board(); - sleep(10); - break; - } - } + foreach ($cron_jobs as $job) { + if ($job['disable_board']) { + cron_disable_board(); + sleep(10); + break; + } + } - require(CRON_DIR .'cron_run.php'); + require(CRON_DIR . 'cron_run.php'); - // Update cron_last_check - bb_update_config(array('cron_last_check' => (TIMENOW + 10))); + // Update cron_last_check + bb_update_config(array('cron_last_check' => (TIMENOW + 10))); +} else { + bb_log(date('H:i:s - ') . getmypid() . ' --x- no active jobs found ----------------------------------------------' . LOG_LF, CRON_LOG_DIR . 'cron_check'); } -else -{ - bb_log(date('H:i:s - ') . getmypid() .' --x- no active jobs found ----------------------------------------------'. LOG_LF, CRON_LOG_DIR .'cron_check'); -} \ No newline at end of file diff --git a/library/includes/cron/cron_init.php b/library/includes/cron/cron_init.php index 8c7398796..dbdfb9674 100644 --- a/library/includes/cron/cron_init.php +++ b/library/includes/cron/cron_init.php @@ -5,63 +5,53 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); // // Functions // -function cron_get_file_lock () +function cron_get_file_lock() { - $lock_obtained = false; + $lock_obtained = false; - if (file_exists(CRON_ALLOWED)) - { + if (file_exists(CRON_ALLOWED)) { # bb_log(date('H:i:s - ') . getmypid() .' -x-- FILE-LOCK try'. LOG_LF, CRON_LOG_DIR .'cron_check'); - $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING); - } - elseif (file_exists(CRON_RUNNING)) - { - cron_release_deadlock(); - } - elseif (!file_exists(CRON_ALLOWED) && !file_exists(CRON_RUNNING)) - { - file_write('', CRON_ALLOWED); - $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING); - } + $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING); + } elseif (file_exists(CRON_RUNNING)) { + cron_release_deadlock(); + } elseif (!file_exists(CRON_ALLOWED) && !file_exists(CRON_RUNNING)) { + file_write('', CRON_ALLOWED); + $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING); + } - return $lock_obtained; + return $lock_obtained; } -function cron_track_running ($mode) +function cron_track_running($mode) { - defined('CRON_STARTMARK') or define('CRON_STARTMARK', TRIGGERS_DIR .'cron_started_at_'. date('Y-m-d_H-i-s') .'_by_pid_'. getmypid()); + defined('CRON_STARTMARK') or define('CRON_STARTMARK', TRIGGERS_DIR . 'cron_started_at_' . date('Y-m-d_H-i-s') . '_by_pid_' . getmypid()); - if ($mode == 'start') - { - cron_touch_lock_file(CRON_RUNNING); - file_write('', CRON_STARTMARK); - } - elseif ($mode == 'end') - { - unlink(CRON_STARTMARK); - } + if ($mode == 'start') { + cron_touch_lock_file(CRON_RUNNING); + file_write('', CRON_STARTMARK); + } elseif ($mode == 'end') { + unlink(CRON_STARTMARK); + } } // // Run cron // -if (cron_get_file_lock()) -{ - ignore_user_abort(true); - register_shutdown_function('cron_release_file_lock'); - register_shutdown_function('cron_enable_board'); +if (cron_get_file_lock()) { + ignore_user_abort(true); + register_shutdown_function('cron_release_file_lock'); + register_shutdown_function('cron_enable_board'); # bb_log(date('H:i:s - ') . getmypid() .' --x- FILE-LOCK OBTAINED ###############'. LOG_LF, CRON_LOG_DIR .'cron_check'); - cron_track_running('start'); + cron_track_running('start'); - require(CRON_DIR .'cron_check.php'); + require(CRON_DIR . 'cron_check.php'); - cron_track_running('end'); + cron_track_running('end'); } -if (defined('IN_CRON')) -{ - bb_log(date('H:i:s - ') . getmypid() .' --x- ALL jobs FINISHED *************************************************'. LOG_LF, CRON_LOG_DIR .'cron_check'); -} \ No newline at end of file +if (defined('IN_CRON')) { + bb_log(date('H:i:s - ') . getmypid() . ' --x- ALL jobs FINISHED *************************************************' . LOG_LF, CRON_LOG_DIR . 'cron_check'); +} diff --git a/library/includes/cron/cron_run.php b/library/includes/cron/cron_run.php index 45660da8a..151c2657f 100644 --- a/library/includes/cron/cron_run.php +++ b/library/includes/cron/cron_run.php @@ -31,66 +31,59 @@ DB()->add_shutdown_query(" "); // $cron_jobs obtained in cron_check.php -foreach ($cron_jobs as $job) -{ - $job_script = CRON_JOB_DIR . basename($job['cron_script']); +foreach ($cron_jobs as $job) { + $job_script = CRON_JOB_DIR . basename($job['cron_script']); - if (file_exists($job_script)) - { - $cron_start_time = utime(); - $cron_runtime_log = ''; - $cron_write_log = (CRON_LOG_ENABLED && (CRON_FORCE_LOG || $job['log_enabled'] >= 1)); - $cron_sql_log_file = CRON_LOG_DIR .'SQL-'. basename($job['cron_script']); + if (file_exists($job_script)) { + $cron_start_time = utime(); + $cron_runtime_log = ''; + $cron_write_log = (CRON_LOG_ENABLED && (CRON_FORCE_LOG || $job['log_enabled'] >= 1)); + $cron_sql_log_file = CRON_LOG_DIR . 'SQL-' . basename($job['cron_script']); - if ($cron_write_log) - { - $msg = array(); - $msg[] = 'start'; - $msg[] = date('m-d'); - $msg[] = date('H:i:s'); - $msg[] = sprintf('%-4s', round(sys('la'), 1)); - $msg[] = sprintf('%05d', getmypid()); - $msg[] = $job['cron_title']; - $msg = join(LOG_SEPR, $msg); - bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); - } + if ($cron_write_log) { + $msg = array(); + $msg[] = 'start'; + $msg[] = date('m-d'); + $msg[] = date('H:i:s'); + $msg[] = sprintf('%-4s', round(sys('la'), 1)); + $msg[] = sprintf('%05d', getmypid()); + $msg[] = $job['cron_title']; + $msg = join(LOG_SEPR, $msg); + bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); + } - if ($job['log_sql_queries']) - { - DB()->log_next_query(100000, $cron_sql_log_file); - } + if ($job['log_sql_queries']) { + DB()->log_next_query(100000, $cron_sql_log_file); + } - set_time_limit(600); - require($job_script); + set_time_limit(600); + require($job_script); - if ($job['log_sql_queries']) - { - DB()->log_next_query(0); - bb_log(LOG_LF, $cron_sql_log_file); - } + if ($job['log_sql_queries']) { + DB()->log_next_query(0); + bb_log(LOG_LF, $cron_sql_log_file); + } - if ($cron_write_log) - { - $msg = array(); - $msg[] = ' end'; - $msg[] = date('m-d'); - $msg[] = date('H:i:s'); - $msg[] = sprintf('%-4s', round(sys('la'), 1)); - $msg[] = sprintf('%05d', getmypid()); - $msg[] = round(utime() - $cron_start_time) .'/'. round(utime() - TIMESTART) . ' sec'; - $msg = join(LOG_SEPR, $msg); - $msg .= LOG_LF .'------=-------=----------=------=-------=----------'; - bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); + if ($cron_write_log) { + $msg = array(); + $msg[] = ' end'; + $msg[] = date('m-d'); + $msg[] = date('H:i:s'); + $msg[] = sprintf('%-4s', round(sys('la'), 1)); + $msg[] = sprintf('%05d', getmypid()); + $msg[] = round(utime() - $cron_start_time) . '/' . round(utime() - TIMESTART) . ' sec'; + $msg = join(LOG_SEPR, $msg); + $msg .= LOG_LF . '------=-------=----------=------=-------=----------'; + bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); - if ($cron_runtime_log) - { - $runtime_log_file = ($job['log_file']) ? $job['log_file'] : $job['cron_script']; - bb_log($cron_runtime_log . LOG_LF, CRON_LOG_DIR . basename($runtime_log_file)); - } - } + if ($cron_runtime_log) { + $runtime_log_file = ($job['log_file']) ? $job['log_file'] : $job['cron_script']; + bb_log($cron_runtime_log . LOG_LF, CRON_LOG_DIR . basename($runtime_log_file)); + } + } - DB()->query(" - UPDATE ". BB_CRON ." SET + DB()->query(" + UPDATE " . BB_CRON . " SET last_run = NOW(), run_counter = run_counter + 1, next_run = @@ -114,16 +107,13 @@ foreach ($cron_jobs as $job) LIMIT 1 "); - sleep(1); + sleep(1); - if (utime() - TIMESTART > 600) - { - return; // чтобы daily скрипты не блокировали надолго interval'ные - } - } - else - { - $cron_err_msg = "Can not run \"{$job['cron_title']}\" : file \"$job_script\" not found". LOG_LF; - bb_log($cron_err_msg, 'cron_error'); - } -} \ No newline at end of file + if (utime() - TIMESTART > 600) { + return; // чтобы daily скрипты не блокировали надолго interval'ные + } + } else { + $cron_err_msg = "Can not run \"{$job['cron_title']}\" : file \"$job_script\" not found" . LOG_LF; + bb_log($cron_err_msg, 'cron_error'); + } +} diff --git a/library/includes/cron/jobs/board_maintenance.php b/library/includes/cron/jobs/board_maintenance.php index dc7bae484..d449fccc6 100644 --- a/library/includes/cron/jobs/board_maintenance.php +++ b/library/includes/cron/jobs/board_maintenance.php @@ -5,7 +5,7 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require_once(INC_DIR .'functions_admin.php'); +require_once(INC_DIR . 'functions_admin.php'); // Синхронизация sync('topic', 'all'); @@ -13,40 +13,35 @@ sync('user_posts', 'all'); sync_all_forums(); // Чистка bb_poll_users -if ($poll_max_days = (int) $di->config->get('poll_max_days')) -{ - $per_cycle = 20000; - $row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM ". BB_POLL_USERS); - $start_id = (int) $row['start_id']; - $finish_id = (int) $row['finish_id']; +if ($poll_max_days = (int)$di->config->get('poll_max_days')) { + $per_cycle = 20000; + $row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM " . BB_POLL_USERS); + $start_id = (int)$row['start_id']; + $finish_id = (int)$row['finish_id']; - while (true) - { - set_time_limit(600); - $end_id = $start_id + $per_cycle - 1; + while (true) { + set_time_limit(600); + $end_id = $start_id + $per_cycle - 1; - DB()->query(" - DELETE FROM ". BB_POLL_USERS ." + DB()->query(" + DELETE FROM " . BB_POLL_USERS . " WHERE topic_id BETWEEN $start_id AND $end_id AND vote_dt < DATE_SUB(NOW(), INTERVAL $poll_max_days DAY) "); - if ($end_id > $finish_id) - { - break; - } - if (!($start_id % ($per_cycle*10))) - { - sleep(1); - } - $start_id += $per_cycle; - } + if ($end_id > $finish_id) { + break; + } + if (!($start_id % ($per_cycle * 10))) { + sleep(1); + } + $start_id += $per_cycle; + } } // Чистка user_newpasswd -DB()->query("UPDATE ". BB_USERS ." SET user_newpasswd = '' WHERE user_lastvisit < ". (TIMENOW - 7*86400)); +DB()->query("UPDATE " . BB_USERS . " SET user_newpasswd = '' WHERE user_lastvisit < " . (TIMENOW - 7 * 86400)); // Чистка кеша постов -if ($posts_days = intval($di->config->get('posts_cache_days_keep'))) -{ - DB()->query("DELETE FROM ". BB_POSTS_HTML ." WHERE post_html_time < DATE_SUB(NOW(), INTERVAL $posts_days DAY)"); -} \ No newline at end of file +if ($posts_days = intval($di->config->get('posts_cache_days_keep'))) { + DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_html_time < DATE_SUB(NOW(), INTERVAL $posts_days DAY)"); +} diff --git a/library/includes/cron/jobs/clean_dlstat.php b/library/includes/cron/jobs/clean_dlstat.php index 6e0698cc2..6be2422e8 100644 --- a/library/includes/cron/jobs/clean_dlstat.php +++ b/library/includes/cron/jobs/clean_dlstat.php @@ -7,62 +7,58 @@ $di = \TorrentPier\Di::getInstance(); // Delete staled dl-status records $keeping_dlstat = array( - DL_STATUS_WILL => (int) $di->config->get('dl_will_days_keep'), - DL_STATUS_DOWN => (int) $di->config->get('dl_down_days_keep'), - DL_STATUS_COMPLETE => (int) $di->config->get('dl_complete_days_keep'), - DL_STATUS_CANCEL => (int) $di->config->get('dl_cancel_days_keep'), + DL_STATUS_WILL => (int)$di->config->get('dl_will_days_keep'), + DL_STATUS_DOWN => (int)$di->config->get('dl_down_days_keep'), + DL_STATUS_COMPLETE => (int)$di->config->get('dl_complete_days_keep'), + DL_STATUS_CANCEL => (int)$di->config->get('dl_cancel_days_keep'), ); $delete_dlstat_sql = array(); -foreach ($keeping_dlstat as $dl_status => $days_to_keep) -{ - if ($days_to_keep) - { - $delete_dlstat_sql[] = " +foreach ($keeping_dlstat as $dl_status => $days_to_keep) { + if ($days_to_keep) { + $delete_dlstat_sql[] = " user_status = $dl_status AND last_modified_dlstatus < DATE_SUB(NOW(), INTERVAL $days_to_keep DAY) "; - } + } } -if ($delete_dlstat_sql = join(') OR (', $delete_dlstat_sql)) -{ - DB()->query("DELETE QUICK FROM ". BB_BT_DLSTATUS ." WHERE ($delete_dlstat_sql)"); +if ($delete_dlstat_sql = join(') OR (', $delete_dlstat_sql)) { + DB()->query("DELETE QUICK FROM " . BB_BT_DLSTATUS . " WHERE ($delete_dlstat_sql)"); } // Delete orphans DB()->query(" DELETE QUICK dl - FROM ". BB_BT_DLSTATUS ." dl - LEFT JOIN ". BB_USERS ." u USING(user_id) + FROM " . BB_BT_DLSTATUS . " dl + LEFT JOIN " . BB_USERS . " u USING(user_id) WHERE u.user_id IS NULL "); DB()->query(" DELETE QUICK dl - FROM ". BB_BT_DLSTATUS ." dl - LEFT JOIN ". BB_TOPICS ." t USING(topic_id) + FROM " . BB_BT_DLSTATUS . " dl + LEFT JOIN " . BB_TOPICS . " t USING(topic_id) WHERE t.topic_id IS NULL "); // Tor-Stats cleanup -if ($torstat_days_keep = intval($di->config->get('torstat_days_keep'))) -{ - DB()->query("DELETE QUICK FROM ". BB_BT_TORSTAT ." WHERE last_modified_torstat < DATE_SUB(NOW(), INTERVAL $torstat_days_keep DAY)"); +if ($torstat_days_keep = intval($di->config->get('torstat_days_keep'))) { + DB()->query("DELETE QUICK FROM " . BB_BT_TORSTAT . " WHERE last_modified_torstat < DATE_SUB(NOW(), INTERVAL $torstat_days_keep DAY)"); } DB()->query(" DELETE QUICK tst - FROM ". BB_BT_TORSTAT ." tst - LEFT JOIN ". BB_BT_TORRENTS ." tor USING(topic_id) + FROM " . BB_BT_TORSTAT . " tst + LEFT JOIN " . BB_BT_TORRENTS . " tor USING(topic_id) WHERE tor.topic_id IS NULL "); DB()->query(" UPDATE - ". BB_BT_USERS ." + " . BB_BT_USERS . " SET up_yesterday = up_today, down_yesterday = down_today, @@ -73,11 +69,11 @@ DB()->query(" DB()->query(" UPDATE - ". BB_BT_USERS ." + " . BB_BT_USERS . " SET up_today = 0, down_today = 0, up_release_today = 0, up_bonus_today = 0, points_today = 0 -"); \ No newline at end of file +"); diff --git a/library/includes/cron/jobs/clean_log.php b/library/includes/cron/jobs/clean_log.php index 96ef50020..65aa6a4b2 100644 --- a/library/includes/cron/jobs/clean_log.php +++ b/library/includes/cron/jobs/clean_log.php @@ -5,9 +5,9 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$log_days_keep = (int) $di->config->get('log_days_keep'); +$log_days_keep = (int)$di->config->get('log_days_keep'); DB()->query(" - DELETE FROM ". BB_LOG ." - WHERE log_time < ". (TIMENOW - 86400*$log_days_keep) ." -"); \ No newline at end of file + DELETE FROM " . BB_LOG . " + WHERE log_time < " . (TIMENOW - 86400 * $log_days_keep) . " +"); diff --git a/library/includes/cron/jobs/clean_search_results.php b/library/includes/cron/jobs/clean_search_results.php index a15f76368..d1584c905 100644 --- a/library/includes/cron/jobs/clean_search_results.php +++ b/library/includes/cron/jobs/clean_search_results.php @@ -2,9 +2,9 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -$search_results_expire = TIMENOW - 3*3600; +$search_results_expire = TIMENOW - 3 * 3600; DB()->query(" - DELETE FROM ". BB_SEARCH ." + DELETE FROM " . BB_SEARCH . " WHERE search_time < $search_results_expire -"); \ No newline at end of file +"); diff --git a/library/includes/cron/jobs/ds_update_cat_forums.php b/library/includes/cron/jobs/ds_update_cat_forums.php index 094ffea2b..35f493c50 100644 --- a/library/includes/cron/jobs/ds_update_cat_forums.php +++ b/library/includes/cron/jobs/ds_update_cat_forums.php @@ -2,4 +2,4 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -$datastore->update('cat_forums'); \ No newline at end of file +$datastore->update('cat_forums'); diff --git a/library/includes/cron/jobs/ds_update_stats.php b/library/includes/cron/jobs/ds_update_stats.php index 52bd760e4..e3bdfadcb 100644 --- a/library/includes/cron/jobs/ds_update_stats.php +++ b/library/includes/cron/jobs/ds_update_stats.php @@ -2,4 +2,4 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -$datastore->update('stats'); \ No newline at end of file +$datastore->update('stats'); diff --git a/library/includes/cron/jobs/flash_topic_view.php b/library/includes/cron/jobs/flash_topic_view.php index d06fdb252..9a0764ba9 100644 --- a/library/includes/cron/jobs/flash_topic_view.php +++ b/library/includes/cron/jobs/flash_topic_view.php @@ -4,15 +4,15 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); // Lock tables DB()->lock(array( - BB_TOPICS .' t', - BUF_TOPIC_VIEW .' buf', + BB_TOPICS . ' t', + BUF_TOPIC_VIEW . ' buf', )); // Flash buffered records DB()->query(" UPDATE - ". BB_TOPICS ." t, - ". BUF_TOPIC_VIEW ." buf + " . BB_TOPICS . " t, + " . BUF_TOPIC_VIEW . " buf SET t.topic_views = t.topic_views + buf.topic_views WHERE @@ -20,7 +20,7 @@ DB()->query(" "); // Delete buffered records -DB()->query("DELETE buf FROM ". BUF_TOPIC_VIEW ." buf"); +DB()->query("DELETE buf FROM " . BUF_TOPIC_VIEW . " buf"); // Unlock tables -DB()->unlock(); \ No newline at end of file +DB()->unlock(); diff --git a/library/includes/cron/jobs/prune_forums.php b/library/includes/cron/jobs/prune_forums.php index 3b5e48e82..4ff9afd68 100644 --- a/library/includes/cron/jobs/prune_forums.php +++ b/library/includes/cron/jobs/prune_forums.php @@ -5,14 +5,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require_once(INC_DIR .'functions_admin.php'); +require_once(INC_DIR . 'functions_admin.php'); -if ($di->config->get('prune_enable')) -{ - $sql = "SELECT forum_id, prune_days FROM ". BB_FORUMS ." WHERE prune_days != 0"; +if ($di->config->get('prune_enable')) { + $sql = "SELECT forum_id, prune_days FROM " . BB_FORUMS . " WHERE prune_days != 0"; - foreach (DB()->fetch_rowset($sql) as $row) - { - topic_delete('prune', $row['forum_id'], (TIMENOW - 86400*$row['prune_days'])); - } -} \ No newline at end of file + foreach (DB()->fetch_rowset($sql) as $row) { + topic_delete('prune', $row['forum_id'], (TIMENOW - 86400 * $row['prune_days'])); + } +} diff --git a/library/includes/cron/jobs/prune_inactive_users.php b/library/includes/cron/jobs/prune_inactive_users.php index c763d8c15..ec1c6d275 100644 --- a/library/includes/cron/jobs/prune_inactive_users.php +++ b/library/includes/cron/jobs/prune_inactive_users.php @@ -5,56 +5,49 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require_once(INC_DIR .'functions_admin.php'); +require_once(INC_DIR . 'functions_admin.php'); $users_per_cycle = 1000; -while (true) -{ - set_time_limit(600); +while (true) { + set_time_limit(600); - $prune_users = $not_activated_users = $not_active_users = array(); + $prune_users = $not_activated_users = $not_active_users = array(); - if ($not_activated_days = intval($di->config->get('user_not_activated_days_keep'))) - { - $sql = DB()->fetch_rowset("SELECT user_id FROM ". BB_USERS ." + if ($not_activated_days = intval($di->config->get('user_not_activated_days_keep'))) { + $sql = DB()->fetch_rowset("SELECT user_id FROM " . BB_USERS . " WHERE user_level = 0 AND user_lastvisit = 0 AND user_session_time = 0 - AND user_regdate <= ". (TIMENOW - 86400 * $not_activated_days) ." - AND user_id NOT IN(". EXCLUDED_USERS .") + AND user_regdate <= " . (TIMENOW - 86400 * $not_activated_days) . " + AND user_id NOT IN(" . EXCLUDED_USERS . ") LIMIT $users_per_cycle"); - foreach ($sql as $row) - { - $not_activated_users[] = $row['user_id']; - } - } + foreach ($sql as $row) { + $not_activated_users[] = $row['user_id']; + } + } - if ($not_active_days = intval($di->config->get('user_not_active_days_keep'))) - { - $sql = DB()->fetch_rowset("SELECT user_id FROM ". BB_USERS ." + if ($not_active_days = intval($di->config->get('user_not_active_days_keep'))) { + $sql = DB()->fetch_rowset("SELECT user_id FROM " . BB_USERS . " WHERE user_level = 0 AND user_posts = 0 - AND user_lastvisit <= ". (TIMENOW - 86400 * $not_active_days) ." - AND user_id NOT IN(". EXCLUDED_USERS .") + AND user_lastvisit <= " . (TIMENOW - 86400 * $not_active_days) . " + AND user_id NOT IN(" . EXCLUDED_USERS . ") LIMIT $users_per_cycle"); - foreach ($sql as $row) - { - $not_active_users[] = $row['user_id']; - } - } + foreach ($sql as $row) { + $not_active_users[] = $row['user_id']; + } + } - if ($prune_users = $not_activated_users + $not_active_users) - { - user_delete($prune_users); - } + if ($prune_users = $not_activated_users + $not_active_users) { + user_delete($prune_users); + } - if (count($prune_users) < $users_per_cycle) - { - break; - } + if (count($prune_users) < $users_per_cycle) { + break; + } - sleep(3); -} \ No newline at end of file + sleep(3); +} diff --git a/library/includes/cron/jobs/prune_topic_moved.php b/library/includes/cron/jobs/prune_topic_moved.php index 519540ac3..7086b745f 100644 --- a/library/includes/cron/jobs/prune_topic_moved.php +++ b/library/includes/cron/jobs/prune_topic_moved.php @@ -5,13 +5,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if ($di->config->get('topic_moved_days_keep')) -{ - $prune_time = TIMENOW - 86400*$di->config->get('topic_moved_days_keep'); +if ($di->config->get('topic_moved_days_keep')) { + $prune_time = TIMENOW - 86400 * $di->config->get('topic_moved_days_keep'); - DB()->query(" - DELETE FROM ". BB_TOPICS ." - WHERE topic_status = ". TOPIC_MOVED ." + DB()->query(" + DELETE FROM " . BB_TOPICS . " + WHERE topic_status = " . TOPIC_MOVED . " AND topic_time < $prune_time "); -} \ No newline at end of file +} diff --git a/library/includes/cron/jobs/sessions_cleanup.php b/library/includes/cron/jobs/sessions_cleanup.php index ff76d0a12..31dc085b5 100644 --- a/library/includes/cron/jobs/sessions_cleanup.php +++ b/library/includes/cron/jobs/sessions_cleanup.php @@ -5,28 +5,28 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$user_session_expire_time = TIMENOW - intval($di->config->get('user_session_duration')); +$user_session_expire_time = TIMENOW - intval($di->config->get('user_session_duration')); $admin_session_expire_time = TIMENOW - intval($di->config->get('admin_session_duration')); -$user_session_gc_time = $user_session_expire_time - intval($di->config->get('user_session_gc_ttl')); +$user_session_gc_time = $user_session_expire_time - intval($di->config->get('user_session_gc_ttl')); $admin_session_gc_time = $admin_session_expire_time; // ############################ Tables LOCKED ################################ DB()->lock(array( - BB_USERS .' u', - BB_SESSIONS .' s', + BB_USERS . ' u', + BB_SESSIONS . ' s', )); // Update user's session time DB()->query(" UPDATE - ". BB_USERS ." u, - ". BB_SESSIONS ." s + " . BB_USERS . " u, + " . BB_SESSIONS . " s SET u.user_session_time = IF(u.user_session_time < s.session_time, s.session_time, u.user_session_time) WHERE u.user_id = s.session_user_id - AND s.session_user_id != ". GUEST_UID ." + AND s.session_user_id != " . GUEST_UID . " AND ( (s.session_time < $user_session_expire_time AND s.session_admin = 0) OR @@ -42,9 +42,9 @@ sleep(5); // Delete staled sessions DB()->query(" DELETE s - FROM ". BB_SESSIONS ." s + FROM " . BB_SESSIONS . " s WHERE (s.session_time < $user_session_gc_time AND s.session_admin = 0) OR (s.session_time < $admin_session_gc_time AND s.session_admin != 0) -"); \ No newline at end of file +"); diff --git a/library/includes/cron/jobs/sitemap.php b/library/includes/cron/jobs/sitemap.php index 7bc7b6e64..a427af9a4 100644 --- a/library/includes/cron/jobs/sitemap.php +++ b/library/includes/cron/jobs/sitemap.php @@ -2,17 +2,16 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -require(CLASS_DIR .'sitemap.php'); +require(CLASS_DIR . 'sitemap.php'); $map = new sitemap(); $map->create(); -if (file_exists(BB_ROOT. "/sitemap/sitemap.xml")) -{ - $map_link = make_url('/sitemap/sitemap.xml'); +if (file_exists(BB_ROOT . "/sitemap/sitemap.xml")) { + $map_link = make_url('/sitemap/sitemap.xml'); - $map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link); - $map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link); - $map->send_url("http://www.bing.com/ping?sitemap=", $map_link); - $map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link); -} \ No newline at end of file + $map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link); + $map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link); + $map->send_url("http://www.bing.com/ping?sitemap=", $map_link); + $map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link); +} diff --git a/library/includes/cron/jobs/tr_cleanup_and_dlstat.php b/library/includes/cron/jobs/tr_cleanup_and_dlstat.php index 2c36ef4ad..fece807f8 100644 --- a/library/includes/cron/jobs/tr_cleanup_and_dlstat.php +++ b/library/includes/cron/jobs/tr_cleanup_and_dlstat.php @@ -7,102 +7,98 @@ $di = \TorrentPier\Di::getInstance(); $releaser = DL_STATUS_RELEASER; -define('NEW_BB_BT_LAST_TORSTAT', 'new_bt_last_torstat'); -define('OLD_BB_BT_LAST_TORSTAT', 'old_bt_last_torstat'); +define('NEW_BB_BT_LAST_TORSTAT', 'new_bt_last_torstat'); +define('OLD_BB_BT_LAST_TORSTAT', 'old_bt_last_torstat'); define('NEW_BB_BT_LAST_USERSTAT', 'new_bt_last_userstat'); define('OLD_BB_BT_LAST_USERSTAT', 'old_bt_last_userstat'); -DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_LAST_TORSTAT .", ". NEW_BB_BT_LAST_USERSTAT); -DB()->query("DROP TABLE IF EXISTS ". OLD_BB_BT_LAST_TORSTAT .", ". OLD_BB_BT_LAST_USERSTAT); +DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_LAST_TORSTAT . ", " . NEW_BB_BT_LAST_USERSTAT); +DB()->query("DROP TABLE IF EXISTS " . OLD_BB_BT_LAST_TORSTAT . ", " . OLD_BB_BT_LAST_USERSTAT); -DB()->query("CREATE TABLE ". NEW_BB_BT_LAST_TORSTAT ." LIKE ". BB_BT_LAST_TORSTAT); -DB()->query("CREATE TABLE ". NEW_BB_BT_LAST_USERSTAT ." LIKE ". BB_BT_LAST_USERSTAT); +DB()->query("CREATE TABLE " . NEW_BB_BT_LAST_TORSTAT . " LIKE " . BB_BT_LAST_TORSTAT); +DB()->query("CREATE TABLE " . NEW_BB_BT_LAST_USERSTAT . " LIKE " . BB_BT_LAST_USERSTAT); DB()->expect_slow_query(600); // Update dlstat (part 1) -if ($tr_cfg['update_dlstat']) -{ - // ############################ Tables LOCKED ################################ - DB()->lock(array( - BB_BT_TRACKER, - NEW_BB_BT_LAST_TORSTAT, - )); +if ($tr_cfg['update_dlstat']) { + // ############################ Tables LOCKED ################################ + DB()->lock(array( + BB_BT_TRACKER, + NEW_BB_BT_LAST_TORSTAT, + )); - // Get PER TORRENT user's dlstat from tracker - DB()->query(" - INSERT INTO ". NEW_BB_BT_LAST_TORSTAT ." + // Get PER TORRENT user's dlstat from tracker + DB()->query(" + INSERT INTO " . NEW_BB_BT_LAST_TORSTAT . " (topic_id, user_id, dl_status, up_add, down_add, release_add, speed_up, speed_down) SELECT topic_id, user_id, IF(releaser, $releaser, seeder), SUM(up_add), SUM(down_add), IF(releaser, SUM(up_add), 0), SUM(speed_up), SUM(speed_down) - FROM ". BB_BT_TRACKER ." + FROM " . BB_BT_TRACKER . " WHERE (up_add != 0 OR down_add != 0) GROUP BY topic_id, user_id "); - // Reset up/down additions in tracker - DB()->query("UPDATE ". BB_BT_TRACKER ." SET up_add = 0, down_add = 0"); + // Reset up/down additions in tracker + DB()->query("UPDATE " . BB_BT_TRACKER . " SET up_add = 0, down_add = 0"); - DB()->unlock(); - // ############################ Tables UNLOCKED ############################## + DB()->unlock(); + // ############################ Tables UNLOCKED ############################## } // Update last seeder info in BUF DB()->query(" - REPLACE INTO ". BUF_LAST_SEEDER ." + REPLACE INTO " . BUF_LAST_SEEDER . " (topic_id, seeder_last_seen) SELECT - topic_id, ". TIMENOW ." - FROM ". BB_BT_TRACKER ." + topic_id, " . TIMENOW . " + FROM " . BB_BT_TRACKER . " WHERE seeder = 1 GROUP BY topic_id "); // Clean peers table -if ($tr_cfg['autoclean']) -{ - $announce_interval = max(intval($di->config->get('announce_interval')), 60); - $expire_factor = max(floatval($tr_cfg['expire_factor']), 1); - $peer_expire_time = TIMENOW - floor($announce_interval * $expire_factor); +if ($tr_cfg['autoclean']) { + $announce_interval = max(intval($di->config->get('announce_interval')), 60); + $expire_factor = max(floatval($tr_cfg['expire_factor']), 1); + $peer_expire_time = TIMENOW - floor($announce_interval * $expire_factor); - DB()->query("DELETE FROM ". BB_BT_TRACKER ." WHERE update_time < $peer_expire_time"); + DB()->query("DELETE FROM " . BB_BT_TRACKER . " WHERE update_time < $peer_expire_time"); } // Update dlstat (part 2) -if ($tr_cfg['update_dlstat']) -{ - // Set "only 1 seeder" bonus - DB()->query(" +if ($tr_cfg['update_dlstat']) { + // Set "only 1 seeder" bonus + DB()->query(" UPDATE - ". NEW_BB_BT_LAST_TORSTAT ." tb, - ". BB_BT_TRACKER_SNAP ." sn + " . NEW_BB_BT_LAST_TORSTAT . " tb, + " . BB_BT_TRACKER_SNAP . " sn SET tb.bonus_add = tb.up_add WHERE tb.topic_id = sn.topic_id AND sn.seeders = 1 AND tb.up_add != 0 - AND tb.dl_status = ". DL_STATUS_COMPLETE ." + AND tb.dl_status = " . DL_STATUS_COMPLETE . " "); - // Get SUMMARIZED user's dlstat - DB()->query(" - INSERT INTO ". NEW_BB_BT_LAST_USERSTAT ." + // Get SUMMARIZED user's dlstat + DB()->query(" + INSERT INTO " . NEW_BB_BT_LAST_USERSTAT . " (user_id, up_add, down_add, release_add, bonus_add, speed_up, speed_down) SELECT user_id, SUM(up_add), SUM(down_add), SUM(release_add), SUM(bonus_add), SUM(speed_up), SUM(speed_down) - FROM ". NEW_BB_BT_LAST_TORSTAT ." + FROM " . NEW_BB_BT_LAST_TORSTAT . " GROUP BY user_id "); - // Update TOTAL user's dlstat - // This is not needed if Ocelot enabled. It's important. - if (!$di->config->get('ocelot.enabled')) - { - DB()->query(" + // Update TOTAL user's dlstat + // This is not needed if Ocelot enabled. It's important. + if (!$di->config->get('ocelot.enabled')) { + DB()->query(" UPDATE - ". BB_BT_USERS ." u, - ". NEW_BB_BT_LAST_USERSTAT ." ub + " . BB_BT_USERS . " u, + " . NEW_BB_BT_LAST_USERSTAT . " ub SET u.u_up_total = u.u_up_total + ub.up_add, u.u_down_total = u.u_down_total + ub.down_add, @@ -114,47 +110,47 @@ if ($tr_cfg['update_dlstat']) u.up_bonus_today = u.up_bonus_today + ub.bonus_add WHERE u.user_id = ub.user_id "); - } + } - // Delete from dl_list what exists in BUF but not exsits in NEW - DB()->query(" + // Delete from dl_list what exists in BUF but not exsits in NEW + DB()->query(" DELETE dl - FROM ". BB_BT_DLSTATUS ." dl - INNER JOIN ". NEW_BB_BT_LAST_TORSTAT ." buf USING(user_id, topic_id) + FROM " . BB_BT_DLSTATUS . " dl + INNER JOIN " . NEW_BB_BT_LAST_TORSTAT . " buf USING(user_id, topic_id) WHERE buf.user_id IS NULL AND buf.topic_id IS NULL "); - // Update DL-Status - DB()->query(" - REPLACE INTO ". BB_BT_DLSTATUS ." + // Update DL-Status + DB()->query(" + REPLACE INTO " . BB_BT_DLSTATUS . " (user_id, topic_id, user_status) SELECT user_id, topic_id, dl_status - FROM ". NEW_BB_BT_LAST_TORSTAT ." + FROM " . NEW_BB_BT_LAST_TORSTAT . " "); - // Update PER TORRENT DL-Status (for "completed" counter) - DB()->query(" - INSERT IGNORE INTO ". BB_BT_TORSTAT ." + // Update PER TORRENT DL-Status (for "completed" counter) + DB()->query(" + INSERT IGNORE INTO " . BB_BT_TORSTAT . " (topic_id, user_id) SELECT topic_id, user_id - FROM ". NEW_BB_BT_LAST_TORSTAT ." - WHERE dl_status = ". DL_STATUS_COMPLETE ." + FROM " . NEW_BB_BT_LAST_TORSTAT . " + WHERE dl_status = " . DL_STATUS_COMPLETE . " "); } DB()->query(" RENAME TABLE - ". BB_BT_LAST_TORSTAT ." TO ". OLD_BB_BT_LAST_TORSTAT .", - ". NEW_BB_BT_LAST_TORSTAT ." TO ". BB_BT_LAST_TORSTAT ." + " . BB_BT_LAST_TORSTAT . " TO " . OLD_BB_BT_LAST_TORSTAT . ", + " . NEW_BB_BT_LAST_TORSTAT . " TO " . BB_BT_LAST_TORSTAT . " "); -DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_LAST_TORSTAT .", ". OLD_BB_BT_LAST_TORSTAT); +DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_LAST_TORSTAT . ", " . OLD_BB_BT_LAST_TORSTAT); DB()->query(" RENAME TABLE - ". BB_BT_LAST_USERSTAT ." TO ". OLD_BB_BT_LAST_USERSTAT .", - ". NEW_BB_BT_LAST_USERSTAT ." TO ". BB_BT_LAST_USERSTAT ." + " . BB_BT_LAST_USERSTAT . " TO " . OLD_BB_BT_LAST_USERSTAT . ", + " . NEW_BB_BT_LAST_USERSTAT . " TO " . BB_BT_LAST_USERSTAT . " "); -DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_LAST_USERSTAT .", ". OLD_BB_BT_LAST_USERSTAT); \ No newline at end of file +DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_LAST_USERSTAT . ", " . OLD_BB_BT_LAST_USERSTAT); diff --git a/library/includes/cron/jobs/tr_complete_count.php b/library/includes/cron/jobs/tr_complete_count.php index abd2361a5..754b8ce2f 100644 --- a/library/includes/cron/jobs/tr_complete_count.php +++ b/library/includes/cron/jobs/tr_complete_count.php @@ -5,38 +5,35 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if ($di->config->get('ocelot.enabled')) -{ - // Update TORRENT "completed" counters - DB()->query(" +if ($di->config->get('ocelot.enabled')) { + // Update TORRENT "completed" counters + DB()->query(" UPDATE - ". BB_BT_TORRENTS ." tor, - ". BB_BT_TRACKER_SNAP. " snap + " . BB_BT_TORRENTS . " tor, + " . BB_BT_TRACKER_SNAP . " snap SET tor.complete_count = snap.complete WHERE tor.topic_id = snap.topic_id "); -} -else -{ - // Get complete counts - DB()->query(" +} else { + // Get complete counts + DB()->query(" CREATE TEMPORARY TABLE tmp_complete_count SELECT topic_id, COUNT(*) AS compl_cnt - FROM ". BB_BT_TORSTAT ." + FROM " . BB_BT_TORSTAT . " WHERE completed = 0 GROUP BY topic_id "); - // Update USER "completed" counters - DB()->query("UPDATE ". BB_BT_TORSTAT ." SET completed = 1"); + // Update USER "completed" counters + DB()->query("UPDATE " . BB_BT_TORSTAT . " SET completed = 1"); - // Update TORRENT "completed" counters - DB()->query(" + // Update TORRENT "completed" counters + DB()->query(" UPDATE - ". BB_BT_TORRENTS ." tor, + " . BB_BT_TORRENTS . " tor, tmp_complete_count tmp SET tor.complete_count = tor.complete_count + tmp.compl_cnt @@ -44,6 +41,6 @@ else tor.topic_id = tmp.topic_id "); - // Drop tmp table - DB()->query("DROP TEMPORARY TABLE tmp_complete_count"); -} \ No newline at end of file + // Drop tmp table + DB()->query("DROP TEMPORARY TABLE tmp_complete_count"); +} diff --git a/library/includes/cron/jobs/tr_maintenance.php b/library/includes/cron/jobs/tr_maintenance.php index c7e864edc..022b9575f 100644 --- a/library/includes/cron/jobs/tr_maintenance.php +++ b/library/includes/cron/jobs/tr_maintenance.php @@ -5,40 +5,37 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if (empty($di->config->get('seeder_last_seen_days_keep')) || empty($di->config->get('seeder_never_seen_days_keep'))) -{ - return; +if (empty($di->config->get('seeder_last_seen_days_keep')) || empty($di->config->get('seeder_never_seen_days_keep'))) { + return; } -$last_seen_time = TIMENOW - 86400*$di->config->get('seeder_last_seen_days_keep'); -$never_seen_time = TIMENOW - 86400*$di->config->get('seeder_never_seen_days_keep'); +$last_seen_time = TIMENOW - 86400 * $di->config->get('seeder_last_seen_days_keep'); +$never_seen_time = TIMENOW - 86400 * $di->config->get('seeder_never_seen_days_keep'); $limit_sql = 3000; $topics_sql = []; $sql = "SELECT topic_id - FROM ". BB_BT_TORRENTS ." + FROM " . BB_BT_TORRENTS . " WHERE reg_time < $never_seen_time AND seeder_last_seen < $last_seen_time LIMIT $limit_sql"; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $topics_sql[] = $row['topic_id']; +foreach (DB()->fetch_rowset($sql) as $row) { + $topics_sql[] = $row['topic_id']; } $dead_tor_sql = join(',', $topics_sql); -if ($dead_tor_sql) -{ - // Delete torstat - DB()->query(" - DELETE FROM ". BB_BT_TORSTAT ." +if ($dead_tor_sql) { + // Delete torstat + DB()->query(" + DELETE FROM " . BB_BT_TORSTAT . " WHERE topic_id IN($dead_tor_sql) "); - // Remove torrents - DB()->query(" - DELETE FROM ". BB_BT_TORRENTS ." + // Remove torrents + DB()->query(" + DELETE FROM " . BB_BT_TORRENTS . " WHERE topic_id IN($dead_tor_sql) "); -} \ No newline at end of file +} diff --git a/library/includes/cron/jobs/tr_make_snapshot.php b/library/includes/cron/jobs/tr_make_snapshot.php index 5302ae906..aaf8c0429 100644 --- a/library/includes/cron/jobs/tr_make_snapshot.php +++ b/library/includes/cron/jobs/tr_make_snapshot.php @@ -10,30 +10,27 @@ DB()->expect_slow_query(600); // // Make tracker snapshot // -if (!$di->config->get('ocelot.enabled')) -{ - define('NEW_BB_BT_TRACKER_SNAP', 'new_tracker_snap'); - define('OLD_BB_BT_TRACKER_SNAP', 'old_tracker_snap'); +if (!$di->config->get('ocelot.enabled')) { + define('NEW_BB_BT_TRACKER_SNAP', 'new_tracker_snap'); + define('OLD_BB_BT_TRACKER_SNAP', 'old_tracker_snap'); - DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_TRACKER_SNAP . ", " . OLD_BB_BT_TRACKER_SNAP); - DB()->query("CREATE TABLE " . NEW_BB_BT_TRACKER_SNAP . " LIKE " . BB_BT_TRACKER_SNAP); + DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_TRACKER_SNAP . ", " . OLD_BB_BT_TRACKER_SNAP); + DB()->query("CREATE TABLE " . NEW_BB_BT_TRACKER_SNAP . " LIKE " . BB_BT_TRACKER_SNAP); } $per_cycle = 50000; -$row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM ". BB_BT_TRACKER); -$start_id = (int) $row['start_id']; -$finish_id = (int) $row['finish_id']; +$row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM " . BB_BT_TRACKER); +$start_id = (int)$row['start_id']; +$finish_id = (int)$row['finish_id']; -while (true) -{ - set_time_limit(600); - $end_id = $start_id + $per_cycle - 1; +while (true) { + set_time_limit(600); + $end_id = $start_id + $per_cycle - 1; - $val = array(); + $val = array(); - if (!$di->config->get('ocelot.enabled')) - { - $sql = " + if (!$di->config->get('ocelot.enabled')) { + $sql = " SELECT topic_id, SUM(seeder) AS seeders, (COUNT(*) - SUM(seeder)) AS leechers, SUM(speed_up) AS speed_up, SUM(speed_down) AS speed_down @@ -41,66 +38,56 @@ while (true) WHERE topic_id BETWEEN $start_id AND $end_id GROUP BY topic_id "; - } - else - { - $sql = " + } else { + $sql = " SELECT topic_id, SUM(speed_up) AS speed_up, SUM(speed_down) AS speed_down FROM " . BB_BT_TRACKER . " WHERE topic_id BETWEEN $start_id AND $end_id GROUP BY topic_id "; - } + } - foreach (DB()->fetch_rowset($sql) as $row) - { - $val[] = join(',', $row); - } + foreach (DB()->fetch_rowset($sql) as $row) { + $val[] = join(',', $row); + } - if ($val) - { - if (!$di->config->get('ocelot.enabled')) - { - DB()->query(" + if ($val) { + if (!$di->config->get('ocelot.enabled')) { + DB()->query(" REPLACE INTO " . NEW_BB_BT_TRACKER_SNAP . " (topic_id, seeders, leechers, speed_up, speed_down) VALUES(" . join('),(', $val) . ") "); - } - else - { - DB()->query(" + } else { + DB()->query(" INSERT INTO " . BB_BT_TRACKER_SNAP . " (topic_id, speed_up, speed_down) - VALUES(". join('),(', $val) .") + VALUES(" . join('),(', $val) . ") ON DUPLICATE KEY UPDATE speed_up = VALUES(speed_up), speed_down = VALUES(speed_down) "); - } - } + } + } - if ($end_id > $finish_id) - { - break; - } + if ($end_id > $finish_id) { + break; + } - if (!($start_id % ($per_cycle*10))) - { - sleep(1); - } + if (!($start_id % ($per_cycle * 10))) { + sleep(1); + } - $start_id += $per_cycle; + $start_id += $per_cycle; } -if (!$di->config->get('ocelot.enabled')) -{ - DB()->query(" +if (!$di->config->get('ocelot.enabled')) { + DB()->query(" RENAME TABLE - ". BB_BT_TRACKER_SNAP ." TO ". OLD_BB_BT_TRACKER_SNAP .", - ". NEW_BB_BT_TRACKER_SNAP ." TO ". BB_BT_TRACKER_SNAP ." + " . BB_BT_TRACKER_SNAP . " TO " . OLD_BB_BT_TRACKER_SNAP . ", + " . NEW_BB_BT_TRACKER_SNAP . " TO " . BB_BT_TRACKER_SNAP . " "); - DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_TRACKER_SNAP .", ". OLD_BB_BT_TRACKER_SNAP); + DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_TRACKER_SNAP . ", " . OLD_BB_BT_TRACKER_SNAP); } // @@ -109,98 +96,94 @@ if (!$di->config->get('ocelot.enabled')) define('NEW_BB_BT_DLSTATUS_SNAP', 'new_dlstatus_snap'); define('OLD_BB_BT_DLSTATUS_SNAP', 'old_dlstatus_snap'); -DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_DLSTATUS_SNAP .", ". OLD_BB_BT_DLSTATUS_SNAP); +DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_DLSTATUS_SNAP . ", " . OLD_BB_BT_DLSTATUS_SNAP); -DB()->query("CREATE TABLE ". NEW_BB_BT_DLSTATUS_SNAP ." LIKE ". BB_BT_DLSTATUS_SNAP); +DB()->query("CREATE TABLE " . NEW_BB_BT_DLSTATUS_SNAP . " LIKE " . BB_BT_DLSTATUS_SNAP); -if ($di->config->get('bt_show_dl_list') && $di->config->get('bt_dl_list_only_count')) -{ - DB()->query(" - INSERT INTO ". NEW_BB_BT_DLSTATUS_SNAP ." +if ($di->config->get('bt_show_dl_list') && $di->config->get('bt_dl_list_only_count')) { + DB()->query(" + INSERT INTO " . NEW_BB_BT_DLSTATUS_SNAP . " (topic_id, dl_status, users_count) SELECT topic_id, user_status, COUNT(*) - FROM ". BB_BT_DLSTATUS ." - WHERE user_status != ". DL_STATUS_RELEASER ." + FROM " . BB_BT_DLSTATUS . " + WHERE user_status != " . DL_STATUS_RELEASER . " GROUP BY topic_id, user_status "); } DB()->query(" RENAME TABLE - ". BB_BT_DLSTATUS_SNAP ." TO ". OLD_BB_BT_DLSTATUS_SNAP .", - ". NEW_BB_BT_DLSTATUS_SNAP ." TO ". BB_BT_DLSTATUS_SNAP ." + " . BB_BT_DLSTATUS_SNAP . " TO " . OLD_BB_BT_DLSTATUS_SNAP . ", + " . NEW_BB_BT_DLSTATUS_SNAP . " TO " . BB_BT_DLSTATUS_SNAP . " "); -DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_DLSTATUS_SNAP .", ". OLD_BB_BT_DLSTATUS_SNAP); +DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_DLSTATUS_SNAP . ", " . OLD_BB_BT_DLSTATUS_SNAP); // // TORHELP // -if ($di->config->get('torhelp_enabled')) -{ - $tor_min_seeders = 0; // "<=" - $tor_min_leechers = 2; // ">=" - $tor_min_completed = 10; // ">=" - $tor_seed_last_seen_days = 3; // "<=" - $tor_downloaded_days_ago = 60; // ">=" - $user_last_seen_online = 15; // minutes - $users_limit = 3000; - $dl_status_ary = array(DL_STATUS_COMPLETE); +if ($di->config->get('torhelp_enabled')) { + $tor_min_seeders = 0; // "<=" + $tor_min_leechers = 2; // ">=" + $tor_min_completed = 10; // ">=" + $tor_seed_last_seen_days = 3; // "<=" + $tor_downloaded_days_ago = 60; // ">=" + $user_last_seen_online = 15; // minutes + $users_limit = 3000; + $dl_status_ary = array(DL_STATUS_COMPLETE); - define('NEW_BB_BT_TORHELP', 'new_torhelp'); - define('OLD_BB_BT_TORHELP', 'old_torhelp'); + define('NEW_BB_BT_TORHELP', 'new_torhelp'); + define('OLD_BB_BT_TORHELP', 'old_torhelp'); - DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_TORHELP .", ". OLD_BB_BT_TORHELP); + DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_TORHELP . ", " . OLD_BB_BT_TORHELP); - DB()->query("CREATE TABLE ". NEW_BB_BT_TORHELP ." LIKE ". BB_BT_TORHELP); + DB()->query("CREATE TABLE " . NEW_BB_BT_TORHELP . " LIKE " . BB_BT_TORHELP); - // Select users - $sql = " + // Select users + $sql = " SELECT DISTINCT session_user_id AS uid - FROM ". BB_SESSIONS ." + FROM " . BB_SESSIONS . " WHERE session_time > (UNIX_TIMESTAMP() - $user_last_seen_online*60) - AND session_user_id != ". GUEST_UID ." + AND session_user_id != " . GUEST_UID . " ORDER BY session_time DESC LIMIT $users_limit "; - $online_users_ary = array(); + $online_users_ary = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $online_users_ary[] = $row['uid']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $online_users_ary[] = $row['uid']; + } - if ($online_users_csv = join(',', $online_users_ary)) - { - DB()->query(" - INSERT INTO ". NEW_BB_BT_TORHELP ." (user_id, topic_id_csv) + if ($online_users_csv = join(',', $online_users_ary)) { + DB()->query(" + INSERT INTO " . NEW_BB_BT_TORHELP . " (user_id, topic_id_csv) SELECT dl.user_id, GROUP_CONCAT(dl.topic_id) - FROM ". BB_BT_TRACKER_SNAP ." trsn - INNER JOIN ". BB_BT_TORRENTS ." tor ON (tor.topic_id = trsn.topic_id) - INNER JOIN ". BB_BT_DLSTATUS ." dl ON (dl.topic_id = tor.topic_id) + FROM " . BB_BT_TRACKER_SNAP . " trsn + INNER JOIN " . BB_BT_TORRENTS . " tor ON (tor.topic_id = trsn.topic_id) + INNER JOIN " . BB_BT_DLSTATUS . " dl ON (dl.topic_id = tor.topic_id) WHERE trsn.seeders <= $tor_min_seeders AND trsn.leechers >= $tor_min_leechers - AND tor.forum_id != ". (int) $di->config->get('trash_forum_id') ." + AND tor.forum_id != " . (int)$di->config->get('trash_forum_id') . " AND tor.complete_count >= $tor_min_completed AND tor.seeder_last_seen <= (UNIX_TIMESTAMP() - $tor_seed_last_seen_days*86400) AND dl.user_id IN($online_users_csv) - AND dl.user_status IN(". get_id_csv($dl_status_ary) .") + AND dl.user_status IN(" . get_id_csv($dl_status_ary) . ") AND dl.last_modified_dlstatus > DATE_SUB(NOW(), INTERVAL $tor_downloaded_days_ago DAY) GROUP BY dl.user_id LIMIT 10000 "); - } + } - DB()->query(" + DB()->query(" RENAME TABLE - ". BB_BT_TORHELP ." TO ". OLD_BB_BT_TORHELP .", - ". NEW_BB_BT_TORHELP ." TO ". BB_BT_TORHELP ." + " . BB_BT_TORHELP . " TO " . OLD_BB_BT_TORHELP . ", + " . NEW_BB_BT_TORHELP . " TO " . BB_BT_TORHELP . " "); - DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_TORHELP .", ". OLD_BB_BT_TORHELP); + DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_TORHELP . ", " . OLD_BB_BT_TORHELP); } -DB()->expect_slow_query(10); \ No newline at end of file +DB()->expect_slow_query(10); diff --git a/library/includes/cron/jobs/tr_seed_bonus.php b/library/includes/cron/jobs/tr_seed_bonus.php index ef9b61768..cb9a3a933 100644 --- a/library/includes/cron/jobs/tr_seed_bonus.php +++ b/library/includes/cron/jobs/tr_seed_bonus.php @@ -7,39 +7,37 @@ $di = \TorrentPier\Di::getInstance(); DB()->expect_slow_query(600); -if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_points') && $di->config->get('seed_bonus_release')) -{ - DB()->query(" +if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_points') && $di->config->get('seed_bonus_release')) { + DB()->query(" CREATE TEMPORARY TABLE tmp_bonus ( user_id INT UNSIGNED NOT NULL DEFAULT '0', release_count INT UNSIGNED NOT NULL DEFAULT '0' ) ENGINE = MEMORY "); - $tor_size = ($di->config->get('seed_bonus_tor_size') * 1073741824); + $tor_size = ($di->config->get('seed_bonus_tor_size') * 1073741824); - DB()->query("INSERT INTO tmp_bonus + DB()->query("INSERT INTO tmp_bonus SELECT bt.user_id, count(bt.seeder) AS release_count - FROM ". BB_BT_TRACKER ." bt, ". BB_BT_TORRENTS ." tor + FROM " . BB_BT_TRACKER . " bt, " . BB_BT_TORRENTS . " tor WHERE tor.topic_id = bt.topic_id AND tor.size > $tor_size AND bt.seeder > 0 GROUP BY user_id "); - $seed_bonus = unserialize($di->config->get('seed_bonus_points')); - $seed_release = unserialize($di->config->get('seed_bonus_release')); + $seed_bonus = unserialize($di->config->get('seed_bonus_points')); + $seed_release = unserialize($di->config->get('seed_bonus_release')); - foreach($seed_bonus as $i => $points) - { - if (!$points || !$seed_release[$i]) continue; + foreach ($seed_bonus as $i => $points) { + if (!$points || !$seed_release[$i]) continue; - $user_points = ((float) $points / 4); - $release = (int) $seed_release[$i]; - $user_regdate = (TIMENOW - $di->config->get('seed_bonus_user_regdate') * 86400); + $user_points = ((float)$points / 4); + $release = (int)$seed_release[$i]; + $user_regdate = (TIMENOW - $di->config->get('seed_bonus_user_regdate') * 86400); - DB()->query(" - UPDATE ". BB_USERS ." u, ". BB_BT_USERS ." bu, tmp_bonus b + DB()->query(" + UPDATE " . BB_USERS . " u, " . BB_BT_USERS . " bu, tmp_bonus b SET u.user_points = u.user_points + '$user_points', bu.points_today = bu.points_today + '$user_points', @@ -50,9 +48,9 @@ if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_point AND b.release_count <= $release AND u.user_regdate < $user_regdate AND u.user_active = 1 - AND u.user_id not IN(". EXCLUDED_USERS .") + AND u.user_id not IN(" . EXCLUDED_USERS . ") "); - } + } - DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_bonus"); -} \ No newline at end of file + DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_bonus"); +} diff --git a/library/includes/cron/jobs/tr_update_seeder_last_seen.php b/library/includes/cron/jobs/tr_update_seeder_last_seen.php index d9f868d9e..84c394bcd 100644 --- a/library/includes/cron/jobs/tr_update_seeder_last_seen.php +++ b/library/includes/cron/jobs/tr_update_seeder_last_seen.php @@ -4,12 +4,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); DB()->query(" UPDATE - ". BUF_LAST_SEEDER ." b, - ". BB_BT_TORRENTS ." tor + " . BUF_LAST_SEEDER . " b, + " . BB_BT_TORRENTS . " tor SET tor.seeder_last_seen = b.seeder_last_seen WHERE tor.topic_id = b.topic_id "); -DB()->query("TRUNCATE TABLE ". BUF_LAST_SEEDER); \ No newline at end of file +DB()->query("TRUNCATE TABLE " . BUF_LAST_SEEDER); diff --git a/library/includes/cron/jobs/update_forums_atom.php b/library/includes/cron/jobs/update_forums_atom.php index 302f0b135..3b1c2bd27 100644 --- a/library/includes/cron/jobs/update_forums_atom.php +++ b/library/includes/cron/jobs/update_forums_atom.php @@ -5,28 +5,21 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require_once(INC_DIR .'functions_atom.php'); +require_once(INC_DIR . 'functions_atom.php'); $timecheck = TIMENOW - 600; -$forums_data = DB()->fetch_rowset("SELECT forum_id, allow_reg_tracker, forum_name FROM ". BB_FORUMS); +$forums_data = DB()->fetch_rowset("SELECT forum_id, allow_reg_tracker, forum_name FROM " . BB_FORUMS); -if (file_exists($di->config->get('atom.path') .'/f/0.atom')) -{ - if (filemtime($di->config->get('atom.path') .'/f/0.atom') <= $timecheck) update_forum_feed(0, $forums_data); -} -else -{ - update_forum_feed(0, $forums_data); +if (file_exists($di->config->get('atom.path') . '/f/0.atom')) { + if (filemtime($di->config->get('atom.path') . '/f/0.atom') <= $timecheck) update_forum_feed(0, $forums_data); +} else { + update_forum_feed(0, $forums_data); } -foreach ($forums_data as $forum_data) -{ - if (file_exists($di->config->get('atom.path') .'/f/'. $forum_data['forum_id'] .'.atom')) - { - if (filemtime($di->config->get('atom.path') .'/f/'. $forum_data['forum_id'] .'.atom') <= $timecheck) update_forum_feed($forum_data['forum_id'], $forum_data); - } - else - { - update_forum_feed($forum_data['forum_id'], $forum_data); - } -} \ No newline at end of file +foreach ($forums_data as $forum_data) { + if (file_exists($di->config->get('atom.path') . '/f/' . $forum_data['forum_id'] . '.atom')) { + if (filemtime($di->config->get('atom.path') . '/f/' . $forum_data['forum_id'] . '.atom') <= $timecheck) update_forum_feed($forum_data['forum_id'], $forum_data); + } else { + update_forum_feed($forum_data['forum_id'], $forum_data); + } +} diff --git a/library/includes/datastore/apc.php b/library/includes/datastore/apc.php index 03a52c1f2..25fd9b704 100644 --- a/library/includes/datastore/apc.php +++ b/library/includes/datastore/apc.php @@ -4,68 +4,64 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_apc extends datastore_common { - var $engine = 'APC'; - var $prefix = null; + var $engine = 'APC'; + var $prefix = null; - function datastore_apc ($prefix = null) - { - if (!$this->is_installed()) - { - die('Error: APC extension not installed'); - } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } + function datastore_apc($prefix = null) + { + if (!$this->is_installed()) { + die('Error: APC extension not installed'); + } + $this->dbg_enabled = sql_dbg_enabled(); + $this->prefix = $prefix; + } - function store ($title, $var) - { - $this->data[$title] = $var; + function store($title, $var) + { + $this->data[$title] = $var; - $this->cur_query = "cache->set('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->set('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return (bool) apc_store($this->prefix . $title, $var); - } + return (bool)apc_store($this->prefix . $title, $var); + } - function clean () - { - foreach ($this->known_items as $title => $script_name) - { - $this->cur_query = "cache->rm('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + function clean() + { + foreach ($this->known_items as $title => $script_name) { + $this->cur_query = "cache->rm('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - apc_delete($this->prefix . $title); - } - } + apc_delete($this->prefix . $title); + } + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) - { - $src = $this->_debug_find_caller('enqueue'); - trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); - } + function _fetch_from_store() + { + if (!$items = $this->queued_items) { + $src = $this->_debug_find_caller('enqueue'); + trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); + } - foreach ($items as $item) - { - $this->cur_query = "cache->get('$item')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + foreach ($items as $item) { + $this->cur_query = "cache->get('$item')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->data[$item] = apc_fetch($this->prefix . $item); - } - } + $this->data[$item] = apc_fetch($this->prefix . $item); + } + } - function is_installed () - { - return function_exists('apc_fetch'); - } -} \ No newline at end of file + function is_installed() + { + return function_exists('apc_fetch'); + } +} diff --git a/library/includes/datastore/build_cat_forums.php b/library/includes/datastore/build_cat_forums.php index 8bb770595..81e6a9291 100644 --- a/library/includes/datastore/build_cat_forums.php +++ b/library/includes/datastore/build_cat_forums.php @@ -11,96 +11,87 @@ $di = \TorrentPier\Di::getInstance(); // cat_forums // $data = array( - 'not_auth_forums' => array( - 'guest_view' => array(), - 'guest_read' => array(), - 'user_view' => array(), - 'user_read' => array(), - ), - 'tracker_forums' => array(), - 'cat_title_html' => array(), - 'forum_name_html' => array(), - 'c' => array(), // also has $data['c']['cat_id']['forums'] key - 'f' => array(), // also has $data['f']['forum_id']['subforums'] key + 'not_auth_forums' => array( + 'guest_view' => array(), + 'guest_read' => array(), + 'user_view' => array(), + 'user_read' => array(), + ), + 'tracker_forums' => array(), + 'cat_title_html' => array(), + 'forum_name_html' => array(), + 'c' => array(), // also has $data['c']['cat_id']['forums'] key + 'f' => array(), // also has $data['f']['forum_id']['subforums'] key ); // Store only these fields from BB_FORUMS in $data['f'] $forum_store_fields = array_flip(array_keys($bf['forum_perm'])); $forum_store_fields += array_flip(array( - 'forum_id', - 'cat_id', - 'forum_name', - 'forum_desc', - 'forum_status', - 'forum_posts', - 'forum_topics', - 'forum_parent', + 'forum_id', + 'cat_id', + 'forum_name', + 'forum_desc', + 'forum_status', + 'forum_posts', + 'forum_topics', + 'forum_parent', )); // Categories -$sql = "SELECT * FROM ". BB_CATEGORIES ." ORDER BY cat_order"; +$sql = "SELECT * FROM " . BB_CATEGORIES . " ORDER BY cat_order"; -foreach(DB()->fetch_rowset($sql) as $row) -{ - $data['c'][$row['cat_id']] = $row; - $data['cat_title_html'][$row['cat_id']] = htmlCHR($row['cat_title']); +foreach (DB()->fetch_rowset($sql) as $row) { + $data['c'][$row['cat_id']] = $row; + $data['cat_title_html'][$row['cat_id']] = htmlCHR($row['cat_title']); } $sql = " SELECT f.* - FROM ". BB_FORUMS ." f, ". BB_CATEGORIES ." c + FROM " . BB_FORUMS . " f, " . BB_CATEGORIES . " c WHERE f.cat_id = c.cat_id ORDER BY c.cat_order, f.forum_order "; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $fid = $row['forum_id']; - $not_auth =& $data['not_auth_forums']; +foreach (DB()->fetch_rowset($sql) as $row) { + $fid = $row['forum_id']; + $not_auth =& $data['not_auth_forums']; - // Find not auth forums - if ($row['auth_view'] != AUTH_ALL) - { - $not_auth['guest_view'][] = $fid; - } - if ($row['auth_view'] != AUTH_ALL && $row['auth_view'] != AUTH_REG) - { - $not_auth['user_view'][] = $fid; - } - if ($row['auth_read'] != AUTH_ALL) - { - $not_auth['guest_read'][] = $fid; - } - if ($row['auth_read'] != AUTH_ALL && $row['auth_read'] != AUTH_REG) - { - $not_auth['user_read'][] = $fid; - } + // Find not auth forums + if ($row['auth_view'] != AUTH_ALL) { + $not_auth['guest_view'][] = $fid; + } + if ($row['auth_view'] != AUTH_ALL && $row['auth_view'] != AUTH_REG) { + $not_auth['user_view'][] = $fid; + } + if ($row['auth_read'] != AUTH_ALL) { + $not_auth['guest_read'][] = $fid; + } + if ($row['auth_read'] != AUTH_ALL && $row['auth_read'] != AUTH_REG) { + $not_auth['user_read'][] = $fid; + } - $data['forum'][$fid] = $row; + $data['forum'][$fid] = $row; - // Store forums data - if ($parent_id = $row['forum_parent']) - { - $parent =& $data['f'][$parent_id]; + // Store forums data + if ($parent_id = $row['forum_parent']) { + $parent =& $data['f'][$parent_id]; - $parent['subforums'][] = $fid; - $parent['forum_posts'] += $row['forum_posts']; - $parent['forum_topics'] += $row['forum_topics']; - } - if ($row['allow_reg_tracker']) - { - $data['tracker_forums'][] = $fid; - } + $parent['subforums'][] = $fid; + $parent['forum_posts'] += $row['forum_posts']; + $parent['forum_topics'] += $row['forum_topics']; + } + if ($row['allow_reg_tracker']) { + $data['tracker_forums'][] = $fid; + } - $data['f'][$fid] = array_intersect_key($row, $forum_store_fields); - $data['forum_name_html'][$fid] = htmlCHR($row['forum_name']); + $data['f'][$fid] = array_intersect_key($row, $forum_store_fields); + $data['forum_name_html'][$fid] = htmlCHR($row['forum_name']); - // Forum ids in cat - $data['c'][$row['cat_id']]['forums'][] = $fid; + // Forum ids in cat + $data['c'][$row['cat_id']]['forums'][] = $fid; } -foreach ($data['not_auth_forums'] as $key => $val) -{ - $data['not_auth_forums'][$key] = join(',', $val); +foreach ($data['not_auth_forums'] as $key => $val) { + $data['not_auth_forums'][$key] = join(',', $val); } $data['tracker_forums'] = join(',', $data['tracker_forums']); @@ -110,20 +101,20 @@ $this->store('cat_forums', $data); // jumpbox // $data = array( - 'guest' => get_forum_select('guest', 'f', null, null, null, 'id="jumpbox" onchange="window.location.href=\'viewforum.php?f=\'+this.value;"'), - 'user' => get_forum_select('user', 'f', null, null, null, 'id="jumpbox" onchange="window.location.href=\'viewforum.php?f=\'+this.value;"'), + 'guest' => get_forum_select('guest', 'f', null, null, null, 'id="jumpbox" onchange="window.location.href=\'viewforum.php?f=\'+this.value;"'), + 'user' => get_forum_select('user', 'f', null, null, null, 'id="jumpbox" onchange="window.location.href=\'viewforum.php?f=\'+this.value;"'), ); $this->store('jumpbox', $data); -file_write($data['guest'], AJAX_HTML_DIR .'jumpbox_guest.html', false, true, true); -file_write($data['user'], AJAX_HTML_DIR .'jumpbox_user.html', false, true, true); +file_write($data['guest'], AJAX_HTML_DIR . 'jumpbox_guest.html', false, true, true); +file_write($data['user'], AJAX_HTML_DIR . 'jumpbox_user.html', false, true, true); // // viewtopic_forum_select // $data = array( - 'viewtopic_forum_select' => get_forum_select('admin', 'new_forum_id'), + 'viewtopic_forum_select' => get_forum_select('admin', 'new_forum_id'), ); $this->store('viewtopic_forum_select', $data); @@ -131,37 +122,35 @@ $this->store('viewtopic_forum_select', $data); // // latest_news // -if ($di->config->get('show_latest_news') && ($news_forum_ids = $di->config->get('latest_news_forum_id'))) -{ - $news_count = max($di->config->get('latest_news_count'), 1); +if ($di->config->get('show_latest_news') && ($news_forum_ids = $di->config->get('latest_news_forum_id'))) { + $news_count = max($di->config->get('latest_news_count'), 1); - $data = DB()->fetch_rowset(" + $data = DB()->fetch_rowset(" SELECT topic_id, topic_time, topic_title, forum_id - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE forum_id IN ($news_forum_ids) AND topic_moved_id = 0 ORDER BY topic_time DESC LIMIT $news_count "); - $this->store('latest_news', $data); + $this->store('latest_news', $data); } // // Network_news // -if ($di->config->get('show_network_news') && ($net_forum_ids = $di->config->get('network_news_forum_id'))) -{ - $net_count = max($di->config->get('network_news_count'), 1); +if ($di->config->get('show_network_news') && ($net_forum_ids = $di->config->get('network_news_forum_id'))) { + $net_count = max($di->config->get('network_news_count'), 1); - $data = DB()->fetch_rowset(" + $data = DB()->fetch_rowset(" SELECT topic_id, topic_time, topic_title, forum_id - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE forum_id IN ($net_forum_ids) AND topic_moved_id = 0 ORDER BY topic_time DESC LIMIT $net_count "); - $this->store('network_news', $data); -} \ No newline at end of file + $this->store('network_news', $data); +} diff --git a/library/includes/datastore/build_moderators.php b/library/includes/datastore/build_moderators.php index 76d2f8b1d..e9aa1e0d5 100644 --- a/library/includes/datastore/build_moderators.php +++ b/library/includes/datastore/build_moderators.php @@ -3,12 +3,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); $data = array( - 'name_users' => array(), // only by personal permissions - 'name_groups' => array(), // only visible to all users - 'mod_users' => array(), // only by personal permissions - 'mod_groups' => array(), // only visible to all users - 'moderators' => array(), // all moderators - 'admins' => array(), // all admins + 'name_users' => array(), // only by personal permissions + 'name_groups' => array(), // only visible to all users + 'mod_users' => array(), // only by personal permissions + 'mod_groups' => array(), // only visible to all users + 'moderators' => array(), // all moderators + 'admins' => array(), // all admins ); // name_users @@ -17,12 +17,12 @@ $sql = " SELECT aa.forum_id, u.user_id, u.username FROM - ". BB_AUTH_ACCESS ." aa, - ". BB_USER_GROUP ." ug, - ". BB_GROUPS ." g, - ". BB_USERS ." u + " . BB_AUTH_ACCESS . " aa, + " . BB_USER_GROUP . " ug, + " . BB_GROUPS . " g, + " . BB_USERS . " u WHERE - aa.forum_perm & ". BF_AUTH_MOD ." + aa.forum_perm & " . BF_AUTH_MOD . " AND ug.group_id = aa.group_id AND ug.user_pending = 0 AND g.group_id = ug.group_id @@ -34,10 +34,9 @@ $sql = " u.username "; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $data['name_users'][$row['user_id']] = $row['username']; - $data['mod_users'][$row['forum_id']][] = $row['user_id']; +foreach (DB()->fetch_rowset($sql) as $row) { + $data['name_users'][$row['user_id']] = $row['username']; + $data['mod_users'][$row['forum_id']][] = $row['user_id']; } // name_groups @@ -46,23 +45,22 @@ $sql = " SELECT aa.forum_id, g.group_id, g.group_name FROM - ". BB_AUTH_ACCESS ." aa, - ". BB_GROUPS ." g + " . BB_AUTH_ACCESS . " aa, + " . BB_GROUPS . " g WHERE - aa.forum_perm & ". BF_AUTH_MOD ." + aa.forum_perm & " . BF_AUTH_MOD . " AND g.group_id = aa.group_id AND g.group_single_user = 0 - AND g.group_type != ". GROUP_HIDDEN ." + AND g.group_type != " . GROUP_HIDDEN . " GROUP BY aa.forum_id, g.group_id ORDER BY g.group_name "; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $data['name_groups'][$row['group_id']] = $row['group_name']; - $data['mod_groups'][$row['forum_id']][] = $row['group_id']; +foreach (DB()->fetch_rowset($sql) as $row) { + $data['name_groups'][$row['group_id']] = $row['group_name']; + $data['mod_groups'][$row['forum_id']][] = $row['group_id']; } // moderators @@ -70,12 +68,12 @@ $sql = " SELECT u.user_id, u.username FROM - ". BB_AUTH_ACCESS ." aa, - ". BB_USER_GROUP ." ug, - ". BB_GROUPS ." g, - ". BB_USERS ." u + " . BB_AUTH_ACCESS . " aa, + " . BB_USER_GROUP . " ug, + " . BB_GROUPS . " g, + " . BB_USERS . " u WHERE - aa.forum_perm & ". BF_AUTH_MOD ." + aa.forum_perm & " . BF_AUTH_MOD . " AND ug.group_id = aa.group_id AND ug.user_pending = 0 AND g.group_id = ug.group_id @@ -86,22 +84,20 @@ $sql = " u.username "; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $data['moderators'][$row['user_id']] = $row['username']; +foreach (DB()->fetch_rowset($sql) as $row) { + $data['moderators'][$row['user_id']] = $row['username']; } // admins $sql = " SELECT user_id, username - FROM ". BB_USERS ." - WHERE user_level = ". ADMIN ." + FROM " . BB_USERS . " + WHERE user_level = " . ADMIN . " ORDER BY username "; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $data['admins'][$row['user_id']] = $row['username']; +foreach (DB()->fetch_rowset($sql) as $row) { + $data['admins'][$row['user_id']] = $row['username']; } -$this->store('moderators', $data); \ No newline at end of file +$this->store('moderators', $data); diff --git a/library/includes/datastore/build_ranks.php b/library/includes/datastore/build_ranks.php index e428b3a11..264fad658 100644 --- a/library/includes/datastore/build_ranks.php +++ b/library/includes/datastore/build_ranks.php @@ -4,11 +4,10 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); $ranks = array(); -$sql = "SELECT rank_id, rank_title, rank_image, rank_style FROM ". BB_RANKS; +$sql = "SELECT rank_id, rank_title, rank_image, rank_style FROM " . BB_RANKS; -foreach (DB()->fetch_rowset($sql) as $row) -{ - $ranks[$row['rank_id']] = $row; +foreach (DB()->fetch_rowset($sql) as $row) { + $ranks[$row['rank_id']] = $row; } -$this->store('ranks', $ranks); \ No newline at end of file +$this->store('ranks', $ranks); diff --git a/library/includes/datastore/build_smilies.php b/library/includes/datastore/build_smilies.php index 23d6e40b0..4c17fa460 100644 --- a/library/includes/datastore/build_smilies.php +++ b/library/includes/datastore/build_smilies.php @@ -7,14 +7,13 @@ $di = \TorrentPier\Di::getInstance(); $smilies = []; -$rowset = DB()->fetch_rowset("SELECT * FROM ". BB_SMILIES); +$rowset = DB()->fetch_rowset("SELECT * FROM " . BB_SMILIES); sort($rowset); -foreach ($rowset as $smile) -{ - $smilies['orig'][] = '#(?<=^|\W)'. preg_quote($smile['code'], '#') .'(?=$|\W)#'; - $smilies['repl'][] = ' '. $smile['emoticon'] .''; - $smilies['smile'][] = $smile; +foreach ($rowset as $smile) { + $smilies['orig'][] = '#(?<=^|\W)' . preg_quote($smile['code'], '#') . '(?=$|\W)#'; + $smilies['repl'][] = ' ' . $smile['emoticon'] . ''; + $smilies['smile'][] = $smile; } -$this->store('smile_replacements', $smilies); \ No newline at end of file +$this->store('smile_replacements', $smilies); diff --git a/library/includes/datastore/build_stats.php b/library/includes/datastore/build_stats.php index 6efac6284..8cda5f718 100644 --- a/library/includes/datastore/build_stats.php +++ b/library/includes/datastore/build_stats.php @@ -8,90 +8,83 @@ $di = \TorrentPier\Di::getInstance(); $data = []; // usercount -$row = DB()->fetch_row("SELECT COUNT(*) AS usercount FROM ". BB_USERS ." WHERE user_id NOT IN(". EXCLUDED_USERS .")"); +$row = DB()->fetch_row("SELECT COUNT(*) AS usercount FROM " . BB_USERS . " WHERE user_id NOT IN(" . EXCLUDED_USERS . ")"); $data['usercount'] = commify($row['usercount']); // newestuser -$row = DB()->fetch_row("SELECT user_id, username, user_rank FROM ". BB_USERS ." WHERE user_active = 1 ORDER BY user_id DESC LIMIT 1"); +$row = DB()->fetch_row("SELECT user_id, username, user_rank FROM " . BB_USERS . " WHERE user_active = 1 ORDER BY user_id DESC LIMIT 1"); $data['newestuser'] = $row; // post/topic count -$row = DB()->fetch_row("SELECT SUM(forum_topics) AS topiccount, SUM(forum_posts) AS postcount FROM ". BB_FORUMS); +$row = DB()->fetch_row("SELECT SUM(forum_topics) AS topiccount, SUM(forum_posts) AS postcount FROM " . BB_FORUMS); $data['postcount'] = commify($row['postcount']); $data['topiccount'] = commify($row['topiccount']); // Tracker stats -if ($di->config->get('tor_stats')) -{ - // torrents stat - $row = DB()->fetch_row("SELECT COUNT(topic_id) AS torrentcount, SUM(size) AS size FROM ". BB_BT_TORRENTS); - $data['torrentcount'] = commify($row['torrentcount']); - $data['size'] = $row['size']; +if ($di->config->get('tor_stats')) { + // torrents stat + $row = DB()->fetch_row("SELECT COUNT(topic_id) AS torrentcount, SUM(size) AS size FROM " . BB_BT_TORRENTS); + $data['torrentcount'] = commify($row['torrentcount']); + $data['size'] = $row['size']; - // peers stat - $row = DB()->fetch_row("SELECT SUM(seeders) AS seeders, SUM(leechers) AS leechers, ((SUM(speed_up) + SUM(speed_down))/2) AS speed FROM ". BB_BT_TRACKER_SNAP); - $data['seeders'] = commify($row['seeders']); - $data['leechers'] = commify($row['leechers']); - $data['peers'] = commify($row['seeders'] + $row['leechers']); - $data['speed'] = $row['speed']; + // peers stat + $row = DB()->fetch_row("SELECT SUM(seeders) AS seeders, SUM(leechers) AS leechers, ((SUM(speed_up) + SUM(speed_down))/2) AS speed FROM " . BB_BT_TRACKER_SNAP); + $data['seeders'] = commify($row['seeders']); + $data['leechers'] = commify($row['leechers']); + $data['peers'] = commify($row['seeders'] + $row['leechers']); + $data['speed'] = $row['speed']; } // gender stat -if ($di->config->get('gender')) -{ - $male = DB()->fetch_row("SELECT COUNT(user_id) AS male FROM ". BB_USERS ." WHERE user_gender = ". MALE ." AND user_id NOT IN(". EXCLUDED_USERS .")"); - $female = DB()->fetch_row("SELECT COUNT(user_id) AS female FROM ". BB_USERS ." WHERE user_gender = ". FEMALE ." AND user_id NOT IN(". EXCLUDED_USERS .")"); - $unselect = DB()->fetch_row("SELECT COUNT(user_id) AS unselect FROM ". BB_USERS ." WHERE user_gender = 0 AND user_id NOT IN(". EXCLUDED_USERS .")"); +if ($di->config->get('gender')) { + $male = DB()->fetch_row("SELECT COUNT(user_id) AS male FROM " . BB_USERS . " WHERE user_gender = " . MALE . " AND user_id NOT IN(" . EXCLUDED_USERS . ")"); + $female = DB()->fetch_row("SELECT COUNT(user_id) AS female FROM " . BB_USERS . " WHERE user_gender = " . FEMALE . " AND user_id NOT IN(" . EXCLUDED_USERS . ")"); + $unselect = DB()->fetch_row("SELECT COUNT(user_id) AS unselect FROM " . BB_USERS . " WHERE user_gender = 0 AND user_id NOT IN(" . EXCLUDED_USERS . ")"); - $data['male'] = $male['male']; - $data['female'] = $female['female']; - $data['unselect'] = $unselect['unselect']; + $data['male'] = $male['male']; + $data['female'] = $female['female']; + $data['unselect'] = $unselect['unselect']; } // birthday stat -if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) -{ - $sql = DB()->fetch_rowset("SELECT user_id, username, user_rank , user_birthday - FROM ". BB_USERS ." - WHERE user_id NOT IN(". EXCLUDED_USERS .") +if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) { + $sql = DB()->fetch_rowset("SELECT user_id, username, user_rank , user_birthday + FROM " . BB_USERS . " + WHERE user_id NOT IN(" . EXCLUDED_USERS . ") AND user_birthday != '0000-00-00' AND user_active = 1 ORDER BY user_level DESC, username "); - $date_today = bb_date(TIMENOW, 'md', false); - $date_forward = bb_date(TIMENOW + ($di->config->get('birthday_check_day')*86400), 'md', false); + $date_today = bb_date(TIMENOW, 'md', false); + $date_forward = bb_date(TIMENOW + ($di->config->get('birthday_check_day') * 86400), 'md', false); - $birthday_today_list = $birthday_week_list = array(); + $birthday_today_list = $birthday_week_list = array(); - foreach ($sql as $row) - { - $user_birthday = date('md', strtotime($row['user_birthday'])); + foreach ($sql as $row) { + $user_birthday = date('md', strtotime($row['user_birthday'])); - if ($user_birthday > $date_today && $user_birthday <= $date_forward) - { - // user are having birthday within the next days - $birthday_week_list[] = array( - 'user_id' => $row['user_id'], - 'username' => $row['username'], - 'user_rank' => $row['user_rank'], - 'user_birthday' => $row['user_birthday'], - ); - } - elseif ($user_birthday == $date_today) - { - //user have birthday today - $birthday_today_list[] = array( - 'user_id' => $row['user_id'], - 'username' => $row['username'], - 'user_rank' => $row['user_rank'], - 'user_birthday' => $row['user_birthday'], - ); - } - } + if ($user_birthday > $date_today && $user_birthday <= $date_forward) { + // user are having birthday within the next days + $birthday_week_list[] = array( + 'user_id' => $row['user_id'], + 'username' => $row['username'], + 'user_rank' => $row['user_rank'], + 'user_birthday' => $row['user_birthday'], + ); + } elseif ($user_birthday == $date_today) { + //user have birthday today + $birthday_today_list[] = array( + 'user_id' => $row['user_id'], + 'username' => $row['username'], + 'user_rank' => $row['user_rank'], + 'user_birthday' => $row['user_birthday'], + ); + } + } - $data['birthday_today_list'] = $birthday_today_list; - $data['birthday_week_list'] = $birthday_week_list; + $data['birthday_today_list'] = $birthday_today_list; + $data['birthday_week_list'] = $birthday_week_list; } -$this->store('stats', $data); \ No newline at end of file +$this->store('stats', $data); diff --git a/library/includes/datastore/common.php b/library/includes/datastore/common.php index 977f73464..3ced04939 100644 --- a/library/includes/datastore/common.php +++ b/library/includes/datastore/common.php @@ -4,170 +4,162 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_common { - /** - * Директория с builder-скриптами (внутри INC_DIR) - */ - var $ds_dir = 'datastore/'; - /** - * Готовая к употреблению data - * array('title' => data) - */ - var $data = array(); - /** - * Список элементов, которые будут извлечены из хранилища при первом же запросе get() - * до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем - * всех элементов одним запросом - * array('title1', 'title2'...) - */ - var $queued_items = array(); + /** + * Директория с builder-скриптами (внутри INC_DIR) + */ + var $ds_dir = 'datastore/'; + /** + * Готовая к употреблению data + * array('title' => data) + */ + var $data = array(); + /** + * Список элементов, которые будут извлечены из хранилища при первом же запросе get() + * до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем + * всех элементов одним запросом + * array('title1', 'title2'...) + */ + var $queued_items = array(); - /** - * 'title' => 'builder script name' inside "includes/datastore" dir - */ - var $known_items = array( - 'cat_forums' => 'build_cat_forums.php', - 'jumpbox' => 'build_cat_forums.php', - 'viewtopic_forum_select' => 'build_cat_forums.php', - 'latest_news' => 'build_cat_forums.php', - 'network_news' => 'build_cat_forums.php', - 'moderators' => 'build_moderators.php', - 'stats' => 'build_stats.php', - 'ranks' => 'build_ranks.php', - 'smile_replacements' => 'build_smilies.php', - ); + /** + * 'title' => 'builder script name' inside "includes/datastore" dir + */ + var $known_items = array( + 'cat_forums' => 'build_cat_forums.php', + 'jumpbox' => 'build_cat_forums.php', + 'viewtopic_forum_select' => 'build_cat_forums.php', + 'latest_news' => 'build_cat_forums.php', + 'network_news' => 'build_cat_forums.php', + 'moderators' => 'build_moderators.php', + 'stats' => 'build_stats.php', + 'ranks' => 'build_ranks.php', + 'smile_replacements' => 'build_smilies.php', + ); - /** - * Constructor - */ - function datastore_common () {} + /** + * Constructor + */ + function datastore_common() + { + } - /** - * @param array(item1_title, item2_title...) or single item's title - */ - function enqueue ($items) - { - foreach ((array) $items as $item) - { - // игнор уже поставленного в очередь либо уже извлеченного - if (!in_array($item, $this->queued_items) && !isset($this->data[$item])) - { - $this->queued_items[] = $item; - } - } - } + /** + * @param array(item1_title, item2_title...) or single item's title + */ + function enqueue($items) + { + foreach ((array)$items as $item) { + // игнор уже поставленного в очередь либо уже извлеченного + if (!in_array($item, $this->queued_items) && !isset($this->data[$item])) { + $this->queued_items[] = $item; + } + } + } - function &get ($title) - { - if (!isset($this->data[$title])) - { - $this->enqueue($title); - $this->_fetch(); - } - return $this->data[$title]; - } + function &get($title) + { + if (!isset($this->data[$title])) { + $this->enqueue($title); + $this->_fetch(); + } + return $this->data[$title]; + } - function store ($item_name, $item_data) {} + function store($item_name, $item_data) + { + } - function rm ($items) - { - foreach ((array) $items as $item) - { - unset($this->data[$item]); - } - } + function rm($items) + { + foreach ((array)$items as $item) { + unset($this->data[$item]); + } + } - function update ($items) - { - if ($items == 'all') - { - $items = array_keys(array_unique($this->known_items)); - } - foreach ((array) $items as $item) - { - $this->_build_item($item); - } - } + function update($items) + { + if ($items == 'all') { + $items = array_keys(array_unique($this->known_items)); + } + foreach ((array)$items as $item) { + $this->_build_item($item); + } + } - function _fetch () - { - $this->_fetch_from_store(); + function _fetch() + { + $this->_fetch_from_store(); - foreach ($this->queued_items as $title) - { - if (!isset($this->data[$title]) || $this->data[$title] === false) - { - $this->_build_item($title); - } - } + foreach ($this->queued_items as $title) { + if (!isset($this->data[$title]) || $this->data[$title] === false) { + $this->_build_item($title); + } + } - $this->queued_items = array(); - } + $this->queued_items = array(); + } - function _fetch_from_store () {} + function _fetch_from_store() + { + } - function _build_item ($title) - { - if (!empty($this->known_items[$title])) - { - require(INC_DIR . $this->ds_dir . $this->known_items[$title]); - } - else - { - trigger_error("Unknown datastore item: $title", E_USER_ERROR); - } - } + function _build_item($title) + { + if (!empty($this->known_items[$title])) { + require(INC_DIR . $this->ds_dir . $this->known_items[$title]); + } else { + trigger_error("Unknown datastore item: $title", E_USER_ERROR); + } + } - var $num_queries = 0; - var $sql_starttime = 0; - var $sql_inittime = 0; - var $sql_timetotal = 0; - var $cur_query_time = 0; + var $num_queries = 0; + var $sql_starttime = 0; + var $sql_inittime = 0; + var $sql_timetotal = 0; + var $cur_query_time = 0; - var $dbg = array(); - var $dbg_id = 0; - var $dbg_enabled = false; - var $cur_query = null; + var $dbg = array(); + var $dbg_id = 0; + var $dbg_enabled = false; + var $cur_query = null; - function debug ($mode, $cur_query = null) - { - if (!$this->dbg_enabled) return; + function debug($mode, $cur_query = null) + { + if (!$this->dbg_enabled) return; - $id =& $this->dbg_id; - $dbg =& $this->dbg[$id]; + $id =& $this->dbg_id; + $dbg =& $this->dbg[$id]; - if ($mode == 'start') - { - $this->sql_starttime = utime(); + 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'] = ''; - } - 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++; - } - } + $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++; + } + } - 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'; - } -} \ No newline at end of file + 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/datastore/file.php b/library/includes/datastore/file.php index 8eeddb7d5..500f6674f 100644 --- a/library/includes/datastore/file.php +++ b/library/includes/datastore/file.php @@ -4,84 +4,77 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_file extends datastore_common { - var $dir = null; - var $prefix = null; - var $engine = 'Filecache'; + var $dir = null; + var $prefix = null; + var $engine = 'Filecache'; - function datastore_file ($dir, $prefix = null) - { - $this->prefix = $prefix; - $this->dir = $dir; - $this->dbg_enabled = sql_dbg_enabled(); - } + function datastore_file($dir, $prefix = null) + { + $this->prefix = $prefix; + $this->dir = $dir; + $this->dbg_enabled = sql_dbg_enabled(); + } - function store ($title, $var) - { - $this->cur_query = "cache->set('$title')"; - $this->debug('start'); + function store($title, $var) + { + $this->cur_query = "cache->set('$title')"; + $this->debug('start'); - $this->data[$title] = $var; + $this->data[$title] = $var; - $filename = $this->dir . clean_filename($this->prefix . $title) . '.php'; + $filename = $this->dir . clean_filename($this->prefix . $title) . '.php'; - $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); + } - function clean () - { - $dir = $this->dir; + function clean() + { + $dir = $this->dir; - if (is_dir($dir)) - { - if ($dh = opendir($dir)) - { - while (($file = readdir($dh)) !== false) - { - if ($file != "." && $file != "..") - { - $filename = $dir . $file; + if (is_dir($dir)) { + if ($dh = opendir($dir)) { + while (($file = readdir($dh)) !== false) { + if ($file != "." && $file != "..") { + $filename = $dir . $file; - unlink($filename); - } - } - closedir($dh); - } - } - } + unlink($filename); + } + } + closedir($dh); + } + } + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) - { - $src = $this->_debug_find_caller('enqueue'); - trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); - } + function _fetch_from_store() + { + if (!$items = $this->queued_items) { + $src = $this->_debug_find_caller('enqueue'); + trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); + } - foreach($items as $item) - { - $filename = $this->dir . $this->prefix . $item . '.php'; + foreach ($items as $item) { + $filename = $this->dir . $this->prefix . $item . '.php'; - $this->cur_query = "cache->get('$item')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->get('$item')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - if(file_exists($filename)) - { - require($filename); + if (file_exists($filename)) { + require($filename); - $this->data[$item] = $filecache; - } - } - } -} \ No newline at end of file + $this->data[$item] = $filecache; + } + } + } +} diff --git a/library/includes/datastore/memcache.php b/library/includes/datastore/memcache.php index b96997fa1..c8c36d8d8 100644 --- a/library/includes/datastore/memcache.php +++ b/library/includes/datastore/memcache.php @@ -4,100 +4,94 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_memcache extends datastore_common { - var $cfg = null; - var $memcache = null; - var $connected = false; - var $engine = 'Memcache'; - var $prefix = null; + var $cfg = null; + var $memcache = null; + var $connected = false; + var $engine = 'Memcache'; + var $prefix = null; - function datastore_memcache ($cfg, $prefix = null) - { - if (!$this->is_installed()) - { - die('Error: Memcached extension not installed'); - } + function datastore_memcache($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(); + } - function connect () - { - $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; + 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; + } - function store ($title, $var) - { - if (!$this->connected) $this->connect(); - $this->data[$title] = $var; + function store($title, $var) + { + if (!$this->connected) $this->connect(); + $this->data[$title] = $var; - $this->cur_query = "cache->set('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->set('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return (bool) $this->memcache->set($this->prefix . $title, $var); - } + return (bool)$this->memcache->set($this->prefix . $title, $var); + } - function clean () - { - if (!$this->connected) $this->connect(); - foreach ($this->known_items as $title => $script_name) - { - $this->cur_query = "cache->rm('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + function clean() + { + if (!$this->connected) $this->connect(); + foreach ($this->known_items as $title => $script_name) { + $this->cur_query = "cache->rm('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->memcache->delete($this->prefix . $title, 0); - } - } + $this->memcache->delete($this->prefix . $title, 0); + } + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) - { - $src = $this->_debug_find_caller('enqueue'); - trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); - } + function _fetch_from_store() + { + if (!$items = $this->queued_items) { + $src = $this->_debug_find_caller('enqueue'); + trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); + } - if (!$this->connected) $this->connect(); - foreach ($items as $item) - { - $this->cur_query = "cache->get('$item')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + if (!$this->connected) $this->connect(); + foreach ($items as $item) { + $this->cur_query = "cache->get('$item')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->data[$item] = $this->memcache->get($this->prefix . $item); - } - } + $this->data[$item] = $this->memcache->get($this->prefix . $item); + } + } - function is_installed () - { - return class_exists('Memcache'); - } -} \ No newline at end of file + function is_installed() + { + return class_exists('Memcache'); + } +} diff --git a/library/includes/datastore/redis.php b/library/includes/datastore/redis.php index b1aa8c398..b660c591b 100644 --- a/library/includes/datastore/redis.php +++ b/library/includes/datastore/redis.php @@ -4,96 +4,90 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_redis extends datastore_common { - var $cfg = null; - var $redis = null; - var $prefix = null; - var $connected = false; - var $engine = 'Redis'; + var $cfg = null; + var $redis = null; + var $prefix = null; + var $connected = false; + var $engine = 'Redis'; - function datastore_redis ($cfg, $prefix = null) - { - if (!$this->is_installed()) - { - die('Error: Redis extension not installed'); - } + function datastore_redis($cfg, $prefix = null) + { + if (!$this->is_installed()) { + die('Error: Redis extension not installed'); + } - $this->cfg = $cfg; - $this->redis = new Redis(); - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } + $this->cfg = $cfg; + $this->redis = new Redis(); + $this->dbg_enabled = sql_dbg_enabled(); + $this->prefix = $prefix; + } - function connect () - { - $this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port']; - $this->debug('start'); + 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; + } - function store ($title, $var) - { - if (!$this->connected) $this->connect(); - $this->data[$title] = $var; + function store($title, $var) + { + if (!$this->connected) $this->connect(); + $this->data[$title] = $var; - $this->cur_query = "cache->set('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->set('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return (bool) $this->redis->set($this->prefix . $title, serialize($var)); - } + return (bool)$this->redis->set($this->prefix . $title, serialize($var)); + } - function clean () - { - if (!$this->connected) $this->connect(); - foreach ($this->known_items as $title => $script_name) - { - $this->cur_query = "cache->rm('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + function clean() + { + if (!$this->connected) $this->connect(); + foreach ($this->known_items as $title => $script_name) { + $this->cur_query = "cache->rm('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->redis->del($this->prefix . $title); - } - } + $this->redis->del($this->prefix . $title); + } + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) - { - $src = $this->_debug_find_caller('enqueue'); - trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); - } + function _fetch_from_store() + { + if (!$items = $this->queued_items) { + $src = $this->_debug_find_caller('enqueue'); + trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); + } - if (!$this->connected) $this->connect(); - foreach ($items as $item) - { - $this->cur_query = "cache->get('$item')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + if (!$this->connected) $this->connect(); + foreach ($items as $item) { + $this->cur_query = "cache->get('$item')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->data[$item] = unserialize($this->redis->get($this->prefix . $item)); - } - } + $this->data[$item] = unserialize($this->redis->get($this->prefix . $item)); + } + } - function is_installed () - { - return class_exists('Redis'); - } -} \ No newline at end of file + function is_installed() + { + return class_exists('Redis'); + } +} diff --git a/library/includes/datastore/sqlite.php b/library/includes/datastore/sqlite.php index ecc5616e1..5c18298c5 100644 --- a/library/includes/datastore/sqlite.php +++ b/library/includes/datastore/sqlite.php @@ -4,63 +4,62 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_sqlite extends datastore_common { - var $engine = 'SQLite'; - var $db = null; - var $prefix = null; - var $cfg = array( - 'db_file_path' => '/path/to/datastore.db.sqlite', - 'table_name' => 'datastore', - 'table_schema' => 'CREATE TABLE datastore ( + var $engine = 'SQLite'; + var $db = null; + var $prefix = null; + var $cfg = array( + 'db_file_path' => '/path/to/datastore.db.sqlite', + 'table_name' => 'datastore', + 'table_schema' => 'CREATE TABLE datastore ( ds_title VARCHAR(255), ds_data TEXT, PRIMARY KEY (ds_title) )', - 'pconnect' => true, - 'con_required' => true, - 'log_name' => 'DATASTORE', - ); + 'pconnect' => true, + 'con_required' => true, + 'log_name' => 'DATASTORE', + ); - function datastore_sqlite ($cfg, $prefix = null) - { - $this->cfg = array_merge($this->cfg, $cfg); - $this->db = new sqlite_common($this->cfg); - $this->prefix = $prefix; - } + function datastore_sqlite($cfg, $prefix = null) + { + $this->cfg = array_merge($this->cfg, $cfg); + $this->db = new sqlite_common($this->cfg); + $this->prefix = $prefix; + } - function store ($item_name, $item_data) - { - $this->data[$item_name] = $item_data; + function store($item_name, $item_data) + { + $this->data[$item_name] = $item_data; - $ds_title = SQLite3::escapeString($this->prefix . $item_name); - $ds_data = SQLite3::escapeString(serialize($item_data)); + $ds_title = SQLite3::escapeString($this->prefix . $item_name); + $ds_data = SQLite3::escapeString(serialize($item_data)); - $result = $this->db->query("REPLACE INTO ". $this->cfg['table_name'] ." (ds_title, ds_data) VALUES ('$ds_title', '$ds_data')"); + $result = $this->db->query("REPLACE INTO " . $this->cfg['table_name'] . " (ds_title, ds_data) VALUES ('$ds_title', '$ds_data')"); - return (bool) $result; - } + return (bool)$result; + } - function clean () - { - $this->db->query("DELETE FROM ". $this->cfg['table_name']); - } + function clean() + { + $this->db->query("DELETE FROM " . $this->cfg['table_name']); + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) return; + function _fetch_from_store() + { + if (!$items = $this->queued_items) return; - $prefix_len = strlen($this->prefix); - $prefix_sql = SQLite3::escapeString($this->prefix); + $prefix_len = strlen($this->prefix); + $prefix_sql = SQLite3::escapeString($this->prefix); - array_deep($items, 'SQLite3::escapeString'); - $items_list = $prefix_sql . join("','$prefix_sql", $items); + array_deep($items, 'SQLite3::escapeString'); + $items_list = $prefix_sql . join("','$prefix_sql", $items); - $rowset = $this->db->fetch_rowset("SELECT ds_title, ds_data FROM ". $this->cfg['table_name'] ." WHERE ds_title IN ('$items_list')"); + $rowset = $this->db->fetch_rowset("SELECT ds_title, ds_data FROM " . $this->cfg['table_name'] . " WHERE ds_title IN ('$items_list')"); - $this->db->debug('start', "unserialize()"); - foreach ($rowset as $row) - { - $this->data[substr($row['ds_title'], $prefix_len)] = unserialize($row['ds_data']); - } - $this->db->debug('stop'); - } -} \ No newline at end of file + $this->db->debug('start', "unserialize()"); + foreach ($rowset as $row) { + $this->data[substr($row['ds_title'], $prefix_len)] = unserialize($row['ds_data']); + } + $this->db->debug('stop'); + } +} diff --git a/library/includes/datastore/xcache.php b/library/includes/datastore/xcache.php index 2bd5f3fb8..975756df3 100644 --- a/library/includes/datastore/xcache.php +++ b/library/includes/datastore/xcache.php @@ -4,69 +4,65 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class datastore_xcache extends datastore_common { - var $prefix = null; - var $engine = 'XCache'; + var $prefix = null; + var $engine = 'XCache'; - function datastore_xcache ($prefix = null) - { - if (!$this->is_installed()) - { - die('Error: XCache extension not installed'); - } + function datastore_xcache($prefix = null) + { + if (!$this->is_installed()) { + die('Error: XCache extension not installed'); + } - $this->dbg_enabled = sql_dbg_enabled(); - $this->prefix = $prefix; - } + $this->dbg_enabled = sql_dbg_enabled(); + $this->prefix = $prefix; + } - function store ($title, $var) - { - $this->data[$title] = $var; + function store($title, $var) + { + $this->data[$title] = $var; - $this->cur_query = "cache->set('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + $this->cur_query = "cache->set('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - return (bool) xcache_set($this->prefix . $title, $var); - } + return (bool)xcache_set($this->prefix . $title, $var); + } - function clean () - { - foreach ($this->known_items as $title => $script_name) - { - $this->cur_query = "cache->rm('$title')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + function clean() + { + foreach ($this->known_items as $title => $script_name) { + $this->cur_query = "cache->rm('$title')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - xcache_unset($this->prefix . $title); - } - } + xcache_unset($this->prefix . $title); + } + } - function _fetch_from_store () - { - if (!$items = $this->queued_items) - { - $src = $this->_debug_find_caller('enqueue'); - trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); - } + function _fetch_from_store() + { + if (!$items = $this->queued_items) { + $src = $this->_debug_find_caller('enqueue'); + trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); + } - foreach ($items as $item) - { - $this->cur_query = "cache->set('$item')"; - $this->debug('start'); - $this->debug('stop'); - $this->cur_query = null; - $this->num_queries++; + foreach ($items as $item) { + $this->cur_query = "cache->set('$item')"; + $this->debug('start'); + $this->debug('stop'); + $this->cur_query = null; + $this->num_queries++; - $this->data[$item] = xcache_get($this->prefix . $item); - } - } + $this->data[$item] = xcache_get($this->prefix . $item); + } + } - function is_installed () - { - return function_exists('xcache_get'); - } -} \ No newline at end of file + function is_installed() + { + return function_exists('xcache_get'); + } +} diff --git a/library/includes/functions.php b/library/includes/functions.php index 730987369..b3ce90d11 100644 --- a/library/includes/functions.php +++ b/library/includes/functions.php @@ -2,130 +2,120 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function get_path_from_id ($id, $ext_id, $base_path, $first_div, $sec_div) +function get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $ext = $di->config->get('file_id_ext.' . $ext_id) ? $di->config->get('file_id_ext.' . $ext_id) : ''; + $ext = $di->config->get('file_id_ext.' . $ext_id) ? $di->config->get('file_id_ext.' . $ext_id) : ''; - return ($base_path ? "$base_path/" : '') . floor($id/$first_div) .'/'. ($id % $sec_div) .'/'. $id . ($ext ? ".$ext" : ''); + return ($base_path ? "$base_path/" : '') . floor($id / $first_div) . '/' . ($id % $sec_div) . '/' . $id . ($ext ? ".$ext" : ''); } -function get_avatar_path ($id, $ext_id, $base_path = null, $first_div = 10000, $sec_div = 100) +function get_avatar_path($id, $ext_id, $base_path = null, $first_div = 10000, $sec_div = 100) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $base_path = isset($base_path) ? $base_path : $di->config->get('avatars.upload_path'); + $base_path = isset($base_path) ? $base_path : $di->config->get('avatars.upload_path'); - return get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div); + return get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div); } -function get_attach_path ($id, $ext_id = '', $base_path = null, $first_div = 10000, $sec_div = 100) +function get_attach_path($id, $ext_id = '', $base_path = null, $first_div = 10000, $sec_div = 100) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $base_path = isset($base_path) ? $base_path : $di->config->get('attach.upload_path'); + $base_path = isset($base_path) ? $base_path : $di->config->get('attach.upload_path'); - return get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div); + return get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div); } -function delete_avatar ($user_id, $avatar_ext_id) +function delete_avatar($user_id, $avatar_ext_id) { - $avatar_file = ($avatar_ext_id) ? get_avatar_path($user_id, $avatar_ext_id) : ''; - return ($avatar_file && file_exists($avatar_file)) ? unlink($avatar_file) : false; + $avatar_file = ($avatar_ext_id) ? get_avatar_path($user_id, $avatar_ext_id) : ''; + return ($avatar_file && file_exists($avatar_file)) ? unlink($avatar_file) : false; } -function delete_attach ($topic_id, $attach_ext_id) +function delete_attach($topic_id, $attach_ext_id) { - $attach_file = ($attach_ext_id) ? get_attach_path($topic_id, $attach_ext_id) : ''; - return ($attach_file && file_exists($attach_file)) ? unlink($attach_file) : false; + $attach_file = ($attach_ext_id) ? get_attach_path($topic_id, $attach_ext_id) : ''; + return ($attach_file && file_exists($attach_file)) ? unlink($attach_file) : false; } -function get_tracks ($type) +function get_tracks($type) { - $c_name = ''; + $c_name = ''; - switch ($type) - { - case 'topic': - $c_name = COOKIE_TOPIC; - break; - case 'forum': - $c_name = COOKIE_FORUM; - break; - case 'pm': - $c_name = COOKIE_PM; - break; - default: - trigger_error(__FUNCTION__ .": invalid type '$type'", E_USER_ERROR); - } - $tracks = !empty($_COOKIE[$c_name]) ? unserialize($_COOKIE[$c_name]) : false; - return ($tracks) ? $tracks : array(); + switch ($type) { + case 'topic': + $c_name = COOKIE_TOPIC; + break; + case 'forum': + $c_name = COOKIE_FORUM; + break; + case 'pm': + $c_name = COOKIE_PM; + break; + default: + trigger_error(__FUNCTION__ . ": invalid type '$type'", E_USER_ERROR); + } + $tracks = !empty($_COOKIE[$c_name]) ? unserialize($_COOKIE[$c_name]) : false; + return ($tracks) ? $tracks : array(); } -function set_tracks ($cookie_name, &$tracking_ary, $tracks = null, $val = TIMENOW) +function set_tracks($cookie_name, &$tracking_ary, $tracks = null, $val = TIMENOW) { - global $tracking_topics, $tracking_forums, $user; + global $tracking_topics, $tracking_forums, $user; - if (IS_GUEST) return; + if (IS_GUEST) return; - $prev_tracking_ary = $tracking_ary; + $prev_tracking_ary = $tracking_ary; - if ($tracks) - { - if (!is_array($tracks)) - { - $tracks = array($tracks => $val); - } - foreach ($tracks as $key => $val) - { - $key = (int) $key; - $val++; - $curr_track_val = !empty($tracking_ary[$key]) ? $tracking_ary[$key] : 0; + if ($tracks) { + if (!is_array($tracks)) { + $tracks = array($tracks => $val); + } + foreach ($tracks as $key => $val) { + $key = (int)$key; + $val++; + $curr_track_val = !empty($tracking_ary[$key]) ? $tracking_ary[$key] : 0; - if ($val > max($curr_track_val, $user->data['user_lastvisit'])) - { - $tracking_ary[$key] = $val; - } - elseif ($curr_track_val < $user->data['user_lastvisit']) - { - unset($tracking_ary[$key]); - } - } - } + if ($val > max($curr_track_val, $user->data['user_lastvisit'])) { + $tracking_ary[$key] = $val; + } elseif ($curr_track_val < $user->data['user_lastvisit']) { + unset($tracking_ary[$key]); + } + } + } - $overflow = count($tracking_topics) + count($tracking_forums) - COOKIE_MAX_TRACKS; + $overflow = count($tracking_topics) + count($tracking_forums) - COOKIE_MAX_TRACKS; - if ($overflow > 0) - { - arsort($tracking_ary); - for ($i = 0; $i < $overflow; $i++) - { - array_pop($tracking_ary); - } - } + if ($overflow > 0) { + arsort($tracking_ary); + for ($i = 0; $i < $overflow; $i++) { + array_pop($tracking_ary); + } + } - if (array_diff($tracking_ary, $prev_tracking_ary)) - { - bb_setcookie($cookie_name, serialize($tracking_ary)); - } + if (array_diff($tracking_ary, $prev_tracking_ary)) { + bb_setcookie($cookie_name, serialize($tracking_ary)); + } } -function get_last_read ($topic_id = 0, $forum_id = 0) +function get_last_read($topic_id = 0, $forum_id = 0) { - global $tracking_topics, $tracking_forums, $user; + global $tracking_topics, $tracking_forums, $user; - $t = isset($tracking_topics[$topic_id]) ? $tracking_topics[$topic_id] : 0; - $f = isset($tracking_forums[$forum_id]) ? $tracking_forums[$forum_id] : 0; - return max($t, $f, $user->data['user_lastvisit']); + $t = isset($tracking_topics[$topic_id]) ? $tracking_topics[$topic_id] : 0; + $f = isset($tracking_forums[$forum_id]) ? $tracking_forums[$forum_id] : 0; + return max($t, $f, $user->data['user_lastvisit']); } -function is_unread ($ref, $topic_id = 0, $forum_id = 0) +function is_unread($ref, $topic_id = 0, $forum_id = 0) { - return (!IS_GUEST && $ref > get_last_read($topic_id, $forum_id)); + return (!IS_GUEST && $ref > get_last_read($topic_id, $forum_id)); } // @@ -134,102 +124,99 @@ function is_unread ($ref, $topic_id = 0, $forum_id = 0) define('AUTH_LIST_ALL', 0); // forum's ACL types (bb_forums: auth_view, auth_read... values) -define('AUTH_REG', 1); -define('AUTH_ACL', 2); +define('AUTH_REG', 1); +define('AUTH_ACL', 2); define('AUTH_ADMIN', 5); // forum_perm bitfields - backward compatible with auth($type) -define('AUTH_ALL', 0); -define('AUTH_VIEW', 1); -define('AUTH_READ', 2); -define('AUTH_MOD', 3); -define('AUTH_POST', 4); -define('AUTH_REPLY', 5); -define('AUTH_EDIT', 6); -define('AUTH_DELETE', 7); -define('AUTH_STICKY', 8); -define('AUTH_ANNOUNCE', 9); -define('AUTH_VOTE', 10); +define('AUTH_ALL', 0); +define('AUTH_VIEW', 1); +define('AUTH_READ', 2); +define('AUTH_MOD', 3); +define('AUTH_POST', 4); +define('AUTH_REPLY', 5); +define('AUTH_EDIT', 6); +define('AUTH_DELETE', 7); +define('AUTH_STICKY', 8); +define('AUTH_ANNOUNCE', 9); +define('AUTH_VOTE', 10); define('AUTH_POLLCREATE', 11); -define('AUTH_ATTACH', 12); -define('AUTH_DOWNLOAD', 13); +define('AUTH_ATTACH', 12); +define('AUTH_DOWNLOAD', 13); define('BF_AUTH_MOD', bit2dec(AUTH_MOD)); // When defining user permissions, take into account: -define('UG_PERM_BOTH', 1); // both user and group -define('UG_PERM_USER_ONLY', 2); // only personal user permissions +define('UG_PERM_BOTH', 1); // both user and group +define('UG_PERM_USER_ONLY', 2); // only personal user permissions define('UG_PERM_GROUP_ONLY', 3); // only group permissions $bf['forum_perm'] = array( - 'auth_view' => AUTH_VIEW, - 'auth_read' => AUTH_READ, - 'auth_mod' => AUTH_MOD, - 'auth_post' => AUTH_POST, - 'auth_reply' => AUTH_REPLY, - 'auth_edit' => AUTH_EDIT, - 'auth_delete' => AUTH_DELETE, - 'auth_sticky' => AUTH_STICKY, - 'auth_announce' => AUTH_ANNOUNCE, - 'auth_vote' => AUTH_VOTE, - 'auth_pollcreate' => AUTH_POLLCREATE, - 'auth_attachments' => AUTH_ATTACH, - 'auth_download' => AUTH_DOWNLOAD, + 'auth_view' => AUTH_VIEW, + 'auth_read' => AUTH_READ, + 'auth_mod' => AUTH_MOD, + 'auth_post' => AUTH_POST, + 'auth_reply' => AUTH_REPLY, + 'auth_edit' => AUTH_EDIT, + 'auth_delete' => AUTH_DELETE, + 'auth_sticky' => AUTH_STICKY, + 'auth_announce' => AUTH_ANNOUNCE, + 'auth_vote' => AUTH_VOTE, + 'auth_pollcreate' => AUTH_POLLCREATE, + 'auth_attachments' => AUTH_ATTACH, + 'auth_download' => AUTH_DOWNLOAD, ); $bf['user_opt'] = array( # 'dis_opt_name' => ЗАПРЕТЫ используемые администраторами для пользователей # 'user_opt_name' => НАСТРОЙКИ используемые пользователями - 'user_viewemail' => 0, // Показывать e-mail - 'dis_sig' => 1, // Запрет на подпись - 'dis_avatar' => 2, // Запрет на аватар - 'dis_pm' => 3, // Запрет на отправку ЛС - 'user_viewonline' => 4, // Скрывать пребывание пользователя - 'user_notify' => 5, // Сообщать об ответах в отслеживаемых темах - 'user_notify_pm' => 6, // Сообщать о новых ЛС - 'dis_passkey' => 7, // Запрет на добавление passkey, он же запрет на скачивание торрентов - 'user_porn_forums' => 8, // Скрывать контент 18+ - 'user_callseed' => 9, // Позвать скачавших - 'user_empty' => 10, // TODO: не используется - 'dis_topic' => 11, // Запрет на создание новых тем - 'dis_post' => 12, // Запрет на отправку сообщений - 'dis_post_edit' => 13, // Запрет на редактирование сообщений - 'user_dls' => 14, // Скрывать список текущих закачек в профиле - 'user_retracker' => 15, // Добавлять ретрекер к скачиваемым торрентам + 'user_viewemail' => 0, // Показывать e-mail + 'dis_sig' => 1, // Запрет на подпись + 'dis_avatar' => 2, // Запрет на аватар + 'dis_pm' => 3, // Запрет на отправку ЛС + 'user_viewonline' => 4, // Скрывать пребывание пользователя + 'user_notify' => 5, // Сообщать об ответах в отслеживаемых темах + 'user_notify_pm' => 6, // Сообщать о новых ЛС + 'dis_passkey' => 7, // Запрет на добавление passkey, он же запрет на скачивание торрентов + 'user_porn_forums' => 8, // Скрывать контент 18+ + 'user_callseed' => 9, // Позвать скачавших + 'user_empty' => 10, // TODO: не используется + 'dis_topic' => 11, // Запрет на создание новых тем + 'dis_post' => 12, // Запрет на отправку сообщений + 'dis_post_edit' => 13, // Запрет на редактирование сообщений + 'user_dls' => 14, // Скрывать список текущих закачек в профиле + 'user_retracker' => 15, // Добавлять ретрекер к скачиваемым торрентам ); -function bit2dec ($bit_num) +function bit2dec($bit_num) { - if (is_array($bit_num)) - { - $dec = 0; - foreach ($bit_num as $bit) - { - $dec |= (1 << $bit); - } - return $dec; - } - return (1 << $bit_num); + if (is_array($bit_num)) { + $dec = 0; + foreach ($bit_num as $bit) { + $dec |= (1 << $bit); + } + return $dec; + } + return (1 << $bit_num); } -function bf_bit2dec ($bf_array_name, $key) +function bf_bit2dec($bf_array_name, $key) { - global $bf; - if (!isset($bf[$bf_array_name][$key])) - { - trigger_error(__FUNCTION__ .": bitfield '$key' not found", E_USER_ERROR); - } - return (1 << $bf[$bf_array_name][$key]); + global $bf; + if (!isset($bf[$bf_array_name][$key])) { + trigger_error(__FUNCTION__ . ": bitfield '$key' not found", E_USER_ERROR); + } + return (1 << $bf[$bf_array_name][$key]); } -function bf ($int, $bf_array_name, $key) +function bf($int, $bf_array_name, $key) { - return (bf_bit2dec($bf_array_name, $key) & (int) $int); + return (bf_bit2dec($bf_array_name, $key) & (int)$int); } -function setbit (&$int, $bit_num, $on) +function setbit(&$int, $bit_num, $on) { - return ($on) ? $int |= (1 << $bit_num) : $int &= ~(1 << $bit_num); + return ($on) ? $int |= (1 << $bit_num) : $int &= ~(1 << $bit_num); } /* @@ -260,105 +247,88 @@ function setbit (&$int, $bit_num, $on) forum auth levels, this will prevent the auth function having to do its own lookup */ -function auth ($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_PERM_BOTH) +function auth($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_PERM_BOTH) { - global $lang, $bf, $datastore; + global $lang, $bf, $datastore; - $is_guest = true; - $is_admin = false; - $auth = $auth_fields = $u_access = array(); - $add_auth_type_desc = ($forum_id != AUTH_LIST_ALL); + $is_guest = true; + $is_admin = false; + $auth = $auth_fields = $u_access = array(); + $add_auth_type_desc = ($forum_id != AUTH_LIST_ALL); - // - // Get $auth_fields - // - if ($type == AUTH_ALL) - { - $auth_fields = array_keys($bf['forum_perm']); - } - else if ($auth_type = array_search($type, $bf['forum_perm'])) - { - $auth_fields = array($auth_type); - } + // + // Get $auth_fields + // + if ($type == AUTH_ALL) { + $auth_fields = array_keys($bf['forum_perm']); + } else if ($auth_type = array_search($type, $bf['forum_perm'])) { + $auth_fields = array($auth_type); + } - if (empty($auth_fields)) - { - trigger_error(__FUNCTION__ .'(): empty $auth_fields', E_USER_ERROR); - } + if (empty($auth_fields)) { + trigger_error(__FUNCTION__ . '(): empty $auth_fields', E_USER_ERROR); + } - // - // Get $f_access - // - // If f_access has been passed, or auth is needed to return an array of forums - // then we need to pull the auth information on the given forum (or all forums) - if (empty($f_access)) - { - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } + // + // Get $f_access + // + // If f_access has been passed, or auth is needed to return an array of forums + // then we need to pull the auth information on the given forum (or all forums) + if (empty($f_access)) { + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } - if ($forum_id == AUTH_LIST_ALL) - { - $f_access = $forums['f']; - } - else if (isset($forums['f'][$forum_id])) - { - $f_access[$forum_id] = $forums['f'][$forum_id]; - } - } - else if (isset($f_access['forum_id'])) - { - // Change passed $f_access format for later using in foreach() - $f_access = array($f_access['forum_id'] => $f_access); - } + if ($forum_id == AUTH_LIST_ALL) { + $f_access = $forums['f']; + } else if (isset($forums['f'][$forum_id])) { + $f_access[$forum_id] = $forums['f'][$forum_id]; + } + } else if (isset($f_access['forum_id'])) { + // Change passed $f_access format for later using in foreach() + $f_access = array($f_access['forum_id'] => $f_access); + } - if (empty($f_access)) - { - trigger_error(__FUNCTION__ .'(): empty $f_access', E_USER_ERROR); - } + if (empty($f_access)) { + trigger_error(__FUNCTION__ . '(): empty $f_access', E_USER_ERROR); + } - // - // Get user or group permissions - // - $forum_match_sql = ($forum_id != AUTH_LIST_ALL) ? "AND aa.forum_id = ". (int) $forum_id : ''; + // + // Get user or group permissions + // + $forum_match_sql = ($forum_id != AUTH_LIST_ALL) ? "AND aa.forum_id = " . (int)$forum_id : ''; - // GROUP mode - if (!empty($ug_data['group_id'])) - { - $is_guest = false; - $is_admin = false; + // GROUP mode + if (!empty($ug_data['group_id'])) { + $is_guest = false; + $is_admin = false; - $sql = "SELECT aa.forum_id, aa.forum_perm - FROM ". BB_AUTH_ACCESS ." aa - WHERE aa.group_id = ". (int) $ug_data['group_id'] ." + $sql = "SELECT aa.forum_id, aa.forum_perm + FROM " . BB_AUTH_ACCESS . " aa + WHERE aa.group_id = " . (int)$ug_data['group_id'] . " $forum_match_sql"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $u_access[$row['forum_id']] = $row['forum_perm']; - } - } - // USER mode - else if (!empty($ug_data['user_id'])) - { - $is_guest = empty($ug_data['session_logged_in']); - $is_admin = (!$is_guest && $ug_data['user_level'] == ADMIN); + foreach (DB()->fetch_rowset($sql) as $row) { + $u_access[$row['forum_id']] = $row['forum_perm']; + } + } // USER mode + else if (!empty($ug_data['user_id'])) { + $is_guest = empty($ug_data['session_logged_in']); + $is_admin = (!$is_guest && $ug_data['user_level'] == ADMIN); - if ($group_perm != UG_PERM_BOTH) - { - $group_single_user = ($group_perm == UG_PERM_USER_ONLY) ? 1 : 0; + if ($group_perm != UG_PERM_BOTH) { + $group_single_user = ($group_perm == UG_PERM_USER_ONLY) ? 1 : 0; - $sql = " + $sql = " SELECT aa.forum_id, BIT_OR(aa.forum_perm) AS forum_perm FROM - ". BB_USER_GROUP ." ug, - ". BB_GROUPS ." g, - ". BB_AUTH_ACCESS ." aa + " . BB_USER_GROUP . " ug, + " . BB_GROUPS . " g, + " . BB_AUTH_ACCESS . " aa WHERE - ug.user_id = ". (int) $ug_data['user_id'] ." + ug.user_id = " . (int)$ug_data['user_id'] . " AND ug.user_pending = 0 AND g.group_id = ug.group_id AND g.group_single_user = $group_single_user @@ -367,373 +337,343 @@ function auth ($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG GROUP BY aa.forum_id "; - foreach (DB()->fetch_rowset($sql) as $row) - { - $u_access[$row['forum_id']] = $row['forum_perm']; - } - } - else - { - if (!$is_guest && !$is_admin) - { - $sql = "SELECT SQL_CACHE aa.forum_id, aa.forum_perm - FROM ". BB_AUTH_ACCESS_SNAP ." aa - WHERE aa.user_id = ". (int) $ug_data['user_id'] ." + foreach (DB()->fetch_rowset($sql) as $row) { + $u_access[$row['forum_id']] = $row['forum_perm']; + } + } else { + if (!$is_guest && !$is_admin) { + $sql = "SELECT SQL_CACHE aa.forum_id, aa.forum_perm + FROM " . BB_AUTH_ACCESS_SNAP . " aa + WHERE aa.user_id = " . (int)$ug_data['user_id'] . " $forum_match_sql"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $u_access[$row['forum_id']] = $row['forum_perm']; - } - } - } - } + foreach (DB()->fetch_rowset($sql) as $row) { + $u_access[$row['forum_id']] = $row['forum_perm']; + } + } + } + } - // If the user is logged on and the forum type is either ALL or REG then the user has access - // - // If the type if ACL, MOD or ADMIN then we need to see if the user has specific permissions - // to do whatever it is they want to do ... to do this we pull relevant information for the - // user (and any groups they belong to) - // - // Now we compare the users access level against the forums. We assume here that a moderator - // and admin automatically have access to an ACL forum, similarly we assume admins meet an - // auth requirement of MOD - // - foreach ($f_access as $f_id => $f_data) - { - $auth[$f_id]['auth_mod'] = auth_check('forum_perm', 'auth_mod', $u_access, $f_id, $is_admin); + // If the user is logged on and the forum type is either ALL or REG then the user has access + // + // If the type if ACL, MOD or ADMIN then we need to see if the user has specific permissions + // to do whatever it is they want to do ... to do this we pull relevant information for the + // user (and any groups they belong to) + // + // Now we compare the users access level against the forums. We assume here that a moderator + // and admin automatically have access to an ACL forum, similarly we assume admins meet an + // auth requirement of MOD + // + foreach ($f_access as $f_id => $f_data) { + $auth[$f_id]['auth_mod'] = auth_check('forum_perm', 'auth_mod', $u_access, $f_id, $is_admin); - foreach ($auth_fields as $auth_type) - { - if (!isset($f_data[$auth_type])) - { - continue; - } - switch ($f_data[$auth_type]) - { - case AUTH_ALL: - $auth[$f_id][$auth_type] = true; - break; + foreach ($auth_fields as $auth_type) { + if (!isset($f_data[$auth_type])) { + continue; + } + switch ($f_data[$auth_type]) { + case AUTH_ALL: + $auth[$f_id][$auth_type] = true; + break; - case AUTH_REG: - $auth[$f_id][$auth_type] = !$is_guest; - break; + case AUTH_REG: + $auth[$f_id][$auth_type] = !$is_guest; + break; - case AUTH_ACL: - $auth[$f_id][$auth_type] = (auth_check('forum_perm', $auth_type, $u_access, $f_id, $is_admin) || $auth[$f_id]['auth_mod']); - break; + case AUTH_ACL: + $auth[$f_id][$auth_type] = (auth_check('forum_perm', $auth_type, $u_access, $f_id, $is_admin) || $auth[$f_id]['auth_mod']); + break; - case AUTH_MOD: - $auth[$f_id][$auth_type] = $auth[$f_id]['auth_mod']; - break; + case AUTH_MOD: + $auth[$f_id][$auth_type] = $auth[$f_id]['auth_mod']; + break; - case AUTH_ADMIN: - $auth[$f_id][$auth_type] = $is_admin; - break; + case AUTH_ADMIN: + $auth[$f_id][$auth_type] = $is_admin; + break; - default: - $auth[$f_id][$auth_type] = false; - } - if ($add_auth_type_desc) - { - $auth[$f_id][$auth_type .'_type'] =& $lang['AUTH_TYPES'][$f_data[$auth_type]]; - } - } - } + default: + $auth[$f_id][$auth_type] = false; + } + if ($add_auth_type_desc) { + $auth[$f_id][$auth_type . '_type'] =& $lang['AUTH_TYPES'][$f_data[$auth_type]]; + } + } + } - return ($forum_id == AUTH_LIST_ALL) ? $auth : $auth[$forum_id]; + return ($forum_id == AUTH_LIST_ALL) ? $auth : $auth[$forum_id]; } -function auth_check ($bf_ary, $bf_key, $perm_ary, $perm_key, $is_admin = false) +function auth_check($bf_ary, $bf_key, $perm_ary, $perm_key, $is_admin = false) { - if ($is_admin) return true; - if (!isset($perm_ary[$perm_key])) return false; + if ($is_admin) return true; + if (!isset($perm_ary[$perm_key])) return false; - return bf($perm_ary[$perm_key], $bf_ary, $bf_key); + return bf($perm_ary[$perm_key], $bf_ary, $bf_key); } class Date_Delta { - var $auto_granularity = array( - 60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute - 10800 => 'minutes', // 3 hours - 259200 => 'hours', // 3 days - 31363200 => 'mday', // 12 months - 311040000 => 'mon', // 10 years - ); - var $intervals = array(); - var $format = ''; + var $auto_granularity = array( + 60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute + 10800 => 'minutes', // 3 hours + 259200 => 'hours', // 3 days + 31363200 => 'mday', // 12 months + 311040000 => 'mon', // 10 years + ); + var $intervals = array(); + var $format = ''; - // Creates new object. - function Date_Delta() - { - global $lang; + // Creates new object. + function Date_Delta() + { + global $lang; - $this->intervals = $lang['DELTA_TIME']['INTERVALS']; - $this->format = $lang['DELTA_TIME']['FORMAT']; - } + $this->intervals = $lang['DELTA_TIME']['INTERVALS']; + $this->format = $lang['DELTA_TIME']['FORMAT']; + } - // Makes the spellable phrase. - function spellDelta($first, $last, $from = 'auto') - { - if ($last < $first) - { - $old_first = $first; - $first = $last; - $last = $old_first; - } + // Makes the spellable phrase. + function spellDelta($first, $last, $from = 'auto') + { + if ($last < $first) { + $old_first = $first; + $first = $last; + $last = $old_first; + } - if ($from == 'auto') - { - $from = 'year'; - $diff = $last - $first; - foreach ($this->auto_granularity as $seconds_count => $granule) - { - if ($diff < $seconds_count) - { - $from = $granule; - break; - } - } - } + if ($from == 'auto') { + $from = 'year'; + $diff = $last - $first; + foreach ($this->auto_granularity as $seconds_count => $granule) { + if ($diff < $seconds_count) { + $from = $granule; + break; + } + } + } - // Solve data delta. - $delta = $this->getDelta($first, $last); - if (!$delta) return false; + // Solve data delta. + $delta = $this->getDelta($first, $last); + if (!$delta) return false; - // Make spellable phrase. - $parts = array(); - $intervals = $GLOBALS['lang']['DELTA_TIME']['INTERVALS']; + // Make spellable phrase. + $parts = array(); + $intervals = $GLOBALS['lang']['DELTA_TIME']['INTERVALS']; - foreach (array_reverse($delta) as $k => $n) - { - if (!$n) - { - if ($k == $from) - { - if (!$parts) - { - $parts[] = declension($n, $this->intervals[$k], $this->format); - } - break; - } - continue; - } - $parts[] = declension($n, $this->intervals[$k], $this->format); - if ($k == $from) break; - } - return join(' ', $parts); - } + foreach (array_reverse($delta) as $k => $n) { + if (!$n) { + if ($k == $from) { + if (!$parts) { + $parts[] = declension($n, $this->intervals[$k], $this->format); + } + break; + } + continue; + } + $parts[] = declension($n, $this->intervals[$k], $this->format); + if ($k == $from) break; + } + return join(' ', $parts); + } - // returns the associative array with date deltas. - function getDelta($first, $last) - { - if ($last < $first) return false; + // returns the associative array with date deltas. + function getDelta($first, $last) + { + if ($last < $first) return false; - // Solve H:M:S part. - $hms = ($last - $first) % (3600 * 24); - $delta['seconds'] = $hms % 60; - $delta['minutes'] = floor($hms/60) % 60; - $delta['hours'] = floor($hms/3600) % 60; + // Solve H:M:S part. + $hms = ($last - $first) % (3600 * 24); + $delta['seconds'] = $hms % 60; + $delta['minutes'] = floor($hms / 60) % 60; + $delta['hours'] = floor($hms / 3600) % 60; - // Now work only with date, delta time = 0. - $last -= $hms; - $f = getdate($first); - $l = getdate($last); // the same daytime as $first! + // Now work only with date, delta time = 0. + $last -= $hms; + $f = getdate($first); + $l = getdate($last); // the same daytime as $first! - $dYear = $dMon = $dDay = 0; + $dYear = $dMon = $dDay = 0; - // Delta day. Is negative, month overlapping. - $dDay += $l['mday'] - $f['mday']; - if ($dDay < 0) { - $monlen = $this->monthLength(date('Y', $first), date('m', $first)); - $dDay += $monlen; - $dMon--; - } - $delta['mday'] = $dDay; + // Delta day. Is negative, month overlapping. + $dDay += $l['mday'] - $f['mday']; + if ($dDay < 0) { + $monlen = $this->monthLength(date('Y', $first), date('m', $first)); + $dDay += $monlen; + $dMon--; + } + $delta['mday'] = $dDay; - // Delta month. If negative, year overlapping. - $dMon += $l['mon'] - $f['mon']; - if ($dMon < 0) { - $dMon += 12; - $dYear --; - } - $delta['mon'] = $dMon; + // Delta month. If negative, year overlapping. + $dMon += $l['mon'] - $f['mon']; + if ($dMon < 0) { + $dMon += 12; + $dYear--; + } + $delta['mon'] = $dMon; - // Delta year. - $dYear += $l['year'] - $f['year']; - $delta['year'] = $dYear; + // Delta year. + $dYear += $l['year'] - $f['year']; + $delta['year'] = $dYear; - return $delta; - } + return $delta; + } - // Returns the length (in days) of the specified month. - function monthLength($year, $mon) - { - $l = 28; - while (checkdate($mon, $l+1, $year)) $l++; - return $l; - } + // Returns the length (in days) of the specified month. + function monthLength($year, $mon) + { + $l = 28; + while (checkdate($mon, $l + 1, $year)) $l++; + return $l; + } } -function delta_time ($timestamp_1, $timestamp_2 = TIMENOW, $granularity = 'auto') +function delta_time($timestamp_1, $timestamp_2 = TIMENOW, $granularity = 'auto') { - return $GLOBALS['DeltaTime']->spellDelta($timestamp_1, $timestamp_2, $granularity); + return $GLOBALS['DeltaTime']->spellDelta($timestamp_1, $timestamp_2, $granularity); } -function get_select ($select, $selected = null, $return_as = 'html', $first_opt = '»» Выбрать ') +function get_select($select, $selected = null, $return_as = 'html', $first_opt = '»» Выбрать ') { - $select_ary = array(); + $select_ary = array(); - switch ($select) - { - case 'groups': - $sql = "SELECT group_id, group_name FROM ". BB_GROUPS ." WHERE group_single_user = 0 ORDER BY group_name"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $select_ary[$row['group_name']] = $row['group_id']; - } - $select_name = 'g'; - break; + switch ($select) { + case 'groups': + $sql = "SELECT group_id, group_name FROM " . BB_GROUPS . " WHERE group_single_user = 0 ORDER BY group_name"; + foreach (DB()->fetch_rowset($sql) as $row) { + $select_ary[$row['group_name']] = $row['group_id']; + } + $select_name = 'g'; + break; - case 'forum_tpl': - $sql = "SELECT tpl_id, tpl_name FROM ". BB_TOPIC_TPL ." ORDER BY tpl_name"; - $select_ary[$first_opt] = 0; - foreach (DB()->fetch_rowset($sql) as $row) - { - $select_ary[$row['tpl_name']] = $row['tpl_id']; - } - $select_name = 'forum_tpl_select'; - break; - } + case 'forum_tpl': + $sql = "SELECT tpl_id, tpl_name FROM " . BB_TOPIC_TPL . " ORDER BY tpl_name"; + $select_ary[$first_opt] = 0; + foreach (DB()->fetch_rowset($sql) as $row) { + $select_ary[$row['tpl_name']] = $row['tpl_id']; + } + $select_name = 'forum_tpl_select'; + break; + } - return ($return_as == 'html') ? build_select($select_name, $select_ary, $selected) : $select_ary; + return ($return_as == 'html') ? build_select($select_name, $select_ary, $selected) : $select_ary; } class html_common { - var $options = ''; - var $attr = array(); - var $cur_attr = null; - var $max_length = HTML_SELECT_MAX_LENGTH; - var $selected = array(); + var $options = ''; + var $attr = array(); + var $cur_attr = null; + var $max_length = HTML_SELECT_MAX_LENGTH; + var $selected = array(); - function build_select ($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') - { - if (empty($params)) return ''; + function build_select($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') + { + if (empty($params)) return ''; - $this->options = ''; - $this->selected = array_flip((array) $selected); - $this->max_length = $max_length; + $this->options = ''; + $this->selected = array_flip((array)$selected); + $this->max_length = $max_length; - $this->attr = array(); - $this->cur_attr =& $this->attr; + $this->attr = array(); + $this->cur_attr =& $this->attr; - if (isset($params['__attributes'])) - { - $this->attr = $params['__attributes']; - unset($params['__attributes']); - } + if (isset($params['__attributes'])) { + $this->attr = $params['__attributes']; + unset($params['__attributes']); + } - $this->_build_select_rec($params); + $this->_build_select_rec($params); - $select_params = ($js) ? " $js" : ''; - $select_params .= ($multiple_size) ? ' multiple="multiple" size="'. $multiple_size .'"' : ''; - $select_params .= ' name="'. htmlCHR($name) .'"'; - $select_params .= ' id="'. htmlCHR($name) .'"'; + $select_params = ($js) ? " $js" : ''; + $select_params .= ($multiple_size) ? ' multiple="multiple" size="' . $multiple_size . '"' : ''; + $select_params .= ' name="' . htmlCHR($name) . '"'; + $select_params .= ' id="' . htmlCHR($name) . '"'; - return "\n\n"; - } + return "\n\n"; + } - function _build_select_rec ($params) - { - foreach ($params as $opt_name => $opt_val) - { - $opt_name = rtrim($opt_name); + function _build_select_rec($params) + { + foreach ($params as $opt_name => $opt_val) { + $opt_name = rtrim($opt_name); - if (is_array($opt_val)) - { - $this->cur_attr =& $this->cur_attr[$opt_name]; + if (is_array($opt_val)) { + $this->cur_attr =& $this->cur_attr[$opt_name]; - $label = htmlCHR(str_short($opt_name, $this->max_length)); + $label = htmlCHR(str_short($opt_name, $this->max_length)); - $this->options .= "\t\n"; - $this->_build_select_rec($opt_val); - $this->options .= "\t\n"; + $this->options .= "\t\n"; + $this->_build_select_rec($opt_val); + $this->options .= "\t\n"; - $this->cur_attr =& $this->attr; - } - else - { - $text = htmlCHR(str_short($opt_name, $this->max_length)); - $value = ' value="'. htmlCHR($opt_val) .'"'; + $this->cur_attr =& $this->attr; + } else { + $text = htmlCHR(str_short($opt_name, $this->max_length)); + $value = ' value="' . htmlCHR($opt_val) . '"'; - $class = isset($this->cur_attr[$opt_name]['class']) ? ' class="'. $this->cur_attr[$opt_name]['class'] .'"' : ''; - $style = isset($this->cur_attr[$opt_name]['style']) ? ' style="'. $this->cur_attr[$opt_name]['style'] .'"' : ''; + $class = isset($this->cur_attr[$opt_name]['class']) ? ' class="' . $this->cur_attr[$opt_name]['class'] . '"' : ''; + $style = isset($this->cur_attr[$opt_name]['style']) ? ' style="' . $this->cur_attr[$opt_name]['style'] . '"' : ''; - $selected = isset($this->selected[$opt_val]) ? HTML_SELECTED : ''; - $disabled = isset($this->cur_attr[$opt_name]['disabled']) ? HTML_DISABLED : ''; + $selected = isset($this->selected[$opt_val]) ? HTML_SELECTED : ''; + $disabled = isset($this->cur_attr[$opt_name]['disabled']) ? HTML_DISABLED : ''; - $this->options .= "\t\t '. $text ." \n"; - } - } - } + $this->options .= "\t\t ' . $text . " \n"; + } + } + } - function array2html ($array, $ul = 'ul', $li = 'li') - { - $this->out = ''; - $this->_array2html_rec($array, $ul, $li); - return "<$ul class=\"tree-root\">{$this->out}"; - } + function array2html($array, $ul = 'ul', $li = 'li') + { + $this->out = ''; + $this->_array2html_rec($array, $ul, $li); + return "<$ul class=\"tree-root\">{$this->out}"; + } - function _array2html_rec ($array, $ul, $li) - { - foreach ($array as $k => $v) - { - if (is_array($v)) - { - $this->out .= "<$li>$k<$ul>"; - $this->_array2html_rec($v, $ul, $li); - $this->out .= ""; - } - else - { - $this->out .= "<$li>$v"; - } - } - } + function _array2html_rec($array, $ul, $li) + { + foreach ($array as $k => $v) { + if (is_array($v)) { + $this->out .= "<$li>$k<$ul>"; + $this->_array2html_rec($v, $ul, $li); + $this->out .= ""; + } else { + $this->out .= "<$li>$v"; + } + } + } - // all arguments should be already htmlspecialchar()d (if needed) - function build_checkbox ($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1) - { - $name = ' name="'. $name .'" '; - $value = ' value="'. $value .'" '; - $title = ($class) ? ''. $title .'' : $title; - $id = ($id) ? " id=\"$id\" " : ''; - $checked = ($checked) ? HTML_CHECKED : ''; - $disabled = ($disabled) ? HTML_DISABLED : ''; + // all arguments should be already htmlspecialchar()d (if needed) + function build_checkbox($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1) + { + $name = ' name="' . $name . '" '; + $value = ' value="' . $value . '" '; + $title = ($class) ? '' . $title . '' : $title; + $id = ($id) ? " id=\"$id\" " : ''; + $checked = ($checked) ? HTML_CHECKED : ''; + $disabled = ($disabled) ? HTML_DISABLED : ''; - return ''; - } + return ''; + } } -function build_select ($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') +function build_select($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') { - global $html; - return $html->build_select($name, $params, $selected, $max_length, $multiple_size, $js); + global $html; + return $html->build_select($name, $params, $selected, $max_length, $multiple_size, $js); } -function build_checkbox ($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1) +function build_checkbox($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1) { - global $html; - return $html->build_checkbox($name, $title, $checked, $disabled, $class, $id, $value); + global $html; + return $html->build_checkbox($name, $title, $checked, $disabled, $class, $id, $value); } -function replace_quote ($str, $double = true, $single = true) +function replace_quote($str, $double = true, $single = true) { - if ($double) $str = str_replace('"', '"', $str); - if ($single) $str = str_replace("'", ''', $str); - return $str; + if ($double) $str = str_replace('"', '"', $str); + if ($single) $str = str_replace("'", ''', $str); + return $str; } /** @@ -743,26 +683,21 @@ function replace_quote ($str, $double = true, $single = true) * * @return string */ -function build_hidden_fields ($fields_ary) +function build_hidden_fields($fields_ary) { - $out = "\n"; + $out = "\n"; - foreach ($fields_ary as $name => $val) - { - if (is_array($val)) - { - foreach ($val as $ary_key => $ary_val) - { - $out .= '\n"; - } - } - else - { - $out .= '\n"; - } - } + foreach ($fields_ary as $name => $val) { + if (is_array($val)) { + foreach ($val as $ary_key => $ary_val) { + $out .= '\n"; + } + } else { + $out .= '\n"; + } + } - return $out; + return $out; } /** @@ -775,69 +710,55 @@ function build_hidden_fields ($fields_ary) * * @return string */ -function declension ($int, $expressions, $format = '%1$s %2$s') +function declension($int, $expressions, $format = '%1$s %2$s') { - if (!is_array($expressions)) - { - $expressions = $GLOBALS['lang']['DECLENSION'][strtoupper($expressions)]; - } + if (!is_array($expressions)) { + $expressions = $GLOBALS['lang']['DECLENSION'][strtoupper($expressions)]; + } - if (count($expressions) < 3) - { - $expressions[2] = $expressions[1]; - } - $count = intval($int) % 100; + if (count($expressions) < 3) { + $expressions[2] = $expressions[1]; + } + $count = intval($int) % 100; - if ($count >= 5 && $count <= 20) - { - $result = $expressions['2']; - } - else - { - $count = $count % 10; - if ($count == 1) - { - $result = $expressions['0']; - } - elseif ($count >= 2 && $count <= 4) - { - $result = $expressions['1']; - } - else - { - $result = $expressions['2']; - } - } + if ($count >= 5 && $count <= 20) { + $result = $expressions['2']; + } else { + $count = $count % 10; + if ($count == 1) { + $result = $expressions['0']; + } elseif ($count >= 2 && $count <= 4) { + $result = $expressions['1']; + } else { + $result = $expressions['2']; + } + } - return ($format) ? sprintf($format, $int, $result) : $result; + return ($format) ? sprintf($format, $int, $result) : $result; } // http://forum.dklab.ru/php/advises/UrlreplaceargChangesValueOfParameterInUrl.html -function url_arg ($url, $arg, $value, $amp = '&') +function url_arg($url, $arg, $value, $amp = '&') { - $arg = preg_quote($arg, '/'); + $arg = preg_quote($arg, '/'); - // разделяем URL и ANCHOR - $anchor = ''; - if (preg_match('/(.*)(#.*)/s', $url, $m)) - { - $url = $m[1]; - $anchor = $m[2]; - } - // заменяем параметр, если он существует - if (preg_match("/((\?|&|&)$arg=)[^&]*/s", $url, $m)) - { - $cur = $m[0]; - $new = is_null($value) ? '' : $m[1] . urlencode($value); - $url = str_replace($cur, $new, $url); - } - // добавляем параметр - else if (!is_null($value)) - { - $div = (strpos($url, '?') !== false) ? $amp : '?'; - $url = $url . $div . $arg .'='. urlencode($value); - } - return $url . $anchor; + // разделяем URL и ANCHOR + $anchor = ''; + if (preg_match('/(.*)(#.*)/s', $url, $m)) { + $url = $m[1]; + $anchor = $m[2]; + } + // заменяем параметр, если он существует + if (preg_match("/((\?|&|&)$arg=)[^&]*/s", $url, $m)) { + $cur = $m[0]; + $new = is_null($value) ? '' : $m[1] . urlencode($value); + $url = str_replace($cur, $new, $url); + } // добавляем параметр + else if (!is_null($value)) { + $div = (strpos($url, '?') !== false) ? $amp : '?'; + $url = $url . $div . $arg . '=' . urlencode($value); + } + return $url . $anchor; } /** @@ -847,132 +768,108 @@ function url_arg ($url, $arg, $value, $amp = '&') * * @return string */ -function commify ($number) +function commify($number) { - return number_format($number); + return number_format($number); } /** * Returns a size formatted in a more human-friendly format, rounded to the nearest GB, MB, KB.. * * @param $size - * @param null $rounder - * @param null $min + * @param null $rounder + * @param null $min * @param string $space * * @return string */ -function humn_size ($size, $rounder = null, $min = null, $space = ' ') +function humn_size($size, $rounder = null, $min = null, $space = ' ') { - static $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - static $rounders = array(0, 0, 0, 2, 3, 3, 3, 3, 3); + static $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); + static $rounders = array(0, 0, 0, 2, 3, 3, 3, 3, 3); - $size = (float) $size; - $ext = $sizes[0]; - $rnd = $rounders[0]; + $size = (float)$size; + $ext = $sizes[0]; + $rnd = $rounders[0]; - if ($min == 'KB' && $size < 1024) - { - $size = $size / 1024; - $ext = 'KB'; - $rounder = 1; - } - else - { - for ($i = 1, $cnt = count($sizes); ($i < $cnt && $size >= 1024); $i++) - { - $size = $size / 1024; - $ext = $sizes[$i]; - $rnd = $rounders[$i]; - } - } - if (!$rounder) - { - $rounder = $rnd; - } + if ($min == 'KB' && $size < 1024) { + $size = $size / 1024; + $ext = 'KB'; + $rounder = 1; + } else { + for ($i = 1, $cnt = count($sizes); ($i < $cnt && $size >= 1024); $i++) { + $size = $size / 1024; + $ext = $sizes[$i]; + $rnd = $rounders[$i]; + } + } + if (!$rounder) { + $rounder = $rnd; + } - return round($size, $rounder) . $space . $ext; + return round($size, $rounder) . $space . $ext; } -function bt_show_ip ($ip, $port = '') +function bt_show_ip($ip, $port = '') { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (IS_AM) - { - $ip = decode_ip($ip); - $ip .= ($port) ? ":$port" : ''; - return $ip; - } - else - { - return ($di->config->get('bt_show_ip_only_moder')) ? false : decode_ip_xx($ip); - } + if (IS_AM) { + $ip = decode_ip($ip); + $ip .= ($port) ? ":$port" : ''; + return $ip; + } else { + return ($di->config->get('bt_show_ip_only_moder')) ? false : decode_ip_xx($ip); + } } -function bt_show_port ($port) +function bt_show_port($port) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (IS_AM) - { - return $port; - } - else - { - return ($di->config->get('bt_show_port_only_moder')) ? false : $port; - } + if (IS_AM) { + return $port; + } else { + return ($di->config->get('bt_show_port_only_moder')) ? false : $port; + } } -function decode_ip_xx ($ip) +function decode_ip_xx($ip) { - $h = explode('.', chunk_split($ip, 2, '.')); - return hexdec($h[0]) .'.'. hexdec($h[1]) .'.'. hexdec($h[2]) .'.xx'; + $h = explode('.', chunk_split($ip, 2, '.')); + return hexdec($h[0]) . '.' . hexdec($h[1]) . '.' . hexdec($h[2]) . '.xx'; } -function checkbox_get_val (&$key, &$val, $default = 1, $on = 1, $off = 0) +function checkbox_get_val(&$key, &$val, $default = 1, $on = 1, $off = 0) { - global $previous_settings, $search_id; + global $previous_settings, $search_id; - if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) - { - $val = (int) $_REQUEST[$key]; - } - else if (!isset($_REQUEST[$key]) && isset($_REQUEST['prev_'. $key])) - { - $val = $off; - } - else if (isset($previous_settings[$key]) && (!IS_GUEST || !empty($search_id))) - { - $val = ($previous_settings[$key]) ? $on : $off; - } - else - { - $val = $default; - } + if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) { + $val = (int)$_REQUEST[$key]; + } else if (!isset($_REQUEST[$key]) && isset($_REQUEST['prev_' . $key])) { + $val = $off; + } else if (isset($previous_settings[$key]) && (!IS_GUEST || !empty($search_id))) { + $val = ($previous_settings[$key]) ? $on : $off; + } else { + $val = $default; + } } -function select_get_val ($key, &$val, $options_ary, $default, $num = true) +function select_get_val($key, &$val, $options_ary, $default, $num = true) { - global $previous_settings; + global $previous_settings; - if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) - { - if (isset($options_ary[$_REQUEST[$key]])) - { - $val = ($num) ? intval($_REQUEST[$key]) : $_REQUEST[$key]; - } - } - else if (isset($previous_settings[$key])) - { - $val = $previous_settings[$key]; - } - else - { - $val = $default; - } + if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) { + if (isset($options_ary[$_REQUEST[$key]])) { + $val = ($num) ? intval($_REQUEST[$key]) : $_REQUEST[$key]; + } + } else if (isset($previous_settings[$key])) { + $val = $previous_settings[$key]; + } else { + $val = $default; + } } /** @@ -988,29 +885,25 @@ function select_get_val ($key, &$val, $options_ary, $default, $num = true) * @param bool $multibyte * @param bool $strip */ -function set_var (&$result, $var, $type, $multibyte = false, $strip = true) +function set_var(&$result, $var, $type, $multibyte = false, $strip = true) { - settype($var, $type); - $result = $var; + settype($var, $type); + $result = $var; - if ($type == 'string') - { - $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result))); + if ($type == 'string') { + $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result))); - if (!empty($result)) - { - // Make sure multibyte characters are wellformed - if ($multibyte) - { - if (!preg_match('/^./u', $result)) - { - $result = ''; - } - } - } + if (!empty($result)) { + // Make sure multibyte characters are wellformed + if ($multibyte) { + if (!preg_match('/^./u', $result)) { + $result = ''; + } + } + } - $result = ($strip) ? stripslashes($result) : $result; - } + $result = ($strip) ? stripslashes($result) : $result; + } } /** @@ -1025,687 +918,606 @@ function set_var (&$result, $var, $type, $multibyte = false, $strip = true) * * @return array */ -function request_var ($var_name, $default, $multibyte = false, $cookie = false) +function request_var($var_name, $default, $multibyte = false, $cookie = false) { - if (!$cookie && isset($_COOKIE[$var_name])) - { - if (!isset($_GET[$var_name]) && !isset($_POST[$var_name])) - { - return (is_array($default)) ? array() : $default; - } - $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name]; - } + if (!$cookie && isset($_COOKIE[$var_name])) { + if (!isset($_GET[$var_name]) && !isset($_POST[$var_name])) { + return (is_array($default)) ? array() : $default; + } + $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name]; + } - if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name]))) - { - return (is_array($default)) ? array() : $default; - } + if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name]))) { + return (is_array($default)) ? array() : $default; + } - $var = $_REQUEST[$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 ($type == 'array') - { - reset($default); - $default = current($default); - list($sub_key_type, $sub_type) = each($default); - $sub_type = gettype($sub_type); - $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type; - $sub_key_type = gettype($sub_key_type); - } - } + $var = $_REQUEST[$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 ($type == 'array') { + reset($default); + $default = current($default); + list($sub_key_type, $sub_type) = each($default); + $sub_type = gettype($sub_type); + $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type; + $sub_key_type = gettype($sub_key_type); + } + } - if (is_array($var)) - { - $_var = $var; - $var = array(); + if (is_array($var)) { + $_var = $var; + $var = array(); - foreach ($_var as $k => $v) - { - set_var($k, $k, $key_type); - if ($type == 'array' && is_array($v)) - { - foreach ($v as $_k => $_v) - { - if (is_array($_v)) - { - $_v = null; - } - set_var($_k, $_k, $sub_key_type); - set_var($var[$k][$_k], $_v, $sub_type, $multibyte); - } - } - else - { - if ($type == 'array' || is_array($v)) - { - $v = null; - } - set_var($var[$k], $v, $type, $multibyte); - } - } - } - else - { - set_var($var, $var, $type, $multibyte); - } + foreach ($_var as $k => $v) { + set_var($k, $k, $key_type); + if ($type == 'array' && is_array($v)) { + foreach ($v as $_k => $_v) { + if (is_array($_v)) { + $_v = null; + } + set_var($_k, $_k, $sub_key_type); + set_var($var[$k][$_k], $_v, $sub_type, $multibyte); + } + } else { + if ($type == 'array' || is_array($v)) { + $v = null; + } + set_var($var[$k], $v, $type, $multibyte); + } + } + } else { + set_var($var, $var, $type, $multibyte); + } - return $var; + return $var; } -function get_username ($user_id) +function get_username($user_id) { - if (empty($user_id)) - { - return is_array($user_id) ? array() : false; - } - if (is_array($user_id)) - { - $usernames = array(); - foreach (DB()->fetch_rowset("SELECT user_id, username FROM ". BB_USERS ." WHERE user_id IN(". get_id_csv($user_id) .")") as $row) - { - $usernames[$row['user_id']] = $row['username']; - } - return $usernames; - } - else - { - $row = DB()->fetch_row("SELECT username FROM ". BB_USERS ." WHERE user_id = $user_id LIMIT 1"); - return $row['username']; - } + if (empty($user_id)) { + return is_array($user_id) ? array() : false; + } + if (is_array($user_id)) { + $usernames = array(); + foreach (DB()->fetch_rowset("SELECT user_id, username FROM " . BB_USERS . " WHERE user_id IN(" . get_id_csv($user_id) . ")") as $row) { + $usernames[$row['user_id']] = $row['username']; + } + return $usernames; + } else { + $row = DB()->fetch_row("SELECT username FROM " . BB_USERS . " WHERE user_id = $user_id LIMIT 1"); + return $row['username']; + } } -function get_user_id ($username) +function get_user_id($username) { - if (empty($username)) return false; - $row = DB()->fetch_row("SELECT user_id FROM ". BB_USERS ." WHERE username = '". DB()->escape($username) ."' LIMIT 1"); - return $row['user_id']; + if (empty($username)) return false; + $row = DB()->fetch_row("SELECT user_id FROM " . BB_USERS . " WHERE username = '" . DB()->escape($username) . "' LIMIT 1"); + return $row['user_id']; } -function str_short ($text, $max_length, $space = ' ') +function str_short($text, $max_length, $space = ' ') { - if ($max_length && mb_strlen($text, 'UTF-8') > $max_length) - { - $text = mb_substr($text, 0, $max_length, 'UTF-8'); + if ($max_length && mb_strlen($text, 'UTF-8') > $max_length) { + $text = mb_substr($text, 0, $max_length, 'UTF-8'); - if ($last_space_pos = $max_length - intval(strpos(strrev($text), $space))) - { - if ($last_space_pos > round($max_length * 3/4)) - { - $last_space_pos--; - $text = mb_substr($text, 0, $last_space_pos, 'UTF-8'); - } - } - $text .= '...'; - $text = preg_replace('!&#?(\w+)?;?(\w{1,5})?\.\.\.$!', '...', $text); - } + if ($last_space_pos = $max_length - intval(strpos(strrev($text), $space))) { + if ($last_space_pos > round($max_length * 3 / 4)) { + $last_space_pos--; + $text = mb_substr($text, 0, $last_space_pos, 'UTF-8'); + } + } + $text .= '...'; + $text = preg_replace('!&#?(\w+)?;?(\w{1,5})?\.\.\.$!', '...', $text); + } - return $text; + return $text; } -function wbr ($text, $max_word_length = HTML_WBR_LENGTH) +function wbr($text, $max_word_length = HTML_WBR_LENGTH) { - return preg_replace("/([\w\->;:.,~!?(){}@#$%^*\/\\\\]{". $max_word_length ."})/ui", '$1', $text); + return preg_replace("/([\w\->;:.,~!?(){}@#$%^*\/\\\\]{" . $max_word_length . "})/ui", '$1', $text); } -function get_bt_userdata ($user_id) +function get_bt_userdata($user_id) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$cache->has('btu_' . $user_id)) - { - $btu = DB()->fetch_row(" + if (!$cache->has('btu_' . $user_id)) { + $btu = DB()->fetch_row(" SELECT bt.*, SUM(tr.speed_up) AS speed_up, SUM(tr.speed_down) AS speed_down - FROM ". BB_BT_USERS ." bt - LEFT JOIN ". BB_BT_TRACKER ." tr ON (bt.user_id = tr.user_id) - WHERE bt.user_id = ". (int) $user_id ." + FROM " . BB_BT_USERS . " bt + LEFT JOIN " . BB_BT_TRACKER . " tr ON (bt.user_id = tr.user_id) + WHERE bt.user_id = " . (int)$user_id . " GROUP BY bt.user_id LIMIT 1 "); - $cache->set('btu_' . $user_id, $btu, 300); - } + $cache->set('btu_' . $user_id, $btu, 300); + } - $btu = $cache->get('btu_' . $user_id); + $btu = $cache->get('btu_' . $user_id); - return $btu; + return $btu; } -function get_bt_ratio ($btu) +function get_bt_ratio($btu) { - return - (!empty($btu['u_down_total']) && $btu['u_down_total'] > MIN_DL_FOR_RATIO) - ? round((($btu['u_up_total'] + $btu['u_up_release'] + $btu['u_up_bonus']) / $btu['u_down_total']), 2) - : null - ; + return + (!empty($btu['u_down_total']) && $btu['u_down_total'] > MIN_DL_FOR_RATIO) + ? round((($btu['u_up_total'] + $btu['u_up_release'] + $btu['u_up_bonus']) / $btu['u_down_total']), 2) + : null; } -function show_bt_userdata ($user_id) +function show_bt_userdata($user_id) { - global $lang, $template; + global $lang, $template; - $btu = get_bt_userdata($user_id); + $btu = get_bt_userdata($user_id); - $template->assign_vars(array( - 'SHOW_BT_USERDATA' => true, - 'UP_TOTAL' => humn_size($btu['u_up_total']), - 'UP_BONUS' => humn_size($btu['u_up_bonus']), - 'RELEASED' => humn_size($btu['u_up_release']), - 'DOWN_TOTAL' => humn_size($btu['u_down_total']), - 'DOWN_TOTAL_BYTES' => $btu['u_down_total'], - 'USER_RATIO' => get_bt_ratio($btu), - 'MIN_DL_FOR_RATIO' => humn_size(MIN_DL_FOR_RATIO), - 'MIN_DL_BYTES' => MIN_DL_FOR_RATIO, - 'AUTH_KEY' => ($btu['auth_key']) ? $btu['auth_key'] : $lang['NONE'], + $template->assign_vars(array( + 'SHOW_BT_USERDATA' => true, + 'UP_TOTAL' => humn_size($btu['u_up_total']), + 'UP_BONUS' => humn_size($btu['u_up_bonus']), + 'RELEASED' => humn_size($btu['u_up_release']), + 'DOWN_TOTAL' => humn_size($btu['u_down_total']), + 'DOWN_TOTAL_BYTES' => $btu['u_down_total'], + 'USER_RATIO' => get_bt_ratio($btu), + 'MIN_DL_FOR_RATIO' => humn_size(MIN_DL_FOR_RATIO), + 'MIN_DL_BYTES' => MIN_DL_FOR_RATIO, + 'AUTH_KEY' => ($btu['auth_key']) ? $btu['auth_key'] : $lang['NONE'], - 'TD_DL' => humn_size($btu['down_today']), - 'TD_UL' => humn_size($btu['up_today']), - 'TD_REL' => humn_size($btu['up_release_today']), - 'TD_BONUS' => humn_size($btu['up_bonus_today']), - 'TD_POINTS' => ($btu['auth_key']) ? $btu['points_today'] : '0.00', + 'TD_DL' => humn_size($btu['down_today']), + 'TD_UL' => humn_size($btu['up_today']), + 'TD_REL' => humn_size($btu['up_release_today']), + 'TD_BONUS' => humn_size($btu['up_bonus_today']), + 'TD_POINTS' => ($btu['auth_key']) ? $btu['points_today'] : '0.00', - 'YS_DL' => humn_size($btu['down_yesterday']), - 'YS_UL' => humn_size($btu['up_yesterday']), - 'YS_REL' => humn_size($btu['up_release_yesterday']), - 'YS_BONUS' => humn_size($btu['up_bonus_yesterday']), - 'YS_POINTS' => ($btu['auth_key']) ? $btu['points_yesterday'] : '0.00', + 'YS_DL' => humn_size($btu['down_yesterday']), + 'YS_UL' => humn_size($btu['up_yesterday']), + 'YS_REL' => humn_size($btu['up_release_yesterday']), + 'YS_BONUS' => humn_size($btu['up_bonus_yesterday']), + 'YS_POINTS' => ($btu['auth_key']) ? $btu['points_yesterday'] : '0.00', - 'SPEED_UP' => humn_size($btu['speed_up'], 0, 'KB') .'/s', - 'SPEED_DOWN' => humn_size($btu['speed_down'], 0, 'KB') .'/s', - )); + 'SPEED_UP' => humn_size($btu['speed_up'], 0, 'KB') . '/s', + 'SPEED_DOWN' => humn_size($btu['speed_down'], 0, 'KB') . '/s', + )); } -function bb_get_config ($table, $from_db = false, $update_cache = true) +function bb_get_config($table, $from_db = false, $update_cache = true) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - $cfg = []; - if (!$cache->has('config_' . $table)) { - if ($from_db) { - foreach (DB()->fetch_rowset("SELECT * FROM $table") as $row) { - $cfg[$row['config_name']] = $row['config_value']; - } - if ($update_cache) { - $cache->set('config_' . $table, $cfg); - } - } - } + $cfg = []; + if (!$cache->has('config_' . $table)) { + if ($from_db) { + foreach (DB()->fetch_rowset("SELECT * FROM $table") as $row) { + $cfg[$row['config_name']] = $row['config_value']; + } + if ($update_cache) { + $cache->set('config_' . $table, $cfg); + } + } + } - $cfg = $cache->get('config_' . $table); + $cfg = $cache->get('config_' . $table); - return $cfg; + return $cfg; } -function bb_update_config ($params, $table = BB_CONFIG) +function bb_update_config($params, $table = BB_CONFIG) { - $updates = array(); - foreach ($params as $name => $val) - { - $updates[] = array( - 'config_name' => $name, - 'config_value' => $val, - ); - } - $updates = DB()->build_array('MULTI_INSERT', $updates); + $updates = array(); + foreach ($params as $name => $val) { + $updates[] = array( + 'config_name' => $name, + 'config_value' => $val, + ); + } + $updates = DB()->build_array('MULTI_INSERT', $updates); - DB()->query("REPLACE INTO $table $updates"); + DB()->query("REPLACE INTO $table $updates"); - // Update cache - bb_get_config($table, true, true); + // Update cache + bb_get_config($table, true, true); } -function get_db_stat ($mode) +function get_db_stat($mode) { - switch ($mode) - { - case 'usercount': - $sql = "SELECT COUNT(user_id) AS total FROM " . BB_USERS; - break; + switch ($mode) { + case 'usercount': + $sql = "SELECT COUNT(user_id) AS total FROM " . BB_USERS; + break; - case 'newestuser': - $sql = "SELECT user_id, username FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " ORDER BY user_id DESC LIMIT 1"; - break; + case 'newestuser': + $sql = "SELECT user_id, username FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " ORDER BY user_id DESC LIMIT 1"; + break; - case 'postcount': - case 'topiccount': - $sql = "SELECT SUM(forum_topics) AS topic_total, SUM(forum_posts) AS post_total FROM " . BB_FORUMS; - break; - } + case 'postcount': + case 'topiccount': + $sql = "SELECT SUM(forum_topics) AS topic_total, SUM(forum_posts) AS post_total FROM " . BB_FORUMS; + break; + } - if ( !($result = DB()->sql_query($sql)) ) - { - return false; - } + if (!($result = DB()->sql_query($sql))) { + return false; + } - $row = DB()->sql_fetchrow($result); + $row = DB()->sql_fetchrow($result); - switch ($mode) - { - case 'usercount': - return $row['total']; - break; - case 'newestuser': - return $row; - break; - case 'postcount': - return $row['post_total']; - break; - case 'topiccount': - return $row['topic_total']; - break; - } + switch ($mode) { + case 'usercount': + return $row['total']; + break; + case 'newestuser': + return $row; + break; + case 'postcount': + return $row['post_total']; + break; + case 'topiccount': + return $row['topic_total']; + break; + } - return false; + return false; } -function clean_username ($username) +function clean_username($username) { - $username = mb_substr(htmlspecialchars(str_replace("\'", "'", trim($username))), 0, 25, 'UTF-8'); - $username = bb_rtrim($username, "\\"); - $username = str_replace("'", "\'", $username); + $username = mb_substr(htmlspecialchars(str_replace("\'", "'", trim($username))), 0, 25, 'UTF-8'); + $username = bb_rtrim($username, "\\"); + $username = str_replace("'", "\'", $username); - return $username; + return $username; } -function bb_ltrim ($str, $charlist = false) +function bb_ltrim($str, $charlist = false) { - if ($charlist === false) - { - return ltrim($str); - } + if ($charlist === false) { + return ltrim($str); + } - $str = ltrim($str, $charlist); + $str = ltrim($str, $charlist); - return $str; + return $str; } -function bb_rtrim ($str, $charlist = false) +function bb_rtrim($str, $charlist = false) { - if ($charlist === false) - { - return rtrim($str); - } + if ($charlist === false) { + return rtrim($str); + } - $str = rtrim($str, $charlist); + $str = rtrim($str, $charlist); - return $str; + return $str; } // Get Userdata, $u can be username or user_id. If $force_name is true, the username will be forced. -function get_userdata ($u, $force_name = false, $allow_guest = false) +function get_userdata($u, $force_name = false, $allow_guest = false) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$u) return false; + if (!$u) return false; - if (intval($u) == GUEST_UID && $allow_guest) - { - if ($u_data = $cache->get('guest_userdata')) - { - return $u_data; - } - } + if (intval($u) == GUEST_UID && $allow_guest) { + if ($u_data = $cache->get('guest_userdata')) { + return $u_data; + } + } - $u_data = []; - $name_search = false; - $exclude_anon_sql = (!$allow_guest) ? "AND user_id != ". GUEST_UID : ''; + $u_data = []; + $name_search = false; + $exclude_anon_sql = (!$allow_guest) ? "AND user_id != " . GUEST_UID : ''; - if ($force_name || !is_numeric($u)) - { - $name_search = true; - $where_sql = "WHERE username = '". DB()->escape(clean_username($u)) ."'"; - } - else - { - $where_sql = "WHERE user_id = ". (int) $u; - } + if ($force_name || !is_numeric($u)) { + $name_search = true; + $where_sql = "WHERE username = '" . DB()->escape(clean_username($u)) . "'"; + } else { + $where_sql = "WHERE user_id = " . (int)$u; + } - $sql = "SELECT * FROM ". BB_USERS ." $where_sql $exclude_anon_sql LIMIT 1"; + $sql = "SELECT * FROM " . BB_USERS . " $where_sql $exclude_anon_sql LIMIT 1"; - if (!$u_data = DB()->fetch_row($sql)) - { - if (!is_int($u) && !$name_search) - { - $where_sql = "WHERE username = '". DB()->escape(clean_username($u)) ."'"; - $sql = "SELECT * FROM ". BB_USERS ." $where_sql $exclude_anon_sql LIMIT 1"; - $u_data = DB()->fetch_row($sql); - } - } + if (!$u_data = DB()->fetch_row($sql)) { + if (!is_int($u) && !$name_search) { + $where_sql = "WHERE username = '" . DB()->escape(clean_username($u)) . "'"; + $sql = "SELECT * FROM " . BB_USERS . " $where_sql $exclude_anon_sql LIMIT 1"; + $u_data = DB()->fetch_row($sql); + } + } - if ($u_data['user_id'] == GUEST_UID) - { - $cache->set('guest_userdata', $u_data); - } + if ($u_data['user_id'] == GUEST_UID) { + $cache->set('guest_userdata', $u_data); + } - return $u_data; + return $u_data; } -function make_jumpbox ($selected = 0) +function make_jumpbox($selected = 0) { - global $datastore, $template; + global $datastore, $template; - if (!$jumpbox = $datastore->get('jumpbox')) - { - $datastore->update('jumpbox'); - $jumpbox = $datastore->get('jumpbox'); - } + if (!$jumpbox = $datastore->get('jumpbox')) { + $datastore->update('jumpbox'); + $jumpbox = $datastore->get('jumpbox'); + } - $template->assign_vars(array( - 'JUMPBOX' => (IS_GUEST) ? $jumpbox['guest'] : $jumpbox['user'], - )); + $template->assign_vars(array( + 'JUMPBOX' => (IS_GUEST) ? $jumpbox['guest'] : $jumpbox['user'], + )); } // $mode: array(not_auth_forum1,not_auth_forum2,..) or (string) 'mode' -function get_forum_select ($mode = 'guest', $name = POST_FORUM_URL, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '', $all_forums_option = null) +function get_forum_select($mode = 'guest', $name = POST_FORUM_URL, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '', $all_forums_option = null) { - global $lang, $datastore; + global $lang, $datastore; - if (is_array($mode)) - { - $not_auth_forums_fary = array_flip($mode); - $mode = 'not_auth_forums'; - } - if (is_null($max_length)) - { - $max_length = HTML_SELECT_MAX_LENGTH; - } - $select = is_null($all_forums_option) ? array() : array($lang['ALL_AVAILABLE'] => $all_forums_option); - if (!$forums = $datastore->get('cat_forums')) - { - $datastore->update('cat_forums'); - $forums = $datastore->get('cat_forums'); - } + if (is_array($mode)) { + $not_auth_forums_fary = array_flip($mode); + $mode = 'not_auth_forums'; + } + if (is_null($max_length)) { + $max_length = HTML_SELECT_MAX_LENGTH; + } + $select = is_null($all_forums_option) ? array() : array($lang['ALL_AVAILABLE'] => $all_forums_option); + if (!$forums = $datastore->get('cat_forums')) { + $datastore->update('cat_forums'); + $forums = $datastore->get('cat_forums'); + } - foreach ($forums['f'] as $fid => $f) - { - switch ($mode) - { - case 'guest': - if ($f['auth_view'] != AUTH_ALL) continue 2; - break; + foreach ($forums['f'] as $fid => $f) { + switch ($mode) { + case 'guest': + if ($f['auth_view'] != AUTH_ALL) continue 2; + break; - case 'user': - if ($f['auth_view'] != AUTH_ALL && $f['auth_view'] != AUTH_REG) continue 2; - break; + case 'user': + if ($f['auth_view'] != AUTH_ALL && $f['auth_view'] != AUTH_REG) continue 2; + break; - case 'not_auth_forums': - if (isset($not_auth_forums_fary[$f['forum_id']])) continue 2; - break; + case 'not_auth_forums': + if (isset($not_auth_forums_fary[$f['forum_id']])) continue 2; + break; - case 'admin': - break; + case 'admin': + break; - default: - trigger_error(__FUNCTION__ .": invalid mode '$mode'", E_USER_ERROR); - } - $cat_title = $forums['c'][$f['cat_id']]['cat_title']; - $f_name = ($f['forum_parent']) ? ' |- ' : ''; - $f_name .= $f['forum_name']; + default: + trigger_error(__FUNCTION__ . ": invalid mode '$mode'", E_USER_ERROR); + } + $cat_title = $forums['c'][$f['cat_id']]['cat_title']; + $f_name = ($f['forum_parent']) ? ' |- ' : ''; + $f_name .= $f['forum_name']; - while (isset($select[$cat_title][$f_name])) - { - $f_name .= ' '; - } + while (isset($select[$cat_title][$f_name])) { + $f_name .= ' '; + } - $select[$cat_title][$f_name] = $fid; + $select[$cat_title][$f_name] = $fid; - if (!$f['forum_parent']) - { - $class = 'root_forum'; - $class .= isset($f['subforums']) ? ' has_sf' : ''; - $select['__attributes'][$cat_title][$f_name]['class'] = $class; - } - } + if (!$f['forum_parent']) { + $class = 'root_forum'; + $class .= isset($f['subforums']) ? ' has_sf' : ''; + $select['__attributes'][$cat_title][$f_name]['class'] = $class; + } + } - return build_select($name, $select, $selected, $max_length, $multiple_size, $js); + return build_select($name, $select, $selected, $max_length, $multiple_size, $js); } -function setup_style () +function setup_style() { - global $template, $userdata; + global $template, $userdata; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - // AdminCP works only with default template - $tpl_dir_name = defined('IN_ADMIN') ? 'default' : basename($di->config->get('tpl_name')); - $stylesheet = defined('IN_ADMIN') ? 'main.css' : basename($di->config->get('stylesheet')); + // AdminCP works only with default template + $tpl_dir_name = defined('IN_ADMIN') ? 'default' : basename($di->config->get('tpl_name')); + $stylesheet = defined('IN_ADMIN') ? 'main.css' : basename($di->config->get('stylesheet')); - if (!IS_GUEST && !empty($userdata['tpl_name'])) - { - foreach ($di->config->get('templates') as $folder => $name) - { - if ($userdata['tpl_name'] == $folder) $tpl_dir_name = basename($userdata['tpl_name']); - } - } + if (!IS_GUEST && !empty($userdata['tpl_name'])) { + foreach ($di->config->get('templates') as $folder => $name) { + if ($userdata['tpl_name'] == $folder) $tpl_dir_name = basename($userdata['tpl_name']); + } + } - $template = new Template(TEMPLATES_DIR . $tpl_dir_name); - $css_dir = 'styles/' . basename(TEMPLATES_DIR) . '/' . $tpl_dir_name . '/css/'; + $template = new Template(TEMPLATES_DIR . $tpl_dir_name); + $css_dir = 'styles/' . basename(TEMPLATES_DIR) . '/' . $tpl_dir_name . '/css/'; - $template->assign_vars(array( - 'BB_ROOT' => BB_ROOT, - 'SPACER' => make_url('styles/images/spacer.gif'), - 'STYLESHEET' => make_url($css_dir . $stylesheet), - 'EXT_LINK_NEW_WIN' => $di->config->get('ext_link_new_win'), - 'TPL_DIR' => make_url($css_dir), - 'SITE_URL' => make_url('/'), - )); + $template->assign_vars(array( + 'BB_ROOT' => BB_ROOT, + 'SPACER' => make_url('styles/images/spacer.gif'), + 'STYLESHEET' => make_url($css_dir . $stylesheet), + 'EXT_LINK_NEW_WIN' => $di->config->get('ext_link_new_win'), + 'TPL_DIR' => make_url($css_dir), + 'SITE_URL' => make_url('/'), + )); - require(TEMPLATES_DIR . $tpl_dir_name .'/tpl_config.php'); + require(TEMPLATES_DIR . $tpl_dir_name . '/tpl_config.php'); - $theme = array('template_name' => $tpl_dir_name); + $theme = array('template_name' => $tpl_dir_name); - return $theme; + return $theme; } // Create date / time with format and friendly date -function bb_date ($gmepoch, $format = false, $friendly_date = true) +function bb_date($gmepoch, $format = false, $friendly_date = true) { - global $lang, $userdata; + global $lang, $userdata; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$format) $format = $di->config->get('default_dateformat'); - if (empty($lang)) require_once($di->config->get('default_lang_dir') .'main.php'); + if (!$format) $format = $di->config->get('default_dateformat'); + if (empty($lang)) require_once($di->config->get('default_lang_dir') . 'main.php'); - if (empty($userdata['session_logged_in'])) - { - $tz = $di->config->get('board_timezone'); - } - else - { - $tz = $userdata['user_timezone']; - } + if (empty($userdata['session_logged_in'])) { + $tz = $di->config->get('board_timezone'); + } else { + $tz = $userdata['user_timezone']; + } - $date = gmdate($format, $gmepoch + (3600 * $tz)); + $date = gmdate($format, $gmepoch + (3600 * $tz)); - if ($friendly_date) - { - $time_format = ' H:i'; + if ($friendly_date) { + $time_format = ' H:i'; - $today = gmdate('d', TIMENOW + (3600 * $tz)); - $month = gmdate('m', TIMENOW + (3600 * $tz)); - $year = gmdate('Y', TIMENOW + (3600 * $tz)); + $today = gmdate('d', TIMENOW + (3600 * $tz)); + $month = gmdate('m', TIMENOW + (3600 * $tz)); + $year = gmdate('Y', TIMENOW + (3600 * $tz)); - $date_today = gmdate('d', $gmepoch + (3600 * $tz)); - $date_month = gmdate('m', $gmepoch + (3600 * $tz)); - $date_year = gmdate('Y', $gmepoch + (3600 * $tz)); + $date_today = gmdate('d', $gmepoch + (3600 * $tz)); + $date_month = gmdate('m', $gmepoch + (3600 * $tz)); + $date_year = gmdate('Y', $gmepoch + (3600 * $tz)); - if ($date_today == $today && $date_month == $month && $date_year == $year) - { - $date = 'today' . gmdate($time_format, $gmepoch + (3600 * $tz)); - } - elseif ($today != 1 && $date_today == ($today-1) && $date_month == $month && $date_year == $year) - { - $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); - } - elseif ($today == 1 && $month != 1) - { - $yesterday = date ('t', mktime(0, 0, 0, ($month-1), 1, $year)); - if ($date_today == $yesterday && $date_month == ($month-1) && $date_year == $year) - $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); - } - elseif ($today == 1 && $month == 1) - { - $yesterday = date ('t', mktime(0, 0, 0, 12, 1, ($year -1))); - if ($date_today == $yesterday && $date_month == 12 && $date_year == ($year-1)) - $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); - } - } + if ($date_today == $today && $date_month == $month && $date_year == $year) { + $date = 'today' . gmdate($time_format, $gmepoch + (3600 * $tz)); + } elseif ($today != 1 && $date_today == ($today - 1) && $date_month == $month && $date_year == $year) { + $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); + } elseif ($today == 1 && $month != 1) { + $yesterday = date('t', mktime(0, 0, 0, ($month - 1), 1, $year)); + if ($date_today == $yesterday && $date_month == ($month - 1) && $date_year == $year) + $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); + } elseif ($today == 1 && $month == 1) { + $yesterday = date('t', mktime(0, 0, 0, 12, 1, ($year - 1))); + if ($date_today == $yesterday && $date_month == 12 && $date_year == ($year - 1)) + $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); + } + } - return ($di->config->get('translate_dates')) ? strtr(strtoupper($date), $lang['DATETIME']) : $date; + return ($di->config->get('translate_dates')) ? strtr(strtoupper($date), $lang['DATETIME']) : $date; } -function birthday_age ($date) +function birthday_age($date) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$date) return false; + if (!$date) return false; - $tz = TIMENOW + (3600 * $di->config->get('board_timezone')); + $tz = TIMENOW + (3600 * $di->config->get('board_timezone')); - return delta_time(strtotime($date, $tz)); + return delta_time(strtotime($date, $tz)); } // // Pagination routine, generates // page number sequence // -function generate_pagination ($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE) +function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE) { - global $lang, $template; + global $lang, $template; // Pagination Mod - $begin_end = 3; - $from_middle = 1; -/* - By default, $begin_end is 3, and $from_middle is 1, so on page 6 in a 12 page view, it will look like this: + $begin_end = 3; + $from_middle = 1; + /* + By default, $begin_end is 3, and $from_middle is 1, so on page 6 in a 12 page view, it will look like this: - a, d = $begin_end = 3 - b, c = $from_middle = 1 + a, d = $begin_end = 3 + b, c = $from_middle = 1 - "begin" "middle" "end" - | | | - | a b | c d | - | | | | | | | - v v v v v v v - 1, 2, 3 ... 5, 6, 7 ... 10, 11, 12 + "begin" "middle" "end" + | | | + | a b | c d | + | | | | | | | + v v v v v v v + 1, 2, 3 ... 5, 6, 7 ... 10, 11, 12 - Change $begin_end and $from_middle to suit your needs appropriately -*/ + Change $begin_end and $from_middle to suit your needs appropriately + */ - $total_pages = ceil($num_items/$per_page); + $total_pages = ceil($num_items / $per_page); - if ($total_pages == 1 || $num_items == 0) - { - return ''; - } + if ($total_pages == 1 || $num_items == 0) { + return ''; + } - $on_page = floor($start_item / $per_page) + 1; + $on_page = floor($start_item / $per_page) + 1; - $page_string = ''; - if ($total_pages > ((2*($begin_end + $from_middle)) + 2)) - { - $init_page_max = ( $total_pages > $begin_end ) ? $begin_end : $total_pages; - for ($i = 1; $i < $init_page_max + 1; $i++) - { - $page_string .= ( $i == $on_page ) ? '' . $i . '' : '' . $i . ''; - if ($i < $init_page_max) - { - $page_string .= ", "; - } - } - if ($total_pages > $begin_end) - { - if ($on_page > 1 && $on_page < $total_pages) - { - $page_string .= ( $on_page > ($begin_end + $from_middle + 1) ) ? ' ... ' : ', '; + $page_string = ''; + if ($total_pages > ((2 * ($begin_end + $from_middle)) + 2)) { + $init_page_max = ($total_pages > $begin_end) ? $begin_end : $total_pages; + for ($i = 1; $i < $init_page_max + 1; $i++) { + $page_string .= ($i == $on_page) ? '' . $i . '' : '' . $i . ''; + if ($i < $init_page_max) { + $page_string .= ", "; + } + } + if ($total_pages > $begin_end) { + if ($on_page > 1 && $on_page < $total_pages) { + $page_string .= ($on_page > ($begin_end + $from_middle + 1)) ? ' ... ' : ', '; - $init_page_min = ( $on_page > ($begin_end + $from_middle) ) ? $on_page : ($begin_end + $from_middle + 1); + $init_page_min = ($on_page > ($begin_end + $from_middle)) ? $on_page : ($begin_end + $from_middle + 1); - $init_page_max = ( $on_page < $total_pages - ($begin_end + $from_middle) ) ? $on_page : $total_pages - ($begin_end + $from_middle); + $init_page_max = ($on_page < $total_pages - ($begin_end + $from_middle)) ? $on_page : $total_pages - ($begin_end + $from_middle); - for ($i = $init_page_min - $from_middle; $i < $init_page_max + ($from_middle + 1); $i++) - { - $page_string .= ($i == $on_page) ? '' . $i . '' : '' . $i . ''; - if ($i < $init_page_max + $from_middle) - { - $page_string .= ', '; - } - } - $page_string .= ( $on_page < $total_pages - ($begin_end + $from_middle) ) ? ' ... ' : ', '; - } - else - { - $page_string .= ' ... '; - } - for ($i = $total_pages - ($begin_end - 1); $i < $total_pages + 1; $i++) - { - $page_string .= ( $i == $on_page ) ? '' . $i . '' : '' . $i . ''; - if ($i < $total_pages) - { - $page_string .= ", "; - } - } - } - } - else - { - for ($i = 1; $i < $total_pages + 1; $i++) - { - $page_string .= ( $i == $on_page ) ? '' . $i . '' : '' . $i . ''; - if ($i < $total_pages) - { - $page_string .= ', '; - } - } - } + for ($i = $init_page_min - $from_middle; $i < $init_page_max + ($from_middle + 1); $i++) { + $page_string .= ($i == $on_page) ? '' . $i . '' : '' . $i . ''; + if ($i < $init_page_max + $from_middle) { + $page_string .= ', '; + } + } + $page_string .= ($on_page < $total_pages - ($begin_end + $from_middle)) ? ' ... ' : ', '; + } else { + $page_string .= ' ... '; + } + for ($i = $total_pages - ($begin_end - 1); $i < $total_pages + 1; $i++) { + $page_string .= ($i == $on_page) ? '' . $i . '' : '' . $i . ''; + if ($i < $total_pages) { + $page_string .= ", "; + } + } + } + } else { + for ($i = 1; $i < $total_pages + 1; $i++) { + $page_string .= ($i == $on_page) ? '' . $i . '' : '' . $i . ''; + if ($i < $total_pages) { + $page_string .= ', '; + } + } + } - if ($add_prevnext_text) - { - if ($on_page > 1) - { - $page_string = ' ' . $lang['PREVIOUS_PAGE'] . '  ' . $page_string; - } + if ($add_prevnext_text) { + if ($on_page > 1) { + $page_string = ' ' . $lang['PREVIOUS_PAGE'] . '  ' . $page_string; + } - if ($on_page < $total_pages) - { - $page_string .= '  ' . $lang['NEXT_PAGE'] . ''; - } + if ($on_page < $total_pages) { + $page_string .= '  ' . $lang['NEXT_PAGE'] . ''; + } - } + } - $pagination = ($page_string) ? ''. $lang['GOTO_PAGE'] .' :  '. $page_string : ''; - $pagination = str_replace('&start=0', '', $pagination); + $pagination = ($page_string) ? '' . $lang['GOTO_PAGE'] . ' :  ' . $page_string : ''; + $pagination = str_replace('&start=0', '', $pagination); - $template->assign_vars(array( - 'PAGINATION' => $pagination, - 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], ( floor($start_item/$per_page) + 1 ), ceil( $num_items / $per_page )), - 'PG_BASE_URL' => $base_url, - 'PG_PER_PAGE' => $per_page, - )); + $template->assign_vars(array( + 'PAGINATION' => $pagination, + 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], (floor($start_item / $per_page) + 1), ceil($num_items / $per_page)), + 'PG_BASE_URL' => $base_url, + 'PG_PER_PAGE' => $per_page, + )); - return $pagination; + return $pagination; } // @@ -1713,244 +1525,227 @@ function generate_pagination ($base_url, $num_items, $per_page, $start_item, $ad // calling script, note that the vars are passed as references this just makes it easier // to return both sets of arrays // -function obtain_word_list (&$orig_word, &$replacement_word) +function obtain_word_list(&$orig_word, &$replacement_word) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$di->config->get('use_word_censor')) return false; + if (!$di->config->get('use_word_censor')) return false; - if (!$cache->has('censored')) { - $sql = DB()->fetch_rowset("SELECT word, replacement FROM " . BB_WORDS); - if (!$sql) $sql = [['word' => 1, 'replacement' => 1]]; - $cache->set('censored', $sql, 7200); - } + if (!$cache->has('censored')) { + $sql = DB()->fetch_rowset("SELECT word, replacement FROM " . BB_WORDS); + if (!$sql) $sql = [['word' => 1, 'replacement' => 1]]; + $cache->set('censored', $sql, 7200); + } - $sql = $cache->get('censored'); + $sql = $cache->get('censored'); - foreach ($sql as $row) { - $orig_word[] = '#(?ajax_die($msg_text); - } + if (defined('IN_AJAX')) { + $ajax->ajax_die($msg_text); + } - // Check - if (defined('HAS_DIED')) - { - trigger_error(__FUNCTION__ .' was called multiple times', E_USER_ERROR); - } - define('HAS_DIED', 1); - define('DISABLE_CACHING_OUTPUT', true); + // Check + if (defined('HAS_DIED')) { + trigger_error(__FUNCTION__ . ' was called multiple times', E_USER_ERROR); + } + define('HAS_DIED', 1); + define('DISABLE_CACHING_OUTPUT', true); - // If empty lang - if (empty($lang)) - { - require($di->config->get('default_lang_dir') .'main.php'); - } + // If empty lang + if (empty($lang)) { + require($di->config->get('default_lang_dir') . 'main.php'); + } - // If empty session - if (empty($user)) - { - $user->session_start(); - } + // If empty session + if (empty($user)) { + $user->session_start(); + } - // If the header hasn't been output then do it - if (!defined('PAGE_HEADER_SENT')) - { - if (empty($template)) - { - $template = new Template(BB_ROOT ."templates/{$di->config->get('tpl_name')}"); - } - if (empty($theme)) - { - $theme = setup_style(); - } - require(PAGE_HEADER); - } + // If the header hasn't been output then do it + if (!defined('PAGE_HEADER_SENT')) { + if (empty($template)) { + $template = new Template(BB_ROOT . "templates/{$di->config->get('tpl_name')}"); + } + if (empty($theme)) { + $theme = setup_style(); + } + require(PAGE_HEADER); + } - // Check for lang variable - if (!empty($lang[$msg_text])) - { - $msg_text = $lang[$msg_text]; - } + // Check for lang variable + if (!empty($lang[$msg_text])) { + $msg_text = $lang[$msg_text]; + } - $template->assign_vars(array( - 'TPL_BB_DIE' => true, - 'MESSAGE_TEXT' => $msg_text, - )); + $template->assign_vars(array( + 'TPL_BB_DIE' => true, + 'MESSAGE_TEXT' => $msg_text, + )); - $template->set_filenames(array('bb_die' => 'common.tpl')); - $template->pparse('bb_die'); + $template->set_filenames(array('bb_die' => 'common.tpl')); + $template->pparse('bb_die'); - require(PAGE_FOOTER); + require(PAGE_FOOTER); - exit; + exit; } -function bb_simple_die ($txt) +function bb_simple_die($txt) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!empty($_COOKIE['explain'])) - { - bb_die("bb_simple_die:

        $txt"); - } + if (!empty($_COOKIE['explain'])) { + bb_die("bb_simple_die:

        $txt"); + } - header('Content-Type: text/plain; charset='. $di->config->get('charset')); - die($txt); + header('Content-Type: text/plain; charset=' . $di->config->get('charset')); + die($txt); } -function bb_realpath ($path) +function bb_realpath($path) { - return (!function_exists('realpath') || !realpath(INC_DIR . 'functions.php')) ? $path : realpath($path); + return (!function_exists('realpath') || !realpath(INC_DIR . 'functions.php')) ? $path : realpath($path); } -function login_redirect ($url = '') +function login_redirect($url = '') { - redirect(LOGIN_URL . '?redirect='. (($url) ? $url : (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'))); + redirect(LOGIN_URL . '?redirect=' . (($url) ? $url : (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'))); } -function meta_refresh ($url, $time = 5) +function meta_refresh($url, $time = 5) { - global $template; + global $template; - $template->assign_var('META', ''); + $template->assign_var('META', ''); } -function redirect ($url) +function redirect($url) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (headers_sent($filename, $linenum)) - { - trigger_error("Headers already sent in $filename($linenum)", E_USER_ERROR); - } + if (headers_sent($filename, $linenum)) { + trigger_error("Headers already sent in $filename($linenum)", E_USER_ERROR); + } - if (strstr(urldecode($url), "\n") || strstr(urldecode($url), "\r") || strstr(urldecode($url), ';url')) - { - bb_die('Tried to redirect to potentially insecure url'); - } + if (strstr(urldecode($url), "\n") || strstr(urldecode($url), "\r") || strstr(urldecode($url), ';url')) { + bb_die('Tried to redirect to potentially insecure url'); + } - $url = trim($url); - $server_protocol = ($di->config->get('cookie_secure')) ? 'https://' : 'http://'; + $url = trim($url); + $server_protocol = ($di->config->get('cookie_secure')) ? 'https://' : 'http://'; - $server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($di->config->get('server_name'))); - $server_port = ($di->config->get('server_port') <> 80) ? ':' . trim($di->config->get('server_port')) : ''; - $script_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($di->config->get('script_path'))); + $server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($di->config->get('server_name'))); + $server_port = ($di->config->get('server_port') <> 80) ? ':' . trim($di->config->get('server_port')) : ''; + $script_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($di->config->get('script_path'))); - if ($script_name) - { - $script_name = "/$script_name"; - $url = preg_replace("#^$script_name#", '', $url); - } + if ($script_name) { + $script_name = "/$script_name"; + $url = preg_replace("#^$script_name#", '', $url); + } - $redirect_url = $server_protocol . $server_name . $server_port . $script_name . preg_replace('#^\/?(.*?)\/?$#', '/\1', $url); + $redirect_url = $server_protocol . $server_name . $server_port . $script_name . preg_replace('#^\/?(.*?)\/?$#', '/\1', $url); - // Behave as per HTTP/1.1 spec for others - header('Location: '. $redirect_url); - exit; + // Behave as per HTTP/1.1 spec for others + header('Location: ' . $redirect_url); + exit; } // build a list of the sortable fields or return field name -function get_forum_display_sort_option ($selected_row = 0, $action = 'list', $list = 'sort') +function get_forum_display_sort_option($selected_row = 0, $action = 'list', $list = 'sort') { - global $lang; + global $lang; - $forum_display_sort = array( - 'lang_key' => array('LASTPOST', 'SORT_TOPIC_TITLE', 'SORT_TIME'), - 'fields' => array('t.topic_last_post_time', 't.topic_title', 't.topic_time'), - ); - $forum_display_order = array( - 'lang_key' => array('DESC', 'ASC'), - 'fields' => array('DESC', 'ASC'), - ); + $forum_display_sort = array( + 'lang_key' => array('LASTPOST', 'SORT_TOPIC_TITLE', 'SORT_TIME'), + 'fields' => array('t.topic_last_post_time', 't.topic_title', 't.topic_time'), + ); + $forum_display_order = array( + 'lang_key' => array('DESC', 'ASC'), + 'fields' => array('DESC', 'ASC'), + ); - // get the good list - $list_name = 'forum_display_' . $list; - $listrow = $$list_name; + // get the good list + $list_name = 'forum_display_' . $list; + $listrow = $$list_name; - // init the result - $res = ''; - if ( $selected_row > count($listrow['lang_key']) ) - { - $selected_row = 0; - } + // init the result + $res = ''; + if ($selected_row > count($listrow['lang_key'])) { + $selected_row = 0; + } - // build list - if ($action == 'list') - { - for ($i=0; $i < count($listrow['lang_key']); $i++) - { - $selected = ($i==$selected_row) ? ' selected="selected"' : ''; - $l_value = (isset($lang[$listrow['lang_key'][$i]])) ? $lang[$listrow['lang_key'][$i]] : $listrow['lang_key'][$i]; - $res .= ''; - } - } - else - { - // field - $res = $listrow['fields'][$selected_row]; - } - return $res; + // build list + if ($action == 'list') { + for ($i = 0; $i < count($listrow['lang_key']); $i++) { + $selected = ($i == $selected_row) ? ' selected="selected"' : ''; + $l_value = (isset($lang[$listrow['lang_key'][$i]])) ? $lang[$listrow['lang_key'][$i]] : $listrow['lang_key'][$i]; + $res .= ''; + } + } else { + // field + $res = $listrow['fields'][$selected_row]; + } + return $res; } -function clear_dl_list ($topics_csv) +function clear_dl_list($topics_csv) { - DB()->query("DELETE FROM ". BB_BT_DLSTATUS ." WHERE topic_id IN($topics_csv)"); - DB()->query("DELETE FROM ". BB_BT_DLSTATUS_SNAP ." WHERE topic_id IN($topics_csv)"); + DB()->query("DELETE FROM " . BB_BT_DLSTATUS . " WHERE topic_id IN($topics_csv)"); + DB()->query("DELETE FROM " . BB_BT_DLSTATUS_SNAP . " WHERE topic_id IN($topics_csv)"); } // $ids - array(id1,id2,..) or (string) id -function get_id_csv ($ids) +function get_id_csv($ids) { - $ids = array_values((array) $ids); - array_deep($ids, 'intval', 'one-dimensional'); - return (string) join(',', $ids); + $ids = array_values((array)$ids); + array_deep($ids, 'intval', 'one-dimensional'); + return (string)join(',', $ids); } // $ids - array(id1,id2,..) or (string) id1,id2,.. -function get_id_ary ($ids) +function get_id_ary($ids) { - $ids = is_string($ids) ? explode(',', $ids) : array_values((array) $ids); - array_deep($ids, 'intval', 'one-dimensional'); - return (array) $ids; + $ids = is_string($ids) ? explode(',', $ids) : array_values((array)$ids); + array_deep($ids, 'intval', 'one-dimensional'); + return (array)$ids; } -function get_topic_title ($topic_id) +function get_topic_title($topic_id) { - $row = DB()->fetch_row(" - SELECT topic_title FROM ". BB_TOPICS ." WHERE topic_id = ". (int) $topic_id ." + $row = DB()->fetch_row(" + SELECT topic_title FROM " . BB_TOPICS . " WHERE topic_id = " . (int)$topic_id . " "); - return $row['topic_title']; + return $row['topic_title']; } -function forum_exists ($forum_id) +function forum_exists($forum_id) { - return DB()->fetch_row("SELECT forum_id FROM ". BB_FORUMS ." WHERE forum_id = $forum_id LIMIT 1"); + return DB()->fetch_row("SELECT forum_id FROM " . BB_FORUMS . " WHERE forum_id = $forum_id LIMIT 1"); } -function cat_exists ($cat_id) +function cat_exists($cat_id) { - return DB()->fetch_row("SELECT cat_id FROM ". BB_CATEGORIES ." WHERE cat_id = $cat_id LIMIT 1"); + return DB()->fetch_row("SELECT cat_id FROM " . BB_CATEGORIES . " WHERE cat_id = $cat_id LIMIT 1"); } // @@ -1958,224 +1753,205 @@ function cat_exists ($cat_id) // class log_action { - var $log_type = [ - # LOG_TYPE_NAME LOG_TYPE_ID - 'mod_topic_delete' => 1, - 'mod_topic_move' => 2, - 'mod_topic_lock' => 3, - 'mod_topic_unlock' => 4, - 'mod_post_delete' => 5, - 'mod_topic_split' => 6, - 'adm_user_delete' => 7, - 'adm_user_ban' => 8, - 'adm_user_unban' => 9, - 'tor_status_changed' => 10, - 'att_delete' => 11, - 'tor_unreg' => 12, - 'tor_cphold_close' => 13, - 'adm_ban_ip' => 14, - 'adm_ban_email' => 15, - 'adm_ban_name' => 16, - ]; - var $log_type_select = []; - var $log_disabled = false; + var $log_type = [ + # LOG_TYPE_NAME LOG_TYPE_ID + 'mod_topic_delete' => 1, + 'mod_topic_move' => 2, + 'mod_topic_lock' => 3, + 'mod_topic_unlock' => 4, + 'mod_post_delete' => 5, + 'mod_topic_split' => 6, + 'adm_user_delete' => 7, + 'adm_user_ban' => 8, + 'adm_user_unban' => 9, + 'tor_status_changed' => 10, + 'att_delete' => 11, + 'tor_unreg' => 12, + 'tor_cphold_close' => 13, + 'adm_ban_ip' => 14, + 'adm_ban_email' => 15, + 'adm_ban_name' => 16, + ]; + var $log_type_select = []; + var $log_disabled = false; - function init () - { - global $lang; + function init() + { + global $lang; - foreach ($lang['LOG_ACTION']['LOG_TYPE'] as $log_type => $log_desc) - { - $this->log_type_select[strip_tags($log_desc)] = $this->log_type[$log_type]; - } - } + foreach ($lang['LOG_ACTION']['LOG_TYPE'] as $log_type => $log_desc) { + $this->log_type_select[strip_tags($log_desc)] = $this->log_type[$log_type]; + } + } - function mod ($type_name, $args = array()) - { - global $userdata; + function mod($type_name, $args = array()) + { + global $userdata; - if (empty($this->log_type)) $this->init(); - if ($this->log_disabled) return; + if (empty($this->log_type)) $this->init(); + if ($this->log_disabled) return; - $forum_id =& $args['forum_id']; - $forum_id_new =& $args['forum_id_new']; - $topic_id =& $args['topic_id']; - $topic_id_new =& $args['topic_id_new']; - $topic_title =& $args['topic_title']; - $topic_title_new =& $args['topic_title_new']; - $log_msg =& $args['log_msg']; + $forum_id =& $args['forum_id']; + $forum_id_new =& $args['forum_id_new']; + $topic_id =& $args['topic_id']; + $topic_id_new =& $args['topic_id_new']; + $topic_title =& $args['topic_title']; + $topic_title_new =& $args['topic_title_new']; + $log_msg =& $args['log_msg']; - if (!empty($userdata)) - { - $user_id = $userdata['user_id']; - $session_ip = $userdata['session_ip']; - } - else - { - $user_id = ''; - $session_ip = ''; - } + if (!empty($userdata)) { + $user_id = $userdata['user_id']; + $session_ip = $userdata['session_ip']; + } else { + $user_id = ''; + $session_ip = ''; + } - $sql_ary = array( - 'log_type_id' => (int) $this->log_type["$type_name"], - 'log_user_id' => (int) $user_id, - 'log_user_ip' => (string) $session_ip, - 'log_forum_id' => (int) $forum_id, - 'log_forum_id_new' => (int) $forum_id_new, - 'log_topic_id' => (int) $topic_id, - 'log_topic_id_new' => (int) $topic_id_new, - 'log_topic_title' => (string) $topic_title, - 'log_topic_title_new' => (string) $topic_title_new, - 'log_time' => (int) TIMENOW, - 'log_msg' => (string) $log_msg, - ); - $sql_args = DB()->build_array('INSERT', $sql_ary); + $sql_ary = array( + 'log_type_id' => (int)$this->log_type["$type_name"], + 'log_user_id' => (int)$user_id, + 'log_user_ip' => (string)$session_ip, + 'log_forum_id' => (int)$forum_id, + 'log_forum_id_new' => (int)$forum_id_new, + 'log_topic_id' => (int)$topic_id, + 'log_topic_id_new' => (int)$topic_id_new, + 'log_topic_title' => (string)$topic_title, + 'log_topic_title_new' => (string)$topic_title_new, + 'log_time' => (int)TIMENOW, + 'log_msg' => (string)$log_msg, + ); + $sql_args = DB()->build_array('INSERT', $sql_ary); - DB()->query("INSERT INTO ". BB_LOG ." $sql_args"); - } + DB()->query("INSERT INTO " . BB_LOG . " $sql_args"); + } - function admin ($type_name, $args = array()) - { - $this->mod($type_name, $args); - } + function admin($type_name, $args = array()) + { + $this->mod($type_name, $args); + } } -function get_topic_icon ($topic, $is_unread = null) +function get_topic_icon($topic, $is_unread = null) { - global $images; + global $images; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $t_hot = ($topic['topic_replies'] >= $di->config->get('hot_threshold')); - $is_unread = is_null($is_unread) ? is_unread($topic['topic_last_post_time'], $topic['topic_id'], $topic['forum_id']) : $is_unread; + $t_hot = ($topic['topic_replies'] >= $di->config->get('hot_threshold')); + $is_unread = is_null($is_unread) ? is_unread($topic['topic_last_post_time'], $topic['topic_id'], $topic['forum_id']) : $is_unread; - if ($topic['topic_status'] == TOPIC_MOVED) - { - $folder_image = $images['folder']; - } - else - { - $folder = ($t_hot) ? $images['folder_hot'] : $images['folder']; - $folder_new = ($t_hot) ? $images['folder_hot_new'] : $images['folder_new']; + if ($topic['topic_status'] == TOPIC_MOVED) { + $folder_image = $images['folder']; + } else { + $folder = ($t_hot) ? $images['folder_hot'] : $images['folder']; + $folder_new = ($t_hot) ? $images['folder_hot_new'] : $images['folder_new']; - if ($topic['topic_type'] == POST_ANNOUNCE) - { - $folder = $images['folder_announce']; - $folder_new = $images['folder_announce_new']; - } - else if ($topic['topic_type'] == POST_STICKY) - { - $folder = $images['folder_sticky']; - $folder_new = $images['folder_sticky_new']; - } - else if ($topic['topic_status'] == TOPIC_LOCKED) - { - $folder = $images['folder_locked']; - $folder_new = $images['folder_locked_new']; - } - else if (isset($topic['tracker_status'])) - { - $folder = ($t_hot) ? $images['folder_dl_hot'] : $images['folder_dl']; - $folder_new = ($t_hot) ? $images['folder_dl_hot_new'] : $images['folder_dl_new']; - } + if ($topic['topic_type'] == POST_ANNOUNCE) { + $folder = $images['folder_announce']; + $folder_new = $images['folder_announce_new']; + } else if ($topic['topic_type'] == POST_STICKY) { + $folder = $images['folder_sticky']; + $folder_new = $images['folder_sticky_new']; + } else if ($topic['topic_status'] == TOPIC_LOCKED) { + $folder = $images['folder_locked']; + $folder_new = $images['folder_locked_new']; + } else if (isset($topic['tracker_status'])) { + $folder = ($t_hot) ? $images['folder_dl_hot'] : $images['folder_dl']; + $folder_new = ($t_hot) ? $images['folder_dl_hot_new'] : $images['folder_dl_new']; + } - $folder_image = ($is_unread) ? $folder_new : $folder; - } + $folder_image = ($is_unread) ? $folder_new : $folder; + } - return $folder_image; + return $folder_image; } -function build_topic_pagination ($url, $replies, $per_page) +function build_topic_pagination($url, $replies, $per_page) { - $pg = ''; + $pg = ''; - if (++$replies > $per_page) - { - $total_pages = ceil($replies / $per_page); + if (++$replies > $per_page) { + $total_pages = ceil($replies / $per_page); - for ($j=0, $page=1; $j < $replies; $j += $per_page, $page++) - { - $href = ($j) ? "$url&start=$j" : $url; - $pg .= ''. $page .''; + for ($j = 0, $page = 1; $j < $replies; $j += $per_page, $page++) { + $href = ($j) ? "$url&start=$j" : $url; + $pg .= '' . $page . ''; - if ($page == 1 && $total_pages > 3) - { - $pg .= ' .. '; - $page = $total_pages - 2; - $j += ($total_pages - 3) * $per_page; - } - else if ($page < $total_pages) - { - $pg .= ', '; - } - } - } + if ($page == 1 && $total_pages > 3) { + $pg .= ' .. '; + $page = $total_pages - 2; + $j += ($total_pages - 3) * $per_page; + } else if ($page < $total_pages) { + $pg .= ', '; + } + } + } - return $pg; + return $pg; } // // Poll // -function get_poll_data_items_js ($topic_id) +function get_poll_data_items_js($topic_id) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$topic_id_csv = get_id_csv($topic_id)) { - return is_array($topic_id) ? [] : false; - } - $items = []; + if (!$topic_id_csv = get_id_csv($topic_id)) { + return is_array($topic_id) ? [] : false; + } + $items = []; - if (!$cache->has('poll_' . $topic_id)) { - $poll_data = DB()->fetch_rowset(" + if (!$cache->has('poll_' . $topic_id)) { + $poll_data = DB()->fetch_rowset(" SELECT topic_id, vote_id, vote_text, vote_result FROM " . BB_POLL_VOTES . " WHERE topic_id IN($topic_id_csv) ORDER BY topic_id, vote_id "); - $cache->set('poll_' . $topic_id, $poll_data); - } + $cache->set('poll_' . $topic_id, $poll_data); + } - $poll_data = $cache->get('poll_' . $topic_id); + $poll_data = $cache->get('poll_' . $topic_id); - foreach ($poll_data as $row) { - $opt_text_for_js = htmlCHR($row['vote_text']); - $opt_result_for_js = (int)$row['vote_result']; + foreach ($poll_data as $row) { + $opt_text_for_js = htmlCHR($row['vote_text']); + $opt_result_for_js = (int)$row['vote_result']; - $items[$row['topic_id']][$row['vote_id']] = array($opt_text_for_js, $opt_result_for_js); - } - foreach ($items as $k => $v) { - $items[$k] = \Zend\Json\Json::encode($v); - } + $items[$row['topic_id']][$row['vote_id']] = array($opt_text_for_js, $opt_result_for_js); + } + foreach ($items as $k => $v) { + $items[$k] = \Zend\Json\Json::encode($v); + } - return is_array($topic_id) ? $items : $items[$topic_id]; + return is_array($topic_id) ? $items : $items[$topic_id]; } -function poll_is_active ($t_data) +function poll_is_active($t_data) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - return ($t_data['topic_vote'] == 1 && $t_data['topic_time'] > TIMENOW - $di->config->get('poll_max_days') * 86400); + return ($t_data['topic_vote'] == 1 && $t_data['topic_time'] > TIMENOW - $di->config->get('poll_max_days') * 86400); } -function print_confirmation ($tpl_vars) +function print_confirmation($tpl_vars) { - global $template, $lang; + global $template, $lang; - $template->assign_vars(array( - 'TPL_CONFIRM' => true, - 'CONFIRM_TITLE' => $lang['CONFIRM'], - 'FORM_METHOD' => 'post', - )); - $template->assign_vars($tpl_vars); + $template->assign_vars(array( + 'TPL_CONFIRM' => true, + 'CONFIRM_TITLE' => $lang['CONFIRM'], + 'FORM_METHOD' => 'post', + )); + $template->assign_vars($tpl_vars); - print_page('common.tpl'); + print_page('common.tpl'); } /** @@ -2196,471 +1972,415 @@ function print_confirmation ($tpl_vars) * @param string $type * @param string $mode */ -function print_page ($args, $type = '', $mode = '') +function print_page($args, $type = '', $mode = '') { - global $template, $gen_simple_header; + global $template, $gen_simple_header; - $tpl = (is_array($args) && !empty($args['tpl'])) ? $args['tpl'] : $args; - $tpl = ($type === 'admin') ? ADMIN_TPL_DIR . $tpl : $tpl; + $tpl = (is_array($args) && !empty($args['tpl'])) ? $args['tpl'] : $args; + $tpl = ($type === 'admin') ? ADMIN_TPL_DIR . $tpl : $tpl; - $gen_simple_header = (is_array($args) && !empty($args['simple']) OR $type === 'simple') ? true : $gen_simple_header; + $gen_simple_header = (is_array($args) && !empty($args['simple']) OR $type === 'simple') ? true : $gen_simple_header; - if ($mode !== 'no_header') - { - require(PAGE_HEADER); - } + if ($mode !== 'no_header') { + require(PAGE_HEADER); + } - $template->set_filenames(array('body' => $tpl)); - $template->pparse('body'); + $template->set_filenames(array('body' => $tpl)); + $template->pparse('body'); - if ($mode !== 'no_footer') - { - require(PAGE_FOOTER); - } + if ($mode !== 'no_footer') { + require(PAGE_FOOTER); + } } -function clean_title ($str, $replace_underscore = false) +function clean_title($str, $replace_underscore = false) { - $str = ($replace_underscore) ? str_replace('_', ' ', $str) : $str; - $str = htmlCHR(str_compact($str)); - return $str; + $str = ($replace_underscore) ? str_replace('_', ' ', $str) : $str; + $str = htmlCHR(str_compact($str)); + return $str; } -function clean_text_match ($text, $ltrim_star = true, $remove_stopwords = false, $die_if_empty = false) +function clean_text_match($text, $ltrim_star = true, $remove_stopwords = false, $die_if_empty = false) { - global $lang; + global $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $text = str_compact($text); - $ltrim_chars = ($ltrim_star) ? ' *-!' : ' '; - $wrap_with_quotes = preg_match('#^"[^"]+"$#', $text); + $text = str_compact($text); + $ltrim_chars = ($ltrim_star) ? ' *-!' : ' '; + $wrap_with_quotes = preg_match('#^"[^"]+"$#', $text); - $text = ' '. str_compact(ltrim($text, $ltrim_chars)) .' '; + $text = ' ' . str_compact(ltrim($text, $ltrim_chars)) . ' '; - if ($remove_stopwords) - { - $text = remove_stopwords($text); - } + if ($remove_stopwords) { + $text = remove_stopwords($text); + } - if ($di->config->get('sphinx_enabled')) - { - $text = preg_replace('#(?<=\S)\-#u', ' ', $text); // "1-2-3" -> "1 2 3" - $text = preg_replace('#[^0-9a-zA-Zа-яА-ЯёЁ\-_*|]#u', ' ', $text); // допустимые символы (кроме " которые отдельно) - $text = str_replace('-', ' -', $text); // - только в начале слова - $text = str_replace('*', '* ', $text); // * только в конце слова - $text = preg_replace('#\s*\|\s*#u', '|', $text); // "| " -> "|" - $text = preg_replace('#\|+#u', ' | ', $text); // "||" -> "|" - $text = preg_replace('#(?<=\s)[\-*]+\s#u', ' ', $text); // одиночные " - ", " * " - $text = trim($text, ' -|'); - $text = str_compact($text); - $text_match_sql = ($wrap_with_quotes && $text != '') ? '"'. $text .'"' : $text; - } - else - { - $text_match_sql = DB()->escape(trim($text)); - } + if ($di->config->get('sphinx_enabled')) { + $text = preg_replace('#(?<=\S)\-#u', ' ', $text); // "1-2-3" -> "1 2 3" + $text = preg_replace('#[^0-9a-zA-Zа-яА-ЯёЁ\-_*|]#u', ' ', $text); // допустимые символы (кроме " которые отдельно) + $text = str_replace('-', ' -', $text); // - только в начале слова + $text = str_replace('*', '* ', $text); // * только в конце слова + $text = preg_replace('#\s*\|\s*#u', '|', $text); // "| " -> "|" + $text = preg_replace('#\|+#u', ' | ', $text); // "||" -> "|" + $text = preg_replace('#(?<=\s)[\-*]+\s#u', ' ', $text); // одиночные " - ", " * " + $text = trim($text, ' -|'); + $text = str_compact($text); + $text_match_sql = ($wrap_with_quotes && $text != '') ? '"' . $text . '"' : $text; + } else { + $text_match_sql = DB()->escape(trim($text)); + } - if (!$text_match_sql && $die_if_empty) - { - bb_die($lang['NO_SEARCH_MATCH']); - } + if (!$text_match_sql && $die_if_empty) { + bb_die($lang['NO_SEARCH_MATCH']); + } - return $text_match_sql; + return $text_match_sql; } -function init_sphinx () +function init_sphinx() { - global $sphinx; + global $sphinx; - if (!isset($sphinx)) - { - if (!class_exists('SphinxClient')) require(INC_DIR . 'api/sphinx.php'); - $sphinx = new SphinxClient(); + if (!isset($sphinx)) { + if (!class_exists('SphinxClient')) require(INC_DIR . 'api/sphinx.php'); + $sphinx = new SphinxClient(); - $sphinx->SetConnectTimeout(5); - $sphinx->SetRankingMode(SPH_RANK_NONE); - $sphinx->SetMatchMode(SPH_MATCH_BOOLEAN); - } + $sphinx->SetConnectTimeout(5); + $sphinx->SetRankingMode(SPH_RANK_NONE); + $sphinx->SetMatchMode(SPH_MATCH_BOOLEAN); + } } -function log_sphinx_error ($err_type, $err_msg, $query = '') +function log_sphinx_error($err_type, $err_msg, $query = '') { - $ignore_err_txt = array( - 'negation on top level', - 'Query word length is less than min prefix length', - ); - if (!count($ignore_err_txt) || !preg_match('#'. join('|', $ignore_err_txt) .'#i', $err_msg)) - { - $orig_query = strtr($_REQUEST['nm'], array("\n" => '\n')); - bb_log(date('m-d H:i:s') ." | $err_type | $err_msg | $orig_query | $query". LOG_LF, 'sphinx_error'); - } + $ignore_err_txt = array( + 'negation on top level', + 'Query word length is less than min prefix length', + ); + if (!count($ignore_err_txt) || !preg_match('#' . join('|', $ignore_err_txt) . '#i', $err_msg)) { + $orig_query = strtr($_REQUEST['nm'], array("\n" => '\n')); + bb_log(date('m-d H:i:s') . " | $err_type | $err_msg | $orig_query | $query" . LOG_LF, 'sphinx_error'); + } } function get_title_match_topics($search) { - global $sphinx, $userdata, $lang; + global $sphinx, $userdata, $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $where_ids = array(); - $forum_ids = (isset($search['ids']) && is_array($search['ids'])) ? array_diff($search['ids'], array(0 => 0)) : ''; - $title_match_sql = encode_text_match($search['query']); + $where_ids = array(); + $forum_ids = (isset($search['ids']) && is_array($search['ids'])) ? array_diff($search['ids'], array(0 => 0)) : ''; + $title_match_sql = encode_text_match($search['query']); - if ($di->config->get('sphinx_enabled')) - { - init_sphinx(); + if ($di->config->get('sphinx_enabled')) { + init_sphinx(); - $where = (isset($search['topic_match'])) ? 'topics' : 'posts'; + $where = (isset($search['topic_match'])) ? 'topics' : 'posts'; - $sphinx->SetServer($di->config->get('sphinx_topic_titles_host'), $di->config->get('sphinx_topic_titles_port')); - if ($forum_ids) - { - $sphinx->SetFilter('forum_id', $forum_ids, false); - } - if (preg_match('#^"[^"]+"$#u', $title_match_sql)) - { - $sphinx->SetMatchMode(SPH_MATCH_PHRASE); - } - if ($result = $sphinx->Query($title_match_sql, $where, $userdata['username'] . ' (' . CLIENT_IP . ')')) - { - if (!empty($result['matches'])) - { - $where_ids = array_keys($result['matches']); - } - } - else if ($error = $sphinx->GetLastError()) - { - if (strpos($error, 'errno=110')) - { - bb_die($lang['SEARCH_ERROR']); - } - log_sphinx_error('ERR', $error, $title_match_sql); - } - if ($warning = $sphinx->GetLastWarning()) - { - log_sphinx_error('wrn', $warning, $title_match_sql); - } - } - else - { - $where_forum = ($forum_ids) ? "AND forum_id IN(" . join(',', $forum_ids) . ")" : ''; - $search_bool_mode = ($di->config->get('allow_search_in_bool_mode')) ? ' IN BOOLEAN MODE' : ''; + $sphinx->SetServer($di->config->get('sphinx_topic_titles_host'), $di->config->get('sphinx_topic_titles_port')); + if ($forum_ids) { + $sphinx->SetFilter('forum_id', $forum_ids, false); + } + if (preg_match('#^"[^"]+"$#u', $title_match_sql)) { + $sphinx->SetMatchMode(SPH_MATCH_PHRASE); + } + if ($result = $sphinx->Query($title_match_sql, $where, $userdata['username'] . ' (' . CLIENT_IP . ')')) { + if (!empty($result['matches'])) { + $where_ids = array_keys($result['matches']); + } + } else if ($error = $sphinx->GetLastError()) { + if (strpos($error, 'errno=110')) { + bb_die($lang['SEARCH_ERROR']); + } + log_sphinx_error('ERR', $error, $title_match_sql); + } + if ($warning = $sphinx->GetLastWarning()) { + log_sphinx_error('wrn', $warning, $title_match_sql); + } + } else { + $where_forum = ($forum_ids) ? "AND forum_id IN(" . join(',', $forum_ids) . ")" : ''; + $search_bool_mode = ($di->config->get('allow_search_in_bool_mode')) ? ' IN BOOLEAN MODE' : ''; - if (isset($search['topic_match'])) - { - $where_id = 'topic_id'; - $sql = "SELECT topic_id FROM " . BB_TOPICS . " + if (isset($search['topic_match'])) { + $where_id = 'topic_id'; + $sql = "SELECT topic_id FROM " . BB_TOPICS . " WHERE MATCH (topic_title) AGAINST ('$title_match_sql'$search_bool_mode) OR topic_title LIKE '%$title_match_sql%' $where_forum"; - } - else - { - $where_id = 'post_id'; - $sql = "SELECT p.post_id FROM " . BB_POSTS . " p, " . BB_POSTS_SEARCH . " ps + } else { + $where_id = 'post_id'; + $sql = "SELECT p.post_id FROM " . BB_POSTS . " p, " . BB_POSTS_SEARCH . " ps WHERE ps.post_id = p.post_id AND MATCH (ps.search_words) AGAINST ('$title_match_sql'$search_bool_mode) $where_forum"; - } + } - foreach (DB()->fetch_rowset($sql) as $row) - { - $where_ids[] = $row[$where_id]; - } - } + foreach (DB()->fetch_rowset($sql) as $row) { + $where_ids[] = $row[$where_id]; + } + } - return $where_ids; + return $where_ids; } // для более корректного поиска по словам содержащим одиночную кавычку -function encode_text_match ($txt) +function encode_text_match($txt) { - return str_replace("'", ''', $txt); + return str_replace("'", ''', $txt); } -function decode_text_match ($txt) +function decode_text_match($txt) { - return str_replace(''', "'", $txt); + return str_replace(''', "'", $txt); } -function remove_stopwords ($text) +function remove_stopwords($text) { - static $stopwords = null; + static $stopwords = null; - if (is_null($stopwords)) - { - $stopwords = explode(' ', str_compact(file_get_contents(LANG_DIR .'search_stopwords.txt'))); - array_deep($stopwords, 'pad_with_space'); - } + if (is_null($stopwords)) { + $stopwords = explode(' ', str_compact(file_get_contents(LANG_DIR . 'search_stopwords.txt'))); + array_deep($stopwords, 'pad_with_space'); + } - return ($stopwords) ? str_replace($stopwords, ' ', $text) : $text; + return ($stopwords) ? str_replace($stopwords, ' ', $text) : $text; } -function pad_with_space ($str) +function pad_with_space($str) { - return ($str) ? " $str " : $str; + return ($str) ? " $str " : $str; } -function create_magnet ($infohash, $auth_key, $logged_in) +function create_magnet($infohash, $auth_key, $logged_in) { - global $images; + global $images; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $passkey_url = ((!$logged_in || isset($_GET['no_passkey'])) && $di->config->get('bt_tor_browse_only_reg')) ? '' : "?{$di->config->get('passkey_key')}=$auth_key"; + $passkey_url = ((!$logged_in || isset($_GET['no_passkey'])) && $di->config->get('bt_tor_browse_only_reg')) ? '' : "?{$di->config->get('passkey_key')}=$auth_key"; - if ($di->config->get('ocelot.enabled')) - { - return ''; - } - else - { - return ''; - } + if ($di->config->get('ocelot.enabled')) { + return ''; + } else { + return ''; + } } -function set_die_append_msg ($forum_id = null, $topic_id = null, $group_id = null) +function set_die_append_msg($forum_id = null, $topic_id = null, $group_id = null) { - global $lang, $template; + global $lang, $template; - $msg = ''; - $msg .= ($topic_id) ? '

        '. $lang['TOPIC_RETURN'] .'

        ' : ''; - $msg .= ($forum_id) ? '

        '. $lang['FORUM_RETURN'] .'

        ' : ''; - $msg .= ($group_id) ? '

        '. $lang['GROUP_RETURN'] .'

        ' : ''; - $msg .= '

        '. $lang['INDEX_RETURN'] .'

        '; - $template->assign_var('BB_DIE_APPEND_MSG', $msg); + $msg = ''; + $msg .= ($topic_id) ? '

        ' . $lang['TOPIC_RETURN'] . '

        ' : ''; + $msg .= ($forum_id) ? '

        ' . $lang['FORUM_RETURN'] . '

        ' : ''; + $msg .= ($group_id) ? '

        ' . $lang['GROUP_RETURN'] . '

        ' : ''; + $msg .= '

        ' . $lang['INDEX_RETURN'] . '

        '; + $template->assign_var('BB_DIE_APPEND_MSG', $msg); } -function set_pr_die_append_msg ($pr_uid) +function set_pr_die_append_msg($pr_uid) { - global $lang, $template; + global $lang, $template; - $template->assign_var('BB_DIE_APPEND_MSG', ' - '. $lang['PROFILE_RETURN'] .' + $template->assign_var('BB_DIE_APPEND_MSG', ' + ' . $lang['PROFILE_RETURN'] . '

        - '. $lang['PROFILE_EDIT_RETURN'] .' + ' . $lang['PROFILE_EDIT_RETURN'] . '

        - '. $lang['INDEX_RETURN'] .' + ' . $lang['INDEX_RETURN'] . ' '); } -function send_pm ($user_id, $subject, $message, $poster_id = BOT_UID) +function send_pm($user_id, $subject, $message, $poster_id = BOT_UID) { - global $userdata; + global $userdata; - $subject = DB()->escape($subject); - $message = DB()->escape($message); + $subject = DB()->escape($subject); + $message = DB()->escape($message); - if ($poster_id == BOT_UID) - { - $poster_ip = '7f000001'; - } - elseif ($row = DB()->fetch_row("SELECT user_reg_ip FROM ". BB_USERS ." WHERE user_id = $poster_id")) - { - $poster_ip = $row['user_reg_ip']; - } - else - { - $poster_id = $userdata['user_id']; - $poster_ip = USER_IP; - } + if ($poster_id == BOT_UID) { + $poster_ip = '7f000001'; + } elseif ($row = DB()->fetch_row("SELECT user_reg_ip FROM " . BB_USERS . " WHERE user_id = $poster_id")) { + $poster_ip = $row['user_reg_ip']; + } else { + $poster_id = $userdata['user_id']; + $poster_ip = USER_IP; + } - DB()->query("INSERT INTO ". BB_PRIVMSGS ." (privmsgs_type, privmsgs_subject, privmsgs_from_userid, privmsgs_to_userid, privmsgs_date, privmsgs_ip) VALUES (". PRIVMSGS_NEW_MAIL .", '$subject', {$poster_id}, $user_id, ". TIMENOW .", '$poster_ip')"); - $pm_id = DB()->sql_nextid(); + DB()->query("INSERT INTO " . BB_PRIVMSGS . " (privmsgs_type, privmsgs_subject, privmsgs_from_userid, privmsgs_to_userid, privmsgs_date, privmsgs_ip) VALUES (" . PRIVMSGS_NEW_MAIL . ", '$subject', {$poster_id}, $user_id, " . TIMENOW . ", '$poster_ip')"); + $pm_id = DB()->sql_nextid(); - DB()->query("INSERT INTO " . BB_PRIVMSGS_TEXT . " (privmsgs_text_id, privmsgs_text) VALUES ($pm_id, '$message')"); - DB()->query("UPDATE ". BB_USERS ." SET user_new_privmsg = user_new_privmsg + 1, user_last_privmsg = ". TIMENOW .", user_newest_pm_id = $pm_id WHERE user_id = $user_id"); + DB()->query("INSERT INTO " . BB_PRIVMSGS_TEXT . " (privmsgs_text_id, privmsgs_text) VALUES ($pm_id, '$message')"); + DB()->query("UPDATE " . BB_USERS . " SET user_new_privmsg = user_new_privmsg + 1, user_last_privmsg = " . TIMENOW . ", user_newest_pm_id = $pm_id WHERE user_id = $user_id"); } -function profile_url ($data) +function profile_url($data) { - global $lang, $datastore; + global $lang, $datastore; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$ranks = $datastore->get('ranks')) - { - $datastore->update('ranks'); - $ranks = $datastore->get('ranks'); - } + if (!$ranks = $datastore->get('ranks')) { + $datastore->update('ranks'); + $ranks = $datastore->get('ranks'); + } - $user_rank = !empty($data['user_rank']) ? $data['user_rank'] : 0; + $user_rank = !empty($data['user_rank']) ? $data['user_rank'] : 0; - if (isset($ranks[$user_rank])) - { - $title = $ranks[$user_rank]['rank_title']; - $style = $ranks[$user_rank]['rank_style']; - } - if (empty($title)) $title = $lang['USER']; - if (empty($style)) $style = 'colorUser'; + if (isset($ranks[$user_rank])) { + $title = $ranks[$user_rank]['rank_title']; + $style = $ranks[$user_rank]['rank_style']; + } + if (empty($title)) $title = $lang['USER']; + if (empty($style)) $style = 'colorUser'; - if (!$di->config->get('color_nick')) $style = ''; + if (!$di->config->get('color_nick')) $style = ''; - $username = !empty($data['username']) ? $data['username'] : $lang['GUEST']; - $user_id = (!empty($data['user_id']) && $username != $lang['GUEST']) ? $data['user_id'] : GUEST_UID; + $username = !empty($data['username']) ? $data['username'] : $lang['GUEST']; + $user_id = (!empty($data['user_id']) && $username != $lang['GUEST']) ? $data['user_id'] : GUEST_UID; - $profile = ''. $username .''; + $profile = '' . $username . ''; - if (!in_array($user_id, array('', GUEST_UID, BOT_UID)) && $username) - { - $profile = ''. $profile .''; - } + if (!in_array($user_id, array('', GUEST_UID, BOT_UID)) && $username) { + $profile = '' . $profile . ''; + } - return $profile; + return $profile; } -function get_avatar ($user_id, $ext_id, $allow_avatar = true, $size = true, $height = '', $width = '') +function get_avatar($user_id, $ext_id, $allow_avatar = true, $size = true, $height = '', $width = '') { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if ($size) - { - // TODO размеры: s, m, l + кеширование - } + if ($size) { + // TODO размеры: s, m, l + кеширование + } - $height = ($height != '') ? 'height="'. $height .'"' : ''; - $width = ($width != '') ? 'width="'. $width .'"' : ''; + $height = ($height != '') ? 'height="' . $height . '"' : ''; + $width = ($width != '') ? 'width="' . $width . '"' : ''; - $user_avatar = ''. $user_id .''; + $user_avatar = '' . $user_id . ''; - if ($user_id == BOT_UID && $di->config->get('avatars.bot_avatar')) - { - $user_avatar = ''. $user_id .''; - } - else if ($allow_avatar && $ext_id) - { - if (file_exists(get_avatar_path($user_id, $ext_id))) - { - $user_avatar = ''. $user_id .''; - } - } + if ($user_id == BOT_UID && $di->config->get('avatars.bot_avatar')) { + $user_avatar = '' . $user_id . ''; + } else if ($allow_avatar && $ext_id) { + if (file_exists(get_avatar_path($user_id, $ext_id))) { + $user_avatar = '' . $user_id . ''; + } + } - return $user_avatar; + return $user_avatar; } -function gender_image ($gender) +function gender_image($gender) { - global $lang, $images; + global $lang, $images; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$di->config->get('gender')) - { - $user_gender = ''; - return $user_gender; - } - else - { - switch ($gender) - { - case MALE: - $user_gender = ''. $lang['GENDER_SELECT'][MALE] .''; - break; - case FEMALE: - $user_gender = ''. $lang['GENDER_SELECT'][FEMALE] .''; - break; - default: - $user_gender = ''. $lang['GENDER_SELECT'][NOGENDER] .''; - break; - } - } + if (!$di->config->get('gender')) { + $user_gender = ''; + return $user_gender; + } else { + switch ($gender) { + case MALE: + $user_gender = '' . $lang['GENDER_SELECT'][MALE] . ''; + break; + case FEMALE: + $user_gender = '' . $lang['GENDER_SELECT'][FEMALE] . ''; + break; + default: + $user_gender = '' . $lang['GENDER_SELECT'][NOGENDER] . ''; + break; + } + } - return $user_gender; + return $user_gender; } -function is_gold ($type) +function is_gold($type) { - global $lang, $tr_cfg; + global $lang, $tr_cfg; - if (!$tr_cfg['gold_silver_enabled']) - { - $is_gold = ''; - return $is_gold; - } - else - { - switch ($type) - { - case TOR_TYPE_GOLD: - $is_gold = ' '; - break; - case TOR_TYPE_SILVER: - $is_gold = ' '; - break; - default: - $is_gold = ''; - break; - } - } + if (!$tr_cfg['gold_silver_enabled']) { + $is_gold = ''; + return $is_gold; + } else { + switch ($type) { + case TOR_TYPE_GOLD: + $is_gold = ' '; + break; + case TOR_TYPE_SILVER: + $is_gold = ' '; + break; + default: + $is_gold = ''; + break; + } + } - return $is_gold; + return $is_gold; } -function update_atom ($type, $id) +function update_atom($type, $id) { - require_once(INC_DIR .'functions_atom.php'); + require_once(INC_DIR . 'functions_atom.php'); - switch ($type) - { - case 'user': - update_user_feed($id, get_username($id)); - break; + switch ($type) { + case 'user': + update_user_feed($id, get_username($id)); + break; - case 'topic': - $topic_poster = (int) DB()->fetch_row("SELECT topic_poster FROM ". BB_TOPICS ." WHERE topic_id = $id LIMIT 1", 'topic_poster'); - update_user_feed($topic_poster, get_username($topic_poster)); - break; - } + case 'topic': + $topic_poster = (int)DB()->fetch_row("SELECT topic_poster FROM " . BB_TOPICS . " WHERE topic_id = $id LIMIT 1", 'topic_poster'); + update_user_feed($topic_poster, get_username($topic_poster)); + break; + } } -function hash_search ($hash) +function hash_search($hash) { - global $lang; + global $lang; - $hash = htmlCHR(trim($hash)); + $hash = htmlCHR(trim($hash)); - if (!isset($hash) || mb_strlen($hash, 'UTF-8') != 40) - { - bb_die(sprintf($lang['HASH_INVALID'], $hash)); - } + if (!isset($hash) || mb_strlen($hash, 'UTF-8') != 40) { + bb_die(sprintf($lang['HASH_INVALID'], $hash)); + } - $info_hash = DB()->escape(pack("H*", $hash)); + $info_hash = DB()->escape(pack("H*", $hash)); - if ($row = DB()->fetch_row("SELECT topic_id FROM " . BB_BT_TORRENTS . " WHERE info_hash = '$info_hash'")) - { - redirect(TOPIC_URL . $row['topic_id']); - } - else - { - bb_die(sprintf($lang['HASH_NOT_FOUND'], $hash)); - } + if ($row = DB()->fetch_row("SELECT topic_id FROM " . BB_BT_TORRENTS . " WHERE info_hash = '$info_hash'")) { + redirect(TOPIC_URL . $row['topic_id']); + } else { + bb_die(sprintf($lang['HASH_NOT_FOUND'], $hash)); + } } -function bb_captcha ($mode, $callback = '') +function bb_captcha($mode, $callback = '') { - global $lang; + global $lang; - $di = \TorrentPier\Di::getInstance(); + $di = \TorrentPier\Di::getInstance(); - $secret = $di->config->get('captcha.secret_key'); - $public = $di->config->get('captcha.public_key'); - $cp_theme = $di->config->get('captcha.theme'); + $secret = $di->config->get('captcha.secret_key'); + $public = $di->config->get('captcha.public_key'); + $cp_theme = $di->config->get('captcha.theme'); - if (!$public && !$secret) - { - bb_die($lang['CAPTCHA_SETTINGS']); - } + if (!$public && !$secret) { + bb_die($lang['CAPTCHA_SETTINGS']); + } - switch ($mode) - { - case 'get': - return " + switch ($mode) { + case 'get': + return "
        "; - break; + break; - case 'check': + case 'check': $resp = $di->captcha->verify( $di->request->get('g-recaptcha-response', ''), $di->request->server->get('REMOTE_ADDR') ); - if ($resp->isSuccess()) - { - return true; - } - break; + if ($resp->isSuccess()) { + return true; + } + break; - default: - bb_simple_die(__FUNCTION__ . ": invalid mode '$mode'"); - } - return false; -} \ No newline at end of file + default: + bb_simple_die(__FUNCTION__ . ": invalid mode '$mode'"); + } + return false; +} diff --git a/library/includes/functions_admin.php b/library/includes/functions_admin.php index 04efe3ef3..e1758475a 100644 --- a/library/includes/functions_admin.php +++ b/library/includes/functions_admin.php @@ -2,28 +2,25 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function sync_all_forums () +function sync_all_forums() { - foreach (DB()->fetch_rowset("SELECT forum_id FROM ". BB_FORUMS) as $row) - { - sync('forum', $row['forum_id']); - } + foreach (DB()->fetch_rowset("SELECT forum_id FROM " . BB_FORUMS) as $row) { + sync('forum', $row['forum_id']); + } } -function sync ($type, $id) +function sync($type, $id) { - switch ($type) - { - case 'forum': + switch ($type) { + case 'forum': - if (!$forum_csv = get_id_csv($id)) - { - break; - } - // sync posts - $tmp_sync_forums = 'tmp_sync_forums'; + if (!$forum_csv = get_id_csv($id)) { + break; + } + // sync posts + $tmp_sync_forums = 'tmp_sync_forums'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_sync_forums ( forum_id SMALLINT UNSIGNED NOT NULL DEFAULT '0', forum_last_post_id INT UNSIGNED NOT NULL DEFAULT '0', @@ -33,13 +30,13 @@ function sync ($type, $id) PRIMARY KEY (forum_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_sync_forums"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_sync_forums"); - // начальное обнуление значений - $forum_ary = explode(',', $forum_csv); - DB()->query("REPLACE INTO $tmp_sync_forums (forum_id) VALUES(". join('),(', $forum_ary) .")"); + // начальное обнуление значений + $forum_ary = explode(',', $forum_csv); + DB()->query("REPLACE INTO $tmp_sync_forums (forum_id) VALUES(" . join('),(', $forum_ary) . ")"); - DB()->query(" + DB()->query(" REPLACE INTO $tmp_sync_forums (forum_id, forum_last_post_id, forum_last_topic_time, forum_posts, forum_topics) SELECT @@ -48,14 +45,14 @@ function sync ($type, $id) MAX(topic_time), SUM(topic_replies) + COUNT(topic_id), COUNT(topic_id) - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE forum_id IN($forum_csv) GROUP BY forum_id "); - DB()->query(" + DB()->query(" UPDATE - $tmp_sync_forums tmp, ". BB_FORUMS ." f + $tmp_sync_forums tmp, " . BB_FORUMS . " f SET f.forum_last_post_id = tmp.forum_last_post_id, f.forum_last_topic_time = tmp.forum_last_topic_time, @@ -65,25 +62,24 @@ function sync ($type, $id) f.forum_id = tmp.forum_id "); - DB()->query("DROP TEMPORARY TABLE $tmp_sync_forums"); + DB()->query("DROP TEMPORARY TABLE $tmp_sync_forums"); - break; + break; - case 'topic': + case 'topic': - $all_topics = ($id === 'all'); + $all_topics = ($id === 'all'); - if (!$all_topics && !($topic_csv = get_id_csv($id))) - { - break; - } + if (!$all_topics && !($topic_csv = get_id_csv($id))) { + break; + } - // Проверка на остаточные записи об уже удаленных топиках - DB()->query("DELETE FROM ". BB_TOPICS ." WHERE topic_first_post_id NOT IN (SELECT post_id FROM ". BB_POSTS .")"); + // Проверка на остаточные записи об уже удаленных топиках + DB()->query("DELETE FROM " . BB_TOPICS . " WHERE topic_first_post_id NOT IN (SELECT post_id FROM " . BB_POSTS . ")"); - $tmp_sync_topics = 'tmp_sync_topics'; + $tmp_sync_topics = 'tmp_sync_topics'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_sync_topics ( topic_id INT UNSIGNED NOT NULL DEFAULT '0', total_posts INT UNSIGNED NOT NULL DEFAULT '0', @@ -93,11 +89,11 @@ function sync ($type, $id) PRIMARY KEY (topic_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_sync_topics"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_sync_topics"); - $where_sql = (!$all_topics) ? "AND t.topic_id IN($topic_csv)" : ''; + $where_sql = (!$all_topics) ? "AND t.topic_id IN($topic_csv)" : ''; - DB()->query(" + DB()->query(" INSERT INTO $tmp_sync_topics SELECT t.topic_id, @@ -105,16 +101,16 @@ function sync ($type, $id) MIN(p.post_id) AS topic_first_post_id, MAX(p.post_id) AS topic_last_post_id, MAX(p.post_time) AS topic_last_post_time - FROM ". BB_TOPICS ." t - LEFT JOIN ". BB_POSTS ." p ON(p.topic_id = t.topic_id) - WHERE t.topic_status != ". TOPIC_MOVED ." + FROM " . BB_TOPICS . " t + LEFT JOIN " . BB_POSTS . " p ON(p.topic_id = t.topic_id) + WHERE t.topic_status != " . TOPIC_MOVED . " $where_sql GROUP BY t.topic_id "); - DB()->query(" + DB()->query(" UPDATE - $tmp_sync_topics tmp, ". BB_TOPICS ." t + $tmp_sync_topics tmp, " . BB_TOPICS . " t SET t.topic_replies = tmp.total_posts - 1, t.topic_first_post_id = tmp.topic_first_post_id, @@ -124,704 +120,637 @@ function sync ($type, $id) t.topic_id = tmp.topic_id "); - if ($topics = DB()->fetch_rowset("SELECT topic_id FROM ". $tmp_sync_topics ." WHERE total_posts = 0", 'topic_id')) - { - topic_delete($topics); - } + if ($topics = DB()->fetch_rowset("SELECT topic_id FROM " . $tmp_sync_topics . " WHERE total_posts = 0", 'topic_id')) { + topic_delete($topics); + } - DB()->query("DROP TEMPORARY TABLE $tmp_sync_topics"); + DB()->query("DROP TEMPORARY TABLE $tmp_sync_topics"); - break; + break; - case 'user_posts': + case 'user_posts': - $all_users = ($id === 'all'); + $all_users = ($id === 'all'); - if (!$all_users && !($user_csv = get_id_csv($id))) - { - break; - } + if (!$all_users && !($user_csv = get_id_csv($id))) { + break; + } - $tmp_user_posts = 'tmp_sync_user_posts'; + $tmp_user_posts = 'tmp_sync_user_posts'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_user_posts ( user_id INT NOT NULL DEFAULT '0', user_posts MEDIUMINT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (user_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_user_posts"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_user_posts"); - // Set posts count = 0 and then update to real count - $where_user_sql = (!$all_users) ? "AND user_id IN($user_csv)" : "AND user_posts != 0"; - $where_post_sql = (!$all_users) ? "AND poster_id IN($user_csv)" : ''; + // Set posts count = 0 and then update to real count + $where_user_sql = (!$all_users) ? "AND user_id IN($user_csv)" : "AND user_posts != 0"; + $where_post_sql = (!$all_users) ? "AND poster_id IN($user_csv)" : ''; - DB()->query(" + DB()->query(" REPLACE INTO $tmp_user_posts SELECT user_id, 0 - FROM ". BB_USERS ." - WHERE user_id != ". GUEST_UID ." + FROM " . BB_USERS . " + WHERE user_id != " . GUEST_UID . " $where_user_sql UNION SELECT poster_id, COUNT(*) - FROM ". BB_POSTS ." - WHERE poster_id != ". GUEST_UID ." + FROM " . BB_POSTS . " + WHERE poster_id != " . GUEST_UID . " $where_post_sql GROUP BY poster_id "); - DB()->query(" + DB()->query(" UPDATE - $tmp_user_posts tmp, ". BB_USERS ." u + $tmp_user_posts tmp, " . BB_USERS . " u SET u.user_posts = tmp.user_posts WHERE u.user_id = tmp.user_id "); - DB()->query("DROP TEMPORARY TABLE $tmp_user_posts"); + DB()->query("DROP TEMPORARY TABLE $tmp_user_posts"); - break; - } + break; + } } -function topic_delete ($mode_or_topic_id, $forum_id = null, $prune_time = 0, $prune_all = false) +function topic_delete($mode_or_topic_id, $forum_id = null, $prune_time = 0, $prune_all = false) { - global $lang, $log_action; + global $lang, $log_action; - $prune = ($mode_or_topic_id === 'prune'); + $prune = ($mode_or_topic_id === 'prune'); - if (!$prune && !($topic_csv = get_id_csv($mode_or_topic_id))) - { - return false; - } + if (!$prune && !($topic_csv = get_id_csv($mode_or_topic_id))) { + return false; + } - $log_topics = $sync_forums = array(); + $log_topics = $sync_forums = array(); - if ($prune) - { - $sync_forums[$forum_id] = true; - } - else - { - $where_sql = ($forum_csv = get_id_csv($forum_id)) ? "AND forum_id IN($forum_csv)" : ''; + if ($prune) { + $sync_forums[$forum_id] = true; + } else { + $where_sql = ($forum_csv = get_id_csv($forum_id)) ? "AND forum_id IN($forum_csv)" : ''; - $sql = " + $sql = " SELECT topic_id, forum_id, topic_title, topic_status - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) $where_sql "; - $topic_csv = array(); + $topic_csv = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $topic_csv[] = $row['topic_id']; - $log_topics[] = $row; - $sync_forums[$row['forum_id']] = true; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topic_csv[] = $row['topic_id']; + $log_topics[] = $row; + $sync_forums[$row['forum_id']] = true; + } - if (!$topic_csv = get_id_csv($topic_csv)) - { - return false; - } - } + if (!$topic_csv = get_id_csv($topic_csv)) { + return false; + } + } - // Get topics to delete - $tmp_delete_topics = 'tmp_delete_topics'; + // Get topics to delete + $tmp_delete_topics = 'tmp_delete_topics'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_delete_topics ( topic_id INT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (topic_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_delete_topics"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_delete_topics"); - $where_sql = ($prune) ? "forum_id = $forum_id" : "topic_id IN($topic_csv)"; - $where_sql .= ($prune && $prune_time) ? " AND topic_last_post_time < $prune_time" : ''; - $where_sql .= ($prune && !$prune_all) ? " AND topic_type NOT IN(". POST_ANNOUNCE .",". POST_STICKY .")": ''; + $where_sql = ($prune) ? "forum_id = $forum_id" : "topic_id IN($topic_csv)"; + $where_sql .= ($prune && $prune_time) ? " AND topic_last_post_time < $prune_time" : ''; + $where_sql .= ($prune && !$prune_all) ? " AND topic_type NOT IN(" . POST_ANNOUNCE . "," . POST_STICKY . ")" : ''; - DB()->query("INSERT INTO $tmp_delete_topics SELECT topic_id FROM ". BB_TOPICS ." WHERE $where_sql"); + DB()->query("INSERT INTO $tmp_delete_topics SELECT topic_id FROM " . BB_TOPICS . " WHERE $where_sql"); - // Get topics count - $row = DB()->fetch_row("SELECT COUNT(*) AS topics_count FROM $tmp_delete_topics"); + // Get topics count + $row = DB()->fetch_row("SELECT COUNT(*) AS topics_count FROM $tmp_delete_topics"); - if (!$deleted_topics_count = $row['topics_count']) - { - DB()->query("DROP TEMPORARY TABLE $tmp_delete_topics"); - return 0; - } + if (!$deleted_topics_count = $row['topics_count']) { + DB()->query("DROP TEMPORARY TABLE $tmp_delete_topics"); + return 0; + } - // Update user posts count - $tmp_user_posts = 'tmp_user_posts'; + // Update user posts count + $tmp_user_posts = 'tmp_user_posts'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_user_posts ( user_id INT NOT NULL DEFAULT '0', user_posts MEDIUMINT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (user_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_user_posts"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_user_posts"); - DB()->query(" + DB()->query(" INSERT INTO $tmp_user_posts SELECT p.poster_id, COUNT(p.post_id) - FROM ". $tmp_delete_topics ." del, ". BB_POSTS ." p + FROM " . $tmp_delete_topics . " del, " . BB_POSTS . " p WHERE p.topic_id = del.topic_id - AND p.poster_id != ". GUEST_UID ." + AND p.poster_id != " . GUEST_UID . " GROUP BY p.poster_id "); - // Get array for atom update - $atom_csv = array(); - foreach (DB()->fetch_rowset('SELECT user_id FROM '.$tmp_user_posts) as $at) - { - $atom_csv[] = $at['user_id']; - } + // Get array for atom update + $atom_csv = array(); + foreach (DB()->fetch_rowset('SELECT user_id FROM ' . $tmp_user_posts) as $at) { + $atom_csv[] = $at['user_id']; + } - DB()->query(" + DB()->query(" UPDATE - $tmp_user_posts tmp, ". BB_USERS ." u + $tmp_user_posts tmp, " . BB_USERS . " u SET u.user_posts = u.user_posts - tmp.user_posts WHERE u.user_id = tmp.user_id "); - DB()->query("DROP TEMPORARY TABLE $tmp_user_posts"); + DB()->query("DROP TEMPORARY TABLE $tmp_user_posts"); - // Delete votes - DB()->query(" + // Delete votes + DB()->query(" DELETE pv, pu - FROM ". $tmp_delete_topics ." del - LEFT JOIN ". BB_POLL_VOTES ." pv USING(topic_id) - LEFT JOIN ". BB_POLL_USERS ." pu USING(topic_id) + FROM " . $tmp_delete_topics . " del + LEFT JOIN " . BB_POLL_VOTES . " pv USING(topic_id) + LEFT JOIN " . BB_POLL_USERS . " pu USING(topic_id) "); - // Delete posts, posts_text - DB()->query(" + // Delete posts, posts_text + DB()->query(" DELETE p, pt, ph, ps - FROM ". $tmp_delete_topics ." del - LEFT JOIN ". BB_POSTS ." p ON(p.topic_id = del.topic_id) - LEFT JOIN ". BB_POSTS_TEXT ." pt ON(pt.post_id = p.post_id) - LEFT JOIN ". BB_POSTS_HTML ." ph ON(ph.post_id = p.post_id) - LEFT JOIN ". BB_POSTS_SEARCH ." ps ON(ps.post_id = p.post_id) + FROM " . $tmp_delete_topics . " del + LEFT JOIN " . BB_POSTS . " p ON(p.topic_id = del.topic_id) + LEFT JOIN " . BB_POSTS_TEXT . " pt ON(pt.post_id = p.post_id) + LEFT JOIN " . BB_POSTS_HTML . " ph ON(ph.post_id = p.post_id) + LEFT JOIN " . BB_POSTS_SEARCH . " ps ON(ps.post_id = p.post_id) "); - // Delete topics, topics watch - DB()->query(" + // Delete topics, topics watch + DB()->query(" DELETE t, tw - FROM ". $tmp_delete_topics ." del - LEFT JOIN ". BB_TOPICS ." t USING(topic_id) - LEFT JOIN ". BB_TOPICS_WATCH ." tw USING(topic_id) + FROM " . $tmp_delete_topics . " del + LEFT JOIN " . BB_TOPICS . " t USING(topic_id) + LEFT JOIN " . BB_TOPICS_WATCH . " tw USING(topic_id) "); - // Delete topic moved stubs - DB()->query(" + // Delete topic moved stubs + DB()->query(" DELETE t - FROM ". $tmp_delete_topics ." del, ". BB_TOPICS ." t + FROM " . $tmp_delete_topics . " del, " . BB_TOPICS . " t WHERE t.topic_moved_id = del.topic_id "); - // Delete torrents - DB()->query(" + // Delete torrents + DB()->query(" DELETE tor, tr, dl - FROM ". $tmp_delete_topics ." del - LEFT JOIN ". BB_BT_TORRENTS ." tor USING(topic_id) - LEFT JOIN ". BB_BT_TRACKER ." tr USING(topic_id) - LEFT JOIN ". BB_BT_DLSTATUS ." dl USING(topic_id) + FROM " . $tmp_delete_topics . " del + LEFT JOIN " . BB_BT_TORRENTS . " tor USING(topic_id) + LEFT JOIN " . BB_BT_TRACKER . " tr USING(topic_id) + LEFT JOIN " . BB_BT_DLSTATUS . " dl USING(topic_id) "); - // Log action - if ($prune) - { - // TODO: логирование для массового удаления - } - else - { - foreach ($log_topics as $row) - { - if ($row['topic_status'] == TOPIC_MOVED) - { - $row['topic_title'] = ''. $lang['TOPIC_MOVED'] .' '. $row['topic_title']; - } + // Log action + if ($prune) { + // TODO: логирование для массового удаления + } else { + foreach ($log_topics as $row) { + if ($row['topic_status'] == TOPIC_MOVED) { + $row['topic_title'] = '' . $lang['TOPIC_MOVED'] . ' ' . $row['topic_title']; + } - $log_action->mod('mod_topic_delete', array( - 'forum_id' => $row['forum_id'], - 'topic_id' => $row['topic_id'], - 'topic_title' => $row['topic_title'], - )); - } - } + $log_action->mod('mod_topic_delete', array( + 'forum_id' => $row['forum_id'], + 'topic_id' => $row['topic_id'], + 'topic_title' => $row['topic_title'], + )); + } + } - // Sync - sync('forum', array_keys($sync_forums)); + // Sync + sync('forum', array_keys($sync_forums)); - // Update atom feed - foreach ($atom_csv as $atom) - { - update_atom('user', $atom); - } + // Update atom feed + foreach ($atom_csv as $atom) { + update_atom('user', $atom); + } - DB()->query("DROP TEMPORARY TABLE $tmp_delete_topics"); + DB()->query("DROP TEMPORARY TABLE $tmp_delete_topics"); - return $deleted_topics_count; + return $deleted_topics_count; } -function topic_move ($topic_id, $to_forum_id, $from_forum_id = null, $leave_shadow = false, $insert_bot_msg = false) +function topic_move($topic_id, $to_forum_id, $from_forum_id = null, $leave_shadow = false, $insert_bot_msg = false) { - global $log_action; + global $log_action; - $to_forum_id = (int) $to_forum_id; + $to_forum_id = (int)$to_forum_id; - // Verify input params - if (!$topic_csv = get_id_csv($topic_id)) - { - return false; - } - if (!forum_exists($to_forum_id)) - { - return false; - } - if ($from_forum_id && (!forum_exists($from_forum_id) || $to_forum_id == $from_forum_id)) - { - return false; - } + // Verify input params + if (!$topic_csv = get_id_csv($topic_id)) { + return false; + } + if (!forum_exists($to_forum_id)) { + return false; + } + if ($from_forum_id && (!forum_exists($from_forum_id) || $to_forum_id == $from_forum_id)) { + return false; + } - // Get topics info - $where_sql = ($forum_csv = get_id_csv($from_forum_id)) ? "AND forum_id IN($forum_csv)" : ''; + // Get topics info + $where_sql = ($forum_csv = get_id_csv($from_forum_id)) ? "AND forum_id IN($forum_csv)" : ''; - $sql = "SELECT * FROM ". BB_TOPICS ." WHERE topic_id IN($topic_csv) AND topic_status != ". TOPIC_MOVED ." $where_sql"; + $sql = "SELECT * FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) AND topic_status != " . TOPIC_MOVED . " $where_sql"; - $topics = array(); - $sync_forums = array($to_forum_id => true); + $topics = array(); + $sync_forums = array($to_forum_id => true); - foreach (DB()->fetch_rowset($sql) as $row) - { - if ($row['forum_id'] != $to_forum_id) - { - $topics[$row['topic_id']] = $row; - $sync_forums[$row['forum_id']] = true; - } - } + foreach (DB()->fetch_rowset($sql) as $row) { + if ($row['forum_id'] != $to_forum_id) { + $topics[$row['topic_id']] = $row; + $sync_forums[$row['forum_id']] = true; + } + } - if (!$topics || !($topic_csv = get_id_csv(array_keys($topics)))) - { - return false; - } + if (!$topics || !($topic_csv = get_id_csv(array_keys($topics)))) { + return false; + } - // Insert topic in the old forum that indicates that the topic has moved - if ($leave_shadow) - { - $shadows = array(); + // Insert topic in the old forum that indicates that the topic has moved + if ($leave_shadow) { + $shadows = array(); - foreach ($topics as $topic_id => $row) - { - $shadows[] = array( - 'forum_id' => $row['forum_id'], - 'topic_title' => $row['topic_title'], - 'topic_poster' => $row['topic_poster'], - 'topic_time' => TIMENOW, - 'topic_status' => TOPIC_MOVED, - 'topic_type' => POST_NORMAL, - 'topic_vote' => $row['topic_vote'], - 'topic_views' => $row['topic_views'], - 'topic_replies' => $row['topic_replies'], - 'topic_first_post_id' => $row['topic_first_post_id'], - 'topic_last_post_id' => $row['topic_last_post_id'], - 'topic_moved_id' => $topic_id, - 'topic_last_post_time' => $row['topic_last_post_time'], - ); - } - if ($sql_args = DB()->build_array('MULTI_INSERT', $shadows)) - { - DB()->query("INSERT INTO ". BB_TOPICS . $sql_args); - } - } + foreach ($topics as $topic_id => $row) { + $shadows[] = array( + 'forum_id' => $row['forum_id'], + 'topic_title' => $row['topic_title'], + 'topic_poster' => $row['topic_poster'], + 'topic_time' => TIMENOW, + 'topic_status' => TOPIC_MOVED, + 'topic_type' => POST_NORMAL, + 'topic_vote' => $row['topic_vote'], + 'topic_views' => $row['topic_views'], + 'topic_replies' => $row['topic_replies'], + 'topic_first_post_id' => $row['topic_first_post_id'], + 'topic_last_post_id' => $row['topic_last_post_id'], + 'topic_moved_id' => $topic_id, + 'topic_last_post_time' => $row['topic_last_post_time'], + ); + } + if ($sql_args = DB()->build_array('MULTI_INSERT', $shadows)) { + DB()->query("INSERT INTO " . BB_TOPICS . $sql_args); + } + } - DB()->query("UPDATE ". BB_TOPICS ." SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); - DB()->query("UPDATE ". BB_POSTS ." SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); - DB()->query("UPDATE ". BB_BT_TORRENTS ." SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); + DB()->query("UPDATE " . BB_TOPICS . " SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); + DB()->query("UPDATE " . BB_POSTS . " SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET forum_id = $to_forum_id WHERE topic_id IN($topic_csv)"); - // Bot - if ($insert_bot_msg) - { - foreach ($topics as $topic_id => $row) - { - insert_post('after_move', $topic_id, $to_forum_id, $row['forum_id']); - } - sync('topic', array_keys($topics)); - } + // Bot + if ($insert_bot_msg) { + foreach ($topics as $topic_id => $row) { + insert_post('after_move', $topic_id, $to_forum_id, $row['forum_id']); + } + sync('topic', array_keys($topics)); + } - // Sync - sync('forum', array_keys($sync_forums)); + // Sync + sync('forum', array_keys($sync_forums)); - // Log action - foreach ($topics as $topic_id => $row) - { - $log_action->mod('mod_topic_move', array( - 'forum_id' => $row['forum_id'], - 'forum_id_new' => $to_forum_id, - 'topic_id' => $topic_id, - 'topic_title' => $row['topic_title'], - )); - } + // Log action + foreach ($topics as $topic_id => $row) { + $log_action->mod('mod_topic_move', array( + 'forum_id' => $row['forum_id'], + 'forum_id_new' => $to_forum_id, + 'topic_id' => $topic_id, + 'topic_title' => $row['topic_title'], + )); + } - return true; + return true; } -function topic_lock_unlock ($topic_id, $mode, $forum_id = null) +function topic_lock_unlock($topic_id, $mode, $forum_id = null) { - global $log_action; + global $log_action; - if (!$topic_csv = get_id_csv($topic_id)) - { - return false; - } - $new_topic_status = ($mode == 'lock') ? TOPIC_LOCKED : TOPIC_UNLOCKED; - $forum_sql = ($forum_id) ? " AND forum_id = ". (int) $forum_id : ''; + if (!$topic_csv = get_id_csv($topic_id)) { + return false; + } + $new_topic_status = ($mode == 'lock') ? TOPIC_LOCKED : TOPIC_UNLOCKED; + $forum_sql = ($forum_id) ? " AND forum_id = " . (int)$forum_id : ''; - $sql = " + $sql = " SELECT topic_id, topic_title - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) - AND topic_status != ". TOPIC_MOVED ." + AND topic_status != " . TOPIC_MOVED . " AND topic_status != $new_topic_status $forum_sql "; - $topic_ary = array(); + $topic_ary = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $topic_ary[] = $row['topic_id']; - $log_topics[$row['topic_id']] = $row['topic_title']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topic_ary[] = $row['topic_id']; + $log_topics[$row['topic_id']] = $row['topic_title']; + } - if (!$topic_csv = get_id_csv($topic_ary)) - { - return false; - } + if (!$topic_csv = get_id_csv($topic_ary)) { + return false; + } - DB()->query("UPDATE ". BB_TOPICS ." SET topic_status = $new_topic_status WHERE topic_id IN($topic_csv)"); + DB()->query("UPDATE " . BB_TOPICS . " SET topic_status = $new_topic_status WHERE topic_id IN($topic_csv)"); - // Log action - $type = ($mode == 'lock') ? 'mod_topic_lock' : 'mod_topic_unlock'; + // Log action + $type = ($mode == 'lock') ? 'mod_topic_lock' : 'mod_topic_unlock'; - foreach ($log_topics as $topic_id => $topic_title) - { - $log_action->mod($type, array( - 'forum_id' => $forum_id, - 'topic_id' => $topic_id, - 'topic_title' => $topic_title, - )); - } + foreach ($log_topics as $topic_id => $topic_title) { + $log_action->mod($type, array( + 'forum_id' => $forum_id, + 'topic_id' => $topic_id, + 'topic_title' => $topic_title, + )); + } - return true; + return true; } -function topic_stick_unstick ($topic_id, $mode, $forum_id = null) +function topic_stick_unstick($topic_id, $mode, $forum_id = null) { - if (!$topic_csv = get_id_csv($topic_id)) - { - return false; - } - $new_topic_type = ($mode == 'stick') ? POST_STICKY : POST_NORMAL; - $forum_sql = ($forum_id) ? " AND forum_id = ". (int) $forum_id : ''; + if (!$topic_csv = get_id_csv($topic_id)) { + return false; + } + $new_topic_type = ($mode == 'stick') ? POST_STICKY : POST_NORMAL; + $forum_sql = ($forum_id) ? " AND forum_id = " . (int)$forum_id : ''; - $sql = " + $sql = " SELECT topic_id - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) - AND topic_status != ". TOPIC_MOVED ." + AND topic_status != " . TOPIC_MOVED . " AND topic_type != $new_topic_type $forum_sql "; - $topic_ary = DB()->fetch_rowset($sql, 'topic_id'); + $topic_ary = DB()->fetch_rowset($sql, 'topic_id'); - if (!$topic_csv = get_id_csv($topic_ary)) - { - return false; - } + if (!$topic_csv = get_id_csv($topic_ary)) { + return false; + } - DB()->query("UPDATE ". BB_TOPICS ." SET topic_type = $new_topic_type WHERE topic_id IN($topic_csv)"); + DB()->query("UPDATE " . BB_TOPICS . " SET topic_type = $new_topic_type WHERE topic_id IN($topic_csv)"); - return ( DB()->affected_rows() > 0 ); + return (DB()->affected_rows() > 0); } // $exclude_first - в режиме удаления сообщений по списку исключать первое сообщение в теме -function post_delete ($mode_or_post_id, $user_id = null, $exclude_first = true) +function post_delete($mode_or_post_id, $user_id = null, $exclude_first = true) { - global $log_action; + global $log_action; - $del_user_posts = ($mode_or_post_id === 'user'); // Delete all user posts + $del_user_posts = ($mode_or_post_id === 'user'); // Delete all user posts - // Get required params - if ($del_user_posts) - { - if (!$user_csv = get_id_csv($user_id)) return false; - } - else - { - if (!$post_csv = get_id_csv($mode_or_post_id)) return false; + // Get required params + if ($del_user_posts) { + if (!$user_csv = get_id_csv($user_id)) return false; + } else { + if (!$post_csv = get_id_csv($mode_or_post_id)) return false; - // фильтр заглавных сообщений в теме - if ($exclude_first) - { - $sql = "SELECT topic_first_post_id FROM ". BB_TOPICS ." WHERE topic_first_post_id IN($post_csv)"; + // фильтр заглавных сообщений в теме + if ($exclude_first) { + $sql = "SELECT topic_first_post_id FROM " . BB_TOPICS . " WHERE topic_first_post_id IN($post_csv)"; - if ($first_posts = DB()->fetch_rowset($sql, 'topic_first_post_id')) - { - $posts_without_first = array_diff(explode(',', $post_csv), $first_posts); + if ($first_posts = DB()->fetch_rowset($sql, 'topic_first_post_id')) { + $posts_without_first = array_diff(explode(',', $post_csv), $first_posts); - if (!$post_csv = get_id_csv($posts_without_first)) - { - return false; - } - } - } - } + if (!$post_csv = get_id_csv($posts_without_first)) { + return false; + } + } + } + } - // Collect data for logs, sync.. - $log_topics = $sync_forums = $sync_topics = $sync_users = array(); + // Collect data for logs, sync.. + $log_topics = $sync_forums = $sync_topics = $sync_users = array(); - if ($del_user_posts) - { - $sync_topics = DB()->fetch_rowset("SELECT DISTINCT topic_id FROM ". BB_POSTS ." WHERE poster_id IN($user_csv)", 'topic_id'); + if ($del_user_posts) { + $sync_topics = DB()->fetch_rowset("SELECT DISTINCT topic_id FROM " . BB_POSTS . " WHERE poster_id IN($user_csv)", 'topic_id'); - if ($topic_csv = get_id_csv($sync_topics)) - { - foreach (DB()->fetch_rowset("SELECT DISTINCT forum_id FROM ". BB_TOPICS ." WHERE topic_id IN($topic_csv)") as $row) - { - $sync_forums[$row['forum_id']] = true; - } - } - $sync_users = explode(',', $user_csv); - } - else - { - $sql = " + if ($topic_csv = get_id_csv($sync_topics)) { + foreach (DB()->fetch_rowset("SELECT DISTINCT forum_id FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv)") as $row) { + $sync_forums[$row['forum_id']] = true; + } + } + $sync_users = explode(',', $user_csv); + } else { + $sql = " SELECT p.topic_id, p.forum_id, t.topic_title - FROM ". BB_POSTS ." p, ". BB_TOPICS ." t + FROM " . BB_POSTS . " p, " . BB_TOPICS . " t WHERE p.post_id IN($post_csv) AND t.topic_id = p.topic_id GROUP BY t.topic_id "; - foreach (DB()->fetch_rowset($sql) as $row) - { - $log_topics[] = $row; - $sync_topics[] = $row['topic_id']; - $sync_forums[$row['forum_id']] = true; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $log_topics[] = $row; + $sync_topics[] = $row['topic_id']; + $sync_forums[$row['forum_id']] = true; + } - $sync_users = DB()->fetch_rowset("SELECT DISTINCT poster_id FROM ". BB_POSTS ." WHERE post_id IN($post_csv)", 'poster_id'); - } + $sync_users = DB()->fetch_rowset("SELECT DISTINCT poster_id FROM " . BB_POSTS . " WHERE post_id IN($post_csv)", 'poster_id'); + } - // Get all post_id for deleting - $tmp_delete_posts = 'tmp_delete_posts'; + // Get all post_id for deleting + $tmp_delete_posts = 'tmp_delete_posts'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_delete_posts ( post_id INT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (post_id) ) ENGINE = MEMORY "); - DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_delete_posts"); + DB()->add_shutdown_query("DROP TEMPORARY TABLE IF EXISTS $tmp_delete_posts"); - if ($del_user_posts) - { - $where_sql = "poster_id IN($user_csv)"; + if ($del_user_posts) { + $where_sql = "poster_id IN($user_csv)"; - $exclude_posts_ary = array(); - foreach (DB()->fetch_rowset("SELECT topic_first_post_id FROM ". BB_TOPICS ." WHERE topic_poster IN($user_csv)") as $row) - { - $exclude_posts_ary[] = $row['topic_first_post_id']; - } - if ($exclude_posts_csv = get_id_csv($exclude_posts_ary)) - { - $where_sql .= " AND post_id NOT IN($exclude_posts_csv)"; - } - } - else - { - $where_sql = "post_id IN($post_csv)"; - } + $exclude_posts_ary = array(); + foreach (DB()->fetch_rowset("SELECT topic_first_post_id FROM " . BB_TOPICS . " WHERE topic_poster IN($user_csv)") as $row) { + $exclude_posts_ary[] = $row['topic_first_post_id']; + } + if ($exclude_posts_csv = get_id_csv($exclude_posts_ary)) { + $where_sql .= " AND post_id NOT IN($exclude_posts_csv)"; + } + } else { + $where_sql = "post_id IN($post_csv)"; + } - DB()->query("INSERT INTO $tmp_delete_posts SELECT post_id FROM ". BB_POSTS ." WHERE $where_sql"); + DB()->query("INSERT INTO $tmp_delete_posts SELECT post_id FROM " . BB_POSTS . " WHERE $where_sql"); - // Deleted posts count - $row = DB()->fetch_row("SELECT COUNT(*) AS posts_count FROM $tmp_delete_posts"); + // Deleted posts count + $row = DB()->fetch_row("SELECT COUNT(*) AS posts_count FROM $tmp_delete_posts"); - if (!$deleted_posts_count = $row['posts_count']) - { - DB()->query("DROP TEMPORARY TABLE $tmp_delete_posts"); - return 0; - } + if (!$deleted_posts_count = $row['posts_count']) { + DB()->query("DROP TEMPORARY TABLE $tmp_delete_posts"); + return 0; + } - // Delete posts, posts_text - DB()->query(" + // Delete posts, posts_text + DB()->query(" DELETE p, pt, ph, ps - FROM ". $tmp_delete_posts ." del - LEFT JOIN ". BB_POSTS ." p ON(p.post_id = del.post_id) - LEFT JOIN ". BB_POSTS_TEXT ." pt ON(pt.post_id = del.post_id) - LEFT JOIN ". BB_POSTS_HTML ." ph ON(ph.post_id = del.post_id) - LEFT JOIN ". BB_POSTS_SEARCH ." ps ON(ps.post_id = del.post_id) + FROM " . $tmp_delete_posts . " del + LEFT JOIN " . BB_POSTS . " p ON(p.post_id = del.post_id) + LEFT JOIN " . BB_POSTS_TEXT . " pt ON(pt.post_id = del.post_id) + LEFT JOIN " . BB_POSTS_HTML . " ph ON(ph.post_id = del.post_id) + LEFT JOIN " . BB_POSTS_SEARCH . " ps ON(ps.post_id = del.post_id) "); - // Log action - if ($del_user_posts) - { - $log_action->admin('mod_post_delete', array( - 'log_msg' => 'user: '. get_usernames_for_log($user_id) ."
        posts: $deleted_posts_count", - )); - } - else if (!defined('IN_CRON')) - { - foreach ($log_topics as $row) - { - $log_action->mod('mod_post_delete', array( - 'forum_id' => $row['forum_id'], - 'topic_id' => $row['topic_id'], - 'topic_title' => $row['topic_title'], - )); - } - } + // Log action + if ($del_user_posts) { + $log_action->admin('mod_post_delete', array( + 'log_msg' => 'user: ' . get_usernames_for_log($user_id) . "
        posts: $deleted_posts_count", + )); + } else if (!defined('IN_CRON')) { + foreach ($log_topics as $row) { + $log_action->mod('mod_post_delete', array( + 'forum_id' => $row['forum_id'], + 'topic_id' => $row['topic_id'], + 'topic_title' => $row['topic_title'], + )); + } + } - // Sync - sync('topic', $sync_topics); - sync('forum', array_keys($sync_forums)); - sync('user_posts', $sync_users); + // Sync + sync('topic', $sync_topics); + sync('forum', array_keys($sync_forums)); + sync('user_posts', $sync_users); - // Update atom feed - foreach ($sync_topics as $atom_topic) - { - update_atom('topic', $atom_topic); - } - foreach ($sync_users as $atom_user) - { - update_atom('user', $atom_user); - } + // Update atom feed + foreach ($sync_topics as $atom_topic) { + update_atom('topic', $atom_topic); + } + foreach ($sync_users as $atom_user) { + update_atom('user', $atom_user); + } - DB()->query("DROP TEMPORARY TABLE $tmp_delete_posts"); + DB()->query("DROP TEMPORARY TABLE $tmp_delete_posts"); - return $deleted_posts_count; + return $deleted_posts_count; } -function user_delete ($user_id, $delete_posts = false) +function user_delete($user_id, $delete_posts = false) { - global $log_action; + global $log_action; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$user_csv = get_id_csv($user_id)) - { - return false; - } - if (!$user_id = DB()->fetch_rowset("SELECT user_id FROM ". BB_USERS ." WHERE user_id IN($user_csv)", 'user_id')) - { - return false; - } - $user_csv = get_id_csv($user_id); + if (!$user_csv = get_id_csv($user_id)) { + return false; + } + if (!$user_id = DB()->fetch_rowset("SELECT user_id FROM " . BB_USERS . " WHERE user_id IN($user_csv)", 'user_id')) { + return false; + } + $user_csv = get_id_csv($user_id); - // LOG - $log_action->admin('adm_user_delete', array( - 'log_msg' => get_usernames_for_log($user_id), - )); + // LOG + $log_action->admin('adm_user_delete', array( + 'log_msg' => get_usernames_for_log($user_id), + )); - // Avatar - $result = DB()->query("SELECT user_id, avatar_ext_id FROM ". BB_USERS ." WHERE avatar_ext_id > 0 AND user_id IN($user_csv)"); + // Avatar + $result = DB()->query("SELECT user_id, avatar_ext_id FROM " . BB_USERS . " WHERE avatar_ext_id > 0 AND user_id IN($user_csv)"); - while ($row = DB()->fetch_next($result)) - { - delete_avatar($row['user_id'], $row['avatar_ext_id']); - } + while ($row = DB()->fetch_next($result)) { + delete_avatar($row['user_id'], $row['avatar_ext_id']); + } - if ($delete_posts) - { - post_delete('user', $user_id); - } - else - { - DB()->query("UPDATE ". BB_POSTS ." SET poster_id = ". DELETED ." WHERE poster_id IN($user_csv)"); - } + if ($delete_posts) { + post_delete('user', $user_id); + } else { + DB()->query("UPDATE " . BB_POSTS . " SET poster_id = " . DELETED . " WHERE poster_id IN($user_csv)"); + } - DB()->query("UPDATE ". BB_GROUPS ." SET group_moderator = 2 WHERE group_single_user = 0 AND group_moderator IN($user_csv)"); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_poster = ". DELETED ." WHERE topic_poster IN($user_csv)"); - DB()->query("UPDATE ". BB_BT_TORRENTS ." SET poster_id = ". DELETED ." WHERE poster_id IN($user_csv)"); + DB()->query("UPDATE " . BB_GROUPS . " SET group_moderator = 2 WHERE group_single_user = 0 AND group_moderator IN($user_csv)"); + DB()->query("UPDATE " . BB_TOPICS . " SET topic_poster = " . DELETED . " WHERE topic_poster IN($user_csv)"); + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET poster_id = " . DELETED . " WHERE poster_id IN($user_csv)"); - DB()->query(" + DB()->query(" DELETE ug, g, a - FROM ". BB_USER_GROUP ." ug - LEFT JOIN ". BB_GROUPS ." g ON(g.group_id = ug.group_id AND g.group_single_user = 1) - LEFT JOIN ". BB_AUTH_ACCESS ." a ON(a.group_id = g.group_id) + FROM " . BB_USER_GROUP . " ug + LEFT JOIN " . BB_GROUPS . " g ON(g.group_id = ug.group_id AND g.group_single_user = 1) + LEFT JOIN " . BB_AUTH_ACCESS . " a ON(a.group_id = g.group_id) WHERE ug.user_id IN($user_csv) "); - DB()->query(" + DB()->query(" DELETE u, ban, pu, s, tw, asn - FROM ". BB_USERS ." u - LEFT JOIN ". BB_BANLIST ." ban ON(ban.ban_userid = u.user_id) - LEFT JOIN ". BB_POLL_USERS ." pu ON(pu.user_id = u.user_id) - LEFT JOIN ". BB_SESSIONS ." s ON(s.session_user_id = u.user_id) - LEFT JOIN ". BB_TOPICS_WATCH ." tw ON(tw.user_id = u.user_id) - LEFT JOIN ". BB_AUTH_ACCESS_SNAP ." asn ON(asn.user_id = u.user_id) + FROM " . BB_USERS . " u + LEFT JOIN " . BB_BANLIST . " ban ON(ban.ban_userid = u.user_id) + LEFT JOIN " . BB_POLL_USERS . " pu ON(pu.user_id = u.user_id) + LEFT JOIN " . BB_SESSIONS . " s ON(s.session_user_id = u.user_id) + LEFT JOIN " . BB_TOPICS_WATCH . " tw ON(tw.user_id = u.user_id) + LEFT JOIN " . BB_AUTH_ACCESS_SNAP . " asn ON(asn.user_id = u.user_id) WHERE u.user_id IN($user_csv) "); - DB()->query(" + DB()->query(" DELETE btu, tr - FROM ". BB_BT_USERS ." btu - LEFT JOIN ". BB_BT_TRACKER ." tr ON(tr.user_id = btu.user_id) + FROM " . BB_BT_USERS . " btu + LEFT JOIN " . BB_BT_TRACKER . " tr ON(tr.user_id = btu.user_id) WHERE btu.user_id IN($user_csv) "); - // PM - DB()->query(" + // PM + DB()->query(" DELETE pm, pmt - FROM ". BB_PRIVMSGS ." pm - LEFT JOIN ". BB_PRIVMSGS_TEXT ." pmt ON(pmt.privmsgs_text_id = pm.privmsgs_id) + FROM " . BB_PRIVMSGS . " pm + LEFT JOIN " . BB_PRIVMSGS_TEXT . " pmt ON(pmt.privmsgs_text_id = pm.privmsgs_id) WHERE pm.privmsgs_from_userid IN($user_csv) - AND pm.privmsgs_type IN(". PRIVMSGS_SENT_MAIL .','. PRIVMSGS_SAVED_OUT_MAIL .") + AND pm.privmsgs_type IN(" . PRIVMSGS_SENT_MAIL . ',' . PRIVMSGS_SAVED_OUT_MAIL . ") "); - DB()->query(" + DB()->query(" DELETE pm, pmt - FROM ". BB_PRIVMSGS ." pm - LEFT JOIN ". BB_PRIVMSGS_TEXT ." pmt ON(pmt.privmsgs_text_id = pm.privmsgs_id) + FROM " . BB_PRIVMSGS . " pm + LEFT JOIN " . BB_PRIVMSGS_TEXT . " pmt ON(pmt.privmsgs_text_id = pm.privmsgs_id) WHERE pm.privmsgs_to_userid IN($user_csv) - AND pm.privmsgs_type IN(". PRIVMSGS_READ_MAIL .','. PRIVMSGS_SAVED_IN_MAIL .") + AND pm.privmsgs_type IN(" . PRIVMSGS_READ_MAIL . ',' . PRIVMSGS_SAVED_IN_MAIL . ") "); - DB()->query("UPDATE ". BB_PRIVMSGS ." SET privmsgs_from_userid = ". DELETED ." WHERE privmsgs_from_userid IN($user_csv)"); - DB()->query("UPDATE ". BB_PRIVMSGS ." SET privmsgs_to_userid = ". DELETED ." WHERE privmsgs_to_userid IN($user_csv)"); + DB()->query("UPDATE " . BB_PRIVMSGS . " SET privmsgs_from_userid = " . DELETED . " WHERE privmsgs_from_userid IN($user_csv)"); + DB()->query("UPDATE " . BB_PRIVMSGS . " SET privmsgs_to_userid = " . DELETED . " WHERE privmsgs_to_userid IN($user_csv)"); - // Delete user feed - foreach (explode(',', $user_csv) as $user_id) - { - $file_path = $di->config->get('atom.path') .'/u/'. floor($user_id/5000) .'/'. ($user_id % 100) .'/'. $user_id .'.atom'; - unlink($file_path); - } + // Delete user feed + foreach (explode(',', $user_csv) as $user_id) { + $file_path = $di->config->get('atom.path') . '/u/' . floor($user_id / 5000) . '/' . ($user_id % 100) . '/' . $user_id . '.atom'; + unlink($file_path); + } } -function get_usernames_for_log ($user_id) +function get_usernames_for_log($user_id) { - $users_log_msg = array(); + $users_log_msg = array(); - if ($user_csv = get_id_csv($user_id)) - { - $sql = "SELECT user_id, username FROM ". BB_USERS ." WHERE user_id IN($user_csv)"; + if ($user_csv = get_id_csv($user_id)) { + $sql = "SELECT user_id, username FROM " . BB_USERS . " WHERE user_id IN($user_csv)"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $users_log_msg[] = "$row[username] [$row[user_id]]"; - } - } + foreach (DB()->fetch_rowset($sql) as $row) { + $users_log_msg[] = "$row[username] [$row[user_id]]"; + } + } - return join(', ', $users_log_msg); -} \ No newline at end of file + return join(', ', $users_log_msg); +} diff --git a/library/includes/functions_admin_cron.php b/library/includes/functions_admin_cron.php index 121f863b3..673e16780 100644 --- a/library/includes/functions_admin_cron.php +++ b/library/includes/functions_admin_cron.php @@ -2,27 +2,25 @@ function run_jobs($jobs) { - global $tr_cfg, $datastore; + global $tr_cfg, $datastore; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - define('IN_CRON', true); + define('IN_CRON', true); - $sql = "SELECT cron_script FROM " . BB_CRON ." WHERE cron_id IN ($jobs)"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not obtain cron script'); - } + $sql = "SELECT cron_script FROM " . BB_CRON . " WHERE cron_id IN ($jobs)"; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not obtain cron script'); + } - while ($row = DB()->sql_fetchrow($result)) - { - $job = $row['cron_script']; - $job_script = INC_DIR . 'cron/jobs/' . $job; - require($job_script); - } - DB()->query(" - UPDATE ". BB_CRON ." SET + while ($row = DB()->sql_fetchrow($result)) { + $job = $row['cron_script']; + $job_script = INC_DIR . 'cron/jobs/' . $job; + require($job_script); + } + DB()->query(" + UPDATE " . BB_CRON . " SET last_run = NOW(), run_counter = run_counter + 1, next_run = @@ -44,102 +42,99 @@ function run_jobs($jobs) END WHERE cron_id IN ($jobs) "); - sleep(3); - return; + sleep(3); + return; } function delete_jobs($jobs) { - DB()->query("DELETE FROM " . BB_CRON . " WHERE cron_id IN ($jobs)"); - return; + DB()->query("DELETE FROM " . BB_CRON . " WHERE cron_id IN ($jobs)"); + return; } function toggle_active($jobs, $cron_action) { - $active = ($cron_action == 'disable') ? 0 : 1; - DB()->query("UPDATE " . BB_CRON . " SET cron_active = $active WHERE cron_id IN ($jobs)"); - return; + $active = ($cron_action == 'disable') ? 0 : 1; + DB()->query("UPDATE " . BB_CRON . " SET cron_active = $active WHERE cron_id IN ($jobs)"); + return; } -function validate_cron_post($cron_arr) { - $errors = 'Errors in: '; - $errnum = 0; - if (!$cron_arr['cron_title']){ - $errors .= 'cron title (empty value), '; - $errnum++; - } - if (!$cron_arr['cron_script']){ - $errors .= 'cron script (empty value), '; - $errnum++; - } - if ($errnum > 0){ - $result = $errors . ' total ' . $errnum . ' errors
        Back'; - } - else { - $result = 1; - } - return $result; +function validate_cron_post($cron_arr) +{ + $errors = 'Errors in: '; + $errnum = 0; + if (!$cron_arr['cron_title']) { + $errors .= 'cron title (empty value), '; + $errnum++; + } + if (!$cron_arr['cron_script']) { + $errors .= 'cron script (empty value), '; + $errnum++; + } + if ($errnum > 0) { + $result = $errors . ' total ' . $errnum . ' errors
        Back'; + } else { + $result = 1; + } + return $result; } function insert_cron_job($cron_arr) { - $row = DB()->fetch_row("SELECT cron_title, cron_script FROM ". BB_CRON ." WHERE cron_title = '". $_POST['cron_title'] ."' or cron_script = '". $_POST['cron_script'] ."' "); + $row = DB()->fetch_row("SELECT cron_title, cron_script FROM " . BB_CRON . " WHERE cron_title = '" . $_POST['cron_title'] . "' or cron_script = '" . $_POST['cron_script'] . "' "); - if ($row) - { - global $lang; + if ($row) { + global $lang; - if ($_POST['cron_script'] == $row['cron_script']) - { - $langmode = $lang['SCRIPT_DUPLICATE']; - } - else $langmode = $lang['TITLE_DUPLICATE']; + if ($_POST['cron_script'] == $row['cron_script']) { + $langmode = $lang['SCRIPT_DUPLICATE']; + } else $langmode = $lang['TITLE_DUPLICATE']; - $message = $langmode . "

        " . sprintf($lang['CLICK_RETURN_JOBS_ADDED'], "", "") . "

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

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

        " . sprintf($lang['CLICK_RETURN_JOBS_ADDED'], "", "") . "

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

        " . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], "", ""); - bb_die($message); - } + bb_die($message); + } - $cron_active = $cron_arr['cron_active']; - $cron_title = $cron_arr['cron_title']; - $cron_script = $cron_arr['cron_script']; - $schedule = $cron_arr['schedule']; - $run_day = $cron_arr['run_day']; - $run_time = $cron_arr['run_time']; - $run_order = $cron_arr['run_order']; - $last_run = $cron_arr['last_run']; - $next_run = $cron_arr['next_run']; - $run_interval = $cron_arr['run_interval']; - $log_enabled = $cron_arr['log_enabled']; - $log_file = $cron_arr['log_file']; - $log_sql_queries = $cron_arr['log_sql_queries']; - $disable_board = $cron_arr['disable_board']; - $run_counter = $cron_arr['run_counter']; + $cron_active = $cron_arr['cron_active']; + $cron_title = $cron_arr['cron_title']; + $cron_script = $cron_arr['cron_script']; + $schedule = $cron_arr['schedule']; + $run_day = $cron_arr['run_day']; + $run_time = $cron_arr['run_time']; + $run_order = $cron_arr['run_order']; + $last_run = $cron_arr['last_run']; + $next_run = $cron_arr['next_run']; + $run_interval = $cron_arr['run_interval']; + $log_enabled = $cron_arr['log_enabled']; + $log_file = $cron_arr['log_file']; + $log_sql_queries = $cron_arr['log_sql_queries']; + $disable_board = $cron_arr['disable_board']; + $run_counter = $cron_arr['run_counter']; - DB()->query("INSERT INTO ". BB_CRON ." (cron_active, cron_title, cron_script, schedule, run_day, run_time, run_order, last_run, next_run, run_interval, log_enabled, log_file, log_sql_queries, disable_board, run_counter) VALUES ( + DB()->query("INSERT INTO " . BB_CRON . " (cron_active, cron_title, cron_script, schedule, run_day, run_time, run_order, last_run, next_run, run_interval, log_enabled, log_file, log_sql_queries, disable_board, run_counter) VALUES ( $cron_active, '$cron_title', '$cron_script', '$schedule', '$run_day', '$run_time', '$run_order', '$last_run', '$next_run', '$run_interval', $log_enabled, '$log_file', $log_sql_queries, $disable_board, '$run_counter')"); } function update_cron_job($cron_arr) { - $cron_id = $cron_arr['cron_id']; - $cron_active = $cron_arr['cron_active']; - $cron_title = DB()->escape($cron_arr['cron_title']); - $cron_script = DB()->escape($cron_arr['cron_script']); - $schedule = $cron_arr['schedule']; - $run_day = $cron_arr['run_day']; - $run_time = $cron_arr['run_time']; - $run_order = $cron_arr['run_order']; - $last_run = $cron_arr['last_run']; - $next_run = $cron_arr['next_run']; - $run_interval = $cron_arr['run_interval']; - $log_enabled = $cron_arr['log_enabled']; - $log_file = DB()->escape($cron_arr['log_file']); - $log_sql_queries = $cron_arr['log_sql_queries']; - $disable_board = $cron_arr['disable_board']; - $run_counter = $cron_arr['run_counter']; + $cron_id = $cron_arr['cron_id']; + $cron_active = $cron_arr['cron_active']; + $cron_title = DB()->escape($cron_arr['cron_title']); + $cron_script = DB()->escape($cron_arr['cron_script']); + $schedule = $cron_arr['schedule']; + $run_day = $cron_arr['run_day']; + $run_time = $cron_arr['run_time']; + $run_order = $cron_arr['run_order']; + $last_run = $cron_arr['last_run']; + $next_run = $cron_arr['next_run']; + $run_interval = $cron_arr['run_interval']; + $log_enabled = $cron_arr['log_enabled']; + $log_file = DB()->escape($cron_arr['log_file']); + $log_sql_queries = $cron_arr['log_sql_queries']; + $disable_board = $cron_arr['disable_board']; + $run_counter = $cron_arr['run_counter']; - DB()->query("UPDATE " . BB_CRON . " SET + DB()->query("UPDATE " . BB_CRON . " SET cron_active = '$cron_active', cron_title = '$cron_title', cron_script = '$cron_script', @@ -157,4 +152,4 @@ function update_cron_job($cron_arr) run_counter = '$run_counter' WHERE cron_id = $cron_id "); -} \ No newline at end of file +} diff --git a/library/includes/functions_admin_torrent.php b/library/includes/functions_admin_torrent.php index b7475c951..29504c556 100644 --- a/library/includes/functions_admin_torrent.php +++ b/library/includes/functions_admin_torrent.php @@ -2,112 +2,95 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function update_table_bool ($table_name, $key, $field_name, $field_def_val) +function update_table_bool($table_name, $key, $field_name, $field_def_val) { - // Clear current status - $sql = "UPDATE $table_name + // Clear current status + $sql = "UPDATE $table_name SET $field_name = $field_def_val WHERE 1"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not update '. $table_name); - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not update ' . $table_name); + } - if (isset($_POST[$field_name])) - { - // Get new status - $in_sql = array(); + if (isset($_POST[$field_name])) { + // Get new status + $in_sql = array(); - foreach ($_POST[$field_name] as $i => $val) - { - $in_sql[] = intval($val); - } + foreach ($_POST[$field_name] as $i => $val) { + $in_sql[] = intval($val); + } - // Update status - if ($in_sql = join(',', $in_sql)) - { - $sql = "UPDATE $table_name + // Update status + if ($in_sql = join(',', $in_sql)) { + $sql = "UPDATE $table_name SET $field_name = 1 WHERE $key IN($in_sql)"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not update '. $table_name); - } - } - } - return; + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not update ' . $table_name); + } + } + } + return; } -function set_tpl_vars ($default_cfg, $cfg) +function set_tpl_vars($default_cfg, $cfg) { - global $template; + global $template; - foreach ($default_cfg as $config_name => $config_value) - { - $template->assign_vars(array(strtoupper($config_name) => htmlspecialchars($cfg[$config_name]))); - } + foreach ($default_cfg as $config_name => $config_value) { + $template->assign_vars(array(strtoupper($config_name) => htmlspecialchars($cfg[$config_name]))); + } } -function set_tpl_vars_bool ($default_cfg, $cfg) +function set_tpl_vars_bool($default_cfg, $cfg) { - global $template, $lang; + global $template, $lang; - foreach ($default_cfg as $config_name => $config_value) - { - // YES/NO 'checked="checked"' - $template->assign_vars(array( - strtoupper($config_name) .'_YES' => ($cfg[$config_name]) ? HTML_CHECKED : '', - strtoupper($config_name) .'_NO' => (!$cfg[$config_name]) ? HTML_CHECKED : '', - )); - // YES/NO lang vars - $template->assign_vars(array( - 'L_'. strtoupper($config_name) .'_YES' => ($cfg[$config_name]) ? "$lang[YES]" : $lang['YES'], - 'L_'. strtoupper($config_name) .'_NO' => (!$cfg[$config_name]) ? "$lang[NO]" : $lang['NO'], - )); - } + foreach ($default_cfg as $config_name => $config_value) { + // YES/NO 'checked="checked"' + $template->assign_vars(array( + strtoupper($config_name) . '_YES' => ($cfg[$config_name]) ? HTML_CHECKED : '', + strtoupper($config_name) . '_NO' => (!$cfg[$config_name]) ? HTML_CHECKED : '', + )); + // YES/NO lang vars + $template->assign_vars(array( + 'L_' . strtoupper($config_name) . '_YES' => ($cfg[$config_name]) ? "$lang[YES]" : $lang['YES'], + 'L_' . strtoupper($config_name) . '_NO' => (!$cfg[$config_name]) ? "$lang[NO]" : $lang['NO'], + )); + } } -function set_tpl_vars_lang ($default_cfg) +function set_tpl_vars_lang($default_cfg) { - global $template, $lang; + global $template, $lang; - foreach ($default_cfg as $config_name => $config_value) - { - $template->assign_vars(array( - 'L_'. strtoupper($config_name) => isset($lang[$config_name]) ? $lang[$config_name] : '', - 'L_'. strtoupper($config_name) .'_EXPL' => isset($lang[$config_name .'_expl']) ? $lang[$config_name .'_expl'] : '', - 'L_'. strtoupper($config_name) .'_HEAD' => isset($lang[$config_name .'_head']) ? $lang[$config_name .'_head'] : '', - )); + foreach ($default_cfg as $config_name => $config_value) { + $template->assign_vars(array( + 'L_' . strtoupper($config_name) => isset($lang[$config_name]) ? $lang[$config_name] : '', + 'L_' . strtoupper($config_name) . '_EXPL' => isset($lang[$config_name . '_expl']) ? $lang[$config_name . '_expl'] : '', + 'L_' . strtoupper($config_name) . '_HEAD' => isset($lang[$config_name . '_head']) ? $lang[$config_name . '_head'] : '', + )); - } + } } -function update_config_table ($table_name, $default_cfg, $cfg, $type) +function update_config_table($table_name, $default_cfg, $cfg, $type) { - foreach ($default_cfg as $config_name => $config_value) - { - if (isset($_POST[$config_name]) && $_POST[$config_name] != $cfg[$config_name]) - { - if ($type == 'str') - { - $config_value = $_POST[$config_name]; - } - else if ($type == 'bool') - { - $config_value = ($_POST[$config_name]) ? 1 : 0; - } - else if ($type == 'num') - { - $config_value = abs(intval($_POST[$config_name])); - } - else - { - return; - } + foreach ($default_cfg as $config_name => $config_value) { + if (isset($_POST[$config_name]) && $_POST[$config_name] != $cfg[$config_name]) { + if ($type == 'str') { + $config_value = $_POST[$config_name]; + } else if ($type == 'bool') { + $config_value = ($_POST[$config_name]) ? 1 : 0; + } else if ($type == 'num') { + $config_value = abs(intval($_POST[$config_name])); + } else { + return; + } - bb_update_config(array($config_name => $config_value), $table_name); - } - } -} \ No newline at end of file + bb_update_config(array($config_name => $config_value), $table_name); + } + } +} diff --git a/library/includes/functions_atom.php b/library/includes/functions_atom.php index 956ac2b40..c35d4c1ce 100644 --- a/library/includes/functions_atom.php +++ b/library/includes/functions_atom.php @@ -5,188 +5,171 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); // Максимум записей = 50 // [Обновлено] - если дата изменения первого поста топика не старее недели (?) или в топике новые сообщения не старее недели (?) -function update_forum_feed ($forum_id, $forum_data) +function update_forum_feed($forum_id, $forum_data) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $file_path = $di->config->get('atom.path') .'/f/'. $forum_id .'.atom'; - $select_tor_sql = $join_tor_sql = ''; - if ($forum_id == 0) $forum_data['atom_forum_name'] = 'Общая по всем разделам'; - if ($forum_id > 0 && $forum_data['atom_tr_allowed']) - { - $select_tor_sql = ', tor.size AS tor_size, tor.tor_status'; - $join_tor_sql = "LEFT JOIN ". BB_BT_TORRENTS ." tor ON(t.topic_id = tor.topic_id)"; - } - if ($forum_id == 0) - { - $sql = " + $file_path = $di->config->get('atom.path') . '/f/' . $forum_id . '.atom'; + $select_tor_sql = $join_tor_sql = ''; + if ($forum_id == 0) $forum_data['atom_forum_name'] = 'Общая по всем разделам'; + if ($forum_id > 0 && $forum_data['atom_tr_allowed']) { + $select_tor_sql = ', tor.size AS tor_size, tor.tor_status'; + $join_tor_sql = "LEFT JOIN " . BB_BT_TORRENTS . " tor ON(t.topic_id = tor.topic_id)"; + } + if ($forum_id == 0) { + $sql = " SELECT t.topic_id, t.topic_title, t.topic_status, u1.username AS first_username, p1.post_time AS topic_first_post_time, p1.post_edit_time AS topic_first_post_edit_time, p2.post_time AS topic_last_post_time, p2.post_edit_time AS topic_last_post_edit_time, tor.size AS tor_size, tor.tor_status - FROM ". BB_BT_TORRENTS ." tor - LEFT JOIN ". BB_TOPICS ." t ON(tor.topic_id = t.topic_id) - LEFT JOIN ". BB_USERS ." u1 ON(t.topic_poster = u1.user_id) - LEFT JOIN ". BB_POSTS ." p1 ON(t.topic_first_post_id = p1.post_id) - LEFT JOIN ". BB_POSTS ." p2 ON(t.topic_last_post_id = p2.post_id) + FROM " . BB_BT_TORRENTS . " tor + LEFT JOIN " . BB_TOPICS . " t ON(tor.topic_id = t.topic_id) + LEFT JOIN " . BB_USERS . " u1 ON(t.topic_poster = u1.user_id) + LEFT JOIN " . BB_POSTS . " p1 ON(t.topic_first_post_id = p1.post_id) + LEFT JOIN " . BB_POSTS . " p2 ON(t.topic_last_post_id = p2.post_id) ORDER BY t.topic_last_post_time DESC LIMIT 100 "; - } - else if ($forum_id > 0) - { - $sql = " + } else if ($forum_id > 0) { + $sql = " SELECT t.topic_id, t.topic_title, t.topic_status, u1.username AS first_username, p1.post_time AS topic_first_post_time, p1.post_edit_time AS topic_first_post_edit_time, p2.post_time AS topic_last_post_time, p2.post_edit_time AS topic_last_post_edit_time $select_tor_sql - FROM ". BB_TOPICS ." t - LEFT JOIN ". BB_USERS ." u1 ON(t.topic_poster = u1.user_id) - LEFT JOIN ". BB_POSTS ." p1 ON(t.topic_first_post_id = p1.post_id) - LEFT JOIN ". BB_POSTS ." p2 ON(t.topic_last_post_id = p2.post_id) + FROM " . BB_TOPICS . " t + LEFT JOIN " . BB_USERS . " u1 ON(t.topic_poster = u1.user_id) + LEFT JOIN " . BB_POSTS . " p1 ON(t.topic_first_post_id = p1.post_id) + LEFT JOIN " . BB_POSTS . " p2 ON(t.topic_last_post_id = p2.post_id) $join_tor_sql WHERE t.forum_id = $forum_id ORDER BY t.topic_last_post_time DESC LIMIT 50 "; - } - $topics_tmp = DB()->fetch_rowset($sql); - $topics = array(); - foreach ($topics_tmp as $topic) - { - if (isset($topic['topic_status'])) - { - if ($topic['topic_status'] == TOPIC_MOVED) continue; - } - if (isset($topic['tor_status'])) - { - if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; - } - $topics[] = $topic; - } - if (!count($topics)) - { - unlink($file_path); - return false; - } - if (create_atom($file_path, 'f', $forum_id, htmlCHR($forum_data['atom_forum_name']), $topics)) return true; - else return false; + } + $topics_tmp = DB()->fetch_rowset($sql); + $topics = array(); + foreach ($topics_tmp as $topic) { + if (isset($topic['topic_status'])) { + if ($topic['topic_status'] == TOPIC_MOVED) continue; + } + if (isset($topic['tor_status'])) { + if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; + } + $topics[] = $topic; + } + if (!count($topics)) { + unlink($file_path); + return false; + } + if (create_atom($file_path, 'f', $forum_id, htmlCHR($forum_data['atom_forum_name']), $topics)) return true; + else return false; } -function update_user_feed ($user_id, $username) +function update_user_feed($user_id, $username) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $file_path = $di->config->get('atom.path') .'/u/'. floor($user_id/5000) .'/'. ($user_id % 100) .'/'. $user_id .'.atom'; - $sql = " + $file_path = $di->config->get('atom.path') . '/u/' . floor($user_id / 5000) . '/' . ($user_id % 100) . '/' . $user_id . '.atom'; + $sql = " SELECT t.topic_id, t.topic_title, t.topic_status, u1.username AS first_username, p1.post_time AS topic_first_post_time, p1.post_edit_time AS topic_first_post_edit_time, p2.post_time AS topic_last_post_time, p2.post_edit_time AS topic_last_post_edit_time, tor.size AS tor_size, tor.tor_status - FROM ". BB_TOPICS ." t - LEFT JOIN ". BB_USERS ." u1 ON(t.topic_poster = u1.user_id) - LEFT JOIN ". BB_POSTS ." p1 ON(t.topic_first_post_id = p1.post_id) - LEFT JOIN ". BB_POSTS ." p2 ON(t.topic_last_post_id = p2.post_id) - LEFT JOIN ". BB_BT_TORRENTS ." tor ON(t.topic_id = tor.topic_id) + FROM " . BB_TOPICS . " t + LEFT JOIN " . BB_USERS . " u1 ON(t.topic_poster = u1.user_id) + LEFT JOIN " . BB_POSTS . " p1 ON(t.topic_first_post_id = p1.post_id) + LEFT JOIN " . BB_POSTS . " p2 ON(t.topic_last_post_id = p2.post_id) + LEFT JOIN " . BB_BT_TORRENTS . " tor ON(t.topic_id = tor.topic_id) WHERE t.topic_poster = $user_id ORDER BY t.topic_last_post_time DESC LIMIT 50 "; - $topics_tmp = DB()->fetch_rowset($sql); - $topics = array(); - foreach ($topics_tmp as $topic) - { - if (isset($topic['topic_status'])) - { - if ($topic['topic_status'] == TOPIC_MOVED) continue; - } - if (isset($topic['tor_status'])) - { - if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; - } - $topics[] = $topic; - } - if (!count($topics)) - { - unlink($file_path); - return false; - } - if (create_atom($file_path, 'u', $user_id, wbr($username), $topics)) return true; - else return false; + $topics_tmp = DB()->fetch_rowset($sql); + $topics = array(); + foreach ($topics_tmp as $topic) { + if (isset($topic['topic_status'])) { + if ($topic['topic_status'] == TOPIC_MOVED) continue; + } + if (isset($topic['tor_status'])) { + if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; + } + $topics[] = $topic; + } + if (!count($topics)) { + unlink($file_path); + return false; + } + if (create_atom($file_path, 'u', $user_id, wbr($username), $topics)) return true; + else return false; } -function create_atom ($file_path, $mode, $id, $title, $topics) +function create_atom($file_path, $mode, $id, $title, $topics) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $dir = dirname($file_path); - if (!file_exists($dir)) - { - if (!bb_mkdir($dir)) return false; - } - foreach ($topics as $topic) - { - $last_time = $topic['topic_last_post_time']; - if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; - $date = bb_date($last_time, 'Y-m-d', 0); - $time = bb_date($last_time, 'H:i:s', 0); - break; - } - $atom = ""; - $atom .= "\n"; - $atom .= "config->get('server_name') . $di->config->get('script_path') ."\">\n"; - $atom .= "$title\n"; - $atom .= "". $date ."T$time+00:00\n"; - $atom .= "tag:rto.feed,2000:/$mode/$id\n"; - $atom .= "config->get('server_name') . $di->config->get('script_path') ."\" />\n"; - foreach ($topics as $topic) - { - $topic_id = $topic['topic_id']; - $tor_size = ''; - if (isset($topic['tor_size'])) - { - $tor_size = str_replace(' ', ' ', ' ['. humn_size($topic['tor_size']) .']'); - } - $topic_title = $topic['topic_title']; - $orig_word = array(); - $replacement_word = array(); - obtain_word_list($orig_word, $replacement_word); - if (count($orig_word)) - { - $topic_title = preg_replace($orig_word, $replacement_word, $topic_title); - } - $topic_title = wbr($topic_title); - $author_name = ($topic['first_username']) ? wbr($topic['first_username']) : 'Гость'; - $last_time = $topic['topic_last_post_time']; - if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; - $date = bb_date($last_time, 'Y-m-d', 0); - $time = bb_date($last_time, 'H:i:s', 0); - $updated = ''; - $checktime = TIMENOW - 604800; // неделя (week) - if ($topic['topic_first_post_edit_time'] && $topic['topic_first_post_edit_time'] > $checktime) $updated = '[Обновлено] '; - $atom .= "\n"; - $atom .= " <![CDATA[$updated$topic_title$tor_size]]>\n"; - $atom .= " \n"; - $atom .= " $author_name\n"; - $atom .= " \n"; - $atom .= " ". $date ."T$time+00:00\n"; - $atom .= " tag:rto.feed,". $date .":/t/$topic_id\n"; - $atom .= " \n"; - $atom .= "\n"; - } - $atom .= ""; - unlink($file_path); - $fp = fopen($file_path, "w"); - fwrite($fp, $atom); - fclose ($fp); - return true; -} \ No newline at end of file + $dir = dirname($file_path); + if (!file_exists($dir)) { + if (!bb_mkdir($dir)) return false; + } + foreach ($topics as $topic) { + $last_time = $topic['topic_last_post_time']; + if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; + $date = bb_date($last_time, 'Y-m-d', 0); + $time = bb_date($last_time, 'H:i:s', 0); + break; + } + $atom = ""; + $atom .= "\n"; + $atom .= "config->get('server_name') . $di->config->get('script_path') . "\">\n"; + $atom .= "$title\n"; + $atom .= "" . $date . "T$time+00:00\n"; + $atom .= "tag:rto.feed,2000:/$mode/$id\n"; + $atom .= "config->get('server_name') . $di->config->get('script_path') . "\" />\n"; + foreach ($topics as $topic) { + $topic_id = $topic['topic_id']; + $tor_size = ''; + if (isset($topic['tor_size'])) { + $tor_size = str_replace(' ', ' ', ' [' . humn_size($topic['tor_size']) . ']'); + } + $topic_title = $topic['topic_title']; + $orig_word = array(); + $replacement_word = array(); + obtain_word_list($orig_word, $replacement_word); + if (count($orig_word)) { + $topic_title = preg_replace($orig_word, $replacement_word, $topic_title); + } + $topic_title = wbr($topic_title); + $author_name = ($topic['first_username']) ? wbr($topic['first_username']) : 'Гость'; + $last_time = $topic['topic_last_post_time']; + if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; + $date = bb_date($last_time, 'Y-m-d', 0); + $time = bb_date($last_time, 'H:i:s', 0); + $updated = ''; + $checktime = TIMENOW - 604800; // неделя (week) + if ($topic['topic_first_post_edit_time'] && $topic['topic_first_post_edit_time'] > $checktime) $updated = '[Обновлено] '; + $atom .= "\n"; + $atom .= " <![CDATA[$updated$topic_title$tor_size]]>\n"; + $atom .= " \n"; + $atom .= " $author_name\n"; + $atom .= " \n"; + $atom .= " " . $date . "T$time+00:00\n"; + $atom .= " tag:rto.feed," . $date . ":/t/$topic_id\n"; + $atom .= " \n"; + $atom .= "\n"; + } + $atom .= ""; + unlink($file_path); + $fp = fopen($file_path, "w"); + fwrite($fp, $atom); + fclose($fp); + return true; +} diff --git a/library/includes/functions_dev.php b/library/includes/functions_dev.php index c5ec1224f..b1e3bac0c 100644 --- a/library/includes/functions_dev.php +++ b/library/includes/functions_dev.php @@ -2,55 +2,50 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function get_sql_log () +function get_sql_log() { - global $DBS, $sphinx, $datastore; + global $DBS, $sphinx, $datastore; - $log = ''; + $log = ''; - foreach ($DBS->srv as $srv_name => $db_obj) - { - $log .= !empty($db_obj) ? get_sql_log_html($db_obj, "$srv_name [MySQL]") : ''; - } + foreach ($DBS->srv as $srv_name => $db_obj) { + $log .= !empty($db_obj) ? get_sql_log_html($db_obj, "$srv_name [MySQL]") : ''; + } - $log .= !empty($sphinx) ? get_sql_log_html($sphinx, '$sphinx') : ''; + $log .= !empty($sphinx) ? get_sql_log_html($sphinx, '$sphinx') : ''; - if (!empty($datastore->db->dbg)) - { - $log .= get_sql_log_html($datastore->db, 'cache: datastore ['.$datastore->engine.']'); - } - else if(!empty($datastore->dbg)) - { - $log .= get_sql_log_html($datastore, 'cache: datastore ['.$datastore->engine.']'); - } + if (!empty($datastore->db->dbg)) { + $log .= get_sql_log_html($datastore->db, 'cache: datastore [' . $datastore->engine . ']'); + } else if (!empty($datastore->dbg)) { + $log .= get_sql_log_html($datastore, 'cache: datastore [' . $datastore->engine . ']'); + } - return $log; + return $log; } -function get_sql_log_html ($db_obj, $log_name) +function get_sql_log_html($db_obj, $log_name) { - $log = ''; + $log = ''; - foreach ($db_obj->dbg as $i => $dbg) - { - $id = "sql_{$i}_". mt_rand(); - $sql = short_query($dbg['sql'], true); - $time = sprintf('%.4f', $dbg['time']); - $perc = sprintf('[%2d]', $dbg['time']*100/$db_obj->sql_timetotal); - $info = !empty($dbg['info']) ? $dbg['info'] .' ['. $dbg['src'] .']' : $dbg['src']; + foreach ($db_obj->dbg as $i => $dbg) { + $id = "sql_{$i}_" . mt_rand(); + $sql = short_query($dbg['sql'], true); + $time = sprintf('%.4f', $dbg['time']); + $perc = sprintf('[%2d]', $dbg['time'] * 100 / $db_obj->sql_timetotal); + $info = !empty($dbg['info']) ? $dbg['info'] . ' [' . $dbg['src'] . ']' : $dbg['src']; - $log .= '' - . '
        ' - . ''. $time .' ' - . ''. $perc .'' - . ' ' - . ''. $sql .'' - . ' # '. $info .' ' - . '
        ' - . "\n"; - } - return ' -
        '. $log_name .'
        - '. $log .' + $log .= '' + . '
        ' + . '' . $time . ' ' + . '' . $perc . '' + . ' ' + . '' . $sql . '' + . ' # ' . $info . ' ' + . '
        ' + . "\n"; + } + return ' +
        ' . $log_name . '
        + ' . $log . ' '; -} \ No newline at end of file +} diff --git a/library/includes/functions_group.php b/library/includes/functions_group.php index eb2420842..d6658963b 100644 --- a/library/includes/functions_group.php +++ b/library/includes/functions_group.php @@ -2,20 +2,19 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function update_user_level ($user_id) +function update_user_level($user_id) { - global $datastore; + global $datastore; - if (is_array($user_id)) - { - $user_id = join(',', $user_id); - } - $user_groups_in = ($user_id !== 'all') ? "AND ug.user_id IN($user_id)" : ''; - $users_in = ($user_id !== 'all') ? "AND u.user_id IN($user_id)" : ''; + if (is_array($user_id)) { + $user_id = join(',', $user_id); + } + $user_groups_in = ($user_id !== 'all') ? "AND ug.user_id IN($user_id)" : ''; + $users_in = ($user_id !== 'all') ? "AND u.user_id IN($user_id)" : ''; - $tmp_table = 'tmp_levels'; + $tmp_table = 'tmp_levels'; - DB()->query(" + DB()->query(" CREATE TEMPORARY TABLE $tmp_table ( user_id MEDIUMINT NOT NULL DEFAULT '0', user_level TINYINT NOT NULL DEFAULT '0', @@ -23,184 +22,176 @@ function update_user_level ($user_id) ) ENGINE = MEMORY "); - DB()->query(" + DB()->query(" REPLACE INTO $tmp_table (user_id, user_level) - SELECT u.user_id, ". USER ." - FROM ". BB_USERS ." u - WHERE user_level NOT IN(". USER .",". ADMIN .") + SELECT u.user_id, " . USER . " + FROM " . BB_USERS . " u + WHERE user_level NOT IN(" . USER . "," . ADMIN . ") $users_in UNION - SELECT DISTINCT ug.user_id, ". GROUP_MEMBER ." - FROM ". BB_GROUPS ." g, ". BB_USER_GROUP ." ug + SELECT DISTINCT ug.user_id, " . GROUP_MEMBER . " + FROM " . BB_GROUPS . " g, " . BB_USER_GROUP . " ug WHERE g.group_single_user = 0 AND ug.group_id = g.group_id AND ug.user_pending = 0 $user_groups_in UNION - SELECT DISTINCT ug.user_id, ". MOD ." - FROM ". BB_AUTH_ACCESS ." aa, ". BB_USER_GROUP ." ug - WHERE aa.forum_perm & ". BF_AUTH_MOD ." + SELECT DISTINCT ug.user_id, " . MOD . " + FROM " . BB_AUTH_ACCESS . " aa, " . BB_USER_GROUP . " ug + WHERE aa.forum_perm & " . BF_AUTH_MOD . " AND ug.group_id = aa.group_id AND ug.user_pending = 0 $user_groups_in "); - DB()->query(" - UPDATE ". BB_USERS ." u, $tmp_table lev SET + DB()->query(" + UPDATE " . BB_USERS . " u, $tmp_table lev SET u.user_level = lev.user_level WHERE lev.user_id = u.user_id - AND u.user_level NOT IN(". ADMIN .") + AND u.user_level NOT IN(" . ADMIN . ") $users_in "); - DB()->query("DROP TEMPORARY TABLE $tmp_table"); + DB()->query("DROP TEMPORARY TABLE $tmp_table"); - update_user_permissions($user_id); - delete_orphan_usergroups(); - $datastore->update('moderators'); + update_user_permissions($user_id); + delete_orphan_usergroups(); + $datastore->update('moderators'); } -function delete_group ($group_id) +function delete_group($group_id) { - $group_id = (int) $group_id; + $group_id = (int)$group_id; - DB()->query(" + DB()->query(" DELETE ug, g, aa - FROM ". BB_USER_GROUP ." ug - LEFT JOIN ". BB_GROUPS ." g ON(g.group_id = $group_id) - LEFT JOIN ". BB_AUTH_ACCESS ." aa ON(aa.group_id = $group_id) + FROM " . BB_USER_GROUP . " ug + LEFT JOIN " . BB_GROUPS . " g ON(g.group_id = $group_id) + LEFT JOIN " . BB_AUTH_ACCESS . " aa ON(aa.group_id = $group_id) WHERE ug.group_id = $group_id "); - DB()->query("UPDATE " . BB_POSTS . " SET attach_rg_sig = 0, poster_rg_id = 0 WHERE poster_rg_id = ". $group_id); + DB()->query("UPDATE " . BB_POSTS . " SET attach_rg_sig = 0, poster_rg_id = 0 WHERE poster_rg_id = " . $group_id); - update_user_level('all'); + update_user_level('all'); } -function add_user_into_group ($group_id, $user_id, $user_pending = 0, $user_time = TIMENOW) +function add_user_into_group($group_id, $user_id, $user_pending = 0, $user_time = TIMENOW) { - $args = DB()->build_array('INSERT', array( - 'group_id' => (int) $group_id, - 'user_id' => (int) $user_id, - 'user_pending' => (int) $user_pending, - 'user_time' => (int) $user_time, - )); - DB()->query("REPLACE INTO ". BB_USER_GROUP . $args); + $args = DB()->build_array('INSERT', array( + 'group_id' => (int)$group_id, + 'user_id' => (int)$user_id, + 'user_pending' => (int)$user_pending, + 'user_time' => (int)$user_time, + )); + DB()->query("REPLACE INTO " . BB_USER_GROUP . $args); - if (!$user_pending) - { - update_user_level($user_id); - } + if (!$user_pending) { + update_user_level($user_id); + } } -function delete_user_group ($group_id, $user_id) +function delete_user_group($group_id, $user_id) { - DB()->query(" - DELETE FROM ". BB_USER_GROUP ." - WHERE user_id = ". (int) $user_id ." - AND group_id = ". (int) $group_id ." + DB()->query(" + DELETE FROM " . BB_USER_GROUP . " + WHERE user_id = " . (int)$user_id . " + AND group_id = " . (int)$group_id . " "); - update_user_level($user_id); + update_user_level($user_id); } -function create_user_group ($user_id) +function create_user_group($user_id) { - DB()->query("INSERT INTO ". BB_GROUPS ." (group_single_user) VALUES (1)"); + DB()->query("INSERT INTO " . BB_GROUPS . " (group_single_user) VALUES (1)"); - $group_id = (int) DB()->sql_nextid(); - $user_id = (int) $user_id; + $group_id = (int)DB()->sql_nextid(); + $user_id = (int)$user_id; - DB()->query("INSERT INTO ". BB_USER_GROUP ." (user_id, group_id, user_time) VALUES ($user_id, $group_id, ". TIMENOW .")"); + DB()->query("INSERT INTO " . BB_USER_GROUP . " (user_id, group_id, user_time) VALUES ($user_id, $group_id, " . TIMENOW . ")"); return $group_id; } -function get_group_data ($group_id) +function get_group_data($group_id) { - if ($group_id === 'all') - { - $sql = "SELECT g.*, u.username AS moderator_name, aa.group_id AS auth_mod - FROM ". BB_GROUPS ." g - LEFT JOIN ". BB_USERS ." u ON(g.group_moderator = u.user_id) - LEFT JOIN ". BB_AUTH_ACCESS ." aa ON(aa.group_id = g.group_id AND aa.forum_perm & ". BF_AUTH_MOD .") + if ($group_id === 'all') { + $sql = "SELECT g.*, u.username AS moderator_name, aa.group_id AS auth_mod + FROM " . BB_GROUPS . " g + LEFT JOIN " . BB_USERS . " u ON(g.group_moderator = u.user_id) + LEFT JOIN " . BB_AUTH_ACCESS . " aa ON(aa.group_id = g.group_id AND aa.forum_perm & " . BF_AUTH_MOD . ") WHERE g.group_single_user = 0 GROUP BY g.group_id ORDER BY g.group_name"; - } - else - { - $sql = "SELECT g.*, u.username AS moderator_name, aa.group_id AS auth_mod - FROM ". BB_GROUPS ." g - LEFT JOIN ". BB_USERS ." u ON(g.group_moderator = u.user_id) - LEFT JOIN ". BB_AUTH_ACCESS ." aa ON(aa.group_id = g.group_id AND aa.forum_perm & ". BF_AUTH_MOD .") - WHERE g.group_id = ". (int) $group_id ." + } else { + $sql = "SELECT g.*, u.username AS moderator_name, aa.group_id AS auth_mod + FROM " . BB_GROUPS . " g + LEFT JOIN " . BB_USERS . " u ON(g.group_moderator = u.user_id) + LEFT JOIN " . BB_AUTH_ACCESS . " aa ON(aa.group_id = g.group_id AND aa.forum_perm & " . BF_AUTH_MOD . ") + WHERE g.group_id = " . (int)$group_id . " AND g.group_single_user = 0 LIMIT 1"; - } - $method = ($group_id === 'all') ? 'fetch_rowset' : 'fetch_row'; - return DB()->$method($sql); + } + $method = ($group_id === 'all') ? 'fetch_rowset' : 'fetch_row'; + return DB()->$method($sql); } -function delete_permissions ($group_id = null, $user_id = null, $cat_id = null) +function delete_permissions($group_id = null, $user_id = null, $cat_id = null) { - $group_id = get_id_csv($group_id); - $user_id = get_id_csv($user_id); - $cat_id = get_id_csv($cat_id); + $group_id = get_id_csv($group_id); + $user_id = get_id_csv($user_id); + $cat_id = get_id_csv($cat_id); - $forums_join_sql = ($cat_id) ? " - INNER JOIN ". BB_FORUMS ." f ON(a.forum_id = f.forum_id AND f.cat_id IN($cat_id)) + $forums_join_sql = ($cat_id) ? " + INNER JOIN " . BB_FORUMS . " f ON(a.forum_id = f.forum_id AND f.cat_id IN($cat_id)) " : ''; - if ($group_id) - { - DB()->query("DELETE a FROM ". BB_AUTH_ACCESS ." a $forums_join_sql WHERE a.group_id IN($group_id)"); - } - if ($user_id) - { - DB()->query("DELETE a FROM ". BB_AUTH_ACCESS_SNAP ." a $forums_join_sql WHERE a.user_id IN($user_id)"); - } + if ($group_id) { + DB()->query("DELETE a FROM " . BB_AUTH_ACCESS . " a $forums_join_sql WHERE a.group_id IN($group_id)"); + } + if ($user_id) { + DB()->query("DELETE a FROM " . BB_AUTH_ACCESS_SNAP . " a $forums_join_sql WHERE a.user_id IN($user_id)"); + } } -function store_permissions ($group_id, $auth_ary) +function store_permissions($group_id, $auth_ary) { - if (empty($auth_ary) || !is_array($auth_ary)) return; + if (empty($auth_ary) || !is_array($auth_ary)) return; - $values = array(); + $values = array(); - foreach ($auth_ary as $forum_id => $permission) - { - $values[] = array( - 'group_id' => (int) $group_id, - 'forum_id' => (int) $forum_id, - 'forum_perm' => (int) $permission, - ); - } - $values = DB()->build_array('MULTI_INSERT', $values); + foreach ($auth_ary as $forum_id => $permission) { + $values[] = array( + 'group_id' => (int)$group_id, + 'forum_id' => (int)$forum_id, + 'forum_perm' => (int)$permission, + ); + } + $values = DB()->build_array('MULTI_INSERT', $values); - DB()->query("INSERT INTO ". BB_AUTH_ACCESS . $values); + DB()->query("INSERT INTO " . BB_AUTH_ACCESS . $values); } -function update_user_permissions ($user_id = 'all') +function update_user_permissions($user_id = 'all') { - if (is_array($user_id)) - { - $user_id = join(',', $user_id); - } - $delete_in = ($user_id !== 'all') ? " WHERE user_id IN($user_id)" : ''; - $users_in = ($user_id !== 'all') ? "AND ug.user_id IN($user_id)" : ''; + if (is_array($user_id)) { + $user_id = join(',', $user_id); + } + $delete_in = ($user_id !== 'all') ? " WHERE user_id IN($user_id)" : ''; + $users_in = ($user_id !== 'all') ? "AND ug.user_id IN($user_id)" : ''; - DB()->query("DELETE FROM ". BB_AUTH_ACCESS_SNAP . $delete_in); + DB()->query("DELETE FROM " . BB_AUTH_ACCESS_SNAP . $delete_in); - DB()->query(" - INSERT INTO ". BB_AUTH_ACCESS_SNAP ." + DB()->query(" + INSERT INTO " . BB_AUTH_ACCESS_SNAP . " (user_id, forum_id, forum_perm) SELECT ug.user_id, aa.forum_id, BIT_OR(aa.forum_perm) FROM - ". BB_USER_GROUP ." ug, - ". BB_GROUPS ." g, - ". BB_AUTH_ACCESS ." aa + " . BB_USER_GROUP . " ug, + " . BB_GROUPS . " g, + " . BB_AUTH_ACCESS . " aa WHERE ug.user_pending = 0 $users_in @@ -211,22 +202,22 @@ function update_user_permissions ($user_id = 'all') "); } -function delete_orphan_usergroups () +function delete_orphan_usergroups() { - // GROUP_SINGLE_USER without AUTH_ACCESS - DB()->query(" + // GROUP_SINGLE_USER without AUTH_ACCESS + DB()->query(" DELETE g - FROM ". BB_GROUPS ." g - LEFT JOIN ". BB_AUTH_ACCESS ." aa USING(group_id) + FROM " . BB_GROUPS . " g + LEFT JOIN " . BB_AUTH_ACCESS . " aa USING(group_id) WHERE g.group_single_user = 1 AND aa.group_id IS NULL "); - // orphan USER_GROUP (against GROUP table) - DB()->query(" + // orphan USER_GROUP (against GROUP table) + DB()->query(" DELETE ug - FROM ". BB_USER_GROUP ." ug - LEFT JOIN ". BB_GROUPS ." g USING(group_id) + FROM " . BB_USER_GROUP . " ug + LEFT JOIN " . BB_GROUPS . " g USING(group_id) WHERE g.group_id IS NULL "); -} \ No newline at end of file +} diff --git a/library/includes/functions_post.php b/library/includes/functions_post.php index 79f333953..05c30cb14 100644 --- a/library/includes/functions_post.php +++ b/library/includes/functions_post.php @@ -7,66 +7,52 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); // function prepare_post(&$mode, &$post_data, &$error_msg, &$username, &$subject, &$message) { - global $user, $userdata, $lang; + global $user, $userdata, $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - // Check username - if (!empty($username)) - { - $username = clean_username($username); + // Check username + if (!empty($username)) { + $username = clean_username($username); - if (!$userdata['session_logged_in'] || ($userdata['session_logged_in'] && $username != $user->name)) - { - require(INC_DIR .'functions_validate.php'); + if (!$userdata['session_logged_in'] || ($userdata['session_logged_in'] && $username != $user->name)) { + require(INC_DIR . 'functions_validate.php'); - if ($err = validate_username($username)) - { - $error_msg .= $err; - } - } - else - { - $username = ''; - } - } + if ($err = validate_username($username)) { + $error_msg .= $err; + } + } else { + $username = ''; + } + } - // Check subject - if (!empty($subject)) - { - $subject = str_replace('&', '&', $subject); - } - else if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) - { - $error_msg .= (!empty($error_msg)) ? '
        ' . $lang['EMPTY_SUBJECT'] : $lang['EMPTY_SUBJECT']; - } + // Check subject + if (!empty($subject)) { + $subject = str_replace('&', '&', $subject); + } else if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) { + $error_msg .= (!empty($error_msg)) ? '
        ' . $lang['EMPTY_SUBJECT'] : $lang['EMPTY_SUBJECT']; + } - // Check message - if (!empty($message)) - { + // Check message + if (!empty($message)) { - } - else if ($mode != 'delete') - { - $error_msg .= (!empty($error_msg)) ? '
        ' . $lang['EMPTY_MESSAGE'] : $lang['EMPTY_MESSAGE']; - } + } else if ($mode != 'delete') { + $error_msg .= (!empty($error_msg)) ? '
        ' . $lang['EMPTY_MESSAGE'] : $lang['EMPTY_MESSAGE']; + } - // Check smilies limit - if ($di->config->get('max_smilies')) - { - $count_smilies = substr_count(bbcode2html($message), 'fetch_row($sql)) && $row['last_post_time']) - { - if ($userdata['user_level'] == USER) - { - if (TIMENOW - $row['last_post_time'] < $di->config->get('flood_interval')) - { - bb_die($lang['FLOOD_ERROR']); - } - } - } - } + if (($row = DB()->fetch_row($sql)) && $row['last_post_time']) { + if ($userdata['user_level'] == USER) { + if (TIMENOW - $row['last_post_time'] < $di->config->get('flood_interval')) { + bb_die($lang['FLOOD_ERROR']); + } + } + } + } - // Double Post Control - if ($mode != 'editpost' && !empty($row['last_post_time']) && !IS_AM) - { - $sql = " + // Double Post Control + if ($mode != 'editpost' && !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 == $post_message) - { - bb_die($lang['DOUBLE_POST_ERROR']); - } - } - } + if ($last_msg == $post_message) { + bb_die($lang['DOUBLE_POST_ERROR']); + } + } + } - if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) - { - $topic_dl_type = (isset($_POST['tracker_status']) && ($post_info['allow_reg_tracker'] || $is_auth['auth_mod'])) ? 1 : 0; + if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) { + $topic_dl_type = (isset($_POST['tracker_status']) && ($post_info['allow_reg_tracker'] || $is_auth['auth_mod'])) ? 1 : 0; - $sql_insert = " + $sql_insert = " INSERT INTO " . BB_TOPICS . " (topic_title, topic_poster, topic_time, forum_id, topic_status, topic_type, tracker_status) VALUES ('$post_subject', " . $userdata['user_id'] . ", $current_time, $forum_id, " . TOPIC_UNLOCKED . ", $topic_type, $topic_dl_type) "; - $sql_update = " + $sql_update = " UPDATE " . BB_TOPICS . " SET @@ -147,82 +125,71 @@ function submit_post($mode, &$post_data, &$message, &$meta, &$forum_id, &$topic_ topic_id = $topic_id "; - $sql = ($mode != "editpost") ? $sql_insert : $sql_update; + $sql = ($mode != "editpost") ? $sql_insert : $sql_update; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #1'); - } + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #1'); + } - if ($mode == 'newtopic') - { - $topic_id = DB()->sql_nextid(); - } - } + if ($mode == 'newtopic') { + $topic_id = DB()->sql_nextid(); + } + } - $edited_sql = ($mode == 'editpost' && !$post_data['last_post'] && $post_data['poster_post']) ? ", post_edit_time = $current_time, post_edit_count = post_edit_count + 1" : ""; + $edited_sql = ($mode == 'editpost' && !$post_data['last_post'] && $post_data['poster_post']) ? ", post_edit_time = $current_time, post_edit_count = post_edit_count + 1" : ""; - if ($update_post_time && $mode == 'editpost' && $post_data['last_post'] && !$post_data['first_post']) - { - $edited_sql .= ", post_time = $current_time "; - //lpt - DB()->sql_query("UPDATE ". BB_TOPICS ." SET topic_last_post_time = $current_time WHERE topic_id = $topic_id LIMIT 1"); - } + if ($update_post_time && $mode == 'editpost' && $post_data['last_post'] && !$post_data['first_post']) { + $edited_sql .= ", post_time = $current_time "; + //lpt + DB()->sql_query("UPDATE " . BB_TOPICS . " SET topic_last_post_time = $current_time WHERE topic_id = $topic_id LIMIT 1"); + } - $sql = ($mode != "editpost") ? "INSERT INTO " . BB_POSTS . " (topic_id, forum_id, poster_id, post_username, post_time, poster_ip, poster_rg_id, attach_rg_sig) VALUES ($topic_id, $forum_id, " . $userdata['user_id'] . ", '$post_username', $current_time, '". USER_IP ."', $poster_rg_id, $attach_rg_sig)" : "UPDATE " . BB_POSTS . " SET post_username = '$post_username'" . $edited_sql . ", poster_rg_id = $poster_rg_id, attach_rg_sig = $attach_rg_sig WHERE post_id = $post_id"; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #2'); - } + $sql = ($mode != "editpost") ? "INSERT INTO " . BB_POSTS . " (topic_id, forum_id, poster_id, post_username, post_time, poster_ip, poster_rg_id, attach_rg_sig) VALUES ($topic_id, $forum_id, " . $userdata['user_id'] . ", '$post_username', $current_time, '" . USER_IP . "', $poster_rg_id, $attach_rg_sig)" : "UPDATE " . BB_POSTS . " SET post_username = '$post_username'" . $edited_sql . ", poster_rg_id = $poster_rg_id, attach_rg_sig = $attach_rg_sig WHERE post_id = $post_id"; + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #2'); + } - if ($mode != 'editpost') - { - $post_id = DB()->sql_nextid(); - } + if ($mode != 'editpost') { + $post_id = DB()->sql_nextid(); + } - $sql = ($mode != 'editpost') ? "INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '$post_message')" : "UPDATE " . BB_POSTS_TEXT . " SET post_text = '$post_message' WHERE post_id = $post_id"; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #3'); - } + $sql = ($mode != 'editpost') ? "INSERT INTO " . BB_POSTS_TEXT . " (post_id, post_text) VALUES ($post_id, '$post_message')" : "UPDATE " . BB_POSTS_TEXT . " SET post_text = '$post_message' WHERE post_id = $post_id"; + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #3'); + } - if ($userdata['user_id'] != BOT_UID) - { - $s_post_message = str_replace('\n', "\n", $post_message); - $s_post_subject = str_replace('\n', "\n", $post_subject); - add_search_words($post_id, stripslashes($s_post_message), stripslashes($s_post_subject)); - } + if ($userdata['user_id'] != BOT_UID) { + $s_post_message = str_replace('\n', "\n", $post_message); + $s_post_subject = str_replace('\n', "\n", $post_subject); + add_search_words($post_id, stripslashes($s_post_message), stripslashes($s_post_subject)); + } - update_post_html(array( - 'post_id' => $post_id, - 'post_text' => $post_message, - )); + update_post_html(array( + 'post_id' => $post_id, + 'post_text' => $post_message, + )); //Обновление кеша новостей на главной - if($di->config->get('show_latest_news')) - { - $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); - if(isset($news_forums[$forum_id]) && $di->config->get('show_latest_news') && $mode == 'newtopic') - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } - } + if ($di->config->get('show_latest_news')) { + $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); + if (isset($news_forums[$forum_id]) && $di->config->get('show_latest_news') && $mode == 'newtopic') { + $datastore->enqueue('latest_news'); + $datastore->update('latest_news'); + } + } - if($di->config->get('show_network_news')) - { - $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); - if(isset($net_forums[$forum_id]) && $di->config->get('show_network_news') && $mode == 'newtopic') - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } - } + if ($di->config->get('show_network_news')) { + $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); + if (isset($net_forums[$forum_id]) && $di->config->get('show_network_news') && $mode == 'newtopic') { + $datastore->enqueue('network_news'); + $datastore->update('network_news'); + } + } - meta_refresh(POST_URL ."$post_id#$post_id"); - set_die_append_msg($forum_id, $topic_id); + meta_refresh(POST_URL . "$post_id#$post_id"); + set_die_append_msg($forum_id, $topic_id); - return $mode; + return $mode; } // @@ -230,96 +197,74 @@ function submit_post($mode, &$post_data, &$message, &$meta, &$forum_id, &$topic_ // function update_post_stats($mode, $post_data, $forum_id, $topic_id, $post_id, $user_id) { - $sign = ($mode == 'delete') ? '- 1' : '+ 1'; - $forum_update_sql = "forum_posts = forum_posts $sign"; - $topic_update_sql = ''; + $sign = ($mode == 'delete') ? '- 1' : '+ 1'; + $forum_update_sql = "forum_posts = forum_posts $sign"; + $topic_update_sql = ''; - if ($mode == 'delete') - { - if ($post_data['last_post']) - { - if ($post_data['first_post']) - { - $forum_update_sql .= ', forum_topics = forum_topics - 1'; - } - else - { - $topic_update_sql .= 'topic_replies = topic_replies - 1'; + if ($mode == 'delete') { + if ($post_data['last_post']) { + if ($post_data['first_post']) { + $forum_update_sql .= ', forum_topics = forum_topics - 1'; + } else { + $topic_update_sql .= 'topic_replies = topic_replies - 1'; - $sql = "SELECT MAX(post_id) AS last_post_id, MAX(post_time) AS topic_last_post_time + $sql = "SELECT MAX(post_id) AS last_post_id, MAX(post_time) AS topic_last_post_time FROM " . BB_POSTS . " WHERE topic_id = $topic_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Error in deleting post #1'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Error in deleting post #1'); + } - if ($row = DB()->sql_fetchrow($result)) - { - $topic_update_sql .= ", topic_last_post_id = {$row['last_post_id']}, topic_last_post_time = {$row['topic_last_post_time']}"; - } - } + if ($row = DB()->sql_fetchrow($result)) { + $topic_update_sql .= ", topic_last_post_id = {$row['last_post_id']}, topic_last_post_time = {$row['topic_last_post_time']}"; + } + } - if ($post_data['last_topic']) - { - $sql = "SELECT MAX(post_id) AS last_post_id + if ($post_data['last_topic']) { + $sql = "SELECT MAX(post_id) AS last_post_id FROM " . BB_POSTS . " WHERE forum_id = $forum_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Error in deleting post #2'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Error in deleting post #2'); + } - if ($row = DB()->sql_fetchrow($result)) - { - $forum_update_sql .= ($row['last_post_id']) ? ', forum_last_post_id = ' . $row['last_post_id'] : ', forum_last_post_id = 0'; - } - } - } - else if ($post_data['first_post']) - { - $sql = "SELECT MIN(post_id) AS first_post_id FROM " . BB_POSTS . " WHERE topic_id = $topic_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Error in deleting post #3'); - } + if ($row = DB()->sql_fetchrow($result)) { + $forum_update_sql .= ($row['last_post_id']) ? ', forum_last_post_id = ' . $row['last_post_id'] : ', forum_last_post_id = 0'; + } + } + } else if ($post_data['first_post']) { + $sql = "SELECT MIN(post_id) AS first_post_id FROM " . BB_POSTS . " WHERE topic_id = $topic_id"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Error in deleting post #3'); + } - if ($row = DB()->sql_fetchrow($result)) - { - $topic_update_sql .= 'topic_replies = topic_replies - 1, topic_first_post_id = ' . $row['first_post_id']; - } - } - else - { - $topic_update_sql .= 'topic_replies = topic_replies - 1'; - } - } - else - { - $forum_update_sql .= ", forum_last_post_id = $post_id" . (($mode == 'newtopic') ? ", forum_topics = forum_topics $sign" : ""); - $topic_update_sql = "topic_last_post_id = $post_id, topic_last_post_time = ". TIMENOW . (($mode == 'reply') ? ", topic_replies = topic_replies $sign" : ", topic_first_post_id = $post_id"); - } + if ($row = DB()->sql_fetchrow($result)) { + $topic_update_sql .= 'topic_replies = topic_replies - 1, topic_first_post_id = ' . $row['first_post_id']; + } + } else { + $topic_update_sql .= 'topic_replies = topic_replies - 1'; + } + } else { + $forum_update_sql .= ", forum_last_post_id = $post_id" . (($mode == 'newtopic') ? ", forum_topics = forum_topics $sign" : ""); + $topic_update_sql = "topic_last_post_id = $post_id, topic_last_post_time = " . TIMENOW . (($mode == 'reply') ? ", topic_replies = topic_replies $sign" : ", topic_first_post_id = $post_id"); + } - $sql = "UPDATE " . BB_FORUMS . " SET $forum_update_sql WHERE forum_id = $forum_id"; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #4'); - } + $sql = "UPDATE " . BB_FORUMS . " SET $forum_update_sql WHERE forum_id = $forum_id"; + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #4'); + } - if ($topic_update_sql != '') - { - $sql = "UPDATE " . BB_TOPICS . " SET $topic_update_sql WHERE topic_id = $topic_id"; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #5'); - } - } + if ($topic_update_sql != '') { + $sql = "UPDATE " . BB_TOPICS . " SET $topic_update_sql WHERE topic_id = $topic_id"; + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #5'); + } + } - $sql = "UPDATE " . BB_USERS . " SET user_posts = user_posts $sign WHERE user_id = $user_id"; - if (!DB()->sql_query($sql)) - { - bb_die('Error in posting #6'); - } + $sql = "UPDATE " . BB_USERS . " SET user_posts = user_posts $sign WHERE user_id = $user_id"; + if (!DB()->sql_query($sql)) { + bb_die('Error in posting #6'); + } } // @@ -327,12 +272,12 @@ function update_post_stats($mode, $post_data, $forum_id, $topic_id, $post_id, $u // function delete_post($mode, $post_data, &$message, &$meta, $forum_id, $topic_id, $post_id) { - global $lang; + global $lang; - $message = $lang['DELETED']; - post_delete($post_id); + $message = $lang['DELETED']; + post_delete($post_id); - set_die_append_msg($forum_id, $topic_id); + set_die_append_msg($forum_id, $topic_id); } // @@ -340,177 +285,155 @@ function delete_post($mode, $post_data, &$message, &$meta, $forum_id, $topic_id, // function user_notification($mode, &$post_data, &$topic_title, &$forum_id, &$topic_id, &$notify_user) { - global $lang, $userdata; + global $lang, $userdata; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!$di->config->get('topic_notify_enabled')) - { - return; - } + if (!$di->config->get('topic_notify_enabled')) { + return; + } - if ($mode != 'delete') - { - if ($mode == 'reply') - { - $update_watched_sql = $user_id_sql = array(); + if ($mode != 'delete') { + if ($mode == 'reply') { + $update_watched_sql = $user_id_sql = 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) - { - $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); - $watch_list = DB()->fetch_rowset("SELECT u.username, u.user_id, u.user_email, u.user_lang + $watch_list = DB()->fetch_rowset("SELECT u.username, u.user_id, u.user_email, u.user_lang FROM " . BB_TOPICS_WATCH . " tw, " . BB_USERS . " u WHERE tw.topic_id = $topic_id - AND tw.user_id NOT IN (". $userdata['user_id'] .", ". EXCLUDED_USERS . $user_id_sql .") - AND tw.notify_status = ". TOPIC_WATCH_NOTIFIED ." + AND tw.user_id NOT IN (" . $userdata['user_id'] . ", " . EXCLUDED_USERS . $user_id_sql . ") + AND tw.notify_status = " . TOPIC_WATCH_NOTIFIED . " AND u.user_id = tw.user_id AND u.user_active = 1 ORDER BY u.user_id "); - if ($watch_list) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + if ($watch_list) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $orig_word = $replacement_word = array(); - obtain_word_list($orig_word, $replacement_word); + $orig_word = $replacement_word = array(); + obtain_word_list($orig_word, $replacement_word); - if (count($orig_word)) - { - $topic_title = preg_replace($orig_word, $replacement_word, $topic_title); - } + if (count($orig_word)) { + $topic_title = preg_replace($orig_word, $replacement_word, $topic_title); + } - $u_topic = make_url(TOPIC_URL . $topic_id .'&view=newest#newest'); - $unwatch_topic = make_url(TOPIC_URL ."$topic_id&unwatch=topic"); + $u_topic = make_url(TOPIC_URL . $topic_id . '&view=newest#newest'); + $unwatch_topic = make_url(TOPIC_URL . "$topic_id&unwatch=topic"); - foreach ($watch_list as $row) - { - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($row['username'] ." <{$row['user_email']}>"); - $emailer->use_template('topic_notify', $row['user_lang']); + foreach ($watch_list as $row) { + $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>"); + $emailer->email_address($row['username'] . " <{$row['user_email']}>"); + $emailer->use_template('topic_notify', $row['user_lang']); - $emailer->assign_vars(array( - 'TOPIC_TITLE' => html_entity_decode($topic_title), - 'SITENAME' => $di->config->get('sitename'), - 'USERNAME' => $row['username'], - 'U_TOPIC' => $u_topic, - 'U_STOP_WATCHING_TOPIC' => $unwatch_topic, - )); + $emailer->assign_vars(array( + 'TOPIC_TITLE' => html_entity_decode($topic_title), + 'SITENAME' => $di->config->get('sitename'), + 'USERNAME' => $row['username'], + 'U_TOPIC' => $u_topic, + 'U_STOP_WATCHING_TOPIC' => $unwatch_topic, + )); - $emailer->send(); - $emailer->reset(); + $emailer->send(); + $emailer->reset(); - $update_watched_sql[] = $row['user_id']; - } - $update_watched_sql = join(',', $update_watched_sql); - } + $update_watched_sql[] = $row['user_id']; + } + $update_watched_sql = join(',', $update_watched_sql); + } - if ($update_watched_sql) - { - DB()->query("UPDATE ". BB_TOPICS_WATCH ." - SET notify_status = ". TOPIC_WATCH_UNNOTIFIED ." + if ($update_watched_sql) { + DB()->query("UPDATE " . BB_TOPICS_WATCH . " + SET notify_status = " . TOPIC_WATCH_UNNOTIFIED . " WHERE topic_id = $topic_id AND user_id IN ($update_watched_sql) "); - } - } + } + } - $topic_watch = DB()->fetch_row("SELECT topic_id FROM ". BB_TOPICS_WATCH ." WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}", 'topic_id'); + $topic_watch = DB()->fetch_row("SELECT topic_id FROM " . BB_TOPICS_WATCH . " WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}", 'topic_id'); - if (!$notify_user && !empty($topic_watch)) - { - DB()->query("DELETE FROM ". BB_TOPICS_WATCH ." WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}"); - } - else if ($notify_user && empty($topic_watch)) - { - DB()->query(" + if (!$notify_user && !empty($topic_watch)) { + DB()->query("DELETE FROM " . BB_TOPICS_WATCH . " WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}"); + } else if ($notify_user && empty($topic_watch)) { + DB()->query(" INSERT INTO " . BB_TOPICS_WATCH . " (user_id, topic_id, notify_status) - VALUES (". $userdata['user_id'] .", $topic_id, ". TOPIC_WATCH_NOTIFIED .") + VALUES (" . $userdata['user_id'] . ", $topic_id, " . TOPIC_WATCH_NOTIFIED . ") "); - } - } + } + } } -function insert_post ($mode, $topic_id, $forum_id = '', $old_forum_id = '', $new_topic_id = '', $new_topic_title = '', $old_topic_id = '', $message = '', $poster_id = '') +function insert_post($mode, $topic_id, $forum_id = '', $old_forum_id = '', $new_topic_id = '', $new_topic_title = '', $old_topic_id = '', $message = '', $poster_id = '') { - global $userdata, $lang; + global $userdata, $lang; - if (!$topic_id) return; + if (!$topic_id) return; - $post_username = $post_subject = $post_text = $poster_ip = ''; + $post_username = $post_subject = $post_text = $poster_ip = ''; - $post_time = $current_time = TIMENOW; + $post_time = $current_time = TIMENOW; - if ($mode == 'after_move') - { - if (!$forum_id || !$old_forum_id) return; + if ($mode == 'after_move') { + if (!$forum_id || !$old_forum_id) return; - $sql = "SELECT forum_id, forum_name - FROM ". BB_FORUMS ." + $sql = "SELECT forum_id, forum_name + FROM " . BB_FORUMS . " WHERE forum_id IN($forum_id, $old_forum_id)"; - $forum_names = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $forum_names[$row['forum_id']] = htmlCHR($row['forum_name']); - } - if (!$forum_names) return; + $forum_names = array(); + foreach (DB()->fetch_rowset($sql) as $row) { + $forum_names[$row['forum_id']] = htmlCHR($row['forum_name']); + } + if (!$forum_names) return; - $post_text = sprintf($lang['BOT_TOPIC_MOVED_FROM_TO'], '[url='. make_url(FORUM_URL . $old_forum_id) .']'. $forum_names[$old_forum_id] .'[/url]', '[url='. make_url(FORUM_URL . $forum_id) .']'. $forum_names[$forum_id] .'[/url]', profile_url($userdata)); + $post_text = sprintf($lang['BOT_TOPIC_MOVED_FROM_TO'], '[url=' . make_url(FORUM_URL . $old_forum_id) . ']' . $forum_names[$old_forum_id] . '[/url]', '[url=' . make_url(FORUM_URL . $forum_id) . ']' . $forum_names[$forum_id] . '[/url]', profile_url($userdata)); - $poster_id = BOT_UID; - $poster_ip = '7f000001'; - } - else if ($mode == 'after_split_to_old') - { - $post_text = sprintf($lang['BOT_MESS_SPLITS'], '[url='. make_url(TOPIC_URL . $new_topic_id) .']'. htmlCHR($new_topic_title) .'[/url]', profile_url($userdata)); + $poster_id = BOT_UID; + $poster_ip = '7f000001'; + } else if ($mode == 'after_split_to_old') { + $post_text = sprintf($lang['BOT_MESS_SPLITS'], '[url=' . make_url(TOPIC_URL . $new_topic_id) . ']' . htmlCHR($new_topic_title) . '[/url]', profile_url($userdata)); - $poster_id = BOT_UID; - $poster_ip = '7f000001'; - } - else if ($mode == 'after_split_to_new') - { - $sql = "SELECT t.topic_title, p.post_time - FROM ". BB_TOPICS ." t, ". BB_POSTS ." p + $poster_id = BOT_UID; + $poster_ip = '7f000001'; + } else if ($mode == 'after_split_to_new') { + $sql = "SELECT t.topic_title, p.post_time + FROM " . BB_TOPICS . " t, " . BB_POSTS . " p WHERE t.topic_id = $old_topic_id AND p.post_id = t.topic_first_post_id"; - if ($row = DB()->fetch_row($sql)) - { - $post_time = $row['post_time'] - 1; + if ($row = DB()->fetch_row($sql)) { + $post_time = $row['post_time'] - 1; - $post_text = sprintf($lang['BOT_TOPIC_SPLITS'], '[url='. make_url(TOPIC_URL . $old_topic_id) .']'. $row['topic_title'] .'[/url]', profile_url($userdata)); + $post_text = sprintf($lang['BOT_TOPIC_SPLITS'], '[url=' . make_url(TOPIC_URL . $old_topic_id) . ']' . $row['topic_title'] . '[/url]', profile_url($userdata)); - $poster_id = BOT_UID; - $poster_ip = '7f000001'; - } - else - { - return; - } - } - else - { - return; - } + $poster_id = BOT_UID; + $poster_ip = '7f000001'; + } else { + return; + } + } else { + return; + } - $post_columns = 'topic_id, forum_id, poster_id, post_username, post_time, poster_ip'; - $post_values = "$topic_id, $forum_id, $poster_id, '$post_username', $post_time, '$poster_ip'"; + $post_columns = 'topic_id, forum_id, poster_id, post_username, post_time, poster_ip'; + $post_values = "$topic_id, $forum_id, $poster_id, '$post_username', $post_time, '$poster_ip'"; - DB()->query("INSERT INTO ". BB_POSTS ." ($post_columns) VALUES ($post_values)"); + DB()->query("INSERT INTO " . BB_POSTS . " ($post_columns) VALUES ($post_values)"); - $post_id = DB()->sql_nextid(); - $post_text = DB()->escape($post_text); + $post_id = DB()->sql_nextid(); + $post_text = DB()->escape($post_text); - $post_text_columns = 'post_id, post_text'; - $post_text_values = "$post_id, '$post_text'"; + $post_text_columns = 'post_id, post_text'; + $post_text_values = "$post_id, '$post_text'"; - DB()->query("INSERT INTO ". BB_POSTS_TEXT ." ($post_text_columns) VALUES ($post_text_values)"); -} \ No newline at end of file + DB()->query("INSERT INTO " . BB_POSTS_TEXT . " ($post_text_columns) VALUES ($post_text_values)"); +} diff --git a/library/includes/functions_torrent.php b/library/includes/functions_torrent.php index ba7d3e036..efc48712a 100644 --- a/library/includes/functions_torrent.php +++ b/library/includes/functions_torrent.php @@ -2,807 +2,688 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -function torrent_auth_check ($forum_id, $poster_id) +function torrent_auth_check($forum_id, $poster_id) { - global $lang, $userdata; + global $lang, $userdata; - if (IS_ADMIN || IS_CP_HOLDER || $poster_id == $userdata['user_id']) - { - return true; - } + if (IS_ADMIN || IS_CP_HOLDER || $poster_id == $userdata['user_id']) { + return true; + } - if (IS_MOD) - { - $is_auth = auth(AUTH_MOD, $forum_id, $userdata); - if ($is_auth['auth_mod']) return true; - } + if (IS_MOD) { + $is_auth = auth(AUTH_MOD, $forum_id, $userdata); + if ($is_auth['auth_mod']) return true; + } - bb_die($lang['NOT_MODERATOR']); + bb_die($lang['NOT_MODERATOR']); } -function tracker_unregister ($topic_id, $redirect_url = '') +function tracker_unregister($topic_id, $redirect_url = '') { - global $lang, $log_action; + global $lang, $log_action; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $tor = DB()->fetch_row(" - SELECT forum_id, tor_status FROM ". BB_BT_TORRENTS ." WHERE topic_id = ". intval($topic_id) ." LIMIT 1 + $tor = DB()->fetch_row(" + SELECT forum_id, tor_status FROM " . BB_BT_TORRENTS . " WHERE topic_id = " . intval($topic_id) . " LIMIT 1 "); - $tor_status = isset($tor['tor_status']) ? $tor['tor_status'] : null; + $tor_status = isset($tor['tor_status']) ? $tor['tor_status'] : null; - // удаление файла - if (defined('IN_AJAX')) - { - if (is_null($tor_status)) - { - return; - } - } - // обычная разрегистрация - else - { - if (is_null($tor_status)) - { - bb_die('Торрент не зарегистрирован'); - } - torrent_auth_check($tor['forum_id'], 0); - } + // удаление файла + if (defined('IN_AJAX')) { + if (is_null($tor_status)) { + return; + } + } // обычная разрегистрация + else { + if (is_null($tor_status)) { + bb_die('Торрент не зарегистрирован'); + } + torrent_auth_check($tor['forum_id'], 0); + } - // Remove peers from tracker - tracker_rm_torrent($topic_id); + // Remove peers from tracker + tracker_rm_torrent($topic_id); - // Delete torrent - DB()->query("DELETE FROM ". BB_BT_TORRENTS ." WHERE topic_id = $topic_id LIMIT 1"); + // Delete torrent + DB()->query("DELETE FROM " . BB_BT_TORRENTS . " WHERE topic_id = $topic_id LIMIT 1"); - // Log action - if (IS_AM || IS_CP_HOLDER) - { - $log_action->mod('tor_unreg', array( - 'forum_id' => $tor['forum_id'], - 'topic_id' => $topic_id, - 'topic_title' => get_topic_title($topic_id), - )); - } + // Log action + if (IS_AM || IS_CP_HOLDER) { + $log_action->mod('tor_unreg', array( + 'forum_id' => $tor['forum_id'], + 'topic_id' => $topic_id, + 'topic_title' => get_topic_title($topic_id), + )); + } - // Unset DL-type for topic - if ($di->config->get('bt_unset_dltype_on_tor_unreg') && $topic_id) - { - DB()->query("UPDATE ". BB_TOPICS ." SET tracker_status = 0 WHERE topic_id = $topic_id LIMIT 1"); - } + // Unset DL-type for topic + if ($di->config->get('bt_unset_dltype_on_tor_unreg') && $topic_id) { + DB()->query("UPDATE " . BB_TOPICS . " SET tracker_status = 0 WHERE topic_id = $topic_id LIMIT 1"); + } - // Ocelot - if ($di->config->get('ocelot.enabled')) - { - if ($row = DB()->fetch_row("SELECT info_hash FROM ". BB_BT_TORRENTS ." WHERE topic_id = $topic_id LIMIT 1")) - { - $info_hash = $row['info_hash']; - } - ocelot_update_tracker('delete_torrent', array('info_hash' => rawurlencode($info_hash), 'id' => $topic_id)); - } + // Ocelot + if ($di->config->get('ocelot.enabled')) { + if ($row = DB()->fetch_row("SELECT info_hash FROM " . BB_BT_TORRENTS . " WHERE topic_id = $topic_id LIMIT 1")) { + $info_hash = $row['info_hash']; + } + ocelot_update_tracker('delete_torrent', array('info_hash' => rawurlencode($info_hash), 'id' => $topic_id)); + } - if (defined('IN_AJAX')) - { - return; - } - else if ($redirect_url) - { - redirect($redirect_url); - } - else - { - set_die_append_msg($tor['forum_id'], $topic_id); - bb_die($lang['BT_UNREGISTERED']); - } + if (defined('IN_AJAX')) { + return; + } else if ($redirect_url) { + redirect($redirect_url); + } else { + set_die_append_msg($tor['forum_id'], $topic_id); + bb_die($lang['BT_UNREGISTERED']); + } } -function torrent_cp_close ($topic_id, $forum_id) +function torrent_cp_close($topic_id, $forum_id) { - global $log_action, $userdata; + global $log_action, $userdata; - DB()->query(" - UPDATE ". BB_BT_TORRENTS ." SET - tor_status = ". TOR_CLOSED_CPHOLD .", - tor_status_time = ". TIMENOW .", - tor_status_uid = ". $userdata['user_id'] ." + DB()->query(" + UPDATE " . BB_BT_TORRENTS . " SET + tor_status = " . TOR_CLOSED_CPHOLD . ", + tor_status_time = " . TIMENOW . ", + tor_status_uid = " . $userdata['user_id'] . " WHERE topic_id = $topic_id LIMIT 1 "); - // Remove peers from tracker - tracker_rm_torrent($topic_id); + // Remove peers from tracker + tracker_rm_torrent($topic_id); - $log_action->mod('tor_cphold_close', array( - 'forum_id' => $forum_id, - 'topic_id' => $topic_id, - 'topic_title' => get_topic_title($topic_id), - )); + $log_action->mod('tor_cphold_close', array( + 'forum_id' => $forum_id, + 'topic_id' => $topic_id, + 'topic_title' => get_topic_title($topic_id), + )); - require_once(INC_DIR .'functions_admin.php'); - topic_lock_unlock($topic_id, 'lock'); + require_once(INC_DIR . 'functions_admin.php'); + topic_lock_unlock($topic_id, 'lock'); } -function tracker_register ($topic_id, $mode = '', $tor_status = TOR_NOT_APPROVED, $reg_time = TIMENOW) +function tracker_register($topic_id, $mode = '', $tor_status = TOR_NOT_APPROVED, $reg_time = TIMENOW) { - global $lang; + global $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $reg_mode = $mode; + $reg_mode = $mode; - $sql = " + $sql = " SELECT t.forum_id, t.topic_poster, t.attach_ext_id, t.tracker_status, f.allow_reg_tracker - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f - WHERE t.topic_id = ". intval($topic_id) ." + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f + WHERE t.topic_id = " . intval($topic_id) . " AND f.forum_id = t.forum_id LIMIT 1 "; - if (!$tor = DB()->fetch_row($sql)) - { - return torrent_error_exit('Invalid topic_id'); - } - $forum_id = $tor['forum_id']; - $poster_id = $tor['topic_poster']; + if (!$tor = DB()->fetch_row($sql)) { + return torrent_error_exit('Invalid topic_id'); + } + $forum_id = $tor['forum_id']; + $poster_id = $tor['topic_poster']; - if ($tor['attach_ext_id'] != 8) return torrent_error_exit($lang['NOT_TORRENT']); - if (!$tor['allow_reg_tracker']) return torrent_error_exit($lang['REG_NOT_ALLOWED_IN_THIS_FORUM']); - if ($tor['tracker_status']) return torrent_error_exit($lang['ALREADY_REG']); + if ($tor['attach_ext_id'] != 8) return torrent_error_exit($lang['NOT_TORRENT']); + if (!$tor['allow_reg_tracker']) return torrent_error_exit($lang['REG_NOT_ALLOWED_IN_THIS_FORUM']); + if ($tor['tracker_status']) return torrent_error_exit($lang['ALREADY_REG']); - if ($reg_mode != 'mcp_tor_register') - { - torrent_auth_check($forum_id, $poster_id); - } + if ($reg_mode != 'mcp_tor_register') { + torrent_auth_check($forum_id, $poster_id); + } - $filename = get_attach_path($topic_id, 8); + $filename = get_attach_path($topic_id, 8); - if (!file_exists($filename)) - { - return torrent_error_exit($lang['NOT_FOUND']); - } - if (!$tor_decoded = bdecode_file($filename)) - { - return torrent_error_exit($lang['TORFILE_INVALID']); - } + if (!file_exists($filename)) { + return torrent_error_exit($lang['NOT_FOUND']); + } + if (!$tor_decoded = bdecode_file($filename)) { + return torrent_error_exit($lang['TORFILE_INVALID']); + } - if ($di->config->get('bt_disable_dht')) - { - $tor_decoded['info']['private'] = (int) 1; - $fp = fopen($filename, 'w+'); - fwrite($fp, \Rych\Bencode\Bencode::encode($tor_decoded)); - fclose($fp); - } + if ($di->config->get('bt_disable_dht')) { + $tor_decoded['info']['private'] = (int)1; + $fp = fopen($filename, 'w+'); + fwrite($fp, \Rych\Bencode\Bencode::encode($tor_decoded)); + fclose($fp); + } - $info = ($tor_decoded['info']) ? $tor_decoded['info'] : array(); + $info = ($tor_decoded['info']) ? $tor_decoded['info'] : array(); - if (!isset($info['name']) || !isset($info['piece length']) || !isset($info['pieces']) || strlen($info['pieces']) % 20 != 0) - { - return torrent_error_exit($lang['TORFILE_INVALID']); - } + if (!isset($info['name']) || !isset($info['piece length']) || !isset($info['pieces']) || strlen($info['pieces']) % 20 != 0) { + return torrent_error_exit($lang['TORFILE_INVALID']); + } - $info_hash = pack('H*', sha1(\Rych\Bencode\Bencode::encode($info))); - $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); - $info_hash_md5 = md5($info_hash); + $info_hash = pack('H*', sha1(\Rych\Bencode\Bencode::encode($info))); + $info_hash_sql = rtrim(DB()->escape($info_hash), ' '); + $info_hash_md5 = md5($info_hash); - // Ocelot - if ($di->config->get('ocelot.enabled')) - { - ocelot_update_tracker('add_torrent', array('info_hash' => rawurlencode($info_hash), 'id' => $topic_id, 'freetorrent' => 0)); - } + // Ocelot + if ($di->config->get('ocelot.enabled')) { + ocelot_update_tracker('add_torrent', array('info_hash' => rawurlencode($info_hash), 'id' => $topic_id, 'freetorrent' => 0)); + } - if ($row = DB()->fetch_row("SELECT topic_id FROM ". BB_BT_TORRENTS ." WHERE info_hash = '$info_hash_sql' LIMIT 1")) - { - return torrent_error_exit(sprintf($lang['BT_REG_FAIL_SAME_HASH'], TOPIC_URL . $row['topic_id'])); - } + if ($row = DB()->fetch_row("SELECT topic_id FROM " . BB_BT_TORRENTS . " WHERE info_hash = '$info_hash_sql' LIMIT 1")) { + return torrent_error_exit(sprintf($lang['BT_REG_FAIL_SAME_HASH'], TOPIC_URL . $row['topic_id'])); + } - $totallen = 0; + $totallen = 0; - if (isset($info['length'])) - { - $totallen = (float) $info['length']; - } - else if (isset($info['files']) && is_array($info['files'])) - { - foreach ($info['files'] as $fn => $f) - { - $totallen += (float) $f['length']; - } - } - else - { - return torrent_error_exit($lang['TORFILE_INVALID']); - } + if (isset($info['length'])) { + $totallen = (float)$info['length']; + } else if (isset($info['files']) && is_array($info['files'])) { + foreach ($info['files'] as $fn => $f) { + $totallen += (float)$f['length']; + } + } else { + return torrent_error_exit($lang['TORFILE_INVALID']); + } - $size = sprintf('%.0f', (float) $totallen); + $size = sprintf('%.0f', (float)$totallen); - $columns = ' info_hash, poster_id, topic_id, forum_id, size, reg_time, tor_status'; - $values = "'$info_hash_sql', $poster_id, $topic_id, $forum_id, '$size', $reg_time, $tor_status"; + $columns = ' info_hash, poster_id, topic_id, forum_id, size, reg_time, tor_status'; + $values = "'$info_hash_sql', $poster_id, $topic_id, $forum_id, '$size', $reg_time, $tor_status"; - $sql = "INSERT INTO ". BB_BT_TORRENTS ." ($columns) VALUES ($values)"; + $sql = "INSERT INTO " . BB_BT_TORRENTS . " ($columns) VALUES ($values)"; - if (!DB()->sql_query($sql)) - { - $sql_error = DB()->sql_error(); + if (!DB()->sql_query($sql)) { + $sql_error = DB()->sql_error(); - if ($sql_error['code'] == 1062) // Duplicate entry - { - return torrent_error_exit($lang['BT_REG_FAIL_SAME_HASH']); - } - bb_die('Could not register torrent on tracker'); - } + if ($sql_error['code'] == 1062) // Duplicate entry + { + return torrent_error_exit($lang['BT_REG_FAIL_SAME_HASH']); + } + bb_die('Could not register torrent on tracker'); + } - // Set topic status - DB()->query("UPDATE ". BB_TOPICS ." SET tracker_status = 1 WHERE topic_id = $topic_id LIMIT 1"); + // Set topic status + DB()->query("UPDATE " . BB_TOPICS . " SET tracker_status = 1 WHERE topic_id = $topic_id LIMIT 1"); - // Remove peers from tracker - tracker_rm_torrent($topic_id); + // Remove peers from tracker + tracker_rm_torrent($topic_id); - if ($reg_mode == 'request' || $reg_mode == 'newtopic') - { - set_die_append_msg($forum_id, $topic_id); - bb_die(sprintf($lang['BT_REGISTERED'], DOWNLOAD_URL . $topic_id)); - } - else if ($reg_mode == 'mcp_tor_register') - { - return 'OK'; - } + if ($reg_mode == 'request' || $reg_mode == 'newtopic') { + set_die_append_msg($forum_id, $topic_id); + bb_die(sprintf($lang['BT_REGISTERED'], DOWNLOAD_URL . $topic_id)); + } else if ($reg_mode == 'mcp_tor_register') { + return 'OK'; + } - return true; + return true; } -function delete_torrent ($topic_id) +function delete_torrent($topic_id) { - tracker_unregister($topic_id); - delete_attach($topic_id, 8); + tracker_unregister($topic_id); + delete_attach($topic_id, 8); - return true; + return true; } -function change_tor_status ($topic_id, $tor_status) +function change_tor_status($topic_id, $tor_status) { - global $userdata; + global $userdata; - $tor_status = (int) $tor_status; + $tor_status = (int)$tor_status; - $tor = DB()->fetch_row("SELECT forum_id, poster_id FROM ". BB_BT_TORRENTS ." WHERE topic_id = ". intval($topic_id) ." LIMIT 1"); + $tor = DB()->fetch_row("SELECT forum_id, poster_id FROM " . BB_BT_TORRENTS . " WHERE topic_id = " . intval($topic_id) . " LIMIT 1"); - torrent_auth_check($tor['forum_id'], $tor['poster_id']); + torrent_auth_check($tor['forum_id'], $tor['poster_id']); - DB()->query(" - UPDATE ". BB_BT_TORRENTS ." SET + DB()->query(" + UPDATE " . BB_BT_TORRENTS . " SET tor_status = $tor_status, checked_user_id = {$userdata['user_id']}, - checked_time = '". TIMENOW ."' + checked_time = '" . TIMENOW . "' WHERE topic_id = $topic_id LIMIT 1 "); } // Set gold / silver type for torrent -function change_tor_type ($topic_id, $tor_status_gold) +function change_tor_type($topic_id, $tor_status_gold) { - global $lang; + global $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (!IS_AM) bb_die($lang['ONLY_FOR_MOD']); + if (!IS_AM) bb_die($lang['ONLY_FOR_MOD']); - $tor_status_gold = intval($tor_status_gold); - $info_hash = null; + $tor_status_gold = intval($tor_status_gold); + $info_hash = null; - DB()->query("UPDATE ". BB_BT_TORRENTS ." SET tor_type = $tor_status_gold WHERE topic_id = $topic_id LIMIT 1"); + DB()->query("UPDATE " . BB_BT_TORRENTS . " SET tor_type = $tor_status_gold WHERE topic_id = $topic_id LIMIT 1"); - // Ocelot - if ($di->config->get('ocelot.enabled')) - { - if ($row = DB()->fetch_row("SELECT info_hash FROM ". BB_BT_TORRENTS ." WHERE topic_id = $topic_id LIMIT 1")) - { - $info_hash = $row['info_hash']; - } - ocelot_update_tracker('update_torrent', array('info_hash' => rawurlencode($info_hash), 'freetorrent' => $tor_status_gold)); - } + // Ocelot + if ($di->config->get('ocelot.enabled')) { + if ($row = DB()->fetch_row("SELECT info_hash FROM " . BB_BT_TORRENTS . " WHERE topic_id = $topic_id LIMIT 1")) { + $info_hash = $row['info_hash']; + } + ocelot_update_tracker('update_torrent', array('info_hash' => rawurlencode($info_hash), 'freetorrent' => $tor_status_gold)); + } } -function send_torrent_with_passkey ($t_data) +function send_torrent_with_passkey($t_data) { - global $lang, $tr_cfg, $userdata; + global $lang, $tr_cfg, $userdata; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $topic_id = $t_data['topic_id']; - $poster_id = $t_data['topic_poster']; - $user_id = $userdata['user_id']; + $topic_id = $t_data['topic_id']; + $poster_id = $t_data['topic_poster']; + $user_id = $userdata['user_id']; - // Запрет на скачивание закрытого или незарегистрированного торрента - $row = DB()->fetch_row("SELECT tor_status FROM ". BB_BT_TORRENTS ." WHERE topic_id = $topic_id LIMIT 1"); + // Запрет на скачивание закрытого или незарегистрированного торрента + $row = DB()->fetch_row("SELECT tor_status FROM " . BB_BT_TORRENTS . " WHERE topic_id = $topic_id LIMIT 1"); - if (!isset($row['tor_status'])) - { - bb_die($lang['PASSKEY_ERR_TOR_NOT_REG']); - } - elseif ($di->config->get('tor_frozen.' . $row['tor_status'])) - { - if (!IS_AM) bb_die("Раздача имеет статус: {$lang['TOR_STATUS_NAME'][$row['tor_status']]}

        Скачивание запрещено"); //TODO: перевести - } + if (!isset($row['tor_status'])) { + bb_die($lang['PASSKEY_ERR_TOR_NOT_REG']); + } elseif ($di->config->get('tor_frozen.' . $row['tor_status'])) { + if (!IS_AM) bb_die("Раздача имеет статус: {$lang['TOR_STATUS_NAME'][$row['tor_status']]}

        Скачивание запрещено"); //TODO: перевести + } - $passkey_val = ''; + $passkey_val = ''; - if ($bt_userdata = get_bt_userdata($user_id)) - { - $passkey_val = $bt_userdata['auth_key']; - } + if ($bt_userdata = get_bt_userdata($user_id)) { + $passkey_val = $bt_userdata['auth_key']; + } - if (!$passkey_val) - { - if (!$passkey_val = generate_passkey($user_id)) - { - bb_simple_die('Could not generate passkey'); - } - elseif ($di->config->get('ocelot.enabled')) - { - ocelot_update_tracker('add_user', array('id' => $user_id ,'passkey' => $passkey_val)); - } - } + if (!$passkey_val) { + if (!$passkey_val = generate_passkey($user_id)) { + bb_simple_die('Could not generate passkey'); + } elseif ($di->config->get('ocelot.enabled')) { + ocelot_update_tracker('add_user', array('id' => $user_id, 'passkey' => $passkey_val)); + } + } - // Ratio limit for torrents dl - $user_ratio = get_bt_ratio($bt_userdata); - $min_ratio = $di->config->get('bt_min_ratio_allow_dl_tor'); + // Ratio limit for torrents dl + $user_ratio = get_bt_ratio($bt_userdata); + $min_ratio = $di->config->get('bt_min_ratio_allow_dl_tor'); - if ($min_ratio && $user_id != $poster_id && !is_null($user_ratio)) - { - if ($user_ratio < $min_ratio) - { - $dl = DB()->fetch_row(" - SELECT user_status FROM ". BB_BT_DLSTATUS ." WHERE topic_id = $topic_id AND user_id = $user_id LIMIT 1 + if ($min_ratio && $user_id != $poster_id && !is_null($user_ratio)) { + if ($user_ratio < $min_ratio) { + $dl = DB()->fetch_row(" + SELECT user_status FROM " . BB_BT_DLSTATUS . " WHERE topic_id = $topic_id AND user_id = $user_id LIMIT 1 "); - if (!isset($dl['user_status']) || $dl['user_status'] != DL_STATUS_COMPLETE) - { - bb_die(sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$user_id&dlc=1")); - } - } - } + if (!isset($dl['user_status']) || $dl['user_status'] != DL_STATUS_COMPLETE) { + bb_die(sprintf($lang['BT_LOW_RATIO_FOR_DL'], round($user_ratio, 2), "search.php?dlu=$user_id&dlc=1")); + } + } + } - /* TODO: восстановить - // лимит количества скачиваний торрент-файлов в день - if ($user_id != $poster_id && !$t_data['is_am']) - { - // лимит - $daily_dls_limit = 50; + /* TODO: восстановить + // лимит количества скачиваний торрент-файлов в день + if ($user_id != $poster_id && !$t_data['is_am']) + { + // лимит + $daily_dls_limit = 50; - if (!is_null($user_ratio) && $user_ratio >= 1 && $bt_userdata['u_up_total'] >= 107374182400 )// 100 GB - { - $daily_dls_limit = 100; - } + if (!is_null($user_ratio) && $user_ratio >= 1 && $bt_userdata['u_up_total'] >= 107374182400 )// 100 GB + { + $daily_dls_limit = 100; + } - // число скачиваний - $daily_dls_cnt = (int) DB()->fetch_row("SELECT dls_cnt FROM ". BB_USER_DLS_DAILY ." WHERE user_id = $user_id LIMIT 1", 'dls_cnt'); + // число скачиваний + $daily_dls_cnt = (int) DB()->fetch_row("SELECT dls_cnt FROM ". BB_USER_DLS_DAILY ." WHERE user_id = $user_id LIMIT 1", 'dls_cnt'); - if ($daily_dls_cnt >= $daily_dls_limit) - { - // повторное скачивание - $can_redownload = DB()->fetch_row("SELECT 1 FROM ". BB_BT_DLS_COUNT ." WHERE topic_id = $topic_id AND user_id = $user_id LIMIT 1"); + if ($daily_dls_cnt >= $daily_dls_limit) + { + // повторное скачивание + $can_redownload = DB()->fetch_row("SELECT 1 FROM ". BB_BT_DLS_COUNT ." WHERE topic_id = $topic_id AND user_id = $user_id LIMIT 1"); - if (!$can_redownload) - { - bb_log(join("\t", array(date('H:i:s'), $user->ip, $user->id, $topic_id))."\n", 'dls/'.date('m-d') .'-limit'); - set_die_append_msg(null, $topic_id); - bb_die("Вы уже исчерпали суточный лимит скачиваний торрент-файлов

        Ваш текущий лимит: $daily_dls_limit в день"); - } - else - { - bb_log(join("\t", array(date('H:i:s'), $user->ip, $user->id, $topic_id))."\n", 'dls/'.date('m-d') .'-redown'); - } - } + if (!$can_redownload) + { + bb_log(join("\t", array(date('H:i:s'), $user->ip, $user->id, $topic_id))."\n", 'dls/'.date('m-d') .'-limit'); + set_die_append_msg(null, $topic_id); + bb_die("Вы уже исчерпали суточный лимит скачиваний торрент-файлов

        Ваш текущий лимит: $daily_dls_limit в день"); + } + else + { + bb_log(join("\t", array(date('H:i:s'), $user->ip, $user->id, $topic_id))."\n", 'dls/'.date('m-d') .'-redown'); + } + } - // счетчик количества скачиваний торрент-файла (для `complete_count` в BB_BT_TORRENTS) - DB()->query("INSERT IGNORE INTO ". BB_BT_DLS_COUNT ." (topic_id, user_id) VALUES ($topic_id, $user_id)"); + // счетчик количества скачиваний торрент-файла (для `complete_count` в BB_BT_TORRENTS) + DB()->query("INSERT IGNORE INTO ". BB_BT_DLS_COUNT ." (topic_id, user_id) VALUES ($topic_id, $user_id)"); - // если файл еще не был скачан этим юзером, увеличиваем счетчик скачиваний - if (DB()->affected_rows() > 0) - { - DB()->query(" - INSERT IGNORE INTO ". BB_USER_DLS_DAILY ." (user_id, dls_cnt) VALUES ($user_id, 1) ON DUPLICATE KEY UPDATE dls_cnt = dls_cnt + 1 - "); - } - } - */ + // если файл еще не был скачан этим юзером, увеличиваем счетчик скачиваний + if (DB()->affected_rows() > 0) + { + DB()->query(" + INSERT IGNORE INTO ". BB_USER_DLS_DAILY ." (user_id, dls_cnt) VALUES ($user_id, 1) ON DUPLICATE KEY UPDATE dls_cnt = dls_cnt + 1 + "); + } + } + */ - $filename = get_attach_path($topic_id, 8); - if (!file_exists($filename)) - { - bb_simple_die($lang['NOT_FOUND']); - } - if (!$tor = bdecode_file($filename)) - { - bb_simple_die($lang['TORFILE_INVALID']); - } + $filename = get_attach_path($topic_id, 8); + if (!file_exists($filename)) { + bb_simple_die($lang['NOT_FOUND']); + } + if (!$tor = bdecode_file($filename)) { + bb_simple_die($lang['TORFILE_INVALID']); + } - // tor cleanup - unset($tor['codepage']); - unset($tor['nodes']); + // tor cleanup + unset($tor['codepage']); + unset($tor['nodes']); - // Announce URL - $announce = $di->config->get('ocelot.enabled') ? strval($di->config->get('ocelot.url') .$passkey_val. "/announce") : strval($di->config->get('bt_announce_url') . "?{$di->config->get('passkey_key')}=$passkey_val"); + // Announce URL + $announce = $di->config->get('ocelot.enabled') ? strval($di->config->get('ocelot.url') . $passkey_val . "/announce") : strval($di->config->get('bt_announce_url') . "?{$di->config->get('passkey_key')}=$passkey_val"); - // Replace original announce url with tracker default - if ($di->config->get('bt_replace_ann_url') || !isset($tor['announce'])) - { - $tor['announce'] = $announce; - } + // Replace original announce url with tracker default + if ($di->config->get('bt_replace_ann_url') || !isset($tor['announce'])) { + $tor['announce'] = $announce; + } - // Delete all additional urls - if ($di->config->get('bt_del_addit_ann_urls') || $di->config->get('bt_disable_dht')) - { - unset($tor['announce-list']); - } - elseif (isset($tor['announce-list'])) - { - $tor['announce-list'] = array_merge($tor['announce-list'], [[$announce]]); - } + // Delete all additional urls + if ($di->config->get('bt_del_addit_ann_urls') || $di->config->get('bt_disable_dht')) { + unset($tor['announce-list']); + } elseif (isset($tor['announce-list'])) { + $tor['announce-list'] = array_merge($tor['announce-list'], [[$announce]]); + } - // Add retracker - if (isset($tr_cfg['retracker']) && $tr_cfg['retracker']) - { - if (bf($userdata['user_opt'], 'user_opt', 'user_retracker') || IS_GUEST) - { - if (!isset($tor['announce-list'])) - { - $tor['announce-list'] = [ - [$announce], - [$tr_cfg['retracker_host']] - ]; - } - else - { - $tor['announce-list'] = array_merge($tor['announce-list'], [[$tr_cfg['retracker_host']]]); - } - } - } + // Add retracker + if (isset($tr_cfg['retracker']) && $tr_cfg['retracker']) { + if (bf($userdata['user_opt'], 'user_opt', 'user_retracker') || IS_GUEST) { + if (!isset($tor['announce-list'])) { + $tor['announce-list'] = [ + [$announce], + [$tr_cfg['retracker_host']] + ]; + } else { + $tor['announce-list'] = array_merge($tor['announce-list'], [[$tr_cfg['retracker_host']]]); + } + } + } - // Add publisher & topic url - $publisher_name = $di->config->get('server_name'); - $publisher_url = make_url(TOPIC_URL . $topic_id); + // Add publisher & topic url + $publisher_name = $di->config->get('server_name'); + $publisher_url = make_url(TOPIC_URL . $topic_id); - $tor['publisher'] = strval($publisher_name); - unset($tor['publisher.utf-8']); + $tor['publisher'] = strval($publisher_name); + unset($tor['publisher.utf-8']); - $tor['publisher-url'] = strval($publisher_url); - unset($tor['publisher-url.utf-8']); + $tor['publisher-url'] = strval($publisher_url); + unset($tor['publisher-url.utf-8']); - $tor['comment'] = strval($publisher_url); - unset($tor['comment.utf-8']); + $tor['comment'] = strval($publisher_url); + unset($tor['comment.utf-8']); - // Send torrent - $output = \Rych\Bencode\Bencode::encode($tor); - $dl_fname = '['.$di->config->get('server_name').'].t' . $topic_id . '.torrent'; + // Send torrent + $output = \Rych\Bencode\Bencode::encode($tor); + $dl_fname = '[' . $di->config->get('server_name') . '].t' . $topic_id . '.torrent'; - if (!empty($_COOKIE['explain'])) - { - $out = "attach path: $filename

        "; - $tor['info']['pieces'] = '[...] '. strlen($tor['info']['pieces']) .' bytes'; - $out .= print_r($tor, true); - bb_die("
        $out
        "); - } + if (!empty($_COOKIE['explain'])) { + $out = "attach path: $filename

        "; + $tor['info']['pieces'] = '[...] ' . strlen($tor['info']['pieces']) . ' bytes'; + $out .= print_r($tor, true); + bb_die("
        $out
        "); + } - header("Content-Type: application/x-bittorrent; name=\"$dl_fname\""); - header("Content-Disposition: attachment; filename=\"$dl_fname\""); + header("Content-Type: application/x-bittorrent; name=\"$dl_fname\""); + header("Content-Disposition: attachment; filename=\"$dl_fname\""); - bb_exit($output); + bb_exit($output); } -function generate_passkey ($user_id, $force_generate = false) +function generate_passkey($user_id, $force_generate = false) { - global $lang; + global $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $user_id = (int) $user_id; + $user_id = (int)$user_id; - // Check if user can change passkey - if (!$force_generate) - { - $sql = "SELECT user_opt FROM ". BB_USERS ." WHERE user_id = $user_id LIMIT 1"; + // Check if user can change passkey + if (!$force_generate) { + $sql = "SELECT user_opt FROM " . BB_USERS . " WHERE user_id = $user_id LIMIT 1"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not query userdata for passkey'); - } - if ($row = DB()->sql_fetchrow($result)) - { - if (bf($row['user_opt'], 'user_opt', 'dis_passkey')) - { - bb_die($lang['NOT_AUTHORISED']); - } - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not query userdata for passkey'); + } + if ($row = DB()->sql_fetchrow($result)) { + if (bf($row['user_opt'], 'user_opt', 'dis_passkey')) { + bb_die($lang['NOT_AUTHORISED']); + } + } + } - // Delete all active user records in tracker - tracker_rm_user($user_id); + // Delete all active user records in tracker + tracker_rm_user($user_id); - for ($i=0; $i < 20; $i++) - { - $passkey_val = make_rand_str(BT_AUTH_KEY_LENGTH); - $old_passkey = null; + for ($i = 0; $i < 20; $i++) { + $passkey_val = make_rand_str(BT_AUTH_KEY_LENGTH); + $old_passkey = null; - if ($row = DB()->fetch_row("SELECT auth_key FROM ". BB_BT_USERS ." WHERE user_id = $user_id LIMIT 1")) - { - $old_passkey = $row['auth_key']; - } + if ($row = DB()->fetch_row("SELECT auth_key FROM " . BB_BT_USERS . " WHERE user_id = $user_id LIMIT 1")) { + $old_passkey = $row['auth_key']; + } - // Insert new row - DB()->query("INSERT IGNORE INTO ". BB_BT_USERS ." (user_id, auth_key) VALUES ($user_id, '$passkey_val')"); + // Insert new row + DB()->query("INSERT IGNORE INTO " . BB_BT_USERS . " (user_id, auth_key) VALUES ($user_id, '$passkey_val')"); - if (DB()->affected_rows() == 1) - { - return $passkey_val; - } - // Update - DB()->query("UPDATE IGNORE ". BB_BT_USERS ." SET auth_key = '$passkey_val' WHERE user_id = $user_id LIMIT 1"); + if (DB()->affected_rows() == 1) { + return $passkey_val; + } + // Update + DB()->query("UPDATE IGNORE " . BB_BT_USERS . " SET auth_key = '$passkey_val' WHERE user_id = $user_id LIMIT 1"); - if (DB()->affected_rows() == 1) - { - // Ocelot - if ($di->config->get('ocelot.enabled')) - { - ocelot_update_tracker('change_passkey', array('oldpasskey' => $old_passkey,'newpasskey' => $passkey_val)); - } - return $passkey_val; - } - } - return false; + if (DB()->affected_rows() == 1) { + // Ocelot + if ($di->config->get('ocelot.enabled')) { + ocelot_update_tracker('change_passkey', array('oldpasskey' => $old_passkey, 'newpasskey' => $passkey_val)); + } + return $passkey_val; + } + } + return false; } -function torrent_error_exit ($message) +function torrent_error_exit($message) { - global $reg_mode, $return_message, $lang; + global $reg_mode, $return_message, $lang; - if (isset($reg_mode) && $reg_mode == 'mcp_tor_register') - { - return $message; - } + if (isset($reg_mode) && $reg_mode == 'mcp_tor_register') { + return $message; + } - $msg = ''; + $msg = ''; - if (isset($reg_mode) && ($reg_mode == 'request' || $reg_mode == 'newtopic')) - { - if (isset($return_message)) - { - $msg .= $return_message .'



        '; - } - $msg .= ''. $lang['BT_REG_FAIL'] .'

        '; - } + if (isset($reg_mode) && ($reg_mode == 'request' || $reg_mode == 'newtopic')) { + if (isset($return_message)) { + $msg .= $return_message . '



        '; + } + $msg .= '' . $lang['BT_REG_FAIL'] . '

        '; + } - bb_die($msg . $message); + bb_die($msg . $message); } -function tracker_rm_torrent ($topic_id) +function tracker_rm_torrent($topic_id) { - return DB()->sql_query("DELETE FROM ". BB_BT_TRACKER ." WHERE topic_id = ". (int) $topic_id); + return DB()->sql_query("DELETE FROM " . BB_BT_TRACKER . " WHERE topic_id = " . (int)$topic_id); } -function tracker_rm_user ($user_id) +function tracker_rm_user($user_id) { - return DB()->sql_query("DELETE FROM ". BB_BT_TRACKER ." WHERE user_id = ". (int) $user_id); + return DB()->sql_query("DELETE FROM " . BB_BT_TRACKER . " WHERE user_id = " . (int)$user_id); } -function ocelot_update_tracker ($action, $updates) +function ocelot_update_tracker($action, $updates) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $get = $di->config->get('ocelot.secret') . "/update?action=$action"; + $get = $di->config->get('ocelot.secret') . "/update?action=$action"; - foreach ($updates as $key => $value) - { - $get .= "&$key=$value"; - } + foreach ($updates as $key => $value) { + $get .= "&$key=$value"; + } - $max_attempts = 3; - $err = false; + $max_attempts = 3; + $err = false; - if (ocelot_send_request($get, $max_attempts, $err) === false) - { - return false; - } + if (ocelot_send_request($get, $max_attempts, $err) === false) { + return false; + } - return true; + return true; } -function ocelot_send_request ($get, $max_attempts = 1, &$err = false) +function ocelot_send_request($get, $max_attempts = 1, &$err = false) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $header = "GET /$get HTTP/1.1\r\nConnection: Close\r\n\r\n"; - $attempts = $sleep = $success = $response = 0; - $start_time = microtime(true); + $header = "GET /$get HTTP/1.1\r\nConnection: Close\r\n\r\n"; + $attempts = $sleep = $success = $response = 0; + $start_time = microtime(true); - while (!$success && $attempts++ < $max_attempts) - { - if ($sleep) - { - sleep($sleep); - } + while (!$success && $attempts++ < $max_attempts) { + if ($sleep) { + sleep($sleep); + } - // Send request - $file = fsockopen($di->config->get('ocelot.host'), $di->config->get('ocelot.port'), $error_num, $error_string); - if ($file) - { - if (fwrite($file, $header) === false) - { - $err = "Failed to fwrite()"; - $sleep = 3; - continue; - } - } - else - { - $err = "Failed to fsockopen() - $error_num - $error_string"; - $sleep = 6; - continue; - } + // Send request + $file = fsockopen($di->config->get('ocelot.host'), $di->config->get('ocelot.port'), $error_num, $error_string); + if ($file) { + if (fwrite($file, $header) === false) { + $err = "Failed to fwrite()"; + $sleep = 3; + continue; + } + } else { + $err = "Failed to fsockopen() - $error_num - $error_string"; + $sleep = 6; + continue; + } - // Check for response - while (!feof($file)) - { - $response .= fread($file, 1024); - } - $data_start = strpos($response, "\r\n\r\n") + 4; - $data_end = strrpos($response, "\n"); - if ($data_end > $data_start) - { - $data = substr($response, $data_start, $data_end - $data_start); - } - else - { - $data = ""; - } - $status = substr($response, $data_end + 1); - if ($status == "success") - { - $success = true; - } - } + // Check for response + while (!feof($file)) { + $response .= fread($file, 1024); + } + $data_start = strpos($response, "\r\n\r\n") + 4; + $data_end = strrpos($response, "\n"); + if ($data_end > $data_start) { + $data = substr($response, $data_start, $data_end - $data_start); + } else { + $data = ""; + } + $status = substr($response, $data_end + 1); + if ($status == "success") { + $success = true; + } + } - return $success; + return $success; } // bdecode: based on OpenTracker -function bdecode_file ($filename) +function bdecode_file($filename) { - $file_contents = file_get_contents($filename); - return bdecode($file_contents); + $file_contents = file_get_contents($filename); + return bdecode($file_contents); } -function bdecode ($str) +function bdecode($str) { - $pos = 0; - return bdecode_r($str, $pos); + $pos = 0; + return bdecode_r($str, $pos); } -function bdecode_r ($str, &$pos) +function bdecode_r($str, &$pos) { - $strlen = strlen($str); + $strlen = strlen($str); - if (($pos < 0) || ($pos >= $strlen)) - { - return null; - } - else if ($str[$pos] == 'i') - { - $pos++; - $numlen = strspn($str, '-0123456789', $pos); - $spos = $pos; - $pos += $numlen; + if (($pos < 0) || ($pos >= $strlen)) { + return null; + } else if ($str[$pos] == 'i') { + $pos++; + $numlen = strspn($str, '-0123456789', $pos); + $spos = $pos; + $pos += $numlen; - if (($pos >= $strlen) || ($str[$pos] != 'e')) - { - return null; - } - else - { - $pos++; - return floatval(substr($str, $spos, $numlen)); - } - } - else if ($str[$pos] == 'd') - { - $pos++; - $ret = array(); + if (($pos >= $strlen) || ($str[$pos] != 'e')) { + return null; + } else { + $pos++; + return floatval(substr($str, $spos, $numlen)); + } + } else if ($str[$pos] == 'd') { + $pos++; + $ret = array(); - while ($pos < $strlen) - { - if ($str[$pos] == 'e') - { - $pos++; - return $ret; - } - else - { - $key = bdecode_r($str, $pos); + while ($pos < $strlen) { + if ($str[$pos] == 'e') { + $pos++; + return $ret; + } else { + $key = bdecode_r($str, $pos); - if ($key === null) - { - return null; - } - else - { - $val = bdecode_r($str, $pos); + if ($key === null) { + return null; + } else { + $val = bdecode_r($str, $pos); - if ($val === null) - { - return null; - } - else if (!is_array($key)) - { - $ret[$key] = $val; - } - } - } - } - return null; - } - else if ($str[$pos] == 'l') - { - $pos++; - $ret = array(); + if ($val === null) { + return null; + } else if (!is_array($key)) { + $ret[$key] = $val; + } + } + } + } + return null; + } else if ($str[$pos] == 'l') { + $pos++; + $ret = array(); - while ($pos < $strlen) - { - if ($str[$pos] == 'e') - { - $pos++; - return $ret; - } - else - { - $val = bdecode_r($str, $pos); + while ($pos < $strlen) { + if ($str[$pos] == 'e') { + $pos++; + return $ret; + } else { + $val = bdecode_r($str, $pos); - if ($val === null) - { - return null; - } - else - { - $ret[] = $val; - } - } - } - return null; - } - else - { - $numlen = strspn($str, '0123456789', $pos); - $spos = $pos; - $pos += $numlen; + if ($val === null) { + return null; + } else { + $ret[] = $val; + } + } + } + return null; + } else { + $numlen = strspn($str, '0123456789', $pos); + $spos = $pos; + $pos += $numlen; - if (($pos >= $strlen) || ($str[$pos] != ':')) - { - return null; - } - else - { - $vallen = intval(substr($str, $spos, $numlen)); - $pos++; - $val = substr($str, $pos, $vallen); + if (($pos >= $strlen) || ($str[$pos] != ':')) { + return null; + } else { + $vallen = intval(substr($str, $spos, $numlen)); + $pos++; + $val = substr($str, $pos, $vallen); - if (strlen($val) != $vallen) - { - return null; - } - else - { - $pos += $vallen; - return $val; - } - } - } -} \ No newline at end of file + if (strlen($val) != $vallen) { + return null; + } else { + $pos += $vallen; + return $val; + } + } + } +} diff --git a/library/includes/functions_upload.php b/library/includes/functions_upload.php index b93717582..8273b293c 100644 --- a/library/includes/functions_upload.php +++ b/library/includes/functions_upload.php @@ -4,163 +4,142 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); class upload_common { - var $cfg = array( - 'max_size' => 0, - 'max_width' => 0, - 'max_height' => 0, - 'allowed_ext' => array(), - 'upload_path' => '', - ); - var $file = array( - 'name' => '', - 'type' => '', - 'size' => 0, - 'tmp_name' => '', - 'error' => UPLOAD_ERR_NO_FILE, - ); - var $orig_name = ''; - var $file_path = ''; // Stored file path - var $file_ext = ''; - var $file_ext_id = ''; - var $file_size = ''; - var $ext_ids = array(); // array_flip($di->config->get('file_id_ext')) - var $errors = array(); - var $img_types = array( - 1 => 'gif', - 2 => 'jpg', - 3 => 'png', - 6 => 'bmp', - 7 => 'tiff', - 8 => 'tiff', - ); + var $cfg = array( + 'max_size' => 0, + 'max_width' => 0, + 'max_height' => 0, + 'allowed_ext' => array(), + 'upload_path' => '', + ); + var $file = array( + 'name' => '', + 'type' => '', + 'size' => 0, + 'tmp_name' => '', + 'error' => UPLOAD_ERR_NO_FILE, + ); + var $orig_name = ''; + var $file_path = ''; // Stored file path + var $file_ext = ''; + var $file_ext_id = ''; + var $file_size = ''; + var $ext_ids = array(); // array_flip($di->config->get('file_id_ext')) + var $errors = array(); + var $img_types = array( + 1 => 'gif', + 2 => 'jpg', + 3 => 'png', + 6 => 'bmp', + 7 => 'tiff', + 8 => 'tiff', + ); - function init ($cfg = array(), $post_params = array(), $uploaded_only = true) - { - global $lang; + function init($cfg = array(), $post_params = array(), $uploaded_only = true) + { + global $lang; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $this->cfg = array_merge($this->cfg, $cfg); - $this->file = $post_params; + $this->cfg = array_merge($this->cfg, $cfg); + $this->file = $post_params; - // upload errors from $_FILES - if ($this->file['error']) - { - $msg = $lang['UPLOAD_ERROR_COMMON']; - $msg .= ($err_desc =& $lang['UPLOAD_ERRORS'][$this->file['error']]) ? " ($err_desc)" : ''; - $this->errors[] = $msg; - return false; - } - // file_exists - if (!file_exists($this->file['tmp_name'])) - { - $this->errors[] = "Uploaded file not exists: {$this->file['tmp_name']}"; - return false; - } - // size - if (!$this->file_size = filesize($this->file['tmp_name'])) - { - $this->errors[] = "Uploaded file is empty: {$this->file['tmp_name']}"; - return false; - } - if ($this->cfg['max_size'] && $this->file_size > $this->cfg['max_size']) - { - $this->errors[] = sprintf($lang['UPLOAD_ERROR_SIZE'], humn_size($this->cfg['max_size'])); - return false; - } - // is_uploaded_file - if ($uploaded_only && !is_uploaded_file($this->file['tmp_name'])) - { - $this->errors[] = "Not uploaded file: {$this->file['tmp_name']}"; - return false; - } - // get ext - $this->ext_ids = array_flip($di->config->get('file_id_ext')); - $file_name_ary = explode('.', $this->file['name']); - $this->file_ext = strtolower(end($file_name_ary)); + // upload errors from $_FILES + if ($this->file['error']) { + $msg = $lang['UPLOAD_ERROR_COMMON']; + $msg .= ($err_desc =& $lang['UPLOAD_ERRORS'][$this->file['error']]) ? " ($err_desc)" : ''; + $this->errors[] = $msg; + return false; + } + // file_exists + if (!file_exists($this->file['tmp_name'])) { + $this->errors[] = "Uploaded file not exists: {$this->file['tmp_name']}"; + return false; + } + // size + if (!$this->file_size = filesize($this->file['tmp_name'])) { + $this->errors[] = "Uploaded file is empty: {$this->file['tmp_name']}"; + return false; + } + if ($this->cfg['max_size'] && $this->file_size > $this->cfg['max_size']) { + $this->errors[] = sprintf($lang['UPLOAD_ERROR_SIZE'], humn_size($this->cfg['max_size'])); + return false; + } + // is_uploaded_file + if ($uploaded_only && !is_uploaded_file($this->file['tmp_name'])) { + $this->errors[] = "Not uploaded file: {$this->file['tmp_name']}"; + return false; + } + // get ext + $this->ext_ids = array_flip($di->config->get('file_id_ext')); + $file_name_ary = explode('.', $this->file['name']); + $this->file_ext = strtolower(end($file_name_ary)); - // img - if ($this->cfg['max_width'] || $this->cfg['max_height']) - { - if ($img_info = getimagesize($this->file['tmp_name'])) - { - list($width, $height, $type, $attr) = $img_info; + // img + if ($this->cfg['max_width'] || $this->cfg['max_height']) { + if ($img_info = getimagesize($this->file['tmp_name'])) { + list($width, $height, $type, $attr) = $img_info; - // redefine ext - if (!$width || !$height || !$type || !isset($this->img_types[$type])) - { - $this->errors[] = $lang['UPLOAD_ERROR_FORMAT']; - return false; - } - $this->file_ext = $this->img_types[$type]; + // redefine ext + if (!$width || !$height || !$type || !isset($this->img_types[$type])) { + $this->errors[] = $lang['UPLOAD_ERROR_FORMAT']; + return false; + } + $this->file_ext = $this->img_types[$type]; - // width & height - if (($this->cfg['max_width'] && $width > $this->cfg['max_width']) || ($this->cfg['max_height'] && $height > $this->cfg['max_height'])) - { - $this->errors[] = sprintf($lang['UPLOAD_ERROR_DIMENSIONS'], $this->cfg['max_width'], $this->cfg['max_height']); - return false; - } - } - else - { - $this->errors[] = $lang['UPLOAD_ERROR_NOT_IMAGE']; - return false; - } - } - // check ext - if ($uploaded_only && (!isset($this->ext_ids[$this->file_ext]) || !in_array($this->file_ext, $this->cfg['allowed_ext'], true))) - { - $this->errors[] = sprintf($lang['UPLOAD_ERROR_NOT_ALLOWED'], htmlCHR($this->file_ext)); - return false; - } - $this->file_ext_id = $this->ext_ids[$this->file_ext]; + // width & height + if (($this->cfg['max_width'] && $width > $this->cfg['max_width']) || ($this->cfg['max_height'] && $height > $this->cfg['max_height'])) { + $this->errors[] = sprintf($lang['UPLOAD_ERROR_DIMENSIONS'], $this->cfg['max_width'], $this->cfg['max_height']); + return false; + } + } else { + $this->errors[] = $lang['UPLOAD_ERROR_NOT_IMAGE']; + return false; + } + } + // check ext + if ($uploaded_only && (!isset($this->ext_ids[$this->file_ext]) || !in_array($this->file_ext, $this->cfg['allowed_ext'], true))) { + $this->errors[] = sprintf($lang['UPLOAD_ERROR_NOT_ALLOWED'], htmlCHR($this->file_ext)); + return false; + } + $this->file_ext_id = $this->ext_ids[$this->file_ext]; - return true; - } + return true; + } - function store ($mode = '', $params = array()) - { - if ($mode == 'avatar') - { - delete_avatar($params['user_id'], $this->file_ext_id); - $file_path = get_avatar_path($params['user_id'], $this->file_ext_id); - return $this->_move($file_path); - } - else if ($mode == 'attach') - { - delete_attach($params['topic_id'], $this->file_ext_id); - $file_path = get_attach_path($params['topic_id'], $this->file_ext_id); - return $this->_move($file_path); - } - else - { - trigger_error("Invalid upload mode: $mode", E_USER_ERROR); - } - } + function store($mode = '', $params = array()) + { + if ($mode == 'avatar') { + delete_avatar($params['user_id'], $this->file_ext_id); + $file_path = get_avatar_path($params['user_id'], $this->file_ext_id); + return $this->_move($file_path); + } else if ($mode == 'attach') { + delete_attach($params['topic_id'], $this->file_ext_id); + $file_path = get_attach_path($params['topic_id'], $this->file_ext_id); + return $this->_move($file_path); + } else { + trigger_error("Invalid upload mode: $mode", E_USER_ERROR); + } + } - function _move ($file_path) - { - $dir = dirname($file_path); - if (!file_exists($dir)) - { - if (!bb_mkdir($dir)) - { - $this->errors[] = "Cannot create dir: $dir"; - return false; - } - } - if (!rename($this->file['tmp_name'], $file_path)) - { - if (!copy($this->file['tmp_name'], $file_path)) - { - $this->errors[] = 'Cannot copy tmp file'; - return false; - } - unlink($this->file['tmp_name']); - } - chmod($file_path, 0664); + function _move($file_path) + { + $dir = dirname($file_path); + if (!file_exists($dir)) { + if (!bb_mkdir($dir)) { + $this->errors[] = "Cannot create dir: $dir"; + return false; + } + } + if (!rename($this->file['tmp_name'], $file_path)) { + if (!copy($this->file['tmp_name'], $file_path)) { + $this->errors[] = 'Cannot copy tmp file'; + return false; + } + unlink($this->file['tmp_name']); + } + chmod($file_path, 0664); - return file_exists($file_path); - } -} \ No newline at end of file + return file_exists($file_path); + } +} diff --git a/library/includes/functions_validate.php b/library/includes/functions_validate.php index 84386276e..a2db0f798 100644 --- a/library/includes/functions_validate.php +++ b/library/includes/functions_validate.php @@ -3,112 +3,92 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); // !!! $username должен быть предварительно обработан clean_username() !!! -function validate_username ($username, $check_ban_and_taken = true) +function validate_username($username, $check_ban_and_taken = true) { - global $user, $lang; + global $user, $lang; - static $name_chars = 'a-z0-9а-яё_@$%^&;(){}\#\-\'.:+ '; + static $name_chars = 'a-z0-9а-яё_@$%^&;(){}\#\-\'.:+ '; - $username = str_compact($username); - $username = clean_username($username); + $username = str_compact($username); + $username = clean_username($username); - // Length - if (mb_strlen($username, 'UTF-8') > USERNAME_MAX_LENGTH) - { - return $lang['USERNAME_TOO_LONG']; - } - else if (mb_strlen($username, 'UTF-8') < USERNAME_MIN_LENGTH) - { - return $lang['USERNAME_TOO_SMALL']; - } - // Allowed symbols - if (!preg_match('#^['.$name_chars.']+$#iu', $username, $m)) - { - $invalid_chars = preg_replace('#['.$name_chars.']#iu', '', $username); - return "{$lang['USERNAME_INVALID']}: ". htmlCHR($invalid_chars) .""; - } - // HTML Entities - if (preg_match_all('/&(#[0-9]+|[a-z]+);/iu', $username, $m)) - { - foreach ($m[0] as $ent) - { - if (!preg_match('/^(&|<|>)$/iu', $ent)) - { - return $lang['USERNAME_INVALID']; - } - } - } - if ($check_ban_and_taken) - { - // Занято - $username_sql = DB()->escape($username); + // Length + if (mb_strlen($username, 'UTF-8') > USERNAME_MAX_LENGTH) { + return $lang['USERNAME_TOO_LONG']; + } else if (mb_strlen($username, 'UTF-8') < USERNAME_MIN_LENGTH) { + return $lang['USERNAME_TOO_SMALL']; + } + // Allowed symbols + if (!preg_match('#^[' . $name_chars . ']+$#iu', $username, $m)) { + $invalid_chars = preg_replace('#[' . $name_chars . ']#iu', '', $username); + return "{$lang['USERNAME_INVALID']}: " . htmlCHR($invalid_chars) . ""; + } + // HTML Entities + if (preg_match_all('/&(#[0-9]+|[a-z]+);/iu', $username, $m)) { + foreach ($m[0] as $ent) { + if (!preg_match('/^(&|<|>)$/iu', $ent)) { + return $lang['USERNAME_INVALID']; + } + } + } + if ($check_ban_and_taken) { + // Занято + $username_sql = DB()->escape($username); - if ($row = DB()->fetch_row("SELECT username FROM ". BB_USERS ." WHERE username = '$username_sql' LIMIT 1")) - { - if ((!IS_GUEST && $row['username'] != $user->name) || IS_GUEST) - { - return $lang['USERNAME_TAKEN']; - } - } - // Запрещено - $banned_names = array(); + if ($row = DB()->fetch_row("SELECT username FROM " . BB_USERS . " WHERE username = '$username_sql' LIMIT 1")) { + if ((!IS_GUEST && $row['username'] != $user->name) || IS_GUEST) { + return $lang['USERNAME_TAKEN']; + } + } + // Запрещено + $banned_names = array(); - foreach (DB()->fetch_rowset("SELECT disallow_username FROM ". BB_DISALLOW ." ORDER BY NULL") as $row) - { - $banned_names[] = str_replace('\*', '.*?', preg_quote($row['disallow_username'], '#u')); - } - if ($banned_names_exp = join('|', $banned_names)) - { - if (preg_match("#^($banned_names_exp)$#iu", $username)) - { - return $lang['USERNAME_DISALLOWED']; - } - } - } + foreach (DB()->fetch_rowset("SELECT disallow_username FROM " . BB_DISALLOW . " ORDER BY NULL") as $row) { + $banned_names[] = str_replace('\*', '.*?', preg_quote($row['disallow_username'], '#u')); + } + if ($banned_names_exp = join('|', $banned_names)) { + if (preg_match("#^($banned_names_exp)$#iu", $username)) { + return $lang['USERNAME_DISALLOWED']; + } + } + } - return false; + return false; } // Check to see if email address is banned or already present in the DB -function validate_email ($email, $check_ban_and_taken = true) +function validate_email($email, $check_ban_and_taken = true) { - global $lang, $userdata; + global $lang, $userdata; - if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) - { - return $lang['EMAIL_INVALID']; - } - if (strlen($email) > USEREMAIL_MAX_LENGTH) - { - return $lang['EMAIL_TOO_LONG']; - } + if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) { + return $lang['EMAIL_INVALID']; + } + if (strlen($email) > USEREMAIL_MAX_LENGTH) { + return $lang['EMAIL_TOO_LONG']; + } - if ($check_ban_and_taken) - { - $banned_emails = array(); + if ($check_ban_and_taken) { + $banned_emails = array(); - foreach (DB()->fetch_rowset("SELECT ban_email FROM ". BB_BANLIST ." ORDER BY NULL") as $row) - { - $banned_emails[] = str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')); - } - if ($banned_emails_exp = join('|', $banned_emails)) - { - if (preg_match("#^($banned_emails_exp)$#i", $email)) - { - return sprintf($lang['EMAIL_BANNED'], $email); - } - } + foreach (DB()->fetch_rowset("SELECT ban_email FROM " . BB_BANLIST . " ORDER BY NULL") as $row) { + $banned_emails[] = str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')); + } + if ($banned_emails_exp = join('|', $banned_emails)) { + if (preg_match("#^($banned_emails_exp)$#i", $email)) { + return sprintf($lang['EMAIL_BANNED'], $email); + } + } - $email_sql = DB()->escape($email); + $email_sql = DB()->escape($email); - if ($row = DB()->fetch_row("SELECT `user_email` FROM ". BB_USERS ." WHERE user_email = '$email_sql' LIMIT 1")) - { - if($row['user_email'] == $userdata['user_email']) - return false; - else - return $lang['EMAIL_TAKEN']; - } - } + if ($row = DB()->fetch_row("SELECT `user_email` FROM " . BB_USERS . " WHERE user_email = '$email_sql' LIMIT 1")) { + if ($row['user_email'] == $userdata['user_email']) + return false; + else + return $lang['EMAIL_TAKEN']; + } + } - return false; -} \ No newline at end of file + return false; +} diff --git a/library/includes/init_bb.php b/library/includes/init_bb.php index f2efc0a3f..d51eab43c 100644 --- a/library/includes/init_bb.php +++ b/library/includes/init_bb.php @@ -4,7 +4,7 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_SCRIPT')) define('BB_SCRIPT', 'undefined'); if (!defined('BB_CFG_LOADED')) trigger_error('File config.php not loaded', E_USER_ERROR); -if (PHP_VERSION < '5.5') die('TorrentPier requires PHP version 5.5 and above (ZF requirement). Your PHP version is '. PHP_VERSION); +if (PHP_VERSION < '5.5') die('TorrentPier requires PHP version 5.5 and above (ZF requirement). Your PHP version is ' . PHP_VERSION); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -19,45 +19,42 @@ $user = null; $client_ip = (filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP)) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1'; $user_ip = encode_ip($client_ip); define('CLIENT_IP', $client_ip); -define('USER_IP', $user_ip); +define('USER_IP', $user_ip); -function send_page ($contents) +function send_page($contents) { - return compress_output($contents); + return compress_output($contents); } define('UA_GZIP_SUPPORTED', (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)); -function compress_output ($contents) +function compress_output($contents) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if ($di->config->get('gzip_compress') && GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) - { - if (UA_GZIP_SUPPORTED && strlen($contents) > 2000) - { - header('Content-Encoding: gzip'); - $contents = gzencode($contents, 1); - } - } + if ($di->config->get('gzip_compress') && GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) { + if (UA_GZIP_SUPPORTED && strlen($contents) > 2000) { + header('Content-Encoding: gzip'); + $contents = gzencode($contents, 1); + } + } - return $contents; + return $contents; } // Start output buffering -if (!defined('IN_AJAX')) -{ - ob_start('send_page'); +if (!defined('IN_AJAX')) { + ob_start('send_page'); } // Cookie params $c = $di->config->get('cookie_prefix'); -define('COOKIE_DATA', $c .'data'); -define('COOKIE_FORUM', $c .'f'); -define('COOKIE_MARK', $c .'mark_read'); -define('COOKIE_TOPIC', $c .'t'); -define('COOKIE_PM', $c .'pm'); +define('COOKIE_DATA', $c . 'data'); +define('COOKIE_FORUM', $c . 'f'); +define('COOKIE_MARK', $c . 'mark_read'); +define('COOKIE_TOPIC', $c . 't'); +define('COOKIE_PM', $c . 'pm'); unset($c); define('COOKIE_SESSION', 0); @@ -66,100 +63,97 @@ define('COOKIE_PERSIST', TIMENOW + 31536000); define('COOKIE_MAX_TRACKS', 90); -function bb_setcookie ($name, $val, $lifetime = COOKIE_PERSIST, $httponly = false) +function bb_setcookie($name, $val, $lifetime = COOKIE_PERSIST, $httponly = false) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - return setcookie($name, $val, $lifetime, $di->config->get('script_path'), $di->config->get('cookie_domain'), $di->config->get('cookie_secure'), $httponly); + return setcookie($name, $val, $lifetime, $di->config->get('script_path'), $di->config->get('cookie_domain'), $di->config->get('cookie_secure'), $httponly); } // Debug options -if (DBG_USER) -{ - ini_set('error_reporting', E_ALL); - ini_set('display_errors', 1); -} -else -{ - unset($_COOKIE['explain']); +if (DBG_USER) { + ini_set('error_reporting', E_ALL); + ini_set('display_errors', 1); +} else { + unset($_COOKIE['explain']); } define('DELETED', -1); // User Levels -define('USER', 0); -define('ADMIN', 1); -define('MOD', 2); +define('USER', 0); +define('ADMIN', 1); +define('MOD', 2); define('GROUP_MEMBER', 20); -define('CP_HOLDER', 25); +define('CP_HOLDER', 25); define('EXCLUDED_USERS', implode(',', [GUEST_UID, BOT_UID])); // User related -define('USER_ACTIVATION_NONE', 0); -define('USER_ACTIVATION_SELF', 1); +define('USER_ACTIVATION_NONE', 0); +define('USER_ACTIVATION_SELF', 1); // Group settings -define('GROUP_OPEN', 0); +define('GROUP_OPEN', 0); define('GROUP_CLOSED', 1); define('GROUP_HIDDEN', 2); // Forum state define('FORUM_UNLOCKED', 0); -define('FORUM_LOCKED', 1); +define('FORUM_LOCKED', 1); // Topic status -define('TOPIC_UNLOCKED', 0); -define('TOPIC_LOCKED', 1); -define('TOPIC_MOVED', 2); +define('TOPIC_UNLOCKED', 0); +define('TOPIC_LOCKED', 1); +define('TOPIC_MOVED', 2); -define('TOPIC_WATCH_NOTIFIED', 1); -define('TOPIC_WATCH_UNNOTIFIED', 0); +define('TOPIC_WATCH_NOTIFIED', 1); +define('TOPIC_WATCH_UNNOTIFIED', 0); // Topic types -define('POST_NORMAL', 0); -define('POST_STICKY', 1); -define('POST_ANNOUNCE', 2); +define('POST_NORMAL', 0); +define('POST_STICKY', 1); +define('POST_ANNOUNCE', 2); // Search types -define('SEARCH_TYPE_POST', 0); -define('SEARCH_TYPE_TRACKER', 1); +define('SEARCH_TYPE_POST', 0); +define('SEARCH_TYPE_TRACKER', 1); // Ajax error codes define('E_AJAX_GENERAL_ERROR', 1000); -define('E_AJAX_NEED_LOGIN', 1001); +define('E_AJAX_NEED_LOGIN', 1001); // Private messaging -define('PRIVMSGS_READ_MAIL', 0); -define('PRIVMSGS_NEW_MAIL', 1); -define('PRIVMSGS_SENT_MAIL', 2); -define('PRIVMSGS_SAVED_IN_MAIL', 3); +define('PRIVMSGS_READ_MAIL', 0); +define('PRIVMSGS_NEW_MAIL', 1); +define('PRIVMSGS_SENT_MAIL', 2); +define('PRIVMSGS_SAVED_IN_MAIL', 3); define('PRIVMSGS_SAVED_OUT_MAIL', 4); -define('PRIVMSGS_UNREAD_MAIL', 5); -define('HAVE_UNREAD_PM', 1); -define('HAVE_NEW_PM', 2); +define('PRIVMSGS_UNREAD_MAIL', 5); +define('HAVE_UNREAD_PM', 1); +define('HAVE_NEW_PM', 2); -define('USERNAME_MIN_LENGTH', 3); +define('USERNAME_MIN_LENGTH', 3); // URL PARAMETERS (hardcoding allowed) -define('POST_CAT_URL', 'c'); -define('POST_FORUM_URL', 'f'); +define('POST_CAT_URL', 'c'); +define('POST_FORUM_URL', 'f'); define('POST_GROUPS_URL', 'g'); -define('POST_POST_URL', 'p'); -define('POST_TOPIC_URL', 't'); -define('POST_USERS_URL', 'u'); +define('POST_POST_URL', 'p'); +define('POST_TOPIC_URL', 't'); +define('POST_USERS_URL', 'u'); // Categories -define('NONE_CAT', 0); -define('IMAGE_CAT', 1); +define('NONE_CAT', 0); +define('IMAGE_CAT', 1); // Torrents define('TOR_STATUS_NORMAL', 0); define('TOR_STATUS_FROZEN', 1); // Gender -define('MALE', 1); -define('FEMALE', 2); +define('MALE', 1); +define('FEMALE', 2); define('NOGENDER', 0); // Poll @@ -170,76 +164,76 @@ define('POLL_FINISHED', 2); define('GROUP_AVATAR_MASK', 999000); // Table names -define('BUF_TOPIC_VIEW', 'buf_topic_view'); -define('BUF_LAST_SEEDER', 'buf_last_seeder'); -define('BB_AUTH_ACCESS_SNAP', 'bb_auth_access_snap'); -define('BB_AUTH_ACCESS', 'bb_auth_access'); -define('BB_BANLIST', 'bb_banlist'); -define('BB_BT_DLSTATUS', 'bb_bt_dlstatus'); -define('BB_BT_DLSTATUS_SNAP', 'bb_bt_dlstatus_snap'); -define('BB_BT_LAST_TORSTAT', 'bb_bt_last_torstat'); -define('BB_BT_LAST_USERSTAT', 'bb_bt_last_userstat'); -define('BB_BT_TORHELP', 'bb_bt_torhelp'); -define('BB_BT_TORSTAT', 'bb_bt_torstat'); -define('BB_CATEGORIES', 'bb_categories'); -define('BB_CONFIG', 'bb_config'); -define('BB_CRON', 'bb_cron'); -define('BB_DISALLOW', 'bb_disallow'); -define('BB_FORUMS', 'bb_forums'); -define('BB_GROUPS', 'bb_groups'); -define('BB_LOG', 'bb_log'); -define('BB_POLL_USERS', 'bb_poll_users'); -define('BB_POLL_VOTES', 'bb_poll_votes'); -define('BB_POSTS_SEARCH', 'bb_posts_search'); -define('BB_POSTS', 'bb_posts'); -define('BB_POSTS_TEXT', 'bb_posts_text'); -define('BB_POSTS_HTML', 'bb_posts_html'); -define('BB_PRIVMSGS', 'bb_privmsgs'); -define('BB_PRIVMSGS_TEXT', 'bb_privmsgs_text'); -define('BB_RANKS', 'bb_ranks'); -define('BB_SEARCH_REBUILD', 'bb_search_rebuild'); -define('BB_SEARCH', 'bb_search_results'); -define('BB_SESSIONS', 'bb_sessions'); -define('BB_SMILIES', 'bb_smilies'); -define('BB_TOPIC_TPL', 'bb_topic_tpl'); -define('BB_TOPICS', 'bb_topics'); -define('BB_TOPICS_WATCH', 'bb_topics_watch'); -define('BB_USER_GROUP', 'bb_user_group'); -define('BB_USERS', 'bb_users'); -define('BB_WORDS', 'bb_words'); +define('BUF_TOPIC_VIEW', 'buf_topic_view'); +define('BUF_LAST_SEEDER', 'buf_last_seeder'); +define('BB_AUTH_ACCESS_SNAP', 'bb_auth_access_snap'); +define('BB_AUTH_ACCESS', 'bb_auth_access'); +define('BB_BANLIST', 'bb_banlist'); +define('BB_BT_DLSTATUS', 'bb_bt_dlstatus'); +define('BB_BT_DLSTATUS_SNAP', 'bb_bt_dlstatus_snap'); +define('BB_BT_LAST_TORSTAT', 'bb_bt_last_torstat'); +define('BB_BT_LAST_USERSTAT', 'bb_bt_last_userstat'); +define('BB_BT_TORHELP', 'bb_bt_torhelp'); +define('BB_BT_TORSTAT', 'bb_bt_torstat'); +define('BB_CATEGORIES', 'bb_categories'); +define('BB_CONFIG', 'bb_config'); +define('BB_CRON', 'bb_cron'); +define('BB_DISALLOW', 'bb_disallow'); +define('BB_FORUMS', 'bb_forums'); +define('BB_GROUPS', 'bb_groups'); +define('BB_LOG', 'bb_log'); +define('BB_POLL_USERS', 'bb_poll_users'); +define('BB_POLL_VOTES', 'bb_poll_votes'); +define('BB_POSTS_SEARCH', 'bb_posts_search'); +define('BB_POSTS', 'bb_posts'); +define('BB_POSTS_TEXT', 'bb_posts_text'); +define('BB_POSTS_HTML', 'bb_posts_html'); +define('BB_PRIVMSGS', 'bb_privmsgs'); +define('BB_PRIVMSGS_TEXT', 'bb_privmsgs_text'); +define('BB_RANKS', 'bb_ranks'); +define('BB_SEARCH_REBUILD', 'bb_search_rebuild'); +define('BB_SEARCH', 'bb_search_results'); +define('BB_SESSIONS', 'bb_sessions'); +define('BB_SMILIES', 'bb_smilies'); +define('BB_TOPIC_TPL', 'bb_topic_tpl'); +define('BB_TOPICS', 'bb_topics'); +define('BB_TOPICS_WATCH', 'bb_topics_watch'); +define('BB_USER_GROUP', 'bb_user_group'); +define('BB_USERS', 'bb_users'); +define('BB_WORDS', 'bb_words'); define('SHOW_PEERS_COUNT', 1); define('SHOW_PEERS_NAMES', 2); -define('SHOW_PEERS_FULL', 3); +define('SHOW_PEERS_FULL', 3); define('SEARCH_ID_LENGTH', 12); -define('SID_LENGTH', 20); +define('SID_LENGTH', 20); define('LOGIN_KEY_LENGTH', 12); -define('USERNAME_MAX_LENGTH', 25); +define('USERNAME_MAX_LENGTH', 25); define('USEREMAIL_MAX_LENGTH', 40); -define('PAGE_HEADER', INC_DIR .'page_header.php'); -define('PAGE_FOOTER', INC_DIR .'page_footer.php'); +define('PAGE_HEADER', INC_DIR . 'page_header.php'); +define('PAGE_FOOTER', INC_DIR . 'page_footer.php'); -define('CAT_URL', 'index.php?c='); +define('CAT_URL', 'index.php?c='); define('DOWNLOAD_URL', 'dl.php?t='); -define('FORUM_URL', 'viewforum.php?f='); -define('GROUP_URL', 'group.php?g='); -define('LOGIN_URL', $di->config->get('login_url')); -define('MODCP_URL', 'modcp.php?f='); -define('PM_URL', $di->config->get('pm_url')); -define('POST_URL', 'viewtopic.php?p='); -define('POSTING_URL', $di->config->get('posting_url')); -define('PROFILE_URL', 'profile.php?mode=viewprofile&u='); -define('BONUS_URL', 'profile.php?mode=bonus'); -define('TOPIC_URL', 'viewtopic.php?t='); +define('FORUM_URL', 'viewforum.php?f='); +define('GROUP_URL', 'group.php?g='); +define('LOGIN_URL', $di->config->get('login_url')); +define('MODCP_URL', 'modcp.php?f='); +define('PM_URL', $di->config->get('pm_url')); +define('POST_URL', 'viewtopic.php?p='); +define('POSTING_URL', $di->config->get('posting_url')); +define('PROFILE_URL', 'profile.php?mode=viewprofile&u='); +define('BONUS_URL', 'profile.php?mode=bonus'); +define('TOPIC_URL', 'viewtopic.php?t='); define('USER_AGENT', strtolower($_SERVER['HTTP_USER_AGENT'])); define('HTML_SELECT_MAX_LENGTH', 60); -define('HTML_WBR_LENGTH', 12); +define('HTML_WBR_LENGTH', 12); -define('HTML_CHECKED', ' checked="checked" '); +define('HTML_CHECKED', ' checked="checked" '); define('HTML_DISABLED', ' disabled="disabled" '); define('HTML_READONLY', ' readonly="readonly" '); define('HTML_SELECTED', ' selected="selected" '); @@ -248,75 +242,74 @@ define('HTML_SF_SPACER', ' |- '); // $GPC define('KEY_NAME', 0); // position in $GPC['xxx'] -define('DEF_VAL', 1); +define('DEF_VAL', 1); define('GPC_TYPE', 2); -define('GET', 1); -define('POST', 2); -define('COOKIE', 3); +define('GET', 1); +define('POST', 2); +define('COOKIE', 3); define('REQUEST', 4); -define('CHBOX', 5); -define('SELECT', 6); +define('CHBOX', 5); +define('SELECT', 6); $dl_link_css = [ - DL_STATUS_RELEASER => 'genmed', - DL_STATUS_WILL => 'dlWill', - DL_STATUS_DOWN => 'leechmed', - DL_STATUS_COMPLETE => 'seedmed', - DL_STATUS_CANCEL => 'dlCancel', + DL_STATUS_RELEASER => 'genmed', + DL_STATUS_WILL => 'dlWill', + DL_STATUS_DOWN => 'leechmed', + DL_STATUS_COMPLETE => 'seedmed', + DL_STATUS_CANCEL => 'dlCancel', ]; $dl_status_css = [ - DL_STATUS_RELEASER => 'genmed', - DL_STATUS_WILL => 'dlWill', - DL_STATUS_DOWN => 'dlDown', - DL_STATUS_COMPLETE => 'dlComplete', - DL_STATUS_CANCEL => 'dlCancel', + DL_STATUS_RELEASER => 'genmed', + DL_STATUS_WILL => 'dlWill', + DL_STATUS_DOWN => 'dlDown', + DL_STATUS_COMPLETE => 'dlComplete', + DL_STATUS_CANCEL => 'dlCancel', ]; // Functions -function send_no_cache_headers () +function send_no_cache_headers() { - header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); - header('Last-Modified: '. gmdate('D, d M Y H:i:s'). ' GMT'); - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Cache-Control: post-check=0, pre-check=0', false); - header('Pragma: no-cache'); + header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Cache-Control: no-store, no-cache, must-revalidate'); + header('Cache-Control: post-check=0, pre-check=0', false); + header('Pragma: no-cache'); } -function bb_exit ($output = '') +function bb_exit($output = '') { - if ($output) - { - echo $output; - } - exit; + if ($output) { + echo $output; + } + exit; } -function htmlCHR ($txt, $double_encode = false, $quote_style = ENT_QUOTES, $charset = 'UTF-8') +function htmlCHR($txt, $double_encode = false, $quote_style = ENT_QUOTES, $charset = 'UTF-8') { - return (string) htmlspecialchars($txt, $quote_style, $charset, $double_encode); + return (string)htmlspecialchars($txt, $quote_style, $charset, $double_encode); } -function html_ent_decode ($txt, $quote_style = ENT_QUOTES, $charset = 'UTF-8') +function html_ent_decode($txt, $quote_style = ENT_QUOTES, $charset = 'UTF-8') { - return (string) html_entity_decode($txt, $quote_style, $charset); + return (string)html_entity_decode($txt, $quote_style, $charset); } -function make_url ($path = '') +function make_url($path = '') { - return FULL_URL . preg_replace('#^\/?(.*?)\/?$#', '\1', $path); + return FULL_URL . preg_replace('#^\/?(.*?)\/?$#', '\1', $path); } -require(INC_DIR .'functions.php'); -require(INC_DIR .'sessions.php'); -require(INC_DIR .'template.php'); -require(CORE_DIR .'mysql.php'); +require(INC_DIR . 'functions.php'); +require(INC_DIR . 'sessions.php'); +require(INC_DIR . 'template.php'); +require(CORE_DIR . 'mysql.php'); $user = new user_common(); $userdata =& $user->data; -if (DBG_USER) require(INC_DIR .'functions_dev.php'); +if (DBG_USER) require(INC_DIR . 'functions_dev.php'); $html = new html_common(); $log_action = new log_action(); @@ -325,95 +318,85 @@ $log_action = new log_action(); $datastore->enqueue(array('cat_forums')); // Дата старта вашего проекта -if (!$di->config->get('board_startdate')) -{ - bb_update_config(array('board_startdate' => TIMENOW)); - DB()->query("UPDATE ". BB_USERS ." SET user_regdate = ". TIMENOW ." WHERE user_id IN(2, ". EXCLUDED_USERS .")"); +if (!$di->config->get('board_startdate')) { + bb_update_config(array('board_startdate' => TIMENOW)); + DB()->query("UPDATE " . BB_USERS . " SET user_regdate = " . TIMENOW . " WHERE user_id IN(2, " . EXCLUDED_USERS . ")"); } // Cron -if ((empty($_POST) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !file_exists(CRON_RUNNING) && ($di->config->get('cron_enabled') || defined('START_CRON'))) || defined('FORCE_CRON')) -{ - if (TIMENOW - $di->config->get('cron_last_check') > $di->config->get('cron_check_interval')) - { - // Update cron_last_check - bb_update_config(array('cron_last_check' => (TIMENOW + 10))); +if ((empty($_POST) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !file_exists(CRON_RUNNING) && ($di->config->get('cron_enabled') || defined('START_CRON'))) || defined('FORCE_CRON')) { + if (TIMENOW - $di->config->get('cron_last_check') > $di->config->get('cron_check_interval')) { + // Update cron_last_check + bb_update_config(array('cron_last_check' => (TIMENOW + 10))); - define('CRON_LOG_ENABLED', true); // global ON/OFF - define('CRON_FORCE_LOG', false); // always log regardless of job settings + define('CRON_LOG_ENABLED', true); // global ON/OFF + define('CRON_FORCE_LOG', false); // always log regardless of job settings - define('CRON_DIR', INC_DIR .'cron/'); - define('CRON_JOB_DIR', CRON_DIR .'jobs/'); - define('CRON_LOG_DIR', 'cron/'); // inside LOG_DIR - define('CRON_LOG_FILE', 'cron'); // without ext + define('CRON_DIR', INC_DIR . 'cron/'); + define('CRON_JOB_DIR', CRON_DIR . 'jobs/'); + define('CRON_LOG_DIR', 'cron/'); // inside LOG_DIR + define('CRON_LOG_FILE', 'cron'); // without ext - bb_log(date('H:i:s - ') . getmypid() .' -x-- DB-LOCK try'. LOG_LF, CRON_LOG_DIR .'cron_check'); + bb_log(date('H:i:s - ') . getmypid() . ' -x-- DB-LOCK try' . LOG_LF, CRON_LOG_DIR . 'cron_check'); - if (DB()->get_lock('cron', 1)) - { - bb_log(date('H:i:s - ') . getmypid() .' --x- DB-LOCK OBTAINED !!!!!!!!!!!!!!!!!'. LOG_LF, CRON_LOG_DIR .'cron_check'); + if (DB()->get_lock('cron', 1)) { + bb_log(date('H:i:s - ') . getmypid() . ' --x- DB-LOCK OBTAINED !!!!!!!!!!!!!!!!!' . LOG_LF, CRON_LOG_DIR . 'cron_check'); - sleep(2); - require(CRON_DIR .'cron_init.php'); + sleep(2); + require(CRON_DIR . 'cron_init.php'); - DB()->release_lock('cron'); - } - } + DB()->release_lock('cron'); + } + } } // Exit if board is disabled via ON/OFF trigger or by admin -if (($di->config->get('board_disable') || file_exists(BB_DISABLED)) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !defined('IN_LOGIN')) -{ - header('HTTP/1.0 503 Service Unavailable'); - if ($di->config->get('board_disable')) - { - // admin lock - send_no_cache_headers(); - bb_die('BOARD_DISABLE'); - } - else if (file_exists(BB_DISABLED)) - { - // trigger lock - cron_release_deadlock(); - send_no_cache_headers(); - bb_die('BOARD_DISABLE_CRON'); - } +if (($di->config->get('board_disable') || file_exists(BB_DISABLED)) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !defined('IN_LOGIN')) { + header('HTTP/1.0 503 Service Unavailable'); + if ($di->config->get('board_disable')) { + // admin lock + send_no_cache_headers(); + bb_die('BOARD_DISABLE'); + } else if (file_exists(BB_DISABLED)) { + // trigger lock + cron_release_deadlock(); + send_no_cache_headers(); + bb_die('BOARD_DISABLE_CRON'); + } } // Cron functions -function cron_release_deadlock () +function cron_release_deadlock() { - if (file_exists(CRON_RUNNING)) - { - if (TIMENOW - filemtime(CRON_RUNNING) > 2400) - { - cron_enable_board(); - cron_release_file_lock(); - } - } + if (file_exists(CRON_RUNNING)) { + if (TIMENOW - filemtime(CRON_RUNNING) > 2400) { + cron_enable_board(); + cron_release_file_lock(); + } + } } -function cron_release_file_lock () +function cron_release_file_lock() { - rename(CRON_RUNNING, CRON_ALLOWED); - cron_touch_lock_file(CRON_ALLOWED); + rename(CRON_RUNNING, CRON_ALLOWED); + cron_touch_lock_file(CRON_ALLOWED); } -function cron_touch_lock_file ($lock_file) +function cron_touch_lock_file($lock_file) { - file_write(make_rand_str(20), $lock_file, 0, true, true); + file_write(make_rand_str(20), $lock_file, 0, true, true); } -function cron_enable_board () +function cron_enable_board() { if (file_exists(BB_DISABLED)) { rename(BB_DISABLED, BB_ENABLED); } } -function cron_disable_board () +function cron_disable_board() { if (file_exists(BB_ENABLED)) { rename(BB_ENABLED, BB_DISABLED); } -} \ No newline at end of file +} diff --git a/library/includes/online_userlist.php b/library/includes/online_userlist.php index a9d0994c2..27c0dba7e 100644 --- a/library/includes/online_userlist.php +++ b/library/includes/online_userlist.php @@ -16,18 +16,18 @@ $time_online = TIMENOW - 300; # $time_online = 0; $ulist = array( - ADMIN => array(), - MOD => array(), - GROUP_MEMBER => array(), - USER => array(), + ADMIN => array(), + MOD => array(), + GROUP_MEMBER => array(), + USER => array(), ); $users_cnt = array( - 'admin' => 0, - 'mod' => 0, - 'group_member' => 0, - 'ignore_load' => 0, - 'user' => 0, - 'guest' => 0, + 'admin' => 0, + 'mod' => 0, + 'group_member' => 0, + 'ignore_load' => 0, + 'user' => 0, + 'guest' => 0, ); $online = $online_short = array('userlist' => ''); @@ -35,111 +35,88 @@ $sql = " SELECT u.username, u.user_id, u.user_opt, u.user_rank, u.user_level, s.session_logged_in, s.session_ip, (s.session_time - s.session_start) AS ses_len, COUNT(s.session_id) AS sessions, COUNT(DISTINCT s.session_ip) AS ips - FROM ". BB_SESSIONS ." s, ". BB_USERS ." u + FROM " . BB_SESSIONS . " s, " . BB_USERS . " u WHERE s.session_time > $time_online AND u.user_id = s.session_user_id GROUP BY s.session_user_id ORDER BY u.username "; -foreach (DB()->fetch_rowset($sql) as $u) -{ - if ($u['session_logged_in']) - { - $stat = array(); - $name = profile_url($u); - $level = $u['user_level']; +foreach (DB()->fetch_rowset($sql) as $u) { + if ($u['session_logged_in']) { + $stat = array(); + $name = profile_url($u); + $level = $u['user_level']; - if ($level == ADMIN) - { - $name = "$name"; - $users_cnt['admin']++; - } - else if ($level == MOD) - { - $name = "$name"; - $users_cnt['mod']++; - } - else if ($level == GROUP_MEMBER) - { - $name = "$name"; - $users_cnt['group_member']++; - } - else - { - $users_cnt['user']++; - } + if ($level == ADMIN) { + $name = "$name"; + $users_cnt['admin']++; + } else if ($level == MOD) { + $name = "$name"; + $users_cnt['mod']++; + } else if ($level == GROUP_MEMBER) { + $name = "$name"; + $users_cnt['group_member']++; + } else { + $users_cnt['user']++; + } - if ($u['sessions'] > 3) - { - $color = ($u['sessions'] > 2) ? '#FF0000' : '#B22222'; - $s = $u['sessions']; - $stat[] = "s:$s"; - } - if ($u['ips'] > 2) - { - $ip = $u['ips']; - $stat[] = "ip:$ip"; - } - if ($u['ses_len'] > 6*3600 && $level == USER) - { - $t = round($u['ses_len'] / 3600, 1); - $stat[] = "t:$t"; - } + if ($u['sessions'] > 3) { + $color = ($u['sessions'] > 2) ? '#FF0000' : '#B22222'; + $s = $u['sessions']; + $stat[] = "s:$s"; + } + if ($u['ips'] > 2) { + $ip = $u['ips']; + $stat[] = "ip:$ip"; + } + if ($u['ses_len'] > 6 * 3600 && $level == USER) { + $t = round($u['ses_len'] / 3600, 1); + $stat[] = "t:$t"; + } - $ulist[$level][] = ($stat) ? "$name [". join(', ', $stat) .']' : $name; - } - else - { - $guests_online = $u['ips']; - $users_cnt['guest'] = $guests_online; - } + $ulist[$level][] = ($stat) ? "$name [" . join(', ', $stat) . ']' : $name; + } else { + $guests_online = $u['ips']; + $users_cnt['guest'] = $guests_online; + } } -if ($ulist) -{ - $inline = $block = $short = array(); +if ($ulist) { + $inline = $block = $short = array(); - foreach ($ulist as $level => $users) - { - if (empty($users)) continue; + foreach ($ulist as $level => $users) { + if (empty($users)) continue; - if (count($users) > 200) - { - $style = 'margin: 3px 0; padding: 2px 4px; border: 1px inset; height: 200px; overflow: auto;'; - $block[] = "
        \n". join(",\n", $users) ."
        \n"; - $short[] = ''. $lang['USERS'] .': '. count($users) .''; - } - else - { - $inline[] = join(",\n", $users); - $short[] = join(",\n", $users); - } + if (count($users) > 200) { + $style = 'margin: 3px 0; padding: 2px 4px; border: 1px inset; height: 200px; overflow: auto;'; + $block[] = "
        \n" . join(",\n", $users) . "
        \n"; + $short[] = '' . $lang['USERS'] . ': ' . count($users) . ''; + } else { + $inline[] = join(",\n", $users); + $short[] = join(",\n", $users); + } - $logged_online += count($users); - } + $logged_online += count($users); + } - $online['userlist'] = join(",\n", $inline) . join("\n", $block); - $online_short['userlist'] = join(",\n", $short); + $online['userlist'] = join(",\n", $inline) . join("\n", $block); + $online_short['userlist'] = join(",\n", $short); } -if (!$online['userlist']) -{ - $online['userlist'] = $online_short['userlist'] = $lang['NONE']; -} -else if (isset($_REQUEST['f'])) -{ - $online['userlist'] = $online_short['userlist'] = $lang['BROWSING_FORUM'] .' '. $online['userlist']; +if (!$online['userlist']) { + $online['userlist'] = $online_short['userlist'] = $lang['NONE']; +} else if (isset($_REQUEST['f'])) { + $online['userlist'] = $online_short['userlist'] = $lang['BROWSING_FORUM'] . ' ' . $online['userlist']; } $total_online = $logged_online + $guests_online; -if ($total_online > $di->config->get('record_online_users')) -{ - bb_update_config(array( - 'record_online_users' => $total_online, - 'record_online_date' => TIMENOW, - )); +if ($total_online > $di->config->get('record_online_users')) { + bb_update_config(array( + 'record_online_users' => $total_online, + 'record_online_date' => TIMENOW, + )); } $online['stat'] = $online_short['stat'] = sprintf($lang['ONLINE_USERS'], $total_online, $logged_online, $guests_online); @@ -156,4 +133,4 @@ $online['cnt'] = $online_short['cnt'] = <<set('online_' . $userdata['user_lang'], $online, 60); -$cache->set('online_short_' . $userdata['user_lang'], $online_short, 60); \ No newline at end of file +$cache->set('online_short_' . $userdata['user_lang'], $online_short, 60); diff --git a/library/includes/page_footer.php b/library/includes/page_footer.php index 0214702a9..351d5938b 100644 --- a/library/includes/page_footer.php +++ b/library/includes/page_footer.php @@ -10,78 +10,71 @@ $di = \TorrentPier\Di::getInstance(); /** @var \TorrentPier\Cache\Adapter $cache */ $cache = $di->cache; -if (!empty($template)) -{ - $template->assign_vars(array( - 'SIMPLE_FOOTER' => !empty($gen_simple_header), - 'POWERED' => base64_decode($lang['POWERED']), - 'SHOW_ADMIN_LINK' => (IS_ADMIN && !defined('IN_ADMIN')), - 'ADMIN_LINK_HREF' => "admin/index.php", - )); +if (!empty($template)) { + $template->assign_vars(array( + 'SIMPLE_FOOTER' => !empty($gen_simple_header), + 'POWERED' => base64_decode($lang['POWERED']), + 'SHOW_ADMIN_LINK' => (IS_ADMIN && !defined('IN_ADMIN')), + 'ADMIN_LINK_HREF' => "admin/index.php", + )); - $template->set_filenames(array('page_footer' => 'page_footer.tpl')); - $template->pparse('page_footer'); + $template->set_filenames(array('page_footer' => 'page_footer.tpl')); + $template->pparse('page_footer'); } $show_dbg_info = (DBG_USER && IS_ADMIN && !(isset($_GET['pane']) && $_GET['pane'] == 'left')); -if(!$di->config->get('gzip_compress')) -{ - flush(); +if (!$di->config->get('gzip_compress')) { + flush(); } -if ($show_dbg_info) -{ - $gen_time = utime() - TIMESTART; - $gen_time_txt = sprintf('%.3f', $gen_time); - $gzip_text = (UA_GZIP_SUPPORTED) ? 'GZIP ' : 'GZIP '; - $gzip_text .= ($di->config->get('gzip_compress')) ? $lang['ON'] : $lang['OFF']; +if ($show_dbg_info) { + $gen_time = utime() - TIMESTART; + $gen_time_txt = sprintf('%.3f', $gen_time); + $gzip_text = (UA_GZIP_SUPPORTED) ? 'GZIP ' : 'GZIP '; + $gzip_text .= ($di->config->get('gzip_compress')) ? $lang['ON'] : $lang['OFF']; - $stat = '[  '. $lang['EXECUTION_TIME'] ." $gen_time_txt ". $lang['SEC']; + $stat = '[  ' . $lang['EXECUTION_TIME'] . " $gen_time_txt " . $lang['SEC']; - if (!empty($DBS)) - { - $sql_t = $DBS->sql_timetotal; - $sql_time_txt = ($sql_t) ? sprintf('%.3f '.$lang['SEC'].' (%d%%) · ', $sql_t, round($sql_t*100/$gen_time)) : ''; - $num_q = $DBS->num_queries; - $stat .= "  |  MySQL: {$sql_time_txt}{$num_q} " . $lang['QUERIES']; - } + if (!empty($DBS)) { + $sql_t = $DBS->sql_timetotal; + $sql_time_txt = ($sql_t) ? sprintf('%.3f ' . $lang['SEC'] . ' (%d%%) · ', $sql_t, round($sql_t * 100 / $gen_time)) : ''; + $num_q = $DBS->num_queries; + $stat .= "  |  MySQL: {$sql_time_txt}{$num_q} " . $lang['QUERIES']; + } - $stat .= "  |  $gzip_text"; + $stat .= "  |  $gzip_text"; - $stat .= '  |  '.$lang['MEMORY']; - $stat .= humn_size($di->config->get('mem_on_start'), 2) .' / '; - $stat .= humn_size(sys('mem_peak'), 2) .' / '; - $stat .= humn_size(sys('mem'), 2); + $stat .= '  |  ' . $lang['MEMORY']; + $stat .= humn_size($di->config->get('mem_on_start'), 2) . ' / '; + $stat .= humn_size(sys('mem_peak'), 2) . ' / '; + $stat .= humn_size(sys('mem'), 2); - if ($l = sys('la')) - { - $l = explode(' ', $l); - for ($i=0; $i < 3; $i++) - { - $l[$i] = round($l[$i], 1); - } - $stat .= "  |  ". $lang['LIMIT'] ." $l[0] $l[1] $l[2]"; - } + if ($l = sys('la')) { + $l = explode(' ', $l); + for ($i = 0; $i < 3; $i++) { + $l[$i] = round($l[$i], 1); + } + $stat .= "  |  " . $lang['LIMIT'] . " $l[0] $l[1] $l[2]"; + } - $stat .= '  ]'; - $stat .= ' - - - + $stat .= '  ]'; + $stat .= ' + + + '; - $stat .= !empty($_COOKIE['sql_log']) ? '[ wrap · max ]' : ''; + $stat .= !empty($_COOKIE['sql_log']) ? '[ wrap · max ]' : ''; - echo '
        '. $stat .'
        '; + echo '
        ' . $stat . '
        '; } echo ' '; -if (DBG_USER && SQL_DEBUG && !(isset($_GET['pane']) && $_GET['pane'] == 'left')) -{ - require(INC_DIR . 'page_footer_dev.php'); +if (DBG_USER && SQL_DEBUG && !(isset($_GET['pane']) && $_GET['pane'] == 'left')) { + require(INC_DIR . 'page_footer_dev.php'); } echo ' @@ -90,11 +83,11 @@ echo ' '; if (defined('REQUESTED_PAGE') && !defined('DISABLE_CACHING_OUTPUT')) { - if (IS_GUEST === true) { - if ($output = ob_get_contents()) { - $cache->set(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'), $output, 300); - } - } + if (IS_GUEST === true) { + if ($output = ob_get_contents()) { + $cache->set(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'), $output, 300); + } + } } -bb_exit(); \ No newline at end of file +bb_exit(); diff --git a/library/includes/page_footer_dev.php b/library/includes/page_footer_dev.php index fc4dc34e0..e37842f6c 100644 --- a/library/includes/page_footer_dev.php +++ b/library/includes/page_footer_dev.php @@ -1,71 +1,76 @@ srv as $srv_name => $db_obj) - { - if (!empty($db_obj->do_explain)) - { - $db_obj->explain('display'); - } - } +if (!empty($_COOKIE['explain'])) { + foreach ($DBS->srv as $srv_name => $db_obj) { + if (!empty($db_obj->do_explain)) { + $db_obj->explain('display'); + } + } } $sql_log = !empty($_COOKIE['sql_log']) ? get_sql_log() : ''; @@ -92,11 +97,10 @@ function fixSqlLog() { echo ''; -if ($sql_log) -{ - echo '
        '. ($sql_log ? $sql_log : '') .'

        '; +if ($sql_log) { + echo '
        ' . ($sql_log ? $sql_log : '') . '

        '; } ?> \ No newline at end of file + $(document).ready(fixSqlLog); + diff --git a/library/includes/page_header.php b/library/includes/page_header.php index 9e99fd64a..c7664d446 100644 --- a/library/includes/page_header.php +++ b/library/includes/page_header.php @@ -13,43 +13,40 @@ $di = \TorrentPier\Di::getInstance(); /** @var \TorrentPier\Cache\Adapter $cache */ $cache = $di->cache; -$logged_in = (int) !empty($userdata['session_logged_in']); +$logged_in = (int)!empty($userdata['session_logged_in']); // Generate logged in/logged out status if ($logged_in) { - $u_login_logout = BB_ROOT . LOGIN_URL . '?logout=1'; + $u_login_logout = BB_ROOT . LOGIN_URL . '?logout=1'; } else { - $u_login_logout = BB_ROOT . LOGIN_URL; + $u_login_logout = BB_ROOT . LOGIN_URL; } // Online userlist -if (defined('SHOW_ONLINE') && SHOW_ONLINE) -{ - $online_full = !empty($_REQUEST['online_full']); - $online_list = ($online_full) ? 'online_' . $userdata['user_lang'] : 'online_short_' . $userdata['user_lang']; +if (defined('SHOW_ONLINE') && SHOW_ONLINE) { + $online_full = !empty($_REQUEST['online_full']); + $online_list = ($online_full) ? 'online_' . $userdata['user_lang'] : 'online_short_' . $userdata['user_lang']; - ${$online_list} = [ - 'stat' => '', - 'userlist' => '', - 'cnt' => '', - ]; + ${$online_list} = [ + 'stat' => '', + 'userlist' => '', + 'cnt' => '', + ]; - if (defined('IS_GUEST') && !(IS_GUEST || IS_USER)) - { - $template->assign_var('SHOW_ONLINE_LIST'); + if (defined('IS_GUEST') && !(IS_GUEST || IS_USER)) { + $template->assign_var('SHOW_ONLINE_LIST'); - if (!${$online_list} = $cache->get($online_list)) - { - require(INC_DIR .'online_userlist.php'); - } - } + if (!${$online_list} = $cache->get($online_list)) { + require(INC_DIR . 'online_userlist.php'); + } + } - $template->assign_vars(array( - 'TOTAL_USERS_ONLINE' => ${$online_list}['stat'], - 'LOGGED_IN_USER_LIST' => ${$online_list}['userlist'], - 'USERS_ONLINE_COUNTS' => ${$online_list}['cnt'], - 'RECORD_USERS' => sprintf($lang['RECORD_ONLINE_USERS'], $di->config->get('record_online_users'), bb_date($di->config->get('record_online_date'))), - )); + $template->assign_vars(array( + 'TOTAL_USERS_ONLINE' => ${$online_list}['stat'], + 'LOGGED_IN_USER_LIST' => ${$online_list}['userlist'], + 'USERS_ONLINE_COUNTS' => ${$online_list}['cnt'], + 'RECORD_USERS' => sprintf($lang['RECORD_ONLINE_USERS'], $di->config->get('record_online_users'), bb_date($di->config->get('record_online_date'))), + )); } // Info about new private messages @@ -57,201 +54,190 @@ $icon_pm = $images['pm_no_new_msg']; $pm_info = $lang['NO_NEW_PM']; $have_new_pm = $have_unread_pm = 0; -if ($logged_in && empty($gen_simple_header) && !defined('IN_ADMIN')) -{ - if ($userdata['user_new_privmsg']) - { - $have_new_pm = $userdata['user_new_privmsg']; - $icon_pm = $images['pm_new_msg']; - $pm_info = declension($userdata['user_new_privmsg'], $lang['NEW_PMS_DECLENSION'], $lang['NEW_PMS_FORMAT']); +if ($logged_in && empty($gen_simple_header) && !defined('IN_ADMIN')) { + if ($userdata['user_new_privmsg']) { + $have_new_pm = $userdata['user_new_privmsg']; + $icon_pm = $images['pm_new_msg']; + $pm_info = declension($userdata['user_new_privmsg'], $lang['NEW_PMS_DECLENSION'], $lang['NEW_PMS_FORMAT']); - if ($userdata['user_last_privmsg'] > $userdata['user_lastvisit'] && defined('IN_PM')) - { - $userdata['user_last_privmsg'] = $userdata['user_lastvisit']; + if ($userdata['user_last_privmsg'] > $userdata['user_lastvisit'] && defined('IN_PM')) { + $userdata['user_last_privmsg'] = $userdata['user_lastvisit']; - db_update_userdata($userdata, array( - 'user_last_privmsg' => $userdata['user_lastvisit'], - )); + db_update_userdata($userdata, array( + 'user_last_privmsg' => $userdata['user_lastvisit'], + )); - $have_new_pm = ($userdata['user_new_privmsg'] > 1); - } - } - if (!$have_new_pm && $userdata['user_unread_privmsg']) - { - // synch unread pm count - if (defined('IN_PM')) - { - $row = DB()->fetch_row(" + $have_new_pm = ($userdata['user_new_privmsg'] > 1); + } + } + if (!$have_new_pm && $userdata['user_unread_privmsg']) { + // synch unread pm count + if (defined('IN_PM')) { + $row = DB()->fetch_row(" SELECT COUNT(*) AS pm_count - FROM ". BB_PRIVMSGS ." - WHERE privmsgs_to_userid = ". $userdata['user_id'] ." - AND privmsgs_type = ". PRIVMSGS_UNREAD_MAIL ." + FROM " . BB_PRIVMSGS . " + WHERE privmsgs_to_userid = " . $userdata['user_id'] . " + AND privmsgs_type = " . PRIVMSGS_UNREAD_MAIL . " GROUP BY privmsgs_to_userid "); - $real_unread_pm_count = (int) $row['pm_count']; + $real_unread_pm_count = (int)$row['pm_count']; - if ($userdata['user_unread_privmsg'] != $real_unread_pm_count) - { - $userdata['user_unread_privmsg'] = $real_unread_pm_count; + if ($userdata['user_unread_privmsg'] != $real_unread_pm_count) { + $userdata['user_unread_privmsg'] = $real_unread_pm_count; - db_update_userdata($userdata, array( - 'user_unread_privmsg' => $real_unread_pm_count, - )); - } - } + db_update_userdata($userdata, array( + 'user_unread_privmsg' => $real_unread_pm_count, + )); + } + } - $pm_info = declension($userdata['user_unread_privmsg'], $lang['UNREAD_PMS_DECLENSION'], $lang['UNREAD_PMS_FORMAT']); - $have_unread_pm = true; - } + $pm_info = declension($userdata['user_unread_privmsg'], $lang['UNREAD_PMS_DECLENSION'], $lang['UNREAD_PMS_FORMAT']); + $have_unread_pm = true; + } } $template->assign_vars(array( - 'HAVE_NEW_PM' => $have_new_pm, - 'HAVE_UNREAD_PM' => $have_unread_pm, + 'HAVE_NEW_PM' => $have_new_pm, + 'HAVE_UNREAD_PM' => $have_unread_pm, )); // The following assigns all _common_ variables that may be used at any point in a template $template->assign_vars(array( - 'SIMPLE_HEADER' => !empty($gen_simple_header), - 'CONTENT_ENCODING' => $di->config->get('lang.' . $userdata['user_lang'] . '.encoding'), + 'SIMPLE_HEADER' => !empty($gen_simple_header), + 'CONTENT_ENCODING' => $di->config->get('lang.' . $userdata['user_lang'] . '.encoding'), - 'IN_ADMIN' => defined('IN_ADMIN'), - 'USER_HIDE_CAT' => (BB_SCRIPT == 'index'), + 'IN_ADMIN' => defined('IN_ADMIN'), + 'USER_HIDE_CAT' => (BB_SCRIPT == 'index'), - 'USER_LANG' => $userdata['user_lang'], + 'USER_LANG' => $userdata['user_lang'], - 'INCLUDE_BBCODE_JS' => !empty($page_cfg['include_bbcode_js']), - 'USER_OPTIONS_JS' => (IS_GUEST) ? '{}' : \Zend\Json\Json::encode($user->opt_js), + 'INCLUDE_BBCODE_JS' => !empty($page_cfg['include_bbcode_js']), + 'USER_OPTIONS_JS' => (IS_GUEST) ? '{}' : \Zend\Json\Json::encode($user->opt_js), - 'USE_TABLESORTER' => !empty($page_cfg['use_tablesorter']), + 'USE_TABLESORTER' => !empty($page_cfg['use_tablesorter']), - 'SITENAME' => $di->config->get('sitename'), - 'U_INDEX' => BB_ROOT ."index.php", - 'T_INDEX' => sprintf($lang['FORUM_INDEX'], $di->config->get('sitename')), + 'SITENAME' => $di->config->get('sitename'), + 'U_INDEX' => BB_ROOT . "index.php", + 'T_INDEX' => sprintf($lang['FORUM_INDEX'], $di->config->get('sitename')), - 'IS_GUEST' => IS_GUEST, - 'IS_USER' => IS_USER, - 'IS_ADMIN' => IS_ADMIN, - 'IS_MOD' => IS_MOD, - 'IS_AM' => IS_AM, + 'IS_GUEST' => IS_GUEST, + 'IS_USER' => IS_USER, + 'IS_ADMIN' => IS_ADMIN, + 'IS_MOD' => IS_MOD, + 'IS_AM' => IS_AM, - 'FORUM_PATH' => FORUM_PATH, - 'FULL_URL' => FULL_URL, + 'FORUM_PATH' => FORUM_PATH, + 'FULL_URL' => FULL_URL, - 'CURRENT_TIME' => sprintf($lang['CURRENT_TIME'], bb_date(TIMENOW, $di->config->get('last_visit_date_format'), false)), - 'S_TIMEZONE' => preg_replace('/\(.*?\)/', '', sprintf($lang['ALL_TIMES'], $lang['TZ'][str_replace(',', '.', floatval($di->config->get('board_timezone')))])), - 'BOARD_TIMEZONE' => $di->config->get('board_timezone'), + 'CURRENT_TIME' => sprintf($lang['CURRENT_TIME'], bb_date(TIMENOW, $di->config->get('last_visit_date_format'), false)), + 'S_TIMEZONE' => preg_replace('/\(.*?\)/', '', sprintf($lang['ALL_TIMES'], $lang['TZ'][str_replace(',', '.', floatval($di->config->get('board_timezone')))])), + 'BOARD_TIMEZONE' => $di->config->get('board_timezone'), - 'PM_INFO' => $pm_info, - 'PRIVMSG_IMG' => $icon_pm, + 'PM_INFO' => $pm_info, + 'PRIVMSG_IMG' => $icon_pm, - 'LOGGED_IN' => $logged_in, - 'SESSION_USER_ID' => $userdata['user_id'], - 'POINTS' => $userdata['user_points'], - 'THIS_USER' => profile_url($userdata), - 'THIS_AVATAR' => get_avatar($userdata['user_id'], $userdata['avatar_ext_id'], !bf($userdata['user_opt'], 'user_opt', 'dis_avatar')), - 'SHOW_LOGIN_LINK' => !defined('IN_LOGIN'), - 'AUTOLOGIN_DISABLED' => !$di->config->get('allow_autologin'), - 'S_LOGIN_ACTION' => LOGIN_URL, + 'LOGGED_IN' => $logged_in, + 'SESSION_USER_ID' => $userdata['user_id'], + 'POINTS' => $userdata['user_points'], + 'THIS_USER' => profile_url($userdata), + 'THIS_AVATAR' => get_avatar($userdata['user_id'], $userdata['avatar_ext_id'], !bf($userdata['user_opt'], 'user_opt', 'dis_avatar')), + 'SHOW_LOGIN_LINK' => !defined('IN_LOGIN'), + 'AUTOLOGIN_DISABLED' => !$di->config->get('allow_autologin'), + 'S_LOGIN_ACTION' => LOGIN_URL, - 'U_CUR_DOWNLOADS' => PROFILE_URL . $userdata['user_id'], - 'U_FORUM' => "viewforum.php", - 'U_GROUPS' => "group.php", - 'U_LOGIN_LOGOUT' => $u_login_logout, - 'U_MEMBERLIST' => "memberlist.php", - 'U_MODCP' => "modcp.php", - 'U_OPTIONS' => "profile.php?mode=editprofile", - 'U_PRIVATEMSGS' => PM_URL . "?folder=inbox", - 'U_PROFILE' => PROFILE_URL . $userdata['user_id'], - 'U_READ_PM' => PM_URL . "?folder=inbox". (($userdata['user_newest_pm_id'] && $userdata['user_new_privmsg'] == 1) ? "&mode=read&p={$userdata['user_newest_pm_id']}" : ''), - 'U_REGISTER' => "profile.php?mode=register", - 'U_SEARCH' => "search.php", - 'U_SEND_PASSWORD' => "profile.php?mode=sendpassword", - 'U_TERMS' => $di->config->get('terms_and_conditions_url'), - 'U_TRACKER' => "tracker.php", + 'U_CUR_DOWNLOADS' => PROFILE_URL . $userdata['user_id'], + 'U_FORUM' => "viewforum.php", + 'U_GROUPS' => "group.php", + 'U_LOGIN_LOGOUT' => $u_login_logout, + 'U_MEMBERLIST' => "memberlist.php", + 'U_MODCP' => "modcp.php", + 'U_OPTIONS' => "profile.php?mode=editprofile", + 'U_PRIVATEMSGS' => PM_URL . "?folder=inbox", + 'U_PROFILE' => PROFILE_URL . $userdata['user_id'], + 'U_READ_PM' => PM_URL . "?folder=inbox" . (($userdata['user_newest_pm_id'] && $userdata['user_new_privmsg'] == 1) ? "&mode=read&p={$userdata['user_newest_pm_id']}" : ''), + 'U_REGISTER' => "profile.php?mode=register", + 'U_SEARCH' => "search.php", + 'U_SEND_PASSWORD' => "profile.php?mode=sendpassword", + 'U_TERMS' => $di->config->get('terms_and_conditions_url'), + 'U_TRACKER' => "tracker.php", - 'SHOW_SIDEBAR1' => (!empty($page_cfg['show_sidebar1'][BB_SCRIPT]) || $di->config->get('show_sidebar1_on_every_page')), - 'SHOW_SIDEBAR2' => (!empty($page_cfg['show_sidebar2'][BB_SCRIPT]) || $di->config->get('show_sidebar2_on_every_page')), + 'SHOW_SIDEBAR1' => (!empty($page_cfg['show_sidebar1'][BB_SCRIPT]) || $di->config->get('show_sidebar1_on_every_page')), + 'SHOW_SIDEBAR2' => (!empty($page_cfg['show_sidebar2'][BB_SCRIPT]) || $di->config->get('show_sidebar2_on_every_page')), - 'HTML_AGREEMENT' => LANG_DIR . 'html/user_agreement.html', - 'HTML_COPYRIGHT' => LANG_DIR . 'html/copyright_holders.html', - 'HTML_ADVERT' => LANG_DIR . 'html/advert.html', - 'HTML_SIDEBAR_1' => LANG_DIR . 'html/sidebar1.html', - 'HTML_SIDEBAR_2' => LANG_DIR . 'html/sidebar2.html', + 'HTML_AGREEMENT' => LANG_DIR . 'html/user_agreement.html', + 'HTML_COPYRIGHT' => LANG_DIR . 'html/copyright_holders.html', + 'HTML_ADVERT' => LANG_DIR . 'html/advert.html', + 'HTML_SIDEBAR_1' => LANG_DIR . 'html/sidebar1.html', + 'HTML_SIDEBAR_2' => LANG_DIR . 'html/sidebar2.html', - // Common urls - 'AVATARS_URL' => 'data/avatars', - 'CAT_URL' => BB_ROOT . CAT_URL, - 'DOWNLOAD_URL' => BB_ROOT . DOWNLOAD_URL, - 'FORUM_URL' => BB_ROOT . FORUM_URL, - 'GROUP_URL' => BB_ROOT . GROUP_URL, - 'LOGIN_URL' => $di->config->get('login_url'), - 'NEWEST_URL' => '&view=newest#newest', - 'PM_URL' => $di->config->get('pm_url'), - 'POST_URL' => BB_ROOT . POST_URL, - 'POSTING_URL' => $di->config->get('posting_url'), - 'PROFILE_URL' => BB_ROOT . PROFILE_URL, - 'TOPIC_URL' => BB_ROOT . TOPIC_URL, + // Common urls + 'AVATARS_URL' => 'data/avatars', + 'CAT_URL' => BB_ROOT . CAT_URL, + 'DOWNLOAD_URL' => BB_ROOT . DOWNLOAD_URL, + 'FORUM_URL' => BB_ROOT . FORUM_URL, + 'GROUP_URL' => BB_ROOT . GROUP_URL, + 'LOGIN_URL' => $di->config->get('login_url'), + 'NEWEST_URL' => '&view=newest#newest', + 'PM_URL' => $di->config->get('pm_url'), + 'POST_URL' => BB_ROOT . POST_URL, + 'POSTING_URL' => $di->config->get('posting_url'), + 'PROFILE_URL' => BB_ROOT . PROFILE_URL, + 'TOPIC_URL' => BB_ROOT . TOPIC_URL, - 'AJAX_HTML_DIR' => AJAX_HTML_DIR, + 'AJAX_HTML_DIR' => AJAX_HTML_DIR, - 'ONLY_NEW_POSTS' => ONLY_NEW_POSTS, - 'ONLY_NEW_TOPICS' => ONLY_NEW_TOPICS, + 'ONLY_NEW_POSTS' => ONLY_NEW_POSTS, + 'ONLY_NEW_TOPICS' => ONLY_NEW_TOPICS, - // Misc - 'BOT_UID' => BOT_UID, - 'COOKIE_MARK' => COOKIE_MARK, - 'SID' => $userdata['session_id'], - 'SID_HIDDEN' => '', + // Misc + 'BOT_UID' => BOT_UID, + 'COOKIE_MARK' => COOKIE_MARK, + 'SID' => $userdata['session_id'], + 'SID_HIDDEN' => '', - 'CHECKED' => HTML_CHECKED, - 'DISABLED' => HTML_DISABLED, - 'READONLY' => HTML_READONLY, - 'SELECTED' => HTML_SELECTED, + 'CHECKED' => HTML_CHECKED, + 'DISABLED' => HTML_DISABLED, + 'READONLY' => HTML_READONLY, + 'SELECTED' => HTML_SELECTED, - 'U_SEARCH_SELF_BY_LAST' => "search.php?uid={$userdata['user_id']}&o=5", - 'U_WATCHED_TOPICS' => "profile.php?mode=watch", + 'U_SEARCH_SELF_BY_LAST' => "search.php?uid={$userdata['user_id']}&o=5", + 'U_WATCHED_TOPICS' => "profile.php?mode=watch", )); -if (!empty($page_cfg['show_torhelp'][BB_SCRIPT]) && !empty($userdata['torhelp'])) -{ - $ignore_time = !empty($_COOKIE['torhelp']) ? (int) $_COOKIE['torhelp'] : 0; +if (!empty($page_cfg['show_torhelp'][BB_SCRIPT]) && !empty($userdata['torhelp'])) { + $ignore_time = !empty($_COOKIE['torhelp']) ? (int)$_COOKIE['torhelp'] : 0; - if (TIMENOW > $ignore_time) - { - if ($ignore_time) - { - bb_setcookie('torhelp', '', COOKIE_EXPIRED); - } + if (TIMENOW > $ignore_time) { + if ($ignore_time) { + bb_setcookie('torhelp', '', COOKIE_EXPIRED); + } - $sql = " + $sql = " SELECT topic_id, topic_title - FROM ". BB_TOPICS ." - WHERE topic_id IN(". $userdata['torhelp'] .") + FROM " . BB_TOPICS . " + WHERE topic_id IN(" . $userdata['torhelp'] . ") LIMIT 8 "; - $torhelp_topics = array(); + $torhelp_topics = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $torhelp_topics[] = ''. $row['topic_title'] .''; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $torhelp_topics[] = '' . $row['topic_title'] . ''; + } - $template->assign_vars(array( - 'TORHELP_TOPICS' => join("\n
      • ", $torhelp_topics), - )); - } + $template->assign_vars(array( + 'TORHELP_TOPICS' => join("
      • \n
      • ", $torhelp_topics), + )); + } } // Login box $in_out = ($logged_in) ? 'in' : 'out'; $template->assign_block_vars("switch_user_logged_{$in_out}", array()); -if (!IS_GUEST) -{ - header('Cache-Control: private, pre-check=0, post-check=0, max-age=0'); - header('Expires: 0'); - header('Pragma: no-cache'); +if (!IS_GUEST) { + header('Cache-Control: private, pre-check=0, post-check=0, max-age=0'); + header('Expires: 0'); + header('Pragma: no-cache'); } $template->set_filenames(array('page_header' => 'page_header.tpl')); @@ -259,7 +245,6 @@ $template->pparse('page_header'); define('PAGE_HEADER_SENT', true); -if (!$di->config->get('gzip_compress')) -{ - flush(); -} \ No newline at end of file +if (!$di->config->get('gzip_compress')) { + flush(); +} diff --git a/library/includes/posting_tpl.php b/library/includes/posting_tpl.php index 7ee21264c..7ca168456 100644 --- a/library/includes/posting_tpl.php +++ b/library/includes/posting_tpl.php @@ -6,77 +6,69 @@ $can_edit_tpl = IS_SUPER_ADMIN; $edit_tpl_mode = ($can_edit_tpl && !empty($_REQUEST['edit_tpl'])); // forum_data -$sql = "SELECT forum_name, allow_reg_tracker, forum_tpl_id FROM ". BB_FORUMS ." WHERE forum_id = $forum_id LIMIT 1"; +$sql = "SELECT forum_name, allow_reg_tracker, forum_tpl_id FROM " . BB_FORUMS . " WHERE forum_id = $forum_id LIMIT 1"; -if (!$forum_id || !($f_data = DB()->fetch_row($sql))) -{ - bb_die($lang['FORUM_NOT_EXIST']); +if (!$forum_id || !($f_data = DB()->fetch_row($sql))) { + bb_die($lang['FORUM_NOT_EXIST']); } // tpl_data $tpl_data = []; -$sql = "SELECT * FROM ". BB_TOPIC_TPL ." WHERE tpl_id = {$f_data['forum_tpl_id']} LIMIT 1"; +$sql = "SELECT * FROM " . BB_TOPIC_TPL . " WHERE tpl_id = {$f_data['forum_tpl_id']} LIMIT 1"; -if (!$f_data['forum_tpl_id'] || !($tpl_data = DB()->fetch_row($sql))) -{ - if (!$edit_tpl_mode) - { - redirect(POSTING_URL . "?mode=newtopic&f=$forum_id"); - } +if (!$f_data['forum_tpl_id'] || !($tpl_data = DB()->fetch_row($sql))) { + if (!$edit_tpl_mode) { + redirect(POSTING_URL . "?mode=newtopic&f=$forum_id"); + } } $template->assign_vars(array( - 'PAGE_TITLE' => $lang['NEW_RELEASE'], - 'FORUM_NAME' => $f_data['forum_name'], - 'FORUM_ID' => $forum_id, - 'TPL_FORM_ACTION' => POSTING_URL . "?mode=newtopic&f=$forum_id", - 'REGULAR_TOPIC_HREF' => POSTING_URL . "?mode=newtopic&f=$forum_id", - 'TOR_REQUIRED' => $f_data['allow_reg_tracker'], - 'EDIT_TPL' => $edit_tpl_mode, - 'CAN_EDIT_TPL' => $can_edit_tpl, - 'EDIT_TPL_URL' => POSTING_URL . "?mode=new_rel&f=$forum_id&edit_tpl=1", + 'PAGE_TITLE' => $lang['NEW_RELEASE'], + 'FORUM_NAME' => $f_data['forum_name'], + 'FORUM_ID' => $forum_id, + 'TPL_FORM_ACTION' => POSTING_URL . "?mode=newtopic&f=$forum_id", + 'REGULAR_TOPIC_HREF' => POSTING_URL . "?mode=newtopic&f=$forum_id", + 'TOR_REQUIRED' => $f_data['allow_reg_tracker'], + 'EDIT_TPL' => $edit_tpl_mode, + 'CAN_EDIT_TPL' => $can_edit_tpl, + 'EDIT_TPL_URL' => POSTING_URL . "?mode=new_rel&f=$forum_id&edit_tpl=1", )); -if ($tpl_data) -{ - // tpl_rules_html - $tpl_rules_html = ''; +if ($tpl_data) { + // tpl_rules_html + $tpl_rules_html = ''; - if ($tpl_data['tpl_rules_post_id']) - { - if (!$tpl_rules_html = bbcode2html(DB()->fetch_row("SELECT post_text FROM ". BB_POSTS_TEXT ." WHERE post_id = ". $tpl_data['tpl_rules_post_id'], 'post_text'))) - { - $tpl_data['tpl_rules_post_id'] = 0; - DB()->query("UPDATE ". BB_TOPIC_TPL ." SET tpl_rules_post_id = 0 WHERE tpl_id = {$f_data['forum_tpl_id']} LIMIT 1"); - } - } + if ($tpl_data['tpl_rules_post_id']) { + if (!$tpl_rules_html = bbcode2html(DB()->fetch_row("SELECT post_text FROM " . BB_POSTS_TEXT . " WHERE post_id = " . $tpl_data['tpl_rules_post_id'], 'post_text'))) { + $tpl_data['tpl_rules_post_id'] = 0; + DB()->query("UPDATE " . BB_TOPIC_TPL . " SET tpl_rules_post_id = 0 WHERE tpl_id = {$f_data['forum_tpl_id']} LIMIT 1"); + } + } - $template->assign_vars(array( - 'TPL_ID' => $tpl_data['tpl_id'], - 'TPL_NAME' => $tpl_data['tpl_name'], - 'TPL_SRC_FORM_VAL' => $tpl_data['tpl_src_form'], - 'TPL_SRC_TITLE_VAL' => $tpl_data['tpl_src_title'], - 'TPL_SRC_MSG_VAL' => $tpl_data['tpl_src_msg'], - 'TPL_RULES_HTML' => $tpl_rules_html, - )); + $template->assign_vars(array( + 'TPL_ID' => $tpl_data['tpl_id'], + 'TPL_NAME' => $tpl_data['tpl_name'], + 'TPL_SRC_FORM_VAL' => $tpl_data['tpl_src_form'], + 'TPL_SRC_TITLE_VAL' => $tpl_data['tpl_src_title'], + 'TPL_SRC_MSG_VAL' => $tpl_data['tpl_src_msg'], + 'TPL_RULES_HTML' => $tpl_rules_html, + )); } -if ($edit_tpl_mode) -{ - $template->assign_vars(array( - 'NO_TPL_ASSIGNED' => !($f_data['forum_tpl_id']), - 'TPL_SELECT' => get_select('forum_tpl', $f_data['forum_tpl_id']), - )); +if ($edit_tpl_mode) { + $template->assign_vars(array( + 'NO_TPL_ASSIGNED' => !($f_data['forum_tpl_id']), + 'TPL_SELECT' => get_select('forum_tpl', $f_data['forum_tpl_id']), + )); - if ($tpl_data) - { - $template->assign_vars(array( - 'TPL_COMMENT' => $tpl_data['tpl_comment'], - 'TPL_RULES_POST_ID' => $tpl_data['tpl_rules_post_id'], - 'TPL_LAST_EDIT_TIME' => bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'), - 'TPL_LAST_EDIT_USER' => get_username(intval($tpl_data['tpl_last_edit_by'])), - 'TPL_LAST_EDIT_TIMESTAMP' => $tpl_data['tpl_last_edit_tm'], - )); - } + if ($tpl_data) { + $template->assign_vars(array( + 'TPL_COMMENT' => $tpl_data['tpl_comment'], + 'TPL_RULES_POST_ID' => $tpl_data['tpl_rules_post_id'], + 'TPL_LAST_EDIT_TIME' => bb_date($tpl_data['tpl_last_edit_tm'], 'd-M-y H:i'), + 'TPL_LAST_EDIT_USER' => get_username(intval($tpl_data['tpl_last_edit_by'])), + 'TPL_LAST_EDIT_TIMESTAMP' => $tpl_data['tpl_last_edit_tm'], + )); + } } -print_page(TEMPLATES_DIR . 'posting_tpl.tpl'); \ No newline at end of file +print_page(TEMPLATES_DIR . 'posting_tpl.tpl'); diff --git a/library/includes/sessions.php b/library/includes/sessions.php index 489a7cacc..a6642101b 100644 --- a/library/includes/sessions.php +++ b/library/includes/sessions.php @@ -2,900 +2,821 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -define('ONLY_NEW_POSTS', 1); +define('ONLY_NEW_POSTS', 1); define('ONLY_NEW_TOPICS', 2); class user_common { - /** - * Config - */ - var $cfg = array( - 'req_login' => false, // requires user to be logged in - 'req_session_admin' => false, // requires active admin session (for moderation or admin actions) - ); + /** + * Config + */ + var $cfg = array( + 'req_login' => false, // requires user to be logged in + 'req_session_admin' => false, // requires active admin session (for moderation or admin actions) + ); - /** - * PHP-JS exchangeable options (JSON'ized as {USER_OPTIONS_JS} in TPL) - */ - var $opt_js = array( - 'only_new' => 0, // show ony new posts or topics - 'h_av' => 0, // hide avatar - 'h_rnk_i' => 0, // hide rank images - 'h_post_i' => 0, // hide post images - 'h_smile' => 0, // hide smilies - 'h_sig' => 0, // hide signatures - 'sp_op' => 0, // show spoiler opened - 'tr_t_ax' => 0, // ajax open topics - 'tr_t_t' => 0, // show time of the creation topics - 'hl_tr' => 1, // show cursor in tracker.php - 'i_aft_l' => 0, // show images only after full loading - 'h_tsp' => 0, // show released title {...} - ); + /** + * PHP-JS exchangeable options (JSON'ized as {USER_OPTIONS_JS} in TPL) + */ + var $opt_js = array( + 'only_new' => 0, // show ony new posts or topics + 'h_av' => 0, // hide avatar + 'h_rnk_i' => 0, // hide rank images + 'h_post_i' => 0, // hide post images + 'h_smile' => 0, // hide smilies + 'h_sig' => 0, // hide signatures + 'sp_op' => 0, // show spoiler opened + 'tr_t_ax' => 0, // ajax open topics + 'tr_t_t' => 0, // show time of the creation topics + 'hl_tr' => 1, // show cursor in tracker.php + 'i_aft_l' => 0, // show images only after full loading + 'h_tsp' => 0, // show released title {...} + ); - /** - * Defaults options for guests - */ - var $opt_js_guest = array( - 'h_av' => 1, // hide avatar - 'h_rnk_i' => 1, // hide rank images - 'h_smile' => 1, // hide smilies - 'h_sig' => 1, // hide signatures - ); + /** + * Defaults options for guests + */ + var $opt_js_guest = array( + 'h_av' => 1, // hide avatar + 'h_rnk_i' => 1, // hide rank images + 'h_smile' => 1, // hide smilies + 'h_sig' => 1, // hide signatures + ); - /** - * Sessiondata - */ - var $sessiondata = array( - 'uk' => null, - 'uid' => null, - 'sid' => '', - ); + /** + * Sessiondata + */ + var $sessiondata = array( + 'uk' => null, + 'uid' => null, + 'sid' => '', + ); - /** - * Old $userdata - */ - var $data = array(); + /** + * Old $userdata + */ + var $data = array(); - /** - * Shortcuts - */ - var $id = null; + /** + * Shortcuts + */ + var $id = null; - /** - * Constructor - */ - function user_common () - { - $this->get_sessiondata(); - } + /** + * Constructor + */ + function user_common() + { + $this->get_sessiondata(); + } - /** - * Start session (restore existent session or create new) - * - * @param array $cfg - * - * @return array|bool - */ - function session_start ($cfg = array()) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Start session (restore existent session or create new) + * + * @param array $cfg + * + * @return array|bool + */ + function session_start($cfg = array()) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $update_sessions_table = false; - $this->cfg = array_merge($this->cfg, $cfg); + $update_sessions_table = false; + $this->cfg = array_merge($this->cfg, $cfg); - $session_id = $this->sessiondata['sid']; + $session_id = $this->sessiondata['sid']; - // Does a session exist? - if ($session_id || !$this->sessiondata['uk']) - { - $SQL = DB()->get_empty_sql_array(); + // Does a session exist? + if ($session_id || !$this->sessiondata['uk']) { + $SQL = DB()->get_empty_sql_array(); - $SQL['SELECT'][] = "u.*, s.*"; + $SQL['SELECT'][] = "u.*, s.*"; - $SQL['FROM'][] = BB_SESSIONS ." s"; - $SQL['INNER JOIN'][] = BB_USERS ." u ON(u.user_id = s.session_user_id)"; + $SQL['FROM'][] = BB_SESSIONS . " s"; + $SQL['INNER JOIN'][] = BB_USERS . " u ON(u.user_id = s.session_user_id)"; - if ($session_id) - { - $SQL['WHERE'][] = "s.session_id = '$session_id'"; + if ($session_id) { + $SQL['WHERE'][] = "s.session_id = '$session_id'"; - if ($di->config->get('torhelp_enabled')) - { - $SQL['SELECT'][] = "th.topic_id_csv AS torhelp"; - $SQL['LEFT JOIN'][] = BB_BT_TORHELP ." th ON(u.user_id = th.user_id)"; - } + if ($di->config->get('torhelp_enabled')) { + $SQL['SELECT'][] = "th.topic_id_csv AS torhelp"; + $SQL['LEFT JOIN'][] = BB_BT_TORHELP . " th ON(u.user_id = th.user_id)"; + } - $userdata_cache_id = $session_id; - } - else - { - $SQL['WHERE'][] = "s.session_ip = '". USER_IP ."'"; - $SQL['WHERE'][] = "s.session_user_id = ". GUEST_UID; + $userdata_cache_id = $session_id; + } else { + $SQL['WHERE'][] = "s.session_ip = '" . USER_IP . "'"; + $SQL['WHERE'][] = "s.session_user_id = " . GUEST_UID; - $userdata_cache_id = USER_IP; - } + $userdata_cache_id = USER_IP; + } - if (!$this->data = cache_get_userdata($userdata_cache_id)) - { - $this->data = DB()->fetch_row($SQL); + if (!$this->data = cache_get_userdata($userdata_cache_id)) { + $this->data = DB()->fetch_row($SQL); - if ($this->data && (TIMENOW - $this->data['session_time']) > $di->config->get('session_update_intrv')) - { - $this->data['session_time'] = TIMENOW; - $update_sessions_table = true; - } + if ($this->data && (TIMENOW - $this->data['session_time']) > $di->config->get('session_update_intrv')) { + $this->data['session_time'] = TIMENOW; + $update_sessions_table = true; + } - cache_set_userdata($this->data); - } - } + cache_set_userdata($this->data); + } + } - // Did the session exist in the DB? - if ($this->data) - { - // Do not check IP assuming equivalence, if IPv4 we'll check only first 24 - // bits ... I've been told (by vHiker) this should alleviate problems with - // load balanced et al proxies while retaining some reliance on IP security. - $ip_check_s = substr($this->data['session_ip'], 0, 6); - $ip_check_u = substr(USER_IP, 0, 6); + // Did the session exist in the DB? + if ($this->data) { + // Do not check IP assuming equivalence, if IPv4 we'll check only first 24 + // bits ... I've been told (by vHiker) this should alleviate problems with + // load balanced et al proxies while retaining some reliance on IP security. + $ip_check_s = substr($this->data['session_ip'], 0, 6); + $ip_check_u = substr(USER_IP, 0, 6); - if ($ip_check_s == $ip_check_u) - { - if ($this->data['user_id'] != GUEST_UID && defined('IN_ADMIN')) - { - define('SID_GET', "sid={$this->data['session_id']}"); - } - $session_id = $this->sessiondata['sid'] = $this->data['session_id']; + if ($ip_check_s == $ip_check_u) { + if ($this->data['user_id'] != GUEST_UID && defined('IN_ADMIN')) { + define('SID_GET', "sid={$this->data['session_id']}"); + } + $session_id = $this->sessiondata['sid'] = $this->data['session_id']; - // Only update session a minute or so after last update - if ($update_sessions_table) - { - DB()->query(" - UPDATE ". BB_SESSIONS ." SET - session_time = ". TIMENOW ." + // Only update session a minute or so after last update + if ($update_sessions_table) { + DB()->query(" + UPDATE " . BB_SESSIONS . " SET + session_time = " . TIMENOW . " WHERE session_id = '$session_id' LIMIT 1 "); - } - $this->set_session_cookies($this->data['user_id']); - } - else - { - $this->data = array(); - } - } - // If we reach here then no (valid) session exists. So we'll create a new one, - // using the cookie user_id if available to pull basic user prefs. - if (!$this->data) - { - $login = false; - $user_id = ($di->config->get('allow_autologin') && $this->sessiondata['uk'] && $this->sessiondata['uid']) ? $this->sessiondata['uid'] : GUEST_UID; + } + $this->set_session_cookies($this->data['user_id']); + } else { + $this->data = array(); + } + } + // If we reach here then no (valid) session exists. So we'll create a new one, + // using the cookie user_id if available to pull basic user prefs. + if (!$this->data) { + $login = false; + $user_id = ($di->config->get('allow_autologin') && $this->sessiondata['uk'] && $this->sessiondata['uid']) ? $this->sessiondata['uid'] : GUEST_UID; - if ($userdata = get_userdata(intval($user_id), false, true)) - { - if ($userdata['user_id'] != GUEST_UID && $userdata['user_active']) - { - if (verify_id($this->sessiondata['uk'], LOGIN_KEY_LENGTH) && $this->verify_autologin_id($userdata, true, false)) - { - $login = ($userdata['autologin_id'] && $this->sessiondata['uk'] === $userdata['autologin_id']); - } - } - } - if (!$userdata || ($userdata['user_id'] != GUEST_UID && !$login)) - { - $userdata = get_userdata(GUEST_UID, false, true); - } + if ($userdata = get_userdata(intval($user_id), false, true)) { + if ($userdata['user_id'] != GUEST_UID && $userdata['user_active']) { + if (verify_id($this->sessiondata['uk'], LOGIN_KEY_LENGTH) && $this->verify_autologin_id($userdata, true, false)) { + $login = ($userdata['autologin_id'] && $this->sessiondata['uk'] === $userdata['autologin_id']); + } + } + } + if (!$userdata || ($userdata['user_id'] != GUEST_UID && !$login)) { + $userdata = get_userdata(GUEST_UID, false, true); + } - $this->session_create($userdata, true); - } + $this->session_create($userdata, true); + } - define('IS_GUEST', (!$this->data['session_logged_in'])); - define('IS_ADMIN', (!IS_GUEST && $this->data['user_level'] == ADMIN)); - define('IS_MOD', (!IS_GUEST && $this->data['user_level'] == MOD)); - define('IS_CP_HOLDER', (!IS_GUEST && $this->data['user_level'] == CP_HOLDER)); - define('IS_GROUP_MEMBER', (!IS_GUEST && $this->data['user_level'] == GROUP_MEMBER)); - define('IS_USER', (!IS_GUEST && $this->data['user_level'] == USER)); - define('IS_SUPER_ADMIN', (IS_ADMIN && $di->config->get('super_admins.' . $this->data['user_id']))); - define('IS_AM', (IS_ADMIN || IS_MOD)); + define('IS_GUEST', (!$this->data['session_logged_in'])); + define('IS_ADMIN', (!IS_GUEST && $this->data['user_level'] == ADMIN)); + define('IS_MOD', (!IS_GUEST && $this->data['user_level'] == MOD)); + define('IS_CP_HOLDER', (!IS_GUEST && $this->data['user_level'] == CP_HOLDER)); + define('IS_GROUP_MEMBER', (!IS_GUEST && $this->data['user_level'] == GROUP_MEMBER)); + define('IS_USER', (!IS_GUEST && $this->data['user_level'] == USER)); + define('IS_SUPER_ADMIN', (IS_ADMIN && $di->config->get('super_admins.' . $this->data['user_id']))); + define('IS_AM', (IS_ADMIN || IS_MOD)); - $this->set_shortcuts(); + $this->set_shortcuts(); - // Redirect guests to login page - if (IS_GUEST && $this->cfg['req_login']) - { - login_redirect(); - } + // Redirect guests to login page + if (IS_GUEST && $this->cfg['req_login']) { + login_redirect(); + } - $this->init_userprefs(); + $this->init_userprefs(); - return $this->data; - } + return $this->data; + } - /** - * Create new session for the given user - * - * @param $userdata - * @param bool $auto_created - * - * @return array - */ - function session_create ($userdata, $auto_created = false) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Create new session for the given user + * + * @param $userdata + * @param bool $auto_created + * + * @return array + */ + function session_create($userdata, $auto_created = false) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $this->data = $userdata; - $session_id = $this->sessiondata['sid']; + $this->data = $userdata; + $session_id = $this->sessiondata['sid']; - $login = (int) ($this->data['user_id'] != GUEST_UID); - $is_user = ($this->data['user_level'] != ADMIN); - $user_id = (int) $this->data['user_id']; - $mod_admin_session = ($this->data['user_level'] == ADMIN || $this->data['user_level'] == MOD); + $login = (int)($this->data['user_id'] != GUEST_UID); + $is_user = ($this->data['user_level'] != ADMIN); + $user_id = (int)$this->data['user_id']; + $mod_admin_session = ($this->data['user_level'] == ADMIN || $this->data['user_level'] == MOD); - // Initial ban check against user_id or IP address - if ($is_user) - { - preg_match('#(..)(..)(..)(..)#', USER_IP, $ip); + // Initial ban check against user_id or IP address + if ($is_user) { + preg_match('#(..)(..)(..)(..)#', USER_IP, $ip); - $where_sql = "ban_ip IN('". USER_IP ."', '$ip[1]$ip[2]$ip[3]ff', '$ip[1]$ip[2]ffff', '$ip[1]ffffff')"; - $where_sql .= ($login) ? " OR ban_userid = $user_id" : ''; + $where_sql = "ban_ip IN('" . USER_IP . "', '$ip[1]$ip[2]$ip[3]ff', '$ip[1]$ip[2]ffff', '$ip[1]ffffff')"; + $where_sql .= ($login) ? " OR ban_userid = $user_id" : ''; - $sql = "SELECT ban_id FROM ". BB_BANLIST ." WHERE $where_sql LIMIT 1"; + $sql = "SELECT ban_id FROM " . BB_BANLIST . " WHERE $where_sql LIMIT 1"; - if (DB()->fetch_row($sql)) - { - header('Location: https://torrentpier.me/banned/'); - } - } + if (DB()->fetch_row($sql)) { + header('Location: https://torrentpier.me/banned/'); + } + } - // Create new session - for ($i=0, $max_try=5; $i <= $max_try; $i++) - { - $session_id = make_rand_str(SID_LENGTH); + // Create new session + for ($i = 0, $max_try = 5; $i <= $max_try; $i++) { + $session_id = make_rand_str(SID_LENGTH); - $args = DB()->build_array('INSERT', array( - 'session_id' => (string) $session_id, - 'session_user_id' => (int) $user_id, - 'session_start' => (int) TIMENOW, - 'session_time' => (int) TIMENOW, - 'session_ip' => (string) USER_IP, - 'session_logged_in' => (int) $login, - 'session_admin' => (int) $mod_admin_session, - )); - $sql = "INSERT INTO ". BB_SESSIONS . $args; + $args = DB()->build_array('INSERT', array( + 'session_id' => (string)$session_id, + 'session_user_id' => (int)$user_id, + 'session_start' => (int)TIMENOW, + 'session_time' => (int)TIMENOW, + 'session_ip' => (string)USER_IP, + 'session_logged_in' => (int)$login, + 'session_admin' => (int)$mod_admin_session, + )); + $sql = "INSERT INTO " . BB_SESSIONS . $args; - if (DB()->query($sql)) - { - break; - } - if ($i == $max_try) - { - trigger_error('Error creating new session', E_USER_ERROR); - } - } - // Update last visit for logged in users - if ($login) - { - $last_visit = $this->data['user_lastvisit']; + if (DB()->query($sql)) { + break; + } + if ($i == $max_try) { + trigger_error('Error creating new session', E_USER_ERROR); + } + } + // Update last visit for logged in users + if ($login) { + $last_visit = $this->data['user_lastvisit']; - if (!$session_time = $this->data['user_session_time']) - { - $last_visit = TIMENOW; - define('FIRST_LOGON', true); - } - else if ($session_time < (TIMENOW - $di->config->get('last_visit_update_intrv'))) - { - $last_visit = max($session_time, (TIMENOW - 86400*$di->config->get('max_last_visit_days'))); - } + if (!$session_time = $this->data['user_session_time']) { + $last_visit = TIMENOW; + define('FIRST_LOGON', true); + } else if ($session_time < (TIMENOW - $di->config->get('last_visit_update_intrv'))) { + $last_visit = max($session_time, (TIMENOW - 86400 * $di->config->get('max_last_visit_days'))); + } - if ($last_visit != $this->data['user_lastvisit']) - { - DB()->query(" - UPDATE ". BB_USERS ." SET - user_session_time = ". TIMENOW .", + if ($last_visit != $this->data['user_lastvisit']) { + DB()->query(" + UPDATE " . BB_USERS . " SET + user_session_time = " . TIMENOW . ", user_lastvisit = $last_visit, - user_last_ip = '". USER_IP ."', - user_reg_ip = IF(user_reg_ip = '', '". USER_IP ."', user_reg_ip) + user_last_ip = '" . USER_IP . "', + user_reg_ip = IF(user_reg_ip = '', '" . USER_IP . "', user_reg_ip) WHERE user_id = $user_id LIMIT 1 "); - bb_setcookie(COOKIE_TOPIC, ''); - bb_setcookie(COOKIE_FORUM, ''); + bb_setcookie(COOKIE_TOPIC, ''); + bb_setcookie(COOKIE_FORUM, ''); - $this->data['user_lastvisit'] = $last_visit; - } - if (!empty($_POST['autologin']) && $di->config->get('allow_autologin')) - { - if (!$auto_created) - { - $this->verify_autologin_id($this->data, true, true); - } - $this->sessiondata['uk'] = $this->data['autologin_id']; - } - $this->sessiondata['uid'] = $user_id; - $this->sessiondata['sid'] = $session_id; - } - $this->data['session_id'] = $session_id; - $this->data['session_ip'] = USER_IP; - $this->data['session_user_id'] = $user_id; - $this->data['session_logged_in'] = $login; - $this->data['session_start'] = TIMENOW; - $this->data['session_time'] = TIMENOW; - $this->data['session_admin'] = $mod_admin_session; + $this->data['user_lastvisit'] = $last_visit; + } + if (!empty($_POST['autologin']) && $di->config->get('allow_autologin')) { + if (!$auto_created) { + $this->verify_autologin_id($this->data, true, true); + } + $this->sessiondata['uk'] = $this->data['autologin_id']; + } + $this->sessiondata['uid'] = $user_id; + $this->sessiondata['sid'] = $session_id; + } + $this->data['session_id'] = $session_id; + $this->data['session_ip'] = USER_IP; + $this->data['session_user_id'] = $user_id; + $this->data['session_logged_in'] = $login; + $this->data['session_start'] = TIMENOW; + $this->data['session_time'] = TIMENOW; + $this->data['session_admin'] = $mod_admin_session; - $this->set_session_cookies($user_id); + $this->set_session_cookies($user_id); - if ($login && (defined('IN_ADMIN') || $mod_admin_session)) - { - define('SID_GET', "sid=$session_id"); - } + if ($login && (defined('IN_ADMIN') || $mod_admin_session)) { + define('SID_GET', "sid=$session_id"); + } - cache_set_userdata($this->data); + cache_set_userdata($this->data); - return $this->data; - } + return $this->data; + } - /** - * Initialize sessiondata stored in cookies - * - * @param bool $update_lastvisit - * @param bool $set_cookie - */ - function session_end ($update_lastvisit = false, $set_cookie = true) - { - DB()->query(" - DELETE FROM ". BB_SESSIONS ." + /** + * Initialize sessiondata stored in cookies + * + * @param bool $update_lastvisit + * @param bool $set_cookie + */ + function session_end($update_lastvisit = false, $set_cookie = true) + { + DB()->query(" + DELETE FROM " . BB_SESSIONS . " WHERE session_id = '{$this->data['session_id']}' "); - if (!IS_GUEST) - { - if ($update_lastvisit) - { - DB()->query(" - UPDATE ". BB_USERS ." SET - user_session_time = ". TIMENOW .", - user_lastvisit = ". TIMENOW .", - user_last_ip = '". USER_IP ."', - user_reg_ip = IF(user_reg_ip = '', '". USER_IP ."', user_reg_ip) + if (!IS_GUEST) { + if ($update_lastvisit) { + DB()->query(" + UPDATE " . BB_USERS . " SET + user_session_time = " . TIMENOW . ", + user_lastvisit = " . TIMENOW . ", + user_last_ip = '" . USER_IP . "', + user_reg_ip = IF(user_reg_ip = '', '" . USER_IP . "', user_reg_ip) WHERE user_id = {$this->data['user_id']} LIMIT 1 "); - } + } - if (isset($_REQUEST['reset_autologin'])) - { - $this->create_autologin_id($this->data, false); + if (isset($_REQUEST['reset_autologin'])) { + $this->create_autologin_id($this->data, false); - DB()->query(" - DELETE FROM ". BB_SESSIONS ." + DB()->query(" + DELETE FROM " . BB_SESSIONS . " WHERE session_user_id = '{$this->data['user_id']}' "); - } - } + } + } - if ($set_cookie) - { - $this->set_session_cookies(GUEST_UID); - } - } + if ($set_cookie) { + $this->set_session_cookies(GUEST_UID); + } + } - /** - * Login - * - * @param $args - * @param bool $mod_admin_login - * - * @return array - */ - function login ($args, $mod_admin_login = false) - { - $username = !empty($args['login_username']) ? clean_username($args['login_username']) : ''; - $password = !empty($args['login_password']) ? $args['login_password'] : ''; + /** + * Login + * + * @param $args + * @param bool $mod_admin_login + * + * @return array + */ + function login($args, $mod_admin_login = false) + { + $username = !empty($args['login_username']) ? clean_username($args['login_username']) : ''; + $password = !empty($args['login_password']) ? $args['login_password'] : ''; - if ($username && $password) - { - $username_sql = str_replace("\\'", "''", $username); - $password_sql = md5(md5($password)); + if ($username && $password) { + $username_sql = str_replace("\\'", "''", $username); + $password_sql = md5(md5($password)); - $sql = " + $sql = " SELECT * - FROM ". BB_USERS ." + FROM " . BB_USERS . " WHERE username = '$username_sql' AND user_password = '$password_sql' AND user_active = 1 - AND user_id != ". GUEST_UID ." + AND user_id != " . GUEST_UID . " LIMIT 1 "; - if ($userdata = DB()->fetch_row($sql)) - { - if (!$userdata['username'] || !$userdata['user_password'] || $userdata['user_id'] == GUEST_UID || md5(md5($password)) !== $userdata['user_password'] || !$userdata['user_active']) - { - trigger_error('invalid userdata', E_USER_ERROR); - } + if ($userdata = DB()->fetch_row($sql)) { + if (!$userdata['username'] || !$userdata['user_password'] || $userdata['user_id'] == GUEST_UID || md5(md5($password)) !== $userdata['user_password'] || !$userdata['user_active']) { + trigger_error('invalid userdata', E_USER_ERROR); + } - // Start mod/admin session - if ($mod_admin_login) - { - DB()->query(" - UPDATE ". BB_SESSIONS ." SET - session_admin = ". $this->data['user_level'] ." - WHERE session_user_id = ". $this->data['user_id'] ." - AND session_id = '". $this->data['session_id'] ."' + // Start mod/admin session + if ($mod_admin_login) { + DB()->query(" + UPDATE " . BB_SESSIONS . " SET + session_admin = " . $this->data['user_level'] . " + WHERE session_user_id = " . $this->data['user_id'] . " + AND session_id = '" . $this->data['session_id'] . "' "); - $this->data['session_admin'] = $this->data['user_level']; - cache_update_userdata($this->data); + $this->data['session_admin'] = $this->data['user_level']; + cache_update_userdata($this->data); - return $this->data; - } - else if ($new_session_userdata = $this->session_create($userdata, false)) - { - // Removing guest sessions from this IP - DB()->query(" - DELETE FROM ". BB_SESSIONS ." - WHERE session_ip = '". USER_IP ."' - AND session_user_id = ". GUEST_UID ." + return $this->data; + } else if ($new_session_userdata = $this->session_create($userdata, false)) { + // Removing guest sessions from this IP + DB()->query(" + DELETE FROM " . BB_SESSIONS . " + WHERE session_ip = '" . USER_IP . "' + AND session_user_id = " . GUEST_UID . " "); - return $new_session_userdata; - } - else - { - trigger_error("Could not start session : login", E_USER_ERROR); - } - } - } + return $new_session_userdata; + } else { + trigger_error("Could not start session : login", E_USER_ERROR); + } + } + } - return array(); - } + return array(); + } - /** - * Initialize sessiondata stored in cookies - */ - function get_sessiondata () - { - $sd_resv = !empty($_COOKIE[COOKIE_DATA]) ? unserialize($_COOKIE[COOKIE_DATA]) : array(); + /** + * Initialize sessiondata stored in cookies + */ + function get_sessiondata() + { + $sd_resv = !empty($_COOKIE[COOKIE_DATA]) ? unserialize($_COOKIE[COOKIE_DATA]) : array(); - // autologin_id - if (!empty($sd_resv['uk']) && verify_id($sd_resv['uk'], LOGIN_KEY_LENGTH)) - { - $this->sessiondata['uk'] = $sd_resv['uk']; - } - // user_id - if (!empty($sd_resv['uid'])) - { - $this->sessiondata['uid'] = intval($sd_resv['uid']); - } - // sid - if (!empty($sd_resv['sid']) && verify_id($sd_resv['sid'], SID_LENGTH)) - { - $this->sessiondata['sid'] = $sd_resv['sid']; - } - } + // autologin_id + if (!empty($sd_resv['uk']) && verify_id($sd_resv['uk'], LOGIN_KEY_LENGTH)) { + $this->sessiondata['uk'] = $sd_resv['uk']; + } + // user_id + if (!empty($sd_resv['uid'])) { + $this->sessiondata['uid'] = intval($sd_resv['uid']); + } + // sid + if (!empty($sd_resv['sid']) && verify_id($sd_resv['sid'], SID_LENGTH)) { + $this->sessiondata['sid'] = $sd_resv['sid']; + } + } - /** - * Store sessiondata in cookies - * - * @param $user_id - */ - function set_session_cookies ($user_id) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Store sessiondata in cookies + * + * @param $user_id + */ + function set_session_cookies($user_id) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if ($user_id == GUEST_UID) - { - $delete_cookies = array( - COOKIE_DATA, - COOKIE_DBG, - 'torhelp', - 'explain', - 'sql_log', - 'sql_log_full', - ); + if ($user_id == GUEST_UID) { + $delete_cookies = array( + COOKIE_DATA, + COOKIE_DBG, + 'torhelp', + 'explain', + 'sql_log', + 'sql_log_full', + ); - foreach ($delete_cookies as $cookie) - { - if (isset($_COOKIE[$cookie])) - { - bb_setcookie($cookie, '', COOKIE_EXPIRED); - } - } - } - else - { - $c_sdata_resv = !empty($_COOKIE[COOKIE_DATA]) ? $_COOKIE[COOKIE_DATA] : null; - $c_sdata_curr = ($this->sessiondata) ? serialize($this->sessiondata) : ''; + foreach ($delete_cookies as $cookie) { + if (isset($_COOKIE[$cookie])) { + bb_setcookie($cookie, '', COOKIE_EXPIRED); + } + } + } else { + $c_sdata_resv = !empty($_COOKIE[COOKIE_DATA]) ? $_COOKIE[COOKIE_DATA] : null; + $c_sdata_curr = ($this->sessiondata) ? serialize($this->sessiondata) : ''; - if ($c_sdata_curr !== $c_sdata_resv) - { - bb_setcookie(COOKIE_DATA, $c_sdata_curr, COOKIE_PERSIST, true); - } - if ($di->config->get('dbg_users.' . $this->data['user_id']) && !isset($_COOKIE[COOKIE_DBG])) - { - bb_setcookie(COOKIE_DBG, 1, COOKIE_SESSION); - } - } - } + if ($c_sdata_curr !== $c_sdata_resv) { + bb_setcookie(COOKIE_DATA, $c_sdata_curr, COOKIE_PERSIST, true); + } + if ($di->config->get('dbg_users.' . $this->data['user_id']) && !isset($_COOKIE[COOKIE_DBG])) { + bb_setcookie(COOKIE_DBG, 1, COOKIE_SESSION); + } + } + } - /** - * Verify autologin_id - * - * @param $userdata - * @param bool $expire_check - * @param bool $create_new - * - * @return bool|string - */ - function verify_autologin_id ($userdata, $expire_check = false, $create_new = true) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** + * Verify autologin_id + * + * @param $userdata + * @param bool $expire_check + * @param bool $create_new + * + * @return bool|string + */ + function verify_autologin_id($userdata, $expire_check = false, $create_new = true) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $autologin_id = $userdata['autologin_id']; + $autologin_id = $userdata['autologin_id']; - if ($expire_check) - { - if ($create_new && !$autologin_id) - { - return $this->create_autologin_id($userdata); - } - else if ($autologin_id && $userdata['user_session_time'] && $di->config->get('max_autologin_time')) - { - if (TIMENOW - $userdata['user_session_time'] > $di->config->get('max_autologin_time')*86400) - { - return $this->create_autologin_id($userdata, $create_new); - } - } - } + if ($expire_check) { + if ($create_new && !$autologin_id) { + return $this->create_autologin_id($userdata); + } else if ($autologin_id && $userdata['user_session_time'] && $di->config->get('max_autologin_time')) { + if (TIMENOW - $userdata['user_session_time'] > $di->config->get('max_autologin_time') * 86400) { + return $this->create_autologin_id($userdata, $create_new); + } + } + } - return verify_id($autologin_id, LOGIN_KEY_LENGTH); - } + return verify_id($autologin_id, LOGIN_KEY_LENGTH); + } - /** - * Create autologin_id - * - * @param $userdata - * @param bool $create_new - * - * @return string - */ - function create_autologin_id ($userdata, $create_new = true) - { - $autologin_id = ($create_new) ? make_rand_str(LOGIN_KEY_LENGTH) : ''; + /** + * Create autologin_id + * + * @param $userdata + * @param bool $create_new + * + * @return string + */ + function create_autologin_id($userdata, $create_new = true) + { + $autologin_id = ($create_new) ? make_rand_str(LOGIN_KEY_LENGTH) : ''; - DB()->query(" - UPDATE ". BB_USERS ." SET + DB()->query(" + UPDATE " . BB_USERS . " SET autologin_id = '$autologin_id' - WHERE user_id = ". (int) $userdata['user_id'] ." + WHERE user_id = " . (int)$userdata['user_id'] . " LIMIT 1 "); - return $autologin_id; - } + return $autologin_id; + } - /** - * Set shortcuts - */ - function set_shortcuts () - { - $this->id =& $this->data['user_id']; - $this->active =& $this->data['user_active']; - $this->name =& $this->data['username']; - $this->lastvisit =& $this->data['user_lastvisit']; - $this->regdate =& $this->data['user_regdate']; - $this->level =& $this->data['user_level']; - $this->opt =& $this->data['user_opt']; + /** + * Set shortcuts + */ + function set_shortcuts() + { + $this->id =& $this->data['user_id']; + $this->active =& $this->data['user_active']; + $this->name =& $this->data['username']; + $this->lastvisit =& $this->data['user_lastvisit']; + $this->regdate =& $this->data['user_regdate']; + $this->level =& $this->data['user_level']; + $this->opt =& $this->data['user_opt']; - $this->ip = CLIENT_IP; - } + $this->ip = CLIENT_IP; + } - /** - * Initialise user settings - */ - function init_userprefs () - { - global $theme, $lang, $DeltaTime; + /** + * Initialise user settings + */ + function init_userprefs() + { + global $theme, $lang, $DeltaTime; - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (defined('LANG_DIR')) return; // prevent multiple calling + if (defined('LANG_DIR')) return; // prevent multiple calling - define('DEFAULT_LANG_DIR', LANG_ROOT_DIR . $di->config->get('default_lang') .'/'); - define('ENGLISH_LANG_DIR', LANG_ROOT_DIR .'en/'); + define('DEFAULT_LANG_DIR', LANG_ROOT_DIR . $di->config->get('default_lang') . '/'); + define('ENGLISH_LANG_DIR', LANG_ROOT_DIR . 'en/'); - if ($this->data['user_id'] != GUEST_UID) - { - if ($this->data['user_lang'] && $this->data['user_lang'] != $di->config->get('default_lang')) - { - define('LANG_DIR', LANG_ROOT_DIR . basename($this->data['user_lang']) .'/'); - } - } + if ($this->data['user_id'] != GUEST_UID) { + if ($this->data['user_lang'] && $this->data['user_lang'] != $di->config->get('default_lang')) { + define('LANG_DIR', LANG_ROOT_DIR . basename($this->data['user_lang']) . '/'); + } + } - $this->data['user_lang'] = $di->config->get('default_lang'); - $this->data['user_timezone'] = $di->config->get('board_timezone'); + $this->data['user_lang'] = $di->config->get('default_lang'); + $this->data['user_timezone'] = $di->config->get('board_timezone'); - if (!defined('LANG_DIR')) define('LANG_DIR', DEFAULT_LANG_DIR); + if (!defined('LANG_DIR')) define('LANG_DIR', DEFAULT_LANG_DIR); - require(LANG_DIR .'main.php'); - setlocale(LC_ALL, $di->config->get('lang.' . $this->data['user_lang'] . '.locale')); + require(LANG_DIR . 'main.php'); + setlocale(LC_ALL, $di->config->get('lang.' . $this->data['user_lang'] . '.locale')); - $theme = setup_style(); - $DeltaTime = new Date_Delta(); + $theme = setup_style(); + $DeltaTime = new Date_Delta(); - // Handle marking posts read - if (!IS_GUEST && !empty($_COOKIE[COOKIE_MARK])) - { - $this->mark_read($_COOKIE[COOKIE_MARK]); - } + // Handle marking posts read + if (!IS_GUEST && !empty($_COOKIE[COOKIE_MARK])) { + $this->mark_read($_COOKIE[COOKIE_MARK]); + } - $this->load_opt_js(); - } + $this->load_opt_js(); + } - /** - * Mark read - * - * @param $type - */ - function mark_read ($type) - { - if ($type === 'all_forums') - { - // Update session time - DB()->query(" - UPDATE ". BB_SESSIONS ." SET - session_time = ". TIMENOW ." + /** + * Mark read + * + * @param $type + */ + function mark_read($type) + { + if ($type === 'all_forums') { + // Update session time + DB()->query(" + UPDATE " . BB_SESSIONS . " SET + session_time = " . TIMENOW . " WHERE session_id = '{$this->data['session_id']}' LIMIT 1 "); - // Update userdata - $this->data['session_time'] = TIMENOW; - $this->data['user_lastvisit'] = TIMENOW; + // Update userdata + $this->data['session_time'] = TIMENOW; + $this->data['user_lastvisit'] = TIMENOW; - // Update lastvisit - db_update_userdata($this->data, array( - 'user_session_time' => $this->data['session_time'], - 'user_lastvisit' => $this->data['user_lastvisit'], - )); + // Update lastvisit + db_update_userdata($this->data, array( + 'user_session_time' => $this->data['session_time'], + 'user_lastvisit' => $this->data['user_lastvisit'], + )); - // Delete cookies - bb_setcookie(COOKIE_TOPIC, ''); - bb_setcookie(COOKIE_FORUM, ''); - bb_setcookie(COOKIE_MARK, ''); - } - } + // Delete cookies + bb_setcookie(COOKIE_TOPIC, ''); + bb_setcookie(COOKIE_FORUM, ''); + bb_setcookie(COOKIE_MARK, ''); + } + } - /** - * Load misc options - */ - function load_opt_js () - { - if (IS_GUEST) - { - $this->opt_js = array_merge($this->opt_js, $this->opt_js_guest); - } - else if (!empty($_COOKIE['opt_js'])) - { - $opt_js = \Zend\Json\Json::decode($_COOKIE['opt_js'], \Zend\Json\Json::TYPE_ARRAY); + /** + * Load misc options + */ + function load_opt_js() + { + if (IS_GUEST) { + $this->opt_js = array_merge($this->opt_js, $this->opt_js_guest); + } else if (!empty($_COOKIE['opt_js'])) { + $opt_js = \Zend\Json\Json::decode($_COOKIE['opt_js'], \Zend\Json\Json::TYPE_ARRAY); - if (is_array($opt_js)) - { - $this->opt_js = array_merge($this->opt_js, $opt_js); - } - } - } + if (is_array($opt_js)) { + $this->opt_js = array_merge($this->opt_js, $opt_js); + } + } + } - /** - * Get not auth forums - * - * @param $auth_type - * - * @return string - */ - function get_not_auth_forums ($auth_type) - { - global $datastore; + /** + * Get not auth forums + * + * @param $auth_type + * + * @return string + */ + function get_not_auth_forums($auth_type) + { + global $datastore; - if (IS_ADMIN) return ''; + if (IS_ADMIN) return ''; - 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'); + } - if ($auth_type == AUTH_VIEW) - { - if (IS_GUEST) - { - return $forums['not_auth_forums']['guest_view']; - } - } - if ($auth_type == AUTH_READ) - { - if (IS_GUEST) - { - return $forums['not_auth_forums']['guest_read']; - } - } + if ($auth_type == AUTH_VIEW) { + if (IS_GUEST) { + return $forums['not_auth_forums']['guest_view']; + } + } + if ($auth_type == AUTH_READ) { + if (IS_GUEST) { + return $forums['not_auth_forums']['guest_read']; + } + } - $auth_field_match = array( - AUTH_VIEW => 'auth_view', - AUTH_READ => 'auth_read', - AUTH_POST => 'auth_post', - AUTH_REPLY => 'auth_reply', - AUTH_EDIT => 'auth_edit', - AUTH_DELETE => 'auth_delete', - AUTH_STICKY => 'auth_sticky', - AUTH_ANNOUNCE => 'auth_announce', - AUTH_VOTE => 'auth_vote', - AUTH_POLLCREATE => 'auth_pollcreate', - AUTH_ATTACH => 'auth_attachments', - AUTH_DOWNLOAD => 'auth_download', - ); + $auth_field_match = array( + AUTH_VIEW => 'auth_view', + AUTH_READ => 'auth_read', + AUTH_POST => 'auth_post', + AUTH_REPLY => 'auth_reply', + AUTH_EDIT => 'auth_edit', + AUTH_DELETE => 'auth_delete', + AUTH_STICKY => 'auth_sticky', + AUTH_ANNOUNCE => 'auth_announce', + AUTH_VOTE => 'auth_vote', + AUTH_POLLCREATE => 'auth_pollcreate', + AUTH_ATTACH => 'auth_attachments', + AUTH_DOWNLOAD => 'auth_download', + ); - $not_auth_forums = array(); - $auth_field = $auth_field_match[$auth_type]; - $is_auth_ary = auth($auth_type, AUTH_LIST_ALL, $this->data); + $not_auth_forums = array(); + $auth_field = $auth_field_match[$auth_type]; + $is_auth_ary = auth($auth_type, AUTH_LIST_ALL, $this->data); - foreach ($is_auth_ary as $forum_id => $is_auth) - { - if (!$is_auth[$auth_field]) - { - $not_auth_forums[] = $forum_id; - } - } + foreach ($is_auth_ary as $forum_id => $is_auth) { + if (!$is_auth[$auth_field]) { + $not_auth_forums[] = $forum_id; + } + } - return join(',', $not_auth_forums); - } + return join(',', $not_auth_forums); + } - /** - * Get excluded forums - * - * @param $auth_type - * @param string $return_as - * - * @return array|string - */ - function get_excluded_forums ($auth_type, $return_as = 'csv') - { - $excluded = array(); + /** + * Get excluded forums + * + * @param $auth_type + * @param string $return_as + * + * @return array|string + */ + function get_excluded_forums($auth_type, $return_as = 'csv') + { + $excluded = array(); - if ($not_auth = $this->get_not_auth_forums($auth_type)) - { - $excluded[] = $not_auth; - } + if ($not_auth = $this->get_not_auth_forums($auth_type)) { + $excluded[] = $not_auth; + } - if (bf($this->opt, 'user_opt', 'user_porn_forums')) - { - global $datastore; + if (bf($this->opt, 'user_opt', 'user_porn_forums')) { + global $datastore; - 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'); + } - if (isset($forums['forum'])) - { - foreach ($forums['forum'] as $key => $row) - { - if ($row['allow_porno_topic']) $excluded[] = $row['forum_id']; - } - } - } + if (isset($forums['forum'])) { + foreach ($forums['forum'] as $key => $row) { + if ($row['allow_porno_topic']) $excluded[] = $row['forum_id']; + } + } + } - switch ($return_as) - { - case 'csv': return join(',', $excluded); - case 'array': return $excluded; - case 'flip': return array_flip(explode(',', $excluded)); - } - } + switch ($return_as) { + case 'csv': + return join(',', $excluded); + case 'array': + return $excluded; + case 'flip': + return array_flip(explode(',', $excluded)); + } + } } // // userdata cache // -function ignore_cached_userdata () +function ignore_cached_userdata() { - return (defined('IN_PM')) ? true : false; + return (defined('IN_PM')) ? true : false; } -function cache_get_userdata ($id) +function cache_get_userdata($id) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (ignore_cached_userdata()) return false; + if (ignore_cached_userdata()) return false; - return $cache->get($id); + return $cache->get($id); } -function cache_set_userdata ($userdata, $force = false) +function cache_set_userdata($userdata, $force = false) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$userdata || (ignore_cached_userdata() && !$force)) return false; + if (!$userdata || (ignore_cached_userdata() && !$force)) return false; - $id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id']; + $id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id']; - return $cache->set($id, $userdata, $di->config->get('session_update_intrv')); + return $cache->set($id, $userdata, $di->config->get('session_update_intrv')); } -function cache_rm_userdata ($userdata) +function cache_rm_userdata($userdata) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - if (!$userdata) return false; + if (!$userdata) return false; - $id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id']; + $id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id']; - return $cache->delete($id); + return $cache->delete($id); } // $user_id - array(id1,id2,..) or (string) id -function cache_rm_user_sessions ($user_id) +function cache_rm_user_sessions($user_id) { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - $user_id = get_id_csv($user_id); + $user_id = get_id_csv($user_id); - $rowset = DB()->fetch_rowset(" - SELECT session_id FROM ". BB_SESSIONS ." WHERE session_user_id IN($user_id) + $rowset = DB()->fetch_rowset(" + SELECT session_id FROM " . BB_SESSIONS . " WHERE session_user_id IN($user_id) "); - foreach ($rowset as $row) - { - $cache->delete($row['session_id']); - } + foreach ($rowset as $row) { + $cache->delete($row['session_id']); + } } -function cache_update_userdata ($userdata) +function cache_update_userdata($userdata) { - return cache_set_userdata($userdata, true); + return cache_set_userdata($userdata, true); } -function db_update_userdata ($userdata, $sql_ary, $data_already_escaped = true) +function db_update_userdata($userdata, $sql_ary, $data_already_escaped = true) { - if (!$userdata) return false; + if (!$userdata) return false; - $sql_args = DB()->build_array('UPDATE', $sql_ary, $data_already_escaped); - DB()->query("UPDATE ". BB_USERS ." SET $sql_args WHERE user_id = {$userdata['user_id']}"); + $sql_args = DB()->build_array('UPDATE', $sql_ary, $data_already_escaped); + DB()->query("UPDATE " . BB_USERS . " SET $sql_args WHERE user_id = {$userdata['user_id']}"); - if (DB()->affected_rows()) - { - cache_rm_userdata($userdata); - } + if (DB()->affected_rows()) { + cache_rm_userdata($userdata); + } - return true; + return true; } // $user_id - array(id1,id2,..) or (string) id -function delete_user_sessions ($user_id) +function delete_user_sessions($user_id) { - cache_rm_user_sessions($user_id); + cache_rm_user_sessions($user_id); - $user_id = get_id_csv($user_id); - DB()->query("DELETE FROM ". BB_SESSIONS ." WHERE session_user_id IN($user_id)"); -} \ No newline at end of file + $user_id = get_id_csv($user_id); + DB()->query("DELETE FROM " . BB_SESSIONS . " WHERE session_user_id IN($user_id)"); +} diff --git a/library/includes/smtp.php b/library/includes/smtp.php index 26cff7680..c6f85bdf4 100644 --- a/library/includes/smtp.php +++ b/library/includes/smtp.php @@ -6,179 +6,156 @@ define('SMTP_INCLUDED', 1); function server_parse($socket, $response, $line = __LINE__) { - $server_response = ''; - while (substr($server_response, 3, 1) != ' ') - { - if (!($server_response = fgets($socket, 256))) - { - bb_die('Could not get mail server response codes'); - } - } + $server_response = ''; + while (substr($server_response, 3, 1) != ' ') { + if (!($server_response = fgets($socket, 256))) { + bb_die('Could not get mail server response codes'); + } + } - if (!(substr($server_response, 0, 3) == $response)) - { - bb_die('Ran into problems sending mail. Response: '. $server_response); - } + if (!(substr($server_response, 0, 3) == $response)) { + bb_die('Ran into problems sending mail. Response: ' . $server_response); + } } // Replacement or substitute for PHP's mail command function smtpmail($mail_to, $subject, $message, $headers = '') { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - // Fix any bare linefeeds in the message to make it RFC821 Compliant. - $message = preg_replace("#(? 1) - { - $headers = join("\n", $headers); - } - else - { - $headers = $headers[0]; - } - } - $headers = chop($headers); + if ($headers != '') { + if (is_array($headers)) { + if (sizeof($headers) > 1) { + $headers = join("\n", $headers); + } else { + $headers = $headers[0]; + } + } + $headers = chop($headers); - // Make sure there are no bare linefeeds in the headers - $headers = preg_replace('#(?config->get('smtp_ssl')) ? 'ssl://' : ''; - if( !$socket = fsockopen($ssl . $di->config->get('smtp_host'), $di->config->get('smtp_port'), $errno, $errstr, 20) ) - { - bb_die('Could not connect to smtp host : '. $errno .' : '. $errstr); - } + // Ok we have error checked as much as we can to this point let's get on it already + $ssl = ($di->config->get('smtp_ssl')) ? 'ssl://' : ''; + if (!$socket = fsockopen($ssl . $di->config->get('smtp_host'), $di->config->get('smtp_port'), $errno, $errstr, 20)) { + bb_die('Could not connect to smtp host : ' . $errno . ' : ' . $errstr); + } - // Wait for reply - server_parse($socket, "220", __LINE__); + // Wait for reply + server_parse($socket, "220", __LINE__); - // Do we want to use AUTH?, send RFC2554 EHLO, else send RFC821 HELO - // This improved as provided by SirSir to accomodate - if( !empty($di->config->get('smtp_username')) && !empty($di->config->get('smtp_password')) ) - { - fputs($socket, "EHLO " . $di->config->get('smtp_host') . "\r\n"); - server_parse($socket, "250", __LINE__); + // Do we want to use AUTH?, send RFC2554 EHLO, else send RFC821 HELO + // This improved as provided by SirSir to accomodate + if (!empty($di->config->get('smtp_username')) && !empty($di->config->get('smtp_password'))) { + fputs($socket, "EHLO " . $di->config->get('smtp_host') . "\r\n"); + server_parse($socket, "250", __LINE__); - fputs($socket, "AUTH LOGIN\r\n"); - server_parse($socket, "334", __LINE__); + fputs($socket, "AUTH LOGIN\r\n"); + server_parse($socket, "334", __LINE__); - fputs($socket, base64_encode($di->config->get('smtp_username')) . "\r\n"); - server_parse($socket, "334", __LINE__); + fputs($socket, base64_encode($di->config->get('smtp_username')) . "\r\n"); + server_parse($socket, "334", __LINE__); - fputs($socket, base64_encode($di->config->get('smtp_password')) . "\r\n"); - server_parse($socket, "235", __LINE__); - } - else - { - fputs($socket, "HELO " . $di->config->get('smtp_host') . "\r\n"); - server_parse($socket, "250", __LINE__); - } + fputs($socket, base64_encode($di->config->get('smtp_password')) . "\r\n"); + server_parse($socket, "235", __LINE__); + } else { + fputs($socket, "HELO " . $di->config->get('smtp_host') . "\r\n"); + server_parse($socket, "250", __LINE__); + } - // From this point onward most server response codes should be 250 - // Specify who the mail is from.... - fputs($socket, "MAIL FROM: <" . $di->config->get('board_email') . ">\r\n"); - server_parse($socket, "250", __LINE__); + // From this point onward most server response codes should be 250 + // Specify who the mail is from.... + fputs($socket, "MAIL FROM: <" . $di->config->get('board_email') . ">\r\n"); + server_parse($socket, "250", __LINE__); - // Add an additional bit of error checking to the To field. - $mail_to = (trim($mail_to) == '') ? 'Undisclosed-recipients:;' : trim($mail_to); - if (preg_match('#[^ ]+\@[^ ]+#', $mail_to)) - { - fputs($socket, "RCPT TO: <$mail_to>\r\n"); - server_parse($socket, "250", __LINE__); - } + // Add an additional bit of error checking to the To field. + $mail_to = (trim($mail_to) == '') ? 'Undisclosed-recipients:;' : trim($mail_to); + if (preg_match('#[^ ]+\@[^ ]+#', $mail_to)) { + fputs($socket, "RCPT TO: <$mail_to>\r\n"); + server_parse($socket, "250", __LINE__); + } - // Ok now do the CC and BCC fields... - reset($bcc); - while(list(, $bcc_address) = each($bcc)) - { - // Add an additional bit of error checking to bcc header... - $bcc_address = trim($bcc_address); - if (preg_match('#[^ ]+\@[^ ]+#', $bcc_address)) - { - fputs($socket, "RCPT TO: <$bcc_address>\r\n"); - server_parse($socket, "250", __LINE__); - } - } + // Ok now do the CC and BCC fields... + reset($bcc); + while (list(, $bcc_address) = each($bcc)) { + // Add an additional bit of error checking to bcc header... + $bcc_address = trim($bcc_address); + if (preg_match('#[^ ]+\@[^ ]+#', $bcc_address)) { + fputs($socket, "RCPT TO: <$bcc_address>\r\n"); + server_parse($socket, "250", __LINE__); + } + } - reset($cc); - while(list(, $cc_address) = each($cc)) - { - // Add an additional bit of error checking to cc header - $cc_address = trim($cc_address); - if (preg_match('#[^ ]+\@[^ ]+#', $cc_address)) - { - fputs($socket, "RCPT TO: <$cc_address>\r\n"); - server_parse($socket, "250", __LINE__); - } - } + reset($cc); + while (list(, $cc_address) = each($cc)) { + // Add an additional bit of error checking to cc header + $cc_address = trim($cc_address); + if (preg_match('#[^ ]+\@[^ ]+#', $cc_address)) { + fputs($socket, "RCPT TO: <$cc_address>\r\n"); + server_parse($socket, "250", __LINE__); + } + } - // Ok now we tell the server we are ready to start sending data - fputs($socket, "DATA\r\n"); + // Ok now we tell the server we are ready to start sending data + fputs($socket, "DATA\r\n"); - // This is the last response code we look for until the end of the message. - server_parse($socket, "354", __LINE__); + // This is the last response code we look for until the end of the message. + server_parse($socket, "354", __LINE__); - // Send the Subject Line... - fputs($socket, "Subject: $subject\r\n"); + // Send the Subject Line... + fputs($socket, "Subject: $subject\r\n"); - // Now the To Header. - fputs($socket, "To: $mail_to\r\n"); + // Now the To Header. + fputs($socket, "To: $mail_to\r\n"); - // Now any custom headers.... - fputs($socket, "$headers\r\n\r\n"); + // Now any custom headers.... + fputs($socket, "$headers\r\n\r\n"); - // Ok now we are ready for the message... - fputs($socket, "$message\r\n"); + // Ok now we are ready for the message... + fputs($socket, "$message\r\n"); - // Ok the all the ingredients are mixed in let's cook this puppy... - fputs($socket, ".\r\n"); - server_parse($socket, "250", __LINE__); + // Ok the all the ingredients are mixed in let's cook this puppy... + fputs($socket, ".\r\n"); + server_parse($socket, "250", __LINE__); - // Now tell the server we are done and close the socket... - fputs($socket, "QUIT\r\n"); - fclose($socket); + // Now tell the server we are done and close the socket... + fputs($socket, "QUIT\r\n"); + fclose($socket); - return TRUE; -} \ No newline at end of file + return TRUE; +} diff --git a/library/includes/template.php b/library/includes/template.php index a8d6e70b4..7c1323c42 100644 --- a/library/includes/template.php +++ b/library/includes/template.php @@ -26,905 +26,905 @@ define('XS_TAG_BEGINELSE', 11); class Template { - // Variable that holds all the data we'll be substituting into the compiled templates - // This will end up being a multi-dimensional array like this: $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value - // If it's a root-level variable, it'll be like this: $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value - // Array "vars" is added for easier access to data - var $_tpldata = array('.' => array(0 => array())); - var $vars; - - // Hash of filenames for each template handle - var $files = array(); - var $files_cache = array(); // array of cache files that exists - var $files_cache2 = array(); // array of cache files (exists or not exists) - - // Root template directory - var $root = ''; - - // Cache directory - var $cachedir = CACHE_DIR; - - // Template root directory - var $tpldir = ''; - - // Default template directory - var $tpldef = 'default'; - - // This will hash handle names to the compiled code for that handle - var $compiled_code = array(); - - // This will hold the uncompiled code for that handle. - var $uncompiled_code = array(); - - // Cache settings - var $use_cache = 1; - var $cache_writable = 1; - - // Auto-compile setting - var $auto_compile = 1; - - // Current template name - var $tpl = ''; - var $cur_tpl = ''; - - // List of replacements (tpl files in this list will be replaced with other tpl files) - var $replace = array(); - - // Counter for include - var $include_count = 0; - - // Extension tpl-cache files - var $cached_tpl_ext = 'php'; - - // eXtreme Styles variables - var $xs_started = 0; - - // These handles will be parsed if pparse() is executed - // Can be used to automatically include header/footer if there is any content - var $preparse = ''; - var $postparse = ''; - - var $lang = array(); - - /** - * Constructor. Installs XS mod on first run or updates it and sets the root dir. - * - * @param string $root - */ - function Template($root = '.') - { - global $lang; - - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); - - // setting pointer "vars" - $this->vars = &$this->_tpldata['.'][0]; - // load configuration - $this->tpldir = TEMPLATES_DIR; - $this->root = $root; - $this->tpl = basename($root); - $this->lang =& $lang; - $this->use_cache = $di->config->get('xs_use_cache'); - } - - /** - * Destroys this template object. Should be called when you're done with it, in order - * to clear out the template data so you can load/parse a new template set. - */ - function destroy() - { - $this->_tpldata = array('.' => array(0 => array())); - $this->vars = &$this->_tpldata['.'][0]; - $this->xs_started = 0; - } - - /** - * Generates a full path+filename for the given filename, which can either - * be an absolute name, or a name relative to the rootdir for this Template object - * - * @param $filename - * @param bool $xs_include - * - * @return string - */ - function make_filename($filename, $xs_include = false) - { - // Check replacements list - if (!$xs_include && isset($this->replace[$filename])) { - $filename = $this->replace[$filename]; - } - // Check if it's an absolute or relative path - if ((substr($filename, 0, 1) !== '/') && (substr($filename, 1, 1) !== ':')) { - return $this->root . '/' . $filename; - } else { - return $filename; - } - } - - /** - * Converts template filename to cache filename - * Returns empty string if non-cachable (for tpl files outside of root dir) - * $filename should be absolute filename - * - * @param $filename - * - * @return string - */ - function make_filename_cache($filename) - { - $filename = clean_filename(str_replace(TEMPLATES_DIR, '', $filename)); - return $this->cachedir . XS_TPL_PREFIX . $filename . '.' . $this->cached_tpl_ext; - } - - /** - * Sets the template filenames for handles. $filename_array - * Should be a hash of handle => filename pairs - * - * @param $filenames - */ - function set_filenames($filenames) - { - foreach ($filenames as $handle => $filename) { - $this->set_filename($handle, $filename); - } - } - - /** - * Assigns template filename for handle - * - * @param $handle - * @param $filename - * @param bool $xs_include - * @param bool $quiet - * - * @return bool - */ - function set_filename($handle, $filename, $xs_include = false, $quiet = false) - { - $can_cache = $this->use_cache; - $this->files[$handle] = $this->make_filename($filename, $xs_include); - $this->files_cache[$handle] = ''; - $this->files_cache2[$handle] = ''; - // Checking if we have valid filename - if (!$this->files[$handle]) { - if ($xs_include || $quiet) { - return false; - } else { - die("Template->make_filename(): Error - invalid template $filename"); - } - } - // Creating cache filename - if ($can_cache) { - $this->files_cache2[$handle] = $this->make_filename_cache($this->files[$handle]); - if (file_exists($this->files_cache2[$handle])) { - $this->files_cache[$handle] = $this->files_cache2[$handle]; - } - } - // Checking if tpl and/or php file exists - if (empty($this->files_cache[$handle]) && !file_exists($this->files[$handle])) { - if ($quiet) { - return false; - } - die('Template->make_filename(): template file not found:

        ' . hide_bb_path($this->files[$handle])); - } - // Checking if we should recompile cache - if (!empty($this->files_cache[$handle])) { - $cache_time = filemtime($this->files_cache[$handle]); - if (filemtime($this->files[$handle]) > $cache_time) { - // File was changed, don't use cache file (will be recompled if configuration allowes it) - $this->files_cache[$handle] = ''; - } - } - return true; - } - - /** - * Includes file or executes code - * - * @param $filename - * @param $code - * @param $handle - */ - function execute($filename, $code, $handle) - { - $this->cur_tpl = $filename; - - global $lang, $user, $tr_cfg; - - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); - - $L =& $lang; - $V =& $this->vars; - - if ($filename) { - include($filename); - } else { - eval($code); - } - } - - /** - * Load the file for the handle, compile the file, and run the compiled code - * This will print out the results of executing the template - * - * @param $handle - * - * @return bool - */ - function pparse($handle) - { - // Parsing header if there is one - if ($this->preparse || $this->postparse) { - $preparse = $this->preparse; - $postparse = $this->postparse; - $this->preparse = ''; - $this->postparse = ''; - if ($preparse) { - $this->pparse($preparse); - } - if ($postparse) { - $str = $handle; - $handle = $postparse; - $this->pparse($str); - } - } - // Checking if handle exists - if (empty($this->files[$handle]) && empty($this->files_cache[$handle])) { - die("Template->loadfile(): no files found for handle $handle"); - } - $this->xs_startup(); - $force_recompile = empty($this->uncompiled_code[$handle]) ? false : true; - // Checking if php file exists - if (!empty($this->files_cache[$handle]) && !$force_recompile) { - // PHP file exists - running it instead of tpl - $this->execute($this->files_cache[$handle], '', $handle); - return true; - } - if (!$this->loadfile($handle)) { - die("Template->pparse(): couldn't load template file for handle $handle"); - } - // Actually compile the template now - if (empty($this->compiled_code[$handle])) { - // Actually compile the code now - if (!empty($this->files_cache2[$handle]) && empty($this->files_cache[$handle]) && !$force_recompile) { - $this->compiled_code[$handle] = $this->compile2($this->uncompiled_code[$handle], $handle, $this->files_cache2[$handle]); - } else { - $this->compiled_code[$handle] = $this->compile2($this->uncompiled_code[$handle], '', ''); - } - } - // Run the compiled code - if (empty($this->files_cache[$handle]) || $force_recompile) { - $this->execute('', $this->compiled_code[$handle], $handle); - } else { - $this->execute($this->files_cache[$handle], '', $handle); - } - return true; - } - - /** - * Precompile file - * - * @param $template - * @param $filename - * - * @return bool - */ - function precompile($template, $filename) - { - global $precompile_num; - if (empty($precompile_num)) { - $precompile_num = 0; - } - $precompile_num++; - $handle = 'precompile_' . $precompile_num; - // Save old configuration - $root = $this->root; - $tpl_name = $this->tpl; - $old_config = $this->use_cache; - $old_autosave = $this->auto_compile; - // Set temporary configuration - $this->root = $this->tpldir . $template; - $this->tpl = $template; - $this->use_cache = 1; - $this->auto_compile = 1; - // Set filename - $res = $this->set_filename($handle, $filename, true, true); - if (!$res || !$this->files_cache2[$handle]) { - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return false; - } - $this->files_cache[$handle] = ''; - // Load template - $res = $this->loadfile($handle); - if (!$res || empty($this->uncompiled_code[$handle])) { - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return false; - } - // Compile the code - $this->compile2($this->uncompiled_code[$handle], $handle, $this->files_cache2[$handle]); - // Restore configuration - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return true; - } - - /** - * Inserts the uncompiled code for $handle as the value of $varname in the root-level - * This can be used to effectively include a template in the middle of another template - * Note that all desired assignments to the variables in $handle should be done BEFORE calling this function - * - * @param $varname - * @param $handle - * - * @return bool - */ - function assign_var_from_handle($varname, $handle) - { - ob_start(); - $res = $this->pparse($handle); - $this->vars[$varname] = ob_get_contents(); - ob_end_clean(); - return $res; - } - - /** - * Block-level variable assignment. Adds a new block iteration with the given variable assignments - * Note that this should only be called once per block iteration - * - * @param $blockname - * @param $vararray - * - * @return bool - */ - function assign_block_vars($blockname, $vararray) - { - if (strstr($blockname, '.')) { - // Nested block - $blocks = explode('.', $blockname); - $blockcount = sizeof($blocks) - 1; - $str = &$this->_tpldata; - for ($i = 0; $i < $blockcount; $i++) { - $str = &$str[$blocks[$i] . '.']; - $str = &$str[sizeof($str) - 1]; - } - // Now we add the block that we're actually assigning to - // We're adding a new iteration to this block with the given variable assignments - $str[$blocks[$blockcount] . '.'][] = $vararray; - } else { - // Top-level block. Add a new iteration to this block with the variable assignments we were given - $this->_tpldata[$blockname . '.'][] = $vararray; - } - return true; - } - - /** - * Root-level variable assignment. Adds to current assignments, overriding - * any existing variable assignment with the same name - * - * @param $vararray - */ - function assign_vars($vararray) - { - foreach ($vararray as $key => $val) { - $this->vars[$key] = $val; - } - } - - /** - * Root-level variable assignment. Adds to current assignments, overriding - * any existing variable assignment with the same name - * - * @param $varname - * @param bool $varval - */ - function assign_var($varname, $varval = true) - { - $this->vars[$varname] = $varval; - } - - /** - * Root-level. Adds to current assignments, appends - * to any existing variable assignment with the same name - * - * @param $vararray - */ - function append_vars($vararray) - { - foreach ($vararray as $key => $val) { - $this->vars[$key] = !isset($this->vars[$key]) ? $val : $this->vars[$key] . $val; - } - } - - /** - * If not already done, load the file for the given handle and populate - * the uncompiled_code[] hash with its code. Do not compile - * - * @param $handle - * - * @return bool - */ - function loadfile($handle) - { - // If cached file exists do nothing - it will be included via include() - if (!empty($this->files_cache[$handle])) { - return true; - } - - // If the file for this handle is already loaded and compiled, do nothing - if (!empty($this->uncompiled_code[$handle])) { - return true; - } - - // If we don't have a file assigned to this handle, die - if (empty($this->files[$handle])) { - die("Template->loadfile(): no file specified for handle $handle"); - } - - $filename = $this->files[$handle]; - - if (($str = file_get_contents($filename)) === false) { - die("Template->loadfile(): file $filename for handle $handle is empty"); - } - - $this->uncompiled_code[$handle] = $str; - - return true; - } - - /** - * Generates a reference to the given variable inside the given (possibly nested) block namespace - * This is a string of the form: $this->_tpldata['parent.'][$_parent_i]['$child1.'][$_child1_i]['$child2.'][$_child2_i]...['varname'] - * It's ready to be inserted into an "echo" line in one of the templates. NOTE: expects a trailing "." on the namespace - * - * @param $namespace - * @param $varname - * - * @return string - */ - function generate_block_varref($namespace, $varname) - { - // Strip the trailing period - $namespace = substr($namespace, 0, strlen($namespace) - 1); - - // Get a reference to the data block for this namespace - $varref = $this->generate_block_data_ref($namespace, true); - - // Append the variable reference - $varref .= "['$varname']"; - - $varref = ""; - - return $varref; - } - - /** - * Generates a reference to the array of data values for the given (possibly nested) block namespace - * This is a string of the form: $this->_tpldata['parent.'][$_parent_i]['$child1.'][$_child1_i]['$child2.'][$_child2_i]...['$childN.'] - * If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above. NOTE: does not expect a trailing "." on the blockname - * - * @param $blockname - * @param $include_last_iterator - * - * @return string - */ - function generate_block_data_ref($blockname, $include_last_iterator) - { - // Get an array of the blocks involved - $blocks = explode('.', $blockname); - $blockcount = sizeof($blocks) - 1; - if ($include_last_iterator) { - return '$' . $blocks[$blockcount] . '_item'; - } else { - return '$' . $blocks[$blockcount - 1] . '_item[\'' . $blocks[$blockcount] . '.\']'; - } - } - - function compile_code($filename, $code) - { - // Load code from file - if (!$code && !empty($filename)) { - $code = file_get_contents($filename); - } - - // Replace tags - $search = array('', ''); - $replace = array('<' . '?php ', ' ?' . '>'); - $code = str_replace($search, $replace, $code); - - // Break it up into lines and put " -->" back - $code_lines = explode(' -->', $code); - $count = count($code_lines); - for ($i = 0; $i < ($count - 1); $i++) { - $code_lines[$i] .= ' -->'; - } - - $block_nesting_level = 0; - $block_names = array(); - $block_names[0] = "."; - $block_items = array(); - $count_if = 0; - - // Prepare array for compiled code - $compiled = array(); - - // Array of switches - $sw = array(); - - // Replace all short php tags - $new_code = array(); - $line_count = count($code_lines); - for ($i = 0; $i < $line_count; $i++) { - $line = $code_lines[$i]; - $pos = strpos($line, ''; - $code_lines[$i] = substr($line, $pos + 2); - $i--; - } - $code_lines = $new_code; - - // Main loop - $line_count = count($code_lines); - for ($i = 0; $i < $line_count; $i++) { - $line = $code_lines[$i]; - // Reset keyword type - $keyword_type = XS_TAG_NONE; - // Check if we have valid keyword in current line - $pos1 = strpos($line, '', $pos1); - if ($pos2 !== false) { - // Find end of keyword in comment - $pos3 = strpos($line, ' ', $pos1 + 5); - if ($pos3 !== false && $pos3 <= $pos2) { - $keyword = substr($line, $pos1 + 5, $pos3 - $pos1 - 5); - // Check keyword against list of supported keywords. case-sensitive - if ($keyword === 'BEGIN') { - $keyword_type = XS_TAG_BEGIN; - } elseif ($keyword === 'END') { - $keyword_type = XS_TAG_END; - } elseif ($keyword === 'INCLUDE') { - $keyword_type = XS_TAG_INCLUDE; - } elseif ($keyword === 'IF') { - $keyword_type = XS_TAG_IF; - } elseif ($keyword === 'ELSE') { - $keyword_type = XS_TAG_ELSE; - } elseif ($keyword === 'ELSEIF') { - $keyword_type = XS_TAG_ELSEIF; - } elseif ($keyword === 'ENDIF') { - $keyword_type = XS_TAG_ENDIF; - } elseif ($keyword === 'BEGINELSE') { - $keyword_type = XS_TAG_BEGINELSE; - } - } - } - if (!$keyword_type) { - // Not valid keyword process the rest of line - $compiled[] = $this->_compile_text(substr($line, 0, $pos1 + 4)); - $code_lines[$i] = substr($line, $pos1 + 4); - $i--; - continue; - } - // Remove code before keyword - if ($pos1 > 0) { - $compiled[] = $this->_compile_text(substr($line, 0, $pos1)); - } - // Remove keyword - $keyword_str = substr($line, $pos1, $pos2 - $pos1 + 4); - $params_str = $pos2 == $pos3 ? '' : substr($line, $pos3 + 1, $pos2 - $pos3 - 1); - $code_lines[$i] = substr($line, $pos2 + 4); - $i--; - - /* - * - */ - if ($keyword_type == XS_TAG_BEGIN) { - $params = explode(' ', $params_str); - $num_params = count($params); - // Get variable name - if ($num_params == 1) { - $var = $params[0]; - } elseif ($num_params == 2) { - if ($params[0] === '') { - $var = $params[1]; - } elseif ($params[1] === '') { - $var = $params[0]; - } else { - // Invalid tag - $compiled[] = $keyword_str; - continue; - } - } else { - // Invalid tag - $compiled[] = $keyword_str; - continue; - } - // Adding code - $block_nesting_level++; - $block_names[$block_nesting_level] = $var; - if (isset($block_items[$var])) { - $block_items[$var]++; - } else { - $block_items[$var] = 1; - } - if ($block_nesting_level < 2) { - // Block is not nested - $line = '<' . "?php\n\n"; - $line .= '$' . $var . '_count = ( isset($this->_tpldata[\'' . $var . '.\']) ) ? sizeof($this->_tpldata[\'' . $var . '.\']) : 0;'; - $line .= "\n" . 'for ($' . $var . '_i = 0; $' . $var . '_i < $' . $var . '_count; $' . $var . '_i++)'; - $line .= "\n" . '{' . "\n"; - $line .= ' $' . $var . '_item = &$this->_tpldata[\'' . $var . '.\'][$' . $var . '_i];' . "\n"; - $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; - $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; - $line .= "\n?" . ">"; - } else { - // This block is nested. Generate a namespace string for this block - $namespace = join('.', $block_names); - // Strip leading period from root level - $namespace = substr($namespace, 2); - // Get a reference to the data array for this block that depends on the current indices of all parent blocks - $varref = $this->generate_block_data_ref($namespace, false); - // Create the for loop code to iterate over this block - $line = '<' . "?php\n\n"; - $line .= '$' . $var . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;'; - $line .= "\n" . 'for ($' . $var . '_i = 0; $' . $var . '_i < $' . $var . '_count; $' . $var . '_i++)'; - $line .= "\n" . '{' . "\n"; - $line .= ' $' . $var . '_item = &' . $varref . '[$' . $var . '_i];' . "\n"; - $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; - $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; - $line .= "\n?" . ">"; - } - $compiled[] = $line; - continue; - } - - /* - * - */ - if ($keyword_type == XS_TAG_END) { - $params = explode(' ', $params_str); - $num_params = count($params); - if ($num_params == 1) { - $var = $params[0]; - } elseif ($num_params == 2 && $params[0] === '') { - $var = $params[1]; - } elseif ($num_params == 2 && $params[1] === '') { - $var = $params[0]; - } else { - $compiled[] = $keyword_str; - continue; - } - // We have the end of a block - $line = '<' . "?php\n\n"; - $line .= '} // END ' . $var . "\n\n"; - $line .= 'if(isset($' . $var . '_item)) { unset($' . $var . '_item); } '; - $line .= "\n\n?" . ">"; - if (isset($block_items[$var])) { - $block_items[$var]--; - } else { - $block_items[$var] = -1; - } - unset($block_names[$block_nesting_level]); - $block_nesting_level--; - $compiled[] = $line; - continue; - } - - /* - * - */ - if ($keyword_type == XS_TAG_BEGINELSE) { - if ($block_nesting_level) { - $var = $block_names[$block_nesting_level]; - $compiled[] = '<' . '?php } if(!$' . $var . '_count) { ?' . '>'; - } else { - $compiled[] = $keyword_str; - continue; - } - } - - /* - * - */ - if ($keyword_type == XS_TAG_INCLUDE) { - $params = explode(' ', $params_str); - $num_params = count($params); - if ($num_params != 1) { - $compiled[] = $keyword_str; - continue; - } - $line = '<' . '?php '; - $filehash = md5($params_str . $this->include_count . TIMENOW); - $line .= ' $this->set_filename(\'xs_include_' . $filehash . '\', \'' . $params_str . '\', true); '; - $line .= ' $this->pparse(\'xs_include_' . $filehash . '\'); '; - $line .= ' ?' . '>'; - $this->include_count++; - $compiled[] = $line; - continue; - } - - /* - * - */ - if ($keyword_type == XS_TAG_IF || $keyword_type == XS_TAG_ELSEIF) { - if (!$count_if) { - $keyword_type = XS_TAG_IF; - } - $str = $this->compile_tag_if($params_str, $keyword_type == XS_TAG_IF ? false : true); - if ($str) { - $compiled[] = ''; - if ($keyword_type == XS_TAG_IF) { - $count_if++; - } - } else { - $compiled[] = $keyword_str; - } - continue; - } - - /* - * - */ - if ($keyword_type == XS_TAG_ELSE && $count_if > 0) { - $compiled[] = ''; - continue; - } - - /* - * - */ - if ($keyword_type == XS_TAG_ENDIF && $count_if > 0) { - $compiled[] = ''; - $count_if--; - continue; - } - } - - // Bring it back into a single string - $code_header = ''; - $code_footer = ''; - - return $code_header . join('', $compiled) . $code_footer; - } - - /* - * Compile code between tags - */ - function _compile_text($code) - { - if (strlen($code) < 3) { - return $code; - } - // Change template varrefs into PHP varrefs. This one will handle varrefs WITH namespaces - $varrefs = array(); - preg_match_all('#\{(([a-z0-9\-_]+?\.)+)([a-z0-9\-_]+?)\}#is', $code, $varrefs); - $varcount = sizeof($varrefs[1]); - $search = array(); - $replace = array(); - for ($i = 0; $i < $varcount; $i++) { - $namespace = $varrefs[1][$i]; - $varname = $varrefs[3][$i]; - $new = $this->generate_block_varref($namespace, $varname); - $search[] = $varrefs[0][$i]; - $replace[] = $new; - } - if (count($search) > 0) { - $code = str_replace($search, $replace, $code); - } - // This will handle the remaining root-level varrefs - $code = preg_replace('#\{(L_([a-z0-9\-_]+?))\}#i', '', $code); - $code = preg_replace('#\{(\$[a-z_][a-z0-9_$\->\'\"\.\[\]]*?)\}#i', '', $code); - $code = preg_replace('#\{(\#([a-z_][a-z0-9_]*?))\}#i', '', $code); - $code = preg_replace('#\{([a-z0-9\-_]+?)\}#i', '', $code); - return $code; - } - - // - // Compile IF tags - much of this is from Smarty with some adaptions for our block level methods - // - function compile_tag_if($tag_args, $elseif) - { - /* Tokenize args for 'if' tag */ - preg_match_all('/(?: + // Variable that holds all the data we'll be substituting into the compiled templates + // This will end up being a multi-dimensional array like this: $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value + // If it's a root-level variable, it'll be like this: $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value + // Array "vars" is added for easier access to data + var $_tpldata = array('.' => array(0 => array())); + var $vars; + + // Hash of filenames for each template handle + var $files = array(); + var $files_cache = array(); // array of cache files that exists + var $files_cache2 = array(); // array of cache files (exists or not exists) + + // Root template directory + var $root = ''; + + // Cache directory + var $cachedir = CACHE_DIR; + + // Template root directory + var $tpldir = ''; + + // Default template directory + var $tpldef = 'default'; + + // This will hash handle names to the compiled code for that handle + var $compiled_code = array(); + + // This will hold the uncompiled code for that handle. + var $uncompiled_code = array(); + + // Cache settings + var $use_cache = 1; + var $cache_writable = 1; + + // Auto-compile setting + var $auto_compile = 1; + + // Current template name + var $tpl = ''; + var $cur_tpl = ''; + + // List of replacements (tpl files in this list will be replaced with other tpl files) + var $replace = array(); + + // Counter for include + var $include_count = 0; + + // Extension tpl-cache files + var $cached_tpl_ext = 'php'; + + // eXtreme Styles variables + var $xs_started = 0; + + // These handles will be parsed if pparse() is executed + // Can be used to automatically include header/footer if there is any content + var $preparse = ''; + var $postparse = ''; + + var $lang = array(); + + /** + * Constructor. Installs XS mod on first run or updates it and sets the root dir. + * + * @param string $root + */ + function Template($root = '.') + { + global $lang; + + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); + + // setting pointer "vars" + $this->vars = &$this->_tpldata['.'][0]; + // load configuration + $this->tpldir = TEMPLATES_DIR; + $this->root = $root; + $this->tpl = basename($root); + $this->lang =& $lang; + $this->use_cache = $di->config->get('xs_use_cache'); + } + + /** + * Destroys this template object. Should be called when you're done with it, in order + * to clear out the template data so you can load/parse a new template set. + */ + function destroy() + { + $this->_tpldata = array('.' => array(0 => array())); + $this->vars = &$this->_tpldata['.'][0]; + $this->xs_started = 0; + } + + /** + * Generates a full path+filename for the given filename, which can either + * be an absolute name, or a name relative to the rootdir for this Template object + * + * @param $filename + * @param bool $xs_include + * + * @return string + */ + function make_filename($filename, $xs_include = false) + { + // Check replacements list + if (!$xs_include && isset($this->replace[$filename])) { + $filename = $this->replace[$filename]; + } + // Check if it's an absolute or relative path + if ((substr($filename, 0, 1) !== '/') && (substr($filename, 1, 1) !== ':')) { + return $this->root . '/' . $filename; + } else { + return $filename; + } + } + + /** + * Converts template filename to cache filename + * Returns empty string if non-cachable (for tpl files outside of root dir) + * $filename should be absolute filename + * + * @param $filename + * + * @return string + */ + function make_filename_cache($filename) + { + $filename = clean_filename(str_replace(TEMPLATES_DIR, '', $filename)); + return $this->cachedir . XS_TPL_PREFIX . $filename . '.' . $this->cached_tpl_ext; + } + + /** + * Sets the template filenames for handles. $filename_array + * Should be a hash of handle => filename pairs + * + * @param $filenames + */ + function set_filenames($filenames) + { + foreach ($filenames as $handle => $filename) { + $this->set_filename($handle, $filename); + } + } + + /** + * Assigns template filename for handle + * + * @param $handle + * @param $filename + * @param bool $xs_include + * @param bool $quiet + * + * @return bool + */ + function set_filename($handle, $filename, $xs_include = false, $quiet = false) + { + $can_cache = $this->use_cache; + $this->files[$handle] = $this->make_filename($filename, $xs_include); + $this->files_cache[$handle] = ''; + $this->files_cache2[$handle] = ''; + // Checking if we have valid filename + if (!$this->files[$handle]) { + if ($xs_include || $quiet) { + return false; + } else { + die("Template->make_filename(): Error - invalid template $filename"); + } + } + // Creating cache filename + if ($can_cache) { + $this->files_cache2[$handle] = $this->make_filename_cache($this->files[$handle]); + if (file_exists($this->files_cache2[$handle])) { + $this->files_cache[$handle] = $this->files_cache2[$handle]; + } + } + // Checking if tpl and/or php file exists + if (empty($this->files_cache[$handle]) && !file_exists($this->files[$handle])) { + if ($quiet) { + return false; + } + die('Template->make_filename(): template file not found:

        ' . hide_bb_path($this->files[$handle])); + } + // Checking if we should recompile cache + if (!empty($this->files_cache[$handle])) { + $cache_time = filemtime($this->files_cache[$handle]); + if (filemtime($this->files[$handle]) > $cache_time) { + // File was changed, don't use cache file (will be recompled if configuration allowes it) + $this->files_cache[$handle] = ''; + } + } + return true; + } + + /** + * Includes file or executes code + * + * @param $filename + * @param $code + * @param $handle + */ + function execute($filename, $code, $handle) + { + $this->cur_tpl = $filename; + + global $lang, $user, $tr_cfg; + + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); + + $L =& $lang; + $V =& $this->vars; + + if ($filename) { + include($filename); + } else { + eval($code); + } + } + + /** + * Load the file for the handle, compile the file, and run the compiled code + * This will print out the results of executing the template + * + * @param $handle + * + * @return bool + */ + function pparse($handle) + { + // Parsing header if there is one + if ($this->preparse || $this->postparse) { + $preparse = $this->preparse; + $postparse = $this->postparse; + $this->preparse = ''; + $this->postparse = ''; + if ($preparse) { + $this->pparse($preparse); + } + if ($postparse) { + $str = $handle; + $handle = $postparse; + $this->pparse($str); + } + } + // Checking if handle exists + if (empty($this->files[$handle]) && empty($this->files_cache[$handle])) { + die("Template->loadfile(): no files found for handle $handle"); + } + $this->xs_startup(); + $force_recompile = empty($this->uncompiled_code[$handle]) ? false : true; + // Checking if php file exists + if (!empty($this->files_cache[$handle]) && !$force_recompile) { + // PHP file exists - running it instead of tpl + $this->execute($this->files_cache[$handle], '', $handle); + return true; + } + if (!$this->loadfile($handle)) { + die("Template->pparse(): couldn't load template file for handle $handle"); + } + // Actually compile the template now + if (empty($this->compiled_code[$handle])) { + // Actually compile the code now + if (!empty($this->files_cache2[$handle]) && empty($this->files_cache[$handle]) && !$force_recompile) { + $this->compiled_code[$handle] = $this->compile2($this->uncompiled_code[$handle], $handle, $this->files_cache2[$handle]); + } else { + $this->compiled_code[$handle] = $this->compile2($this->uncompiled_code[$handle], '', ''); + } + } + // Run the compiled code + if (empty($this->files_cache[$handle]) || $force_recompile) { + $this->execute('', $this->compiled_code[$handle], $handle); + } else { + $this->execute($this->files_cache[$handle], '', $handle); + } + return true; + } + + /** + * Precompile file + * + * @param $template + * @param $filename + * + * @return bool + */ + function precompile($template, $filename) + { + global $precompile_num; + if (empty($precompile_num)) { + $precompile_num = 0; + } + $precompile_num++; + $handle = 'precompile_' . $precompile_num; + // Save old configuration + $root = $this->root; + $tpl_name = $this->tpl; + $old_config = $this->use_cache; + $old_autosave = $this->auto_compile; + // Set temporary configuration + $this->root = $this->tpldir . $template; + $this->tpl = $template; + $this->use_cache = 1; + $this->auto_compile = 1; + // Set filename + $res = $this->set_filename($handle, $filename, true, true); + if (!$res || !$this->files_cache2[$handle]) { + $this->root = $root; + $this->tpl = $tpl_name; + $this->use_cache = $old_config; + $this->auto_compile = $old_autosave; + return false; + } + $this->files_cache[$handle] = ''; + // Load template + $res = $this->loadfile($handle); + if (!$res || empty($this->uncompiled_code[$handle])) { + $this->root = $root; + $this->tpl = $tpl_name; + $this->use_cache = $old_config; + $this->auto_compile = $old_autosave; + return false; + } + // Compile the code + $this->compile2($this->uncompiled_code[$handle], $handle, $this->files_cache2[$handle]); + // Restore configuration + $this->root = $root; + $this->tpl = $tpl_name; + $this->use_cache = $old_config; + $this->auto_compile = $old_autosave; + return true; + } + + /** + * Inserts the uncompiled code for $handle as the value of $varname in the root-level + * This can be used to effectively include a template in the middle of another template + * Note that all desired assignments to the variables in $handle should be done BEFORE calling this function + * + * @param $varname + * @param $handle + * + * @return bool + */ + function assign_var_from_handle($varname, $handle) + { + ob_start(); + $res = $this->pparse($handle); + $this->vars[$varname] = ob_get_contents(); + ob_end_clean(); + return $res; + } + + /** + * Block-level variable assignment. Adds a new block iteration with the given variable assignments + * Note that this should only be called once per block iteration + * + * @param $blockname + * @param $vararray + * + * @return bool + */ + function assign_block_vars($blockname, $vararray) + { + if (strstr($blockname, '.')) { + // Nested block + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + $str = &$this->_tpldata; + for ($i = 0; $i < $blockcount; $i++) { + $str = &$str[$blocks[$i] . '.']; + $str = &$str[sizeof($str) - 1]; + } + // Now we add the block that we're actually assigning to + // We're adding a new iteration to this block with the given variable assignments + $str[$blocks[$blockcount] . '.'][] = $vararray; + } else { + // Top-level block. Add a new iteration to this block with the variable assignments we were given + $this->_tpldata[$blockname . '.'][] = $vararray; + } + return true; + } + + /** + * Root-level variable assignment. Adds to current assignments, overriding + * any existing variable assignment with the same name + * + * @param $vararray + */ + function assign_vars($vararray) + { + foreach ($vararray as $key => $val) { + $this->vars[$key] = $val; + } + } + + /** + * Root-level variable assignment. Adds to current assignments, overriding + * any existing variable assignment with the same name + * + * @param $varname + * @param bool $varval + */ + function assign_var($varname, $varval = true) + { + $this->vars[$varname] = $varval; + } + + /** + * Root-level. Adds to current assignments, appends + * to any existing variable assignment with the same name + * + * @param $vararray + */ + function append_vars($vararray) + { + foreach ($vararray as $key => $val) { + $this->vars[$key] = !isset($this->vars[$key]) ? $val : $this->vars[$key] . $val; + } + } + + /** + * If not already done, load the file for the given handle and populate + * the uncompiled_code[] hash with its code. Do not compile + * + * @param $handle + * + * @return bool + */ + function loadfile($handle) + { + // If cached file exists do nothing - it will be included via include() + if (!empty($this->files_cache[$handle])) { + return true; + } + + // If the file for this handle is already loaded and compiled, do nothing + if (!empty($this->uncompiled_code[$handle])) { + return true; + } + + // If we don't have a file assigned to this handle, die + if (empty($this->files[$handle])) { + die("Template->loadfile(): no file specified for handle $handle"); + } + + $filename = $this->files[$handle]; + + if (($str = file_get_contents($filename)) === false) { + die("Template->loadfile(): file $filename for handle $handle is empty"); + } + + $this->uncompiled_code[$handle] = $str; + + return true; + } + + /** + * Generates a reference to the given variable inside the given (possibly nested) block namespace + * This is a string of the form: $this->_tpldata['parent.'][$_parent_i]['$child1.'][$_child1_i]['$child2.'][$_child2_i]...['varname'] + * It's ready to be inserted into an "echo" line in one of the templates. NOTE: expects a trailing "." on the namespace + * + * @param $namespace + * @param $varname + * + * @return string + */ + function generate_block_varref($namespace, $varname) + { + // Strip the trailing period + $namespace = substr($namespace, 0, strlen($namespace) - 1); + + // Get a reference to the data block for this namespace + $varref = $this->generate_block_data_ref($namespace, true); + + // Append the variable reference + $varref .= "['$varname']"; + + $varref = ""; + + return $varref; + } + + /** + * Generates a reference to the array of data values for the given (possibly nested) block namespace + * This is a string of the form: $this->_tpldata['parent.'][$_parent_i]['$child1.'][$_child1_i]['$child2.'][$_child2_i]...['$childN.'] + * If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above. NOTE: does not expect a trailing "." on the blockname + * + * @param $blockname + * @param $include_last_iterator + * + * @return string + */ + function generate_block_data_ref($blockname, $include_last_iterator) + { + // Get an array of the blocks involved + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + if ($include_last_iterator) { + return '$' . $blocks[$blockcount] . '_item'; + } else { + return '$' . $blocks[$blockcount - 1] . '_item[\'' . $blocks[$blockcount] . '.\']'; + } + } + + function compile_code($filename, $code) + { + // Load code from file + if (!$code && !empty($filename)) { + $code = file_get_contents($filename); + } + + // Replace tags + $search = array('', ''); + $replace = array('<' . '?php ', ' ?' . '>'); + $code = str_replace($search, $replace, $code); + + // Break it up into lines and put " -->" back + $code_lines = explode(' -->', $code); + $count = count($code_lines); + for ($i = 0; $i < ($count - 1); $i++) { + $code_lines[$i] .= ' -->'; + } + + $block_nesting_level = 0; + $block_names = array(); + $block_names[0] = "."; + $block_items = array(); + $count_if = 0; + + // Prepare array for compiled code + $compiled = array(); + + // Array of switches + $sw = array(); + + // Replace all short php tags + $new_code = array(); + $line_count = count($code_lines); + for ($i = 0; $i < $line_count; $i++) { + $line = $code_lines[$i]; + $pos = strpos($line, ''; + $code_lines[$i] = substr($line, $pos + 2); + $i--; + } + $code_lines = $new_code; + + // Main loop + $line_count = count($code_lines); + for ($i = 0; $i < $line_count; $i++) { + $line = $code_lines[$i]; + // Reset keyword type + $keyword_type = XS_TAG_NONE; + // Check if we have valid keyword in current line + $pos1 = strpos($line, '', $pos1); + if ($pos2 !== false) { + // Find end of keyword in comment + $pos3 = strpos($line, ' ', $pos1 + 5); + if ($pos3 !== false && $pos3 <= $pos2) { + $keyword = substr($line, $pos1 + 5, $pos3 - $pos1 - 5); + // Check keyword against list of supported keywords. case-sensitive + if ($keyword === 'BEGIN') { + $keyword_type = XS_TAG_BEGIN; + } elseif ($keyword === 'END') { + $keyword_type = XS_TAG_END; + } elseif ($keyword === 'INCLUDE') { + $keyword_type = XS_TAG_INCLUDE; + } elseif ($keyword === 'IF') { + $keyword_type = XS_TAG_IF; + } elseif ($keyword === 'ELSE') { + $keyword_type = XS_TAG_ELSE; + } elseif ($keyword === 'ELSEIF') { + $keyword_type = XS_TAG_ELSEIF; + } elseif ($keyword === 'ENDIF') { + $keyword_type = XS_TAG_ENDIF; + } elseif ($keyword === 'BEGINELSE') { + $keyword_type = XS_TAG_BEGINELSE; + } + } + } + if (!$keyword_type) { + // Not valid keyword process the rest of line + $compiled[] = $this->_compile_text(substr($line, 0, $pos1 + 4)); + $code_lines[$i] = substr($line, $pos1 + 4); + $i--; + continue; + } + // Remove code before keyword + if ($pos1 > 0) { + $compiled[] = $this->_compile_text(substr($line, 0, $pos1)); + } + // Remove keyword + $keyword_str = substr($line, $pos1, $pos2 - $pos1 + 4); + $params_str = $pos2 == $pos3 ? '' : substr($line, $pos3 + 1, $pos2 - $pos3 - 1); + $code_lines[$i] = substr($line, $pos2 + 4); + $i--; + + /* + * + */ + if ($keyword_type == XS_TAG_BEGIN) { + $params = explode(' ', $params_str); + $num_params = count($params); + // Get variable name + if ($num_params == 1) { + $var = $params[0]; + } elseif ($num_params == 2) { + if ($params[0] === '') { + $var = $params[1]; + } elseif ($params[1] === '') { + $var = $params[0]; + } else { + // Invalid tag + $compiled[] = $keyword_str; + continue; + } + } else { + // Invalid tag + $compiled[] = $keyword_str; + continue; + } + // Adding code + $block_nesting_level++; + $block_names[$block_nesting_level] = $var; + if (isset($block_items[$var])) { + $block_items[$var]++; + } else { + $block_items[$var] = 1; + } + if ($block_nesting_level < 2) { + // Block is not nested + $line = '<' . "?php\n\n"; + $line .= '$' . $var . '_count = ( isset($this->_tpldata[\'' . $var . '.\']) ) ? sizeof($this->_tpldata[\'' . $var . '.\']) : 0;'; + $line .= "\n" . 'for ($' . $var . '_i = 0; $' . $var . '_i < $' . $var . '_count; $' . $var . '_i++)'; + $line .= "\n" . '{' . "\n"; + $line .= ' $' . $var . '_item = &$this->_tpldata[\'' . $var . '.\'][$' . $var . '_i];' . "\n"; + $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; + $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; + $line .= "\n?" . ">"; + } else { + // This block is nested. Generate a namespace string for this block + $namespace = join('.', $block_names); + // Strip leading period from root level + $namespace = substr($namespace, 2); + // Get a reference to the data array for this block that depends on the current indices of all parent blocks + $varref = $this->generate_block_data_ref($namespace, false); + // Create the for loop code to iterate over this block + $line = '<' . "?php\n\n"; + $line .= '$' . $var . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;'; + $line .= "\n" . 'for ($' . $var . '_i = 0; $' . $var . '_i < $' . $var . '_count; $' . $var . '_i++)'; + $line .= "\n" . '{' . "\n"; + $line .= ' $' . $var . '_item = &' . $varref . '[$' . $var . '_i];' . "\n"; + $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; + $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; + $line .= "\n?" . ">"; + } + $compiled[] = $line; + continue; + } + + /* + * + */ + if ($keyword_type == XS_TAG_END) { + $params = explode(' ', $params_str); + $num_params = count($params); + if ($num_params == 1) { + $var = $params[0]; + } elseif ($num_params == 2 && $params[0] === '') { + $var = $params[1]; + } elseif ($num_params == 2 && $params[1] === '') { + $var = $params[0]; + } else { + $compiled[] = $keyword_str; + continue; + } + // We have the end of a block + $line = '<' . "?php\n\n"; + $line .= '} // END ' . $var . "\n\n"; + $line .= 'if(isset($' . $var . '_item)) { unset($' . $var . '_item); } '; + $line .= "\n\n?" . ">"; + if (isset($block_items[$var])) { + $block_items[$var]--; + } else { + $block_items[$var] = -1; + } + unset($block_names[$block_nesting_level]); + $block_nesting_level--; + $compiled[] = $line; + continue; + } + + /* + * + */ + if ($keyword_type == XS_TAG_BEGINELSE) { + if ($block_nesting_level) { + $var = $block_names[$block_nesting_level]; + $compiled[] = '<' . '?php } if(!$' . $var . '_count) { ?' . '>'; + } else { + $compiled[] = $keyword_str; + continue; + } + } + + /* + * + */ + if ($keyword_type == XS_TAG_INCLUDE) { + $params = explode(' ', $params_str); + $num_params = count($params); + if ($num_params != 1) { + $compiled[] = $keyword_str; + continue; + } + $line = '<' . '?php '; + $filehash = md5($params_str . $this->include_count . TIMENOW); + $line .= ' $this->set_filename(\'xs_include_' . $filehash . '\', \'' . $params_str . '\', true); '; + $line .= ' $this->pparse(\'xs_include_' . $filehash . '\'); '; + $line .= ' ?' . '>'; + $this->include_count++; + $compiled[] = $line; + continue; + } + + /* + * + */ + if ($keyword_type == XS_TAG_IF || $keyword_type == XS_TAG_ELSEIF) { + if (!$count_if) { + $keyword_type = XS_TAG_IF; + } + $str = $this->compile_tag_if($params_str, $keyword_type == XS_TAG_IF ? false : true); + if ($str) { + $compiled[] = ''; + if ($keyword_type == XS_TAG_IF) { + $count_if++; + } + } else { + $compiled[] = $keyword_str; + } + continue; + } + + /* + * + */ + if ($keyword_type == XS_TAG_ELSE && $count_if > 0) { + $compiled[] = ''; + continue; + } + + /* + * + */ + if ($keyword_type == XS_TAG_ENDIF && $count_if > 0) { + $compiled[] = ''; + $count_if--; + continue; + } + } + + // Bring it back into a single string + $code_header = ''; + $code_footer = ''; + + return $code_header . join('', $compiled) . $code_footer; + } + + /* + * Compile code between tags + */ + function _compile_text($code) + { + if (strlen($code) < 3) { + return $code; + } + // Change template varrefs into PHP varrefs. This one will handle varrefs WITH namespaces + $varrefs = array(); + preg_match_all('#\{(([a-z0-9\-_]+?\.)+)([a-z0-9\-_]+?)\}#is', $code, $varrefs); + $varcount = sizeof($varrefs[1]); + $search = array(); + $replace = array(); + for ($i = 0; $i < $varcount; $i++) { + $namespace = $varrefs[1][$i]; + $varname = $varrefs[3][$i]; + $new = $this->generate_block_varref($namespace, $varname); + $search[] = $varrefs[0][$i]; + $replace[] = $new; + } + if (count($search) > 0) { + $code = str_replace($search, $replace, $code); + } + // This will handle the remaining root-level varrefs + $code = preg_replace('#\{(L_([a-z0-9\-_]+?))\}#i', '', $code); + $code = preg_replace('#\{(\$[a-z_][a-z0-9_$\->\'\"\.\[\]]*?)\}#i', '', $code); + $code = preg_replace('#\{(\#([a-z_][a-z0-9_]*?))\}#i', '', $code); + $code = preg_replace('#\{([a-z0-9\-_]+?)\}#i', '', $code); + return $code; + } + + // + // Compile IF tags - much of this is from Smarty with some adaptions for our block level methods + // + function compile_tag_if($tag_args, $elseif) + { + /* Tokenize args for 'if' tag */ + preg_match_all('/(?: "[^"\\\\]*(?:\\\\.[^"\\\\]*)*" | \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' | [(),] | [^\s(),]+)/x', $tag_args, $match); - $tokens = $match[0]; - $tokens_cnt = count($tokens); - $is_arg_stack = array(); + $tokens = $match[0]; + $tokens_cnt = count($tokens); + $is_arg_stack = array(); - for ($i = 0; $i < $tokens_cnt; $i++) { - $token = &$tokens[$i]; + for ($i = 0; $i < $tokens_cnt; $i++) { + $token = &$tokens[$i]; - switch ($token) { - case 'eq': - $token = '=='; - break; + switch ($token) { + case 'eq': + $token = '=='; + break; - case 'ne': - case 'neq': - $token = '!='; - break; + case 'ne': + case 'neq': + $token = '!='; + break; - case 'lt': - $token = '<'; - break; + case 'lt': + $token = '<'; + break; - case 'le': - case 'lte': - $token = '<='; - break; + case 'le': + case 'lte': + $token = '<='; + break; - case 'gt': - $token = '>'; - break; + case 'gt': + $token = '>'; + break; - case 'ge': - case 'gte': - $token = '>='; - break; + case 'ge': + case 'gte': + $token = '>='; + break; - case 'and': - $token = '&&'; - break; + case 'and': + $token = '&&'; + break; - case 'or': - $token = '||'; - break; + case 'or': + $token = '||'; + break; - case 'not': - $token = '!'; - break; + case 'not': + $token = '!'; + break; - case 'mod': - $token = '%'; - break; + case 'mod': + $token = '%'; + break; - case '(': - array_push($is_arg_stack, $i); - break; + case '(': + array_push($is_arg_stack, $i); + break; - case 'is': - $is_arg_start = ($tokens[$i - 1] == ')') ? array_pop($is_arg_stack) : $i - 1; - $is_arg = join(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start)); + case 'is': + $is_arg_start = ($tokens[$i - 1] == ')') ? array_pop($is_arg_stack) : $i - 1; + $is_arg = join(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start)); - $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i + 1)); + $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i + 1)); - array_splice($tokens, $is_arg_start, count($tokens), $new_tokens); + array_splice($tokens, $is_arg_start, count($tokens), $new_tokens); - $i = $is_arg_start; - break; + $i = $is_arg_start; + break; - default: - $pattern = '@^ + default: + $pattern = '@^ ( # 1 ([a-z0-9\-_]+?\.)+? # 2 block tpl vars (VAR1.VAR2.) but without last )? @@ -934,161 +934,161 @@ class Template (\#([a-z_][a-z0-9_]*))? # 7 php const ) $@ix'; - if (preg_match($pattern, $token, $m)) { - if (!empty($m[1])) { - $token = $this->generate_block_data_ref(substr($m[1], 0, -1), true) . "['{$m[4]}']"; - } else if (!empty($m[4])) { - $token = ($tokens_cnt == 1) ? "!empty(\$V['{$m[4]}'])" : "\$V['{$m[4]}']"; - } else if (!empty($m[5])) { - $token = ($tokens_cnt == 1) ? "!empty({$m[5]})" : "{$m[5]}"; - } else if (!empty($m[7])) { - $token = ($tokens_cnt == 1) ? "defined('{$m[7]}') && {$m[7]}" : "{$m[7]}"; - } - } - break; - } - } + if (preg_match($pattern, $token, $m)) { + if (!empty($m[1])) { + $token = $this->generate_block_data_ref(substr($m[1], 0, -1), true) . "['{$m[4]}']"; + } else if (!empty($m[4])) { + $token = ($tokens_cnt == 1) ? "!empty(\$V['{$m[4]}'])" : "\$V['{$m[4]}']"; + } else if (!empty($m[5])) { + $token = ($tokens_cnt == 1) ? "!empty({$m[5]})" : "{$m[5]}"; + } else if (!empty($m[7])) { + $token = ($tokens_cnt == 1) ? "defined('{$m[7]}') && {$m[7]}" : "{$m[7]}"; + } + } + break; + } + } - if ($elseif) { - $code = '} elseif (' . join(' ', $tokens) . ') {'; - } else { - $code = 'if (' . join(' ', $tokens) . ') {'; - } + if ($elseif) { + $code = '} elseif (' . join(' ', $tokens) . ') {'; + } else { + $code = 'if (' . join(' ', $tokens) . ') {'; + } - return $code; - } + return $code; + } - // This is from Smarty - function _parse_is_expr($is_arg, $tokens) - { - $expr_end = 0; - $negate_expr = false; + // This is from Smarty + function _parse_is_expr($is_arg, $tokens) + { + $expr_end = 0; + $negate_expr = false; - if (($first_token = array_shift($tokens)) == 'not') { - $negate_expr = true; - $expr_type = array_shift($tokens); - } else { - $expr_type = $first_token; - } + if (($first_token = array_shift($tokens)) == 'not') { + $negate_expr = true; + $expr_type = array_shift($tokens); + } else { + $expr_type = $first_token; + } - switch ($expr_type) { - case 'even': - if ($tokens[$expr_end] == 'by') { - $expr_end++; - $expr_arg = $tokens[$expr_end++]; - $expr = "!(($is_arg / $expr_arg) % $expr_arg)"; - } else { - $expr = "!($is_arg % 2)"; - } - break; + switch ($expr_type) { + case 'even': + if ($tokens[$expr_end] == 'by') { + $expr_end++; + $expr_arg = $tokens[$expr_end++]; + $expr = "!(($is_arg / $expr_arg) % $expr_arg)"; + } else { + $expr = "!($is_arg % 2)"; + } + break; - case 'odd': - if ($tokens[$expr_end] == 'by') { - $expr_end++; - $expr_arg = $tokens[$expr_end++]; - $expr = "(($is_arg / $expr_arg) % $expr_arg)"; - } else { - $expr = "($is_arg % 2)"; - } - break; + case 'odd': + if ($tokens[$expr_end] == 'by') { + $expr_end++; + $expr_arg = $tokens[$expr_end++]; + $expr = "(($is_arg / $expr_arg) % $expr_arg)"; + } else { + $expr = "($is_arg % 2)"; + } + break; - case 'div': - if ($tokens[$expr_end] == 'by') { - $expr_end++; - $expr_arg = $tokens[$expr_end++]; - $expr = "!($is_arg % $expr_arg)"; - } - break; + case 'div': + if ($tokens[$expr_end] == 'by') { + $expr_end++; + $expr_arg = $tokens[$expr_end++]; + $expr = "!($is_arg % $expr_arg)"; + } + break; - default: - break; - } + default: + break; + } - if ($negate_expr) { - $expr = "!($expr)"; - } + if ($negate_expr) { + $expr = "!($expr)"; + } - array_splice($tokens, 0, $expr_end, $expr); + array_splice($tokens, 0, $expr_end, $expr); - return $tokens; - } + return $tokens; + } - /** - * Compiles code and writes to cache if needed - * - * @param $code - * @param $handle - * @param $cache_file - * - * @return string - */ - function compile2($code, $handle, $cache_file) - { - $code = $this->compile_code('', $code); - if ($cache_file && !empty($this->use_cache) && !empty($this->auto_compile)) { - $res = $this->write_cache($cache_file, $code); - if ($handle && $res) { - $this->files_cache[$handle] = $cache_file; - } - } - $code = '?' . '>' . $code . '<' . "?php\n"; - return $code; - } + /** + * Compiles code and writes to cache if needed + * + * @param $code + * @param $handle + * @param $cache_file + * + * @return string + */ + function compile2($code, $handle, $cache_file) + { + $code = $this->compile_code('', $code); + if ($cache_file && !empty($this->use_cache) && !empty($this->auto_compile)) { + $res = $this->write_cache($cache_file, $code); + if ($handle && $res) { + $this->files_cache[$handle] = $cache_file; + } + } + $code = '?' . '>' . $code . '<' . "?php\n"; + return $code; + } - /** - * Compiles the given string of code, and returns the result in a string. - * If "do_not_echo" is true, the returned code will not be directly executable, - * but can be used as part of a variable assignment for use in assign_code_from_handle(). - * This function isn't used and kept only for compatibility with original template.php - * - * @param $code - * @param bool $do_not_echo - * @param string $retvar - * - * @return string - */ - function compile($code, $do_not_echo = false, $retvar = '') - { - $code = ' ?' . '>' . $this->compile_code('', $code) . '<' . "?php \n"; - if ($do_not_echo) { - $code = "ob_start();\n" . $code . "\n\${$retvar} = ob_get_contents();\nob_end_clean();\n"; - } - return $code; - } + /** + * Compiles the given string of code, and returns the result in a string. + * If "do_not_echo" is true, the returned code will not be directly executable, + * but can be used as part of a variable assignment for use in assign_code_from_handle(). + * This function isn't used and kept only for compatibility with original template.php + * + * @param $code + * @param bool $do_not_echo + * @param string $retvar + * + * @return string + */ + function compile($code, $do_not_echo = false, $retvar = '') + { + $code = ' ?' . '>' . $this->compile_code('', $code) . '<' . "?php \n"; + if ($do_not_echo) { + $code = "ob_start();\n" . $code . "\n\${$retvar} = ob_get_contents();\nob_end_clean();\n"; + } + return $code; + } - /** - * Write cache to disk - * - * @param $filename - * @param $code - */ - function write_cache($filename, $code) - { - file_write($code, $filename, false, true, true); - } + /** + * Write cache to disk + * + * @param $filename + * @param $code + */ + function write_cache($filename, $code) + { + file_write($code, $filename, false, true, true); + } - function xs_startup() - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function xs_startup() + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - if (empty($this->xs_started)) { - $this->xs_started = 1; - // Adding language variable - $this->vars['LANG'] = isset($this->vars['LANG']) ? $this->vars['LANG'] : $di->config->get('default_lang'); - // Adding current template - $tpl = $this->root . '/'; - if (substr($tpl, 0, 2) === './') { - $tpl = substr($tpl, 2, strlen($tpl)); - } - $this->vars['TEMPLATE'] = isset($this->vars['TEMPLATE']) ? $this->vars['TEMPLATE'] : $tpl; - $this->vars['TEMPLATE_NAME'] = isset($this->vars['TEMPLATE_NAME']) ? $this->vars['TEMPLATE_NAME'] : $this->tpl; - } - } + if (empty($this->xs_started)) { + $this->xs_started = 1; + // Adding language variable + $this->vars['LANG'] = isset($this->vars['LANG']) ? $this->vars['LANG'] : $di->config->get('default_lang'); + // Adding current template + $tpl = $this->root . '/'; + if (substr($tpl, 0, 2) === './') { + $tpl = substr($tpl, 2, strlen($tpl)); + } + $this->vars['TEMPLATE'] = isset($this->vars['TEMPLATE']) ? $this->vars['TEMPLATE'] : $tpl; + $this->vars['TEMPLATE_NAME'] = isset($this->vars['TEMPLATE_NAME']) ? $this->vars['TEMPLATE_NAME'] : $this->tpl; + } + } - function lang_error($var) - { - trigger_error(basename($this->cur_tpl) . " : undefined language variable {L_{$var}}", E_USER_WARNING); - return "Undefined: {L_{$var}}"; - } -} \ No newline at end of file + function lang_error($var) + { + trigger_error(basename($this->cur_tpl) . " : undefined language variable {L_{$var}}", E_USER_WARNING); + return "Undefined: {L_{$var}}"; + } +} diff --git a/library/includes/torrent_show_dl_list.php b/library/includes/torrent_show_dl_list.php index c29105237..1347735d6 100644 --- a/library/includes/torrent_show_dl_list.php +++ b/library/includes/torrent_show_dl_list.php @@ -5,13 +5,13 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$show_canceled_in_count_mode = false; -$title_date_format = 'Y-m-d'; -$dl_list_sql_limit = 300; // DL-List overall limit +$show_canceled_in_count_mode = false; +$title_date_format = 'Y-m-d'; +$dl_list_sql_limit = 300; // DL-List overall limit $max_dl_users_before_overflow = 100; // for each dl-status $dl_users_overflow_div_height = '120px'; -$dl_users_div_style_normal = 'padding: 0px;'; -$dl_users_div_style_overflow = "padding: 6px; height: $dl_users_overflow_div_height; overflow: auto; border: 1px inset;"; +$dl_users_div_style_normal = 'padding: 0px;'; +$dl_users_div_style_overflow = "padding: 6px; height: $dl_users_overflow_div_height; overflow: auto; border: 1px inset;"; $template->assign_vars(array('DL_BUTTONS' => false)); @@ -23,123 +23,101 @@ $show_dl_buttons = ($dl_topic && $di->config->get('bt_show_dl_list_buttons')); // link to clear DL-List $template->assign_vars(array('S_DL_DELETE' => false)); -if ($is_auth['auth_mod'] && isset($t_data['tracker_status'])) -{ - $s_dl_delete = "'. $lang['DL_LIST_DEL'] .''; - $template->assign_vars(array('S_DL_DELETE' => $s_dl_delete)); +if ($is_auth['auth_mod'] && isset($t_data['tracker_status'])) { + $s_dl_delete = "' . $lang['DL_LIST_DEL'] . ''; + $template->assign_vars(array('S_DL_DELETE' => $s_dl_delete)); } $dl_cat = $dl_count = array(); -if ($show_dl_list) -{ - foreach ($dl_status_css as $i => $desc) - { - $dl_cat[$i] = ''; - $dl_count[$i] = 0; - } +if ($show_dl_list) { + foreach ($dl_status_css as $i => $desc) { + $dl_cat[$i] = ''; + $dl_count[$i] = 0; + } - if ($count_mode) - { - $sql = "SELECT dl_status AS user_status, users_count AS username - FROM ". BB_BT_DLSTATUS_SNAP ." + if ($count_mode) { + $sql = "SELECT dl_status AS user_status, users_count AS username + FROM " . BB_BT_DLSTATUS_SNAP . " WHERE topic_id = $topic_id"; - } - else - { - $sql = "SELECT d.user_status, d.user_id, DATE_FORMAT(d.last_modified_dlstatus, '%Y-%m-%d') AS last_modified_dlstatus, u.username, u.user_rank - FROM ". BB_BT_DLSTATUS ." d, ". BB_USERS ." u + } else { + $sql = "SELECT d.user_status, d.user_id, DATE_FORMAT(d.last_modified_dlstatus, '%Y-%m-%d') AS last_modified_dlstatus, u.username, u.user_rank + FROM " . BB_BT_DLSTATUS . " d, " . BB_USERS . " u WHERE d.topic_id = $topic_id AND d.user_id = u.user_id - AND d.user_status != ". DL_STATUS_RELEASER ." + AND d.user_status != " . DL_STATUS_RELEASER . " ORDER BY d.user_status /* ASC, d.last_modified_dlstatus DESC */ LIMIT $dl_list_sql_limit"; - } + } - if ($dl_info = DB()->fetch_rowset($sql)) - { - if ($count_mode) - { - $template->assign_block_vars('dl_counts', array()); - } - else - { - $template->assign_block_vars('dl_users', array()); - } + if ($dl_info = DB()->fetch_rowset($sql)) { + if ($count_mode) { + $template->assign_block_vars('dl_counts', array()); + } else { + $template->assign_block_vars('dl_users', array()); + } - foreach ($dl_info as $rid => $u) - { - $u_link_class = $dl_status_css[$u['user_status']]; + foreach ($dl_info as $rid => $u) { + $u_link_class = $dl_status_css[$u['user_status']]; - if ($count_mode) - { - $dl_cat[$u['user_status']] = $u['username']; - $dl_count[$u['user_status']] = $u['username']; - } - else - { - $u_prof_href = ($u['user_id'] == GUEST_UID) ? '#' : "profile.php?mode=viewprofile&u=". $u['user_id'] ."#torrent"; - $dl_cat[$u['user_status']] .= ''. profile_url(array('username' => $u['username'], 'user_rank' => $u['user_rank'])) .', '; - $dl_count[$u['user_status']]++; - } - } + if ($count_mode) { + $dl_cat[$u['user_status']] = $u['username']; + $dl_count[$u['user_status']] = $u['username']; + } else { + $u_prof_href = ($u['user_id'] == GUEST_UID) ? '#' : "profile.php?mode=viewprofile&u=" . $u['user_id'] . "#torrent"; + $dl_cat[$u['user_status']] .= '' . profile_url(array('username' => $u['username'], 'user_rank' => $u['user_rank'])) . ', '; + $dl_count[$u['user_status']]++; + } + } - foreach ($dl_status_css as $i => $desc) - { - if ($dl_cat[$i] && !$count_mode) - { - $dl_users_div_style = ($dl_count[$i] > $max_dl_users_before_overflow) ? $dl_users_div_style_overflow : $dl_users_div_style_normal; - $dl_cat[$i][strlen($dl_cat[$i])-2] = ' '; - $dl_cat[$i] = "". $dl_cat[$i] .''; + foreach ($dl_status_css as $i => $desc) { + if ($dl_cat[$i] && !$count_mode) { + $dl_users_div_style = ($dl_count[$i] > $max_dl_users_before_overflow) ? $dl_users_div_style_overflow : $dl_users_div_style_normal; + $dl_cat[$i][strlen($dl_cat[$i]) - 2] = ' '; + $dl_cat[$i] = "" . $dl_cat[$i] . ''; - $template->assign_block_vars('dl_users.users_row', array( - 'DL_OPTION_NAME' => $lang[strtoupper($desc)], - 'DL_OPTION_USERS' => $dl_cat[$i], - 'DL_COUNT' => $dl_count[$i], - 'DL_USERS_DIV_STYLE' => $dl_users_div_style, - )); - } - else if ($dl_count[$i] && $count_mode) - { - if ($i == DL_STATUS_CANCEL && !$show_canceled_in_count_mode) - { - continue; - } - $template->assign_block_vars('dl_counts.count_row', array( - 'DL_OPTION_NAME' => $lang[strtoupper($desc)], - 'DL_OPTION_USERS' => $dl_count[$i], - )); - } - } - } - else - { - $template->assign_block_vars('dl_list_none', array()); - } + $template->assign_block_vars('dl_users.users_row', array( + 'DL_OPTION_NAME' => $lang[strtoupper($desc)], + 'DL_OPTION_USERS' => $dl_cat[$i], + 'DL_COUNT' => $dl_count[$i], + 'DL_USERS_DIV_STYLE' => $dl_users_div_style, + )); + } else if ($dl_count[$i] && $count_mode) { + if ($i == DL_STATUS_CANCEL && !$show_canceled_in_count_mode) { + continue; + } + $template->assign_block_vars('dl_counts.count_row', array( + 'DL_OPTION_NAME' => $lang[strtoupper($desc)], + 'DL_OPTION_USERS' => $dl_count[$i], + )); + } + } + } else { + $template->assign_block_vars('dl_list_none', array()); + } } -if ($show_dl_buttons) -{ - $template->assign_vars(array( - 'DL_BUTTONS' => true, - 'DL_BUT_WILL' => $di->config->get('bt_show_dl_but_will'), - 'DL_BUT_DOWN' => $di->config->get('bt_show_dl_but_down'), - 'DL_BUT_COMPL' => $di->config->get('bt_show_dl_but_compl'), - 'DL_BUT_CANCEL' => $di->config->get('bt_show_dl_but_cancel'), - )); +if ($show_dl_buttons) { + $template->assign_vars(array( + 'DL_BUTTONS' => true, + 'DL_BUT_WILL' => $di->config->get('bt_show_dl_but_will'), + 'DL_BUT_DOWN' => $di->config->get('bt_show_dl_but_down'), + 'DL_BUT_COMPL' => $di->config->get('bt_show_dl_but_compl'), + 'DL_BUT_CANCEL' => $di->config->get('bt_show_dl_but_cancel'), + )); - $dl_hidden_fields = ' - - - + $dl_hidden_fields = ' + + + '; - $template->assign_vars(array( - 'DL_HIDDEN_FIELDS' => $dl_hidden_fields, - 'S_DL_ACTION' => "dl_list.php?". POST_TOPIC_URL ."=$topic_id", - )); + $template->assign_vars(array( + 'DL_HIDDEN_FIELDS' => $dl_hidden_fields, + 'S_DL_ACTION' => "dl_list.php?" . POST_TOPIC_URL . "=$topic_id", + )); } $template->assign_vars(array('SHOW_DL_LIST' => $show_dl_list)); -unset($dl_info); \ No newline at end of file +unset($dl_info); diff --git a/library/includes/ucp/activate.php b/library/includes/ucp/activate.php index 2806c5e33..8d972bc50 100644 --- a/library/includes/ucp/activate.php +++ b/library/includes/ucp/activate.php @@ -2,46 +2,35 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); -if (empty($_GET['u']) || empty($_GET['act_key'])) -{ - bb_die('Bad request'); +if (empty($_GET['u']) || empty($_GET['act_key'])) { + bb_die('Bad request'); } $sql = "SELECT user_active, user_id, username, user_email, user_newpasswd, user_lang, user_actkey FROM " . BB_USERS . " WHERE user_id = " . intval($_GET[POST_USERS_URL]); -if (!($result = DB()->sql_query($sql))) -{ - bb_die('Could not obtain user information'); +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain user information'); } -if ($row = DB()->sql_fetchrow($result)) -{ - if ($row['user_active'] && trim($row['user_actkey']) == '') - { - bb_die($lang['ALREADY_ACTIVATED']); - } - else if ((trim($row['user_actkey']) == trim($_GET['act_key'])) && (trim($row['user_actkey']) != '')) - { - $sql_update_pass = ( $row['user_newpasswd'] != '' ) ? ", user_password = '" . md5(md5($row['user_newpasswd'])) . "', user_newpasswd = ''" : ''; +if ($row = DB()->sql_fetchrow($result)) { + if ($row['user_active'] && trim($row['user_actkey']) == '') { + bb_die($lang['ALREADY_ACTIVATED']); + } else if ((trim($row['user_actkey']) == trim($_GET['act_key'])) && (trim($row['user_actkey']) != '')) { + $sql_update_pass = ($row['user_newpasswd'] != '') ? ", user_password = '" . md5(md5($row['user_newpasswd'])) . "', user_newpasswd = ''" : ''; - $sql = "UPDATE " . BB_USERS . " + $sql = "UPDATE " . BB_USERS . " SET user_active = 1, user_actkey = ''" . $sql_update_pass . " WHERE user_id = " . $row['user_id']; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not update users table'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not update users table'); + } - $message = ( $sql_update_pass == '' ) ? $lang['ACCOUNT_ACTIVE'] : $lang['PASSWORD_ACTIVATED']; - bb_die($message); - } - else - { - bb_die($lang['WRONG_ACTIVATION']); - } + $message = ($sql_update_pass == '') ? $lang['ACCOUNT_ACTIVE'] : $lang['PASSWORD_ACTIVATED']; + bb_die($message); + } else { + bb_die($lang['WRONG_ACTIVATION']); + } +} else { + bb_die($lang['NO_SUCH_USER']); } -else -{ - bb_die($lang['NO_SUCH_USER']); -} \ No newline at end of file diff --git a/library/includes/ucp/bonus.php b/library/includes/ucp/bonus.php index e6905ed9c..3904f1e80 100644 --- a/library/includes/ucp/bonus.php +++ b/library/includes/ucp/bonus.php @@ -5,42 +5,37 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$user_id = $userdata['user_id']; +$user_id = $userdata['user_id']; $user_points = $userdata['user_points']; -if($di->config->get('seed_bonus_enabled') && $di->config->get('bonus_upload') && $di->config->get('bonus_upload_price')) -{ - $upload_row = unserialize($di->config->get('bonus_upload')); - $price_row = unserialize($di->config->get('bonus_upload_price')); -} -else bb_die($lang['EXCHANGE_NOT']); +if ($di->config->get('seed_bonus_enabled') && $di->config->get('bonus_upload') && $di->config->get('bonus_upload_price')) { + $upload_row = unserialize($di->config->get('bonus_upload')); + $price_row = unserialize($di->config->get('bonus_upload_price')); +} else bb_die($lang['EXCHANGE_NOT']); -if (isset($_POST['bonus_id'])) -{ - $id = (int) $_POST['bonus_id']; +if (isset($_POST['bonus_id'])) { + $id = (int)$_POST['bonus_id']; - $btu = get_bt_userdata($user_id); + $btu = get_bt_userdata($user_id); - if (empty($btu)) - { - require(INC_DIR .'functions_torrent.php'); - generate_passkey($user_id, true); - $btu = get_bt_userdata($user_id); - } + if (empty($btu)) { + require(INC_DIR . 'functions_torrent.php'); + generate_passkey($user_id, true); + $btu = get_bt_userdata($user_id); + } - $upload = $upload_row[$id]*1024*1024*1024; - $points = $price_row[$id]; + $upload = $upload_row[$id] * 1024 * 1024 * 1024; + $points = $price_row[$id]; - if ($userdata['user_points'] < $points) - { - meta_refresh('index.php', 5); + if ($userdata['user_points'] < $points) { + meta_refresh('index.php', 5); - $message = $lang['BONUS_NOT_SUCCES'] .'

        '. $lang['BONUS_RETURN'] .'

        '. $lang['RETURN_PROFILE'] .'

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

        ' . $lang['BONUS_RETURN'] . '

        ' . $lang['RETURN_PROFILE'] . '

        ' . sprintf($lang['CLICK_RETURN_INDEX'], '', ''); - bb_die($message); - } + bb_die($message); + } - DB()->query("UPDATE ". BB_BT_USERS ." bu, ". BB_USERS ." u + DB()->query("UPDATE " . BB_BT_USERS . " bu, " . BB_USERS . " u SET bu.u_up_total = u_up_total + $upload, u.user_points = u.user_points - $points @@ -49,35 +44,32 @@ if (isset($_POST['bonus_id'])) AND u.user_id = bu.user_id "); - cache_rm_user_sessions($user_id); - meta_refresh(BONUS_URL, 5); + cache_rm_user_sessions($user_id); + meta_refresh(BONUS_URL, 5); - $message = sprintf($lang['BONUS_SUCCES'], humn_size($upload_row[$id]*1024*1024*1024)); - $message .= '

        '. $lang['BONUS_RETURN'] .'

        '. $lang['RETURN_PROFILE'] .'

        '. sprintf($lang['CLICK_RETURN_INDEX'], '', ''); + $message = sprintf($lang['BONUS_SUCCES'], humn_size($upload_row[$id] * 1024 * 1024 * 1024)); + $message .= '

        ' . $lang['BONUS_RETURN'] . '

        ' . $lang['RETURN_PROFILE'] . '

        ' . sprintf($lang['CLICK_RETURN_INDEX'], '', ''); - bb_die($message); + bb_die($message); +} else { + $template->assign_vars(array( + 'U_USER_PROFILE' => PROFILE_URL . $user_id, + 'S_MODE_ACTION' => 'profile.php?mode=bonus', + 'PAGE_TITLE' => $lang['EXCHANGE_BONUS'], + 'MY_BONUS' => sprintf($lang['MY_BONUS'], $user_points), + )); + + foreach ($price_row as $i => $price) { + if (!$price || !$upload_row[$i]) continue; + $class = ($user_points >= $price) ? 'seed' : 'leech'; + + $template->assign_block_vars('bonus_upload', array( + 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', + 'ID' => $i, + 'DESC' => sprintf($lang['BONUS_UPLOAD_DESC'], humn_size($upload_row[$i] * 1024 * 1024 * 1024)), + 'PRICE' => sprintf($lang['BONUS_UPLOAD_PRICE'], $class, sprintf('%.2f', $price)), + )); + } + + print_page('usercp_bonus.tpl'); } -else -{ - $template->assign_vars(array( - 'U_USER_PROFILE' => PROFILE_URL . $user_id, - 'S_MODE_ACTION' => 'profile.php?mode=bonus', - 'PAGE_TITLE' => $lang['EXCHANGE_BONUS'], - 'MY_BONUS' => sprintf($lang['MY_BONUS'], $user_points), - )); - - foreach($price_row as $i => $price) - { - if(!$price || !$upload_row[$i]) continue; - $class = ($user_points >= $price) ? 'seed' : 'leech'; - - $template->assign_block_vars('bonus_upload', array( - 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', - 'ID' => $i, - 'DESC' => sprintf($lang['BONUS_UPLOAD_DESC'], humn_size($upload_row[$i]*1024*1024*1024)), - 'PRICE' => sprintf($lang['BONUS_UPLOAD_PRICE'], $class, sprintf('%.2f', $price)), - )); - } - - print_page('usercp_bonus.tpl'); -} \ No newline at end of file diff --git a/library/includes/ucp/email.php b/library/includes/ucp/email.php index ead271a56..7f38af97f 100644 --- a/library/includes/ucp/email.php +++ b/library/includes/ucp/email.php @@ -6,25 +6,20 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); $di = \TorrentPier\Di::getInstance(); // Is send through board enabled? No, return to index -if (!$di->config->get('board_email_form')) -{ - redirect("index.php"); +if (!$di->config->get('board_email_form')) { + redirect("index.php"); } set_die_append_msg(); -if ( !empty($_GET[POST_USERS_URL]) || !empty($_POST[POST_USERS_URL]) ) -{ - $user_id = ( !empty($_GET[POST_USERS_URL]) ) ? intval($_GET[POST_USERS_URL]) : intval($_POST[POST_USERS_URL]); -} -else -{ - bb_die($lang['NO_USER_SPECIFIED']); +if (!empty($_GET[POST_USERS_URL]) || !empty($_POST[POST_USERS_URL])) { + $user_id = (!empty($_GET[POST_USERS_URL])) ? intval($_GET[POST_USERS_URL]) : intval($_POST[POST_USERS_URL]); +} else { + bb_die($lang['NO_USER_SPECIFIED']); } -if ( !$userdata['session_logged_in'] ) -{ - redirect(LOGIN_URL . "?redirect=profile.php&mode=email&" . POST_USERS_URL . "=$user_id"); +if (!$userdata['session_logged_in']) { + redirect(LOGIN_URL . "?redirect=profile.php&mode=email&" . POST_USERS_URL . "=$user_id"); } $errors = array(); @@ -34,61 +29,54 @@ $sql = "SELECT username, user_id, user_rank, user_email, user_lang WHERE user_id = $user_id "; -if ($row = DB()->fetch_row($sql)) -{ - $username = $row['username']; - $user_email = $row['user_email']; - $user_lang = $row['user_lang']; +if ($row = DB()->fetch_row($sql)) { + $username = $row['username']; + $user_email = $row['user_email']; + $user_lang = $row['user_lang']; - if ( true || IS_ADMIN ) // TRUE instead of missing user_opt "prevent_email" - { - if (isset($_POST['submit'])) - { - $subject = trim(html_entity_decode($_POST['subject'])); - $message = trim(html_entity_decode($_POST['message'])); + if (true || IS_ADMIN) // TRUE instead of missing user_opt "prevent_email" + { + if (isset($_POST['submit'])) { + $subject = trim(html_entity_decode($_POST['subject'])); + $message = trim(html_entity_decode($_POST['message'])); - if (!$subject) $errors[] = $lang['EMPTY_SUBJECT_EMAIL']; - if (!$message) $errors[] = $lang['EMPTY_MESSAGE_EMAIL']; + if (!$subject) $errors[] = $lang['EMPTY_SUBJECT_EMAIL']; + if (!$message) $errors[] = $lang['EMPTY_MESSAGE_EMAIL']; - if (!$errors) - { - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + if (!$errors) { + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($userdata['username'] ." <{$userdata['user_email']}>"); - $emailer->email_address($username ." <$user_email>"); + $emailer->from($userdata['username'] . " <{$userdata['user_email']}>"); + $emailer->email_address($username . " <$user_email>"); - $emailer->use_template('profile_send_email', $user_lang); - $emailer->set_subject($subject); + $emailer->use_template('profile_send_email', $user_lang); + $emailer->set_subject($subject); - $emailer->assign_vars(array( - 'SITENAME' => $di->config->get('sitename'), - 'FROM_USERNAME' => $userdata['username'], - 'TO_USERNAME' => $username, - 'MESSAGE' => $message, - )); - $emailer->send(); - $emailer->reset(); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('sitename'), + 'FROM_USERNAME' => $userdata['username'], + 'TO_USERNAME' => $username, + 'MESSAGE' => $message, + )); + $emailer->send(); + $emailer->reset(); - bb_die($lang['EMAIL_SENT']); - } - } + bb_die($lang['EMAIL_SENT']); + } + } - $template->assign_vars(array( - 'USERNAME' => profile_url($row), - 'S_HIDDEN_FIELDS' => '', - 'S_POST_ACTION' => "profile.php?mode=email&" . POST_USERS_URL . "=$user_id", - 'ERROR_MESSAGE' => ($errors) ? join('
        ', array_unique($errors)) : '', - )); + $template->assign_vars(array( + 'USERNAME' => profile_url($row), + 'S_HIDDEN_FIELDS' => '', + 'S_POST_ACTION' => "profile.php?mode=email&" . POST_USERS_URL . "=$user_id", + 'ERROR_MESSAGE' => ($errors) ? join('
        ', array_unique($errors)) : '', + )); - print_page('usercp_email.tpl'); - } - else - { - bb_die($lang['USER_PREVENT_EMAIL']); - } + print_page('usercp_email.tpl'); + } else { + bb_die($lang['USER_PREVENT_EMAIL']); + } +} else { + bb_die($lang['USER_NOT_EXIST']); } -else -{ - bb_die($lang['USER_NOT_EXIST']); -} \ No newline at end of file diff --git a/library/includes/ucp/register.php b/library/includes/ucp/register.php index 324833138..35215c427 100644 --- a/library/includes/ucp/register.php +++ b/library/includes/ucp/register.php @@ -9,771 +9,661 @@ array_deep($_POST, 'trim'); set_die_append_msg(); -if (IS_ADMIN) -{ - $new_user = (int) request_var('admin', ''); - if ($new_user) $gen_simple_header = true; +if (IS_ADMIN) { + $new_user = (int)request_var('admin', ''); + if ($new_user) $gen_simple_header = true; - $template->assign_vars(array( - 'NEW_USER' => $new_user, - )); + $template->assign_vars(array( + 'NEW_USER' => $new_user, + )); } $req_email_activation = (IS_ADMIN) ? false : $di->config->get('reg_email_activation'); $can_register = (IS_GUEST || IS_ADMIN); -$submit = !empty($_POST['submit']); -$errors = []; +$submit = !empty($_POST['submit']); +$errors = []; $adm_edit = false; // редактирование админом чужого профиля -require(INC_DIR .'bbcode.php'); -require(INC_DIR .'functions_validate.php'); -require(INC_DIR .'functions_selects.php'); +require(INC_DIR . 'bbcode.php'); +require(INC_DIR . 'functions_validate.php'); +require(INC_DIR . 'functions_selects.php'); $pr_data = []; // данные редактируемого либо регистрационного профиля $db_data = []; // данные для базы: регистрационные либо измененные данные юзера $tp_data = []; // данные для tpl // Данные профиля -switch ($mode) -{ - /** - * Регистрация - */ - case 'register': - if (!$can_register) redirect('index.php'); +switch ($mode) { + /** + * Регистрация + */ + case 'register': + if (!$can_register) redirect('index.php'); - if (!IS_ADMIN) - { - // Ограничение по ip - if($di->config->get('unique_ip')) - { - if($users = DB()->fetch_row("SELECT user_id, username FROM ". BB_USERS ." WHERE user_reg_ip = '". USER_IP ."' LIMIT 1")) - { - bb_die(sprintf($lang['ALREADY_REG_IP'], ''. $users['username'] .'', $di->config->get('tech_admin_email'))); - } - } - // Отключение регистрации - if ($di->config->get('new_user_reg_disabled') || ($req_email_activation && $di->config->get('emailer_disabled'))) - { - bb_die($lang['NEW_USER_REG_DISABLED']); - } - // Ограничение по времени - else if ($di->config->get('new_user_reg_restricted')) - { - if (in_array(date('G'), array(0,/*1,2,3,4,5,6,7,8,11,12,13,14,15,16,*/17,18,19,20,21,22,23))) - { - bb_die($lang['REGISTERED_IN_TIME']); - } - } - } + if (!IS_ADMIN) { + // Ограничение по ip + if ($di->config->get('unique_ip')) { + if ($users = DB()->fetch_row("SELECT user_id, username FROM " . BB_USERS . " WHERE user_reg_ip = '" . USER_IP . "' LIMIT 1")) { + bb_die(sprintf($lang['ALREADY_REG_IP'], '' . $users['username'] . '', $di->config->get('tech_admin_email'))); + } + } + // Отключение регистрации + if ($di->config->get('new_user_reg_disabled') || ($req_email_activation && $di->config->get('emailer_disabled'))) { + bb_die($lang['NEW_USER_REG_DISABLED']); + } // Ограничение по времени + else if ($di->config->get('new_user_reg_restricted')) { + if (in_array(date('G'), array(0,/*1,2,3,4,5,6,7,8,11,12,13,14,15,16,*/ + 17, 18, 19, 20, 21, 22, 23))) { + bb_die($lang['REGISTERED_IN_TIME']); + } + } + } - // field => can_edit - $profile_fields = array( - 'username' => true, - 'user_password' => true, - 'user_email' => true, - 'user_timezone' => true, - 'user_lang' => true, - 'user_opt' => true, - ); + // field => can_edit + $profile_fields = array( + 'username' => true, + 'user_password' => true, + 'user_email' => true, + 'user_timezone' => true, + 'user_lang' => true, + 'user_opt' => true, + ); - $pr_data = array( - 'user_id' => GUEST_UID, - 'username' => '', - 'user_password' => '', - 'user_email' => '', - 'user_timezone' => $di->config->get('board_timezone'), - 'user_lang' => $di->config->get('default_lang'), - 'user_opt' => 0, - 'avatar_ext_id' => 0, - ); - break; + $pr_data = array( + 'user_id' => GUEST_UID, + 'username' => '', + 'user_password' => '', + 'user_email' => '', + 'user_timezone' => $di->config->get('board_timezone'), + 'user_lang' => $di->config->get('default_lang'), + 'user_opt' => 0, + 'avatar_ext_id' => 0, + ); + break; - /** - * Редактирование профиля - */ - case 'editprofile': - if (IS_GUEST) login_redirect(); + /** + * Редактирование профиля + */ + case 'editprofile': + if (IS_GUEST) login_redirect(); - // field => can_edit - $profile_fields = array( - 'user_active' => IS_ADMIN, - 'username' => (IS_ADMIN || $di->config->get('allow_namechange')), - 'user_password' => true, - 'user_email' => true, // должен быть после user_password - 'user_lang' => true, - 'user_gender' => true, - 'user_birthday' => true, - 'user_timezone' => true, - 'user_opt' => true, - 'avatar_ext_id' => true, - 'user_icq' => true, - 'user_skype' => true, - 'user_twitter' => true, - 'user_website' => true, - 'user_from' => true, - 'user_sig' => true, - 'user_occ' => true, - 'user_interests' => true, - 'tpl_name' => true, - ); + // field => can_edit + $profile_fields = array( + 'user_active' => IS_ADMIN, + 'username' => (IS_ADMIN || $di->config->get('allow_namechange')), + 'user_password' => true, + 'user_email' => true, // должен быть после user_password + 'user_lang' => true, + 'user_gender' => true, + 'user_birthday' => true, + 'user_timezone' => true, + 'user_opt' => true, + 'avatar_ext_id' => true, + 'user_icq' => true, + 'user_skype' => true, + 'user_twitter' => true, + 'user_website' => true, + 'user_from' => true, + 'user_sig' => true, + 'user_occ' => true, + 'user_interests' => true, + 'tpl_name' => true, + ); - // Выбор профиля: для юзера свой, для админа любой - if (IS_ADMIN && !empty($_REQUEST['u'])) - { - $pr_user_id = (int) $_REQUEST['u']; - $adm_edit = ($pr_user_id != $userdata['user_id']); - } - else - { - $pr_user_id = $userdata['user_id']; - } - $profile_fields_sql = join(', ', array_keys($profile_fields)); - $sql = " + // Выбор профиля: для юзера свой, для админа любой + if (IS_ADMIN && !empty($_REQUEST['u'])) { + $pr_user_id = (int)$_REQUEST['u']; + $adm_edit = ($pr_user_id != $userdata['user_id']); + } else { + $pr_user_id = $userdata['user_id']; + } + $profile_fields_sql = join(', ', array_keys($profile_fields)); + $sql = " SELECT user_id, user_rank, user_level, $profile_fields_sql - FROM ". BB_USERS ." + FROM " . BB_USERS . " WHERE user_id = $pr_user_id LIMIT 1 "; - if (!$pr_data = DB()->fetch_row($sql)) - { - bb_die($lang['PROFILE_NOT_FOUND']); - } - break; + if (!$pr_data = DB()->fetch_row($sql)) { + bb_die($lang['PROFILE_NOT_FOUND']); + } + break; - default: - trigger_error("invalid mode: $mode", E_USER_ERROR); + default: + trigger_error("invalid mode: $mode", E_USER_ERROR); } // Captcha $need_captcha = ($mode == 'register' && !IS_ADMIN && !$di->config->get('captcha.disabled')); -if ($submit) -{ - if ($need_captcha && !bb_captcha('check')) - { - $errors[] = $lang['CAPTCHA_WRONG']; - } +if ($submit) { + if ($need_captcha && !bb_captcha('check')) { + $errors[] = $lang['CAPTCHA_WRONG']; + } } // Валидация данных $cur_pass_valid = $adm_edit; -foreach ($profile_fields as $field => $can_edit) -{ - switch ($field) - { - /** - * Активация (edit, reg) - */ - case 'user_active': - $active = isset($_POST['user_active']) ? (int) $_POST['user_active'] : $pr_data['user_active']; - if ($submit && $adm_edit) - { - $pr_data['user_active'] = $active; - $db_data['user_active'] = $active; - } - break; +foreach ($profile_fields as $field => $can_edit) { + switch ($field) { + /** + * Активация (edit, reg) + */ + case 'user_active': + $active = isset($_POST['user_active']) ? (int)$_POST['user_active'] : $pr_data['user_active']; + if ($submit && $adm_edit) { + $pr_data['user_active'] = $active; + $db_data['user_active'] = $active; + } + break; - /** - * Имя (edit, reg) - */ - case 'username': - $username = !empty($_POST['username']) ? clean_username($_POST['username']) : $pr_data['username']; + /** + * Имя (edit, reg) + */ + case 'username': + $username = !empty($_POST['username']) ? clean_username($_POST['username']) : $pr_data['username']; - if ($submit) - { - $err = validate_username($username); - if (!$errors && $err && ($mode == 'register')) - { - $errors[] = $err; - } - if ($can_edit && $username != $pr_data['username'] || $mode == 'register') - { - $pr_data['username'] = $username; - $db_data['username'] = $username; - } - } - $tp_data['CAN_EDIT_USERNAME'] = $can_edit; - $tp_data['USERNAME'] = $pr_data['username']; - break; + if ($submit) { + $err = validate_username($username); + if (!$errors && $err && ($mode == 'register')) { + $errors[] = $err; + } + if ($can_edit && $username != $pr_data['username'] || $mode == 'register') { + $pr_data['username'] = $username; + $db_data['username'] = $username; + } + } + $tp_data['CAN_EDIT_USERNAME'] = $can_edit; + $tp_data['USERNAME'] = $pr_data['username']; + break; - /** - * Пароль (edit, reg) - */ - case 'user_password': - if ($submit) - { - $cur_pass = (string) $_POST['cur_pass']; - $new_pass = (string) $_POST['new_pass']; - $cfm_pass = (string) $_POST['cfm_pass']; + /** + * Пароль (edit, reg) + */ + case 'user_password': + if ($submit) { + $cur_pass = (string)$_POST['cur_pass']; + $new_pass = (string)$_POST['new_pass']; + $cfm_pass = (string)$_POST['cfm_pass']; - // пароль для гостя и при смене пароля юзером - if (!empty($new_pass)) - { - if (mb_strlen($new_pass, 'UTF-8') > 20) - { - $errors[] = sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20); - } - elseif (mb_strlen($new_pass, 'UTF-8') < 4) - { - $errors[] = sprintf($lang['CHOOSE_PASS_ERR_MIN'], 4); - } - elseif ($new_pass != $cfm_pass) - { - $errors[] = $lang['CHOOSE_PASS_ERR']; - } - $db_data['user_password'] = md5(md5($new_pass)); - } + // пароль для гостя и при смене пароля юзером + if (!empty($new_pass)) { + if (mb_strlen($new_pass, 'UTF-8') > 20) { + $errors[] = sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20); + } elseif (mb_strlen($new_pass, 'UTF-8') < 4) { + $errors[] = sprintf($lang['CHOOSE_PASS_ERR_MIN'], 4); + } elseif ($new_pass != $cfm_pass) { + $errors[] = $lang['CHOOSE_PASS_ERR']; + } + $db_data['user_password'] = md5(md5($new_pass)); + } - if ($mode == 'register') - { - if (empty($new_pass)) - { - $errors[] = $lang['CHOOSE_PASS']; - } - } - else - { - if (!empty($cur_pass)) - { - $cur_pass_valid = ($pr_data['user_password'] === md5(md5($cur_pass))); - } - if (!empty($new_pass) && !$cur_pass_valid) - { - $errors[] = $lang['CHOOSE_PASS_FAILED']; - } - } - } - break; + if ($mode == 'register') { + if (empty($new_pass)) { + $errors[] = $lang['CHOOSE_PASS']; + } + } else { + if (!empty($cur_pass)) { + $cur_pass_valid = ($pr_data['user_password'] === md5(md5($cur_pass))); + } + if (!empty($new_pass) && !$cur_pass_valid) { + $errors[] = $lang['CHOOSE_PASS_FAILED']; + } + } + } + break; - /** - * E-mail (edit, reg) - */ - case 'user_email': - $email = !empty($_POST['user_email']) ? (string) $_POST['user_email'] : $pr_data['user_email']; - if ($submit) - { - if ($mode == 'register') - { - if (empty($email)) - { - $errors[] = $lang['CHOOSE_E_MAIL']; - } - if (!$errors && ($err = validate_email($email))) - { - $errors[] = $err; - } - $db_data['user_email'] = $email; - } - else if ($email != $pr_data['user_email']) // если смена мейла юзером - { - if (!$cur_pass_valid) - { - $errors[] = $lang['CONFIRM_PASSWORD_EXPLAIN']; - } - if (!$errors && ($err = validate_email($email))) - { - $errors[] = $err; - } - if ($req_email_activation) - { - $pr_data['user_active'] = 0; - $db_data['user_active'] = 0; - } - $db_data['user_email'] = $email; - } - } - $tp_data['USER_EMAIL'] = htmlCHR($email); - break; + /** + * E-mail (edit, reg) + */ + case 'user_email': + $email = !empty($_POST['user_email']) ? (string)$_POST['user_email'] : $pr_data['user_email']; + if ($submit) { + if ($mode == 'register') { + if (empty($email)) { + $errors[] = $lang['CHOOSE_E_MAIL']; + } + if (!$errors && ($err = validate_email($email))) { + $errors[] = $err; + } + $db_data['user_email'] = $email; + } else if ($email != $pr_data['user_email']) // если смена мейла юзером + { + if (!$cur_pass_valid) { + $errors[] = $lang['CONFIRM_PASSWORD_EXPLAIN']; + } + if (!$errors && ($err = validate_email($email))) { + $errors[] = $err; + } + if ($req_email_activation) { + $pr_data['user_active'] = 0; + $db_data['user_active'] = 0; + } + $db_data['user_email'] = $email; + } + } + $tp_data['USER_EMAIL'] = htmlCHR($email); + break; - /** - * Язык (edit, reg) - */ - case 'user_lang': - $user_lang = isset($_POST['user_lang']) ? (string) $_POST['user_lang'] : $pr_data['user_lang']; - if ($submit && ($user_lang != $pr_data['user_lang'] || $mode == 'register')) - { - $pr_data['user_lang'] = $user_lang; - $db_data['user_lang'] = $user_lang; - } - break; + /** + * Язык (edit, reg) + */ + case 'user_lang': + $user_lang = isset($_POST['user_lang']) ? (string)$_POST['user_lang'] : $pr_data['user_lang']; + if ($submit && ($user_lang != $pr_data['user_lang'] || $mode == 'register')) { + $pr_data['user_lang'] = $user_lang; + $db_data['user_lang'] = $user_lang; + } + break; - /** - * Часовой пояс (edit, reg) - */ - case 'user_timezone': - $user_timezone = isset($_POST['user_timezone']) ? (int) $_POST['user_timezone'] : $pr_data['user_timezone']; - if ($submit && ($user_timezone != $pr_data['user_timezone'] || $mode == 'register')) - { - if (isset($lang['TZ'][$user_timezone])) - { - $pr_data['user_timezone'] = $user_timezone; - $db_data['user_timezone'] = $user_timezone; - } - } - break; + /** + * Часовой пояс (edit, reg) + */ + case 'user_timezone': + $user_timezone = isset($_POST['user_timezone']) ? (int)$_POST['user_timezone'] : $pr_data['user_timezone']; + if ($submit && ($user_timezone != $pr_data['user_timezone'] || $mode == 'register')) { + if (isset($lang['TZ'][$user_timezone])) { + $pr_data['user_timezone'] = $user_timezone; + $db_data['user_timezone'] = $user_timezone; + } + } + break; - /** - * Пол (edit, reg) - */ - case 'user_gender': - $user_gender = isset($_POST['user_gender']) ? (int) $_POST['user_gender'] : $pr_data['user_gender']; - if ($submit && $user_gender != $pr_data['user_gender']) - { - $pr_data['user_gender'] = $user_gender; - $db_data['user_gender'] = $user_gender; - } - $tp_data['USER_GENDER'] = build_select('user_gender', array_flip($lang['GENDER_SELECT']), $pr_data['user_gender']); - break; + /** + * Пол (edit, reg) + */ + case 'user_gender': + $user_gender = isset($_POST['user_gender']) ? (int)$_POST['user_gender'] : $pr_data['user_gender']; + if ($submit && $user_gender != $pr_data['user_gender']) { + $pr_data['user_gender'] = $user_gender; + $db_data['user_gender'] = $user_gender; + } + $tp_data['USER_GENDER'] = build_select('user_gender', array_flip($lang['GENDER_SELECT']), $pr_data['user_gender']); + break; - /** - * Возраст (edit) - */ - case 'user_birthday': - $user_birthday = isset($_POST['user_birthday']) ? (string) $_POST['user_birthday'] : $pr_data['user_birthday']; + /** + * Возраст (edit) + */ + case 'user_birthday': + $user_birthday = isset($_POST['user_birthday']) ? (string)$_POST['user_birthday'] : $pr_data['user_birthday']; - if ($submit && $user_birthday != $pr_data['user_birthday']) - { - $birthday_date = date_parse($user_birthday); + if ($submit && $user_birthday != $pr_data['user_birthday']) { + $birthday_date = date_parse($user_birthday); - if (!empty($birthday_date['year'])) - { - if (strtotime($user_birthday) >= TIMENOW) - { - $errors[] = $lang['WRONG_BIRTHDAY_FORMAT']; - } - elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] > $di->config->get('birthday_max_age')) - { - $errors[] = sprintf($lang['BIRTHDAY_TO_HIGH'], $di->config->get('birthday_max_age')); - } - elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] < $di->config->get('birthday_min_age')) - { - $errors[] = sprintf($lang['BIRTHDAY_TO_LOW'], $di->config->get('birthday_min_age')); - } - } + if (!empty($birthday_date['year'])) { + if (strtotime($user_birthday) >= TIMENOW) { + $errors[] = $lang['WRONG_BIRTHDAY_FORMAT']; + } elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] > $di->config->get('birthday_max_age')) { + $errors[] = sprintf($lang['BIRTHDAY_TO_HIGH'], $di->config->get('birthday_max_age')); + } elseif (bb_date(TIMENOW, 'Y', false) - $birthday_date['year'] < $di->config->get('birthday_min_age')) { + $errors[] = sprintf($lang['BIRTHDAY_TO_LOW'], $di->config->get('birthday_min_age')); + } + } - $pr_data['user_birthday'] = $user_birthday; - $db_data['user_birthday'] = $user_birthday; - } - $tp_data['USER_BIRTHDAY'] = $pr_data['user_birthday']; - break; + $pr_data['user_birthday'] = $user_birthday; + $db_data['user_birthday'] = $user_birthday; + } + $tp_data['USER_BIRTHDAY'] = $pr_data['user_birthday']; + break; - /** - * opt (edit) - */ - case 'user_opt': - $user_opt = $pr_data['user_opt']; - $reg_mode = ($mode == 'register'); + /** + * opt (edit) + */ + case 'user_opt': + $user_opt = $pr_data['user_opt']; + $reg_mode = ($mode == 'register'); - $update_user_opt = array( - # 'user_opt_name' => ($reg_mode) ? #reg_value : #in_login_change - 'user_viewemail' => ($reg_mode) ? false : true, - 'user_viewonline' => ($reg_mode) ? false : true, - 'user_notify' => ($reg_mode) ? true : true, - 'user_notify_pm' => ($reg_mode) ? true : true, - 'user_porn_forums' => ($reg_mode) ? false : true, - 'user_dls' => ($reg_mode) ? false : true, - 'user_callseed' => ($reg_mode) ? true : true, - 'user_retracker' => ($reg_mode) ? true : true, - ); + $update_user_opt = array( + # 'user_opt_name' => ($reg_mode) ? #reg_value : #in_login_change + 'user_viewemail' => ($reg_mode) ? false : true, + 'user_viewonline' => ($reg_mode) ? false : true, + 'user_notify' => ($reg_mode) ? true : true, + 'user_notify_pm' => ($reg_mode) ? true : true, + 'user_porn_forums' => ($reg_mode) ? false : true, + 'user_dls' => ($reg_mode) ? false : true, + 'user_callseed' => ($reg_mode) ? true : true, + 'user_retracker' => ($reg_mode) ? true : true, + ); - foreach ($update_user_opt as $opt => $can_change_opt) - { - if ($submit && (isset($_POST[$opt]) && $can_change_opt || $reg_mode)) - { - $change_opt = ($reg_mode) ? $can_change_opt : !empty($_POST[$opt]); - setbit($user_opt, $bf['user_opt'][$opt], $change_opt); - } - $tp_data[strtoupper($opt)] = bf($user_opt, 'user_opt', $opt); - } - if ($submit && ($user_opt != $pr_data['user_opt'] || $reg_mode)) - { - $pr_data['user_opt'] = $user_opt; - $db_data['user_opt'] = (int) $user_opt; - } - break; + foreach ($update_user_opt as $opt => $can_change_opt) { + if ($submit && (isset($_POST[$opt]) && $can_change_opt || $reg_mode)) { + $change_opt = ($reg_mode) ? $can_change_opt : !empty($_POST[$opt]); + setbit($user_opt, $bf['user_opt'][$opt], $change_opt); + } + $tp_data[strtoupper($opt)] = bf($user_opt, 'user_opt', $opt); + } + if ($submit && ($user_opt != $pr_data['user_opt'] || $reg_mode)) { + $pr_data['user_opt'] = $user_opt; + $db_data['user_opt'] = (int)$user_opt; + } + break; - /** - * Avatar (edit) - */ - case 'avatar_ext_id': - if ($submit && !bf($pr_data['user_opt'], 'user_opt', 'dis_avatar')) - { - if (isset($_POST['delete_avatar'])) - { - delete_avatar($pr_data['user_id'], $pr_data['avatar_ext_id']); - $pr_data['avatar_ext_id'] = 0; - $db_data['avatar_ext_id'] = 0; - } - elseif (!empty($_FILES['avatar']['name']) && $di->config->get('avatars.up_allowed')) - { - require(INC_DIR .'functions_upload.php'); - $upload = new upload_common(); + /** + * Avatar (edit) + */ + case 'avatar_ext_id': + if ($submit && !bf($pr_data['user_opt'], 'user_opt', 'dis_avatar')) { + if (isset($_POST['delete_avatar'])) { + delete_avatar($pr_data['user_id'], $pr_data['avatar_ext_id']); + $pr_data['avatar_ext_id'] = 0; + $db_data['avatar_ext_id'] = 0; + } elseif (!empty($_FILES['avatar']['name']) && $di->config->get('avatars.up_allowed')) { + require(INC_DIR . 'functions_upload.php'); + $upload = new upload_common(); - if ($upload->init($di->config->get('avatars'), $_FILES['avatar']) && $upload->store('avatar', $pr_data)) - { - $pr_data['avatar_ext_id'] = $upload->file_ext_id; - $db_data['avatar_ext_id'] = (int) $upload->file_ext_id; - } - else - { - $errors = array_merge($errors, $upload->errors); - } - } - } - $tp_data['AVATARS_MAX_SIZE'] = humn_size($di->config->get('avatars.max_size')); - break; + if ($upload->init($di->config->get('avatars'), $_FILES['avatar']) && $upload->store('avatar', $pr_data)) { + $pr_data['avatar_ext_id'] = $upload->file_ext_id; + $db_data['avatar_ext_id'] = (int)$upload->file_ext_id; + } else { + $errors = array_merge($errors, $upload->errors); + } + } + } + $tp_data['AVATARS_MAX_SIZE'] = humn_size($di->config->get('avatars.max_size')); + break; - /** - * ICQ (edit) - */ - case 'user_icq': - $icq = isset($_POST['user_icq']) ? (string) $_POST['user_icq'] : $pr_data['user_icq']; - if ($submit && $icq != $pr_data['user_icq']) - { - if ($icq == '' || preg_match('#^\d{6,15}$#', $icq)) - { - $pr_data['user_icq'] = $icq; - $db_data['user_icq'] = (string) $icq; - } - else - { - $pr_data['user_icq'] = ''; - $errors[] = htmlCHR($lang['ICQ_ERROR']); - } - } - $tp_data['USER_ICQ'] = $pr_data['user_icq']; - break; + /** + * ICQ (edit) + */ + case 'user_icq': + $icq = isset($_POST['user_icq']) ? (string)$_POST['user_icq'] : $pr_data['user_icq']; + if ($submit && $icq != $pr_data['user_icq']) { + if ($icq == '' || preg_match('#^\d{6,15}$#', $icq)) { + $pr_data['user_icq'] = $icq; + $db_data['user_icq'] = (string)$icq; + } else { + $pr_data['user_icq'] = ''; + $errors[] = htmlCHR($lang['ICQ_ERROR']); + } + } + $tp_data['USER_ICQ'] = $pr_data['user_icq']; + break; - /** - * Сайт (edit) - */ - case 'user_website': - $website = isset($_POST['user_website']) ? (string) $_POST['user_website'] : $pr_data['user_website']; - $website = htmlCHR($website); - if ($submit && $website != $pr_data['user_website']) - { - if ($website == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $website)) - { - $pr_data['user_website'] = $website; - $db_data['user_website'] = (string) $website; - } - else - { - $pr_data['user_website'] = ''; - $errors[] = htmlCHR($lang['WEBSITE_ERROR']); - } - } - $tp_data['USER_WEBSITE'] = $pr_data['user_website']; - break; + /** + * Сайт (edit) + */ + case 'user_website': + $website = isset($_POST['user_website']) ? (string)$_POST['user_website'] : $pr_data['user_website']; + $website = htmlCHR($website); + if ($submit && $website != $pr_data['user_website']) { + if ($website == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $website)) { + $pr_data['user_website'] = $website; + $db_data['user_website'] = (string)$website; + } else { + $pr_data['user_website'] = ''; + $errors[] = htmlCHR($lang['WEBSITE_ERROR']); + } + } + $tp_data['USER_WEBSITE'] = $pr_data['user_website']; + break; - /** - * Откуда (edit) - */ - case 'user_from': - $from = isset($_POST['user_from']) ? (string) $_POST['user_from'] : $pr_data['user_from']; - $from = htmlCHR($from); - if ($submit && $from != $pr_data['user_from']) - { - $pr_data['user_from'] = $from; - $db_data['user_from'] = (string) $from; - } - $tp_data['USER_FROM'] = $pr_data['user_from']; - break; + /** + * Откуда (edit) + */ + case 'user_from': + $from = isset($_POST['user_from']) ? (string)$_POST['user_from'] : $pr_data['user_from']; + $from = htmlCHR($from); + if ($submit && $from != $pr_data['user_from']) { + $pr_data['user_from'] = $from; + $db_data['user_from'] = (string)$from; + } + $tp_data['USER_FROM'] = $pr_data['user_from']; + break; - /** - * Подпись (edit) - */ - case 'user_sig': - $sig = isset($_POST['user_sig']) ? (string) $_POST['user_sig'] : $pr_data['user_sig']; - if ($submit && $sig != $pr_data['user_sig']) - { - $sig = prepare_message($sig); + /** + * Подпись (edit) + */ + case 'user_sig': + $sig = isset($_POST['user_sig']) ? (string)$_POST['user_sig'] : $pr_data['user_sig']; + if ($submit && $sig != $pr_data['user_sig']) { + $sig = prepare_message($sig); - if (mb_strlen($sig, 'UTF-8') > $di->config->get('max_sig_chars')) - { - $errors[] = $lang['SIGNATURE_TOO_LONG']; - } - else if (preg_match('#<(a|b|i|u|table|tr|td|img) #i', $sig) || preg_match('#(href|src|target|title)=#i', $sig)) - { - $errors[] = $lang['SIGNATURE_ERROR_HTML']; - } + if (mb_strlen($sig, 'UTF-8') > $di->config->get('max_sig_chars')) { + $errors[] = $lang['SIGNATURE_TOO_LONG']; + } else if (preg_match('#<(a|b|i|u|table|tr|td|img) #i', $sig) || preg_match('#(href|src|target|title)=#i', $sig)) { + $errors[] = $lang['SIGNATURE_ERROR_HTML']; + } - $pr_data['user_sig'] = $sig; - $db_data['user_sig'] = (string) $sig; - } - $tp_data['USER_SIG'] = $pr_data['user_sig']; - break; + $pr_data['user_sig'] = $sig; + $db_data['user_sig'] = (string)$sig; + } + $tp_data['USER_SIG'] = $pr_data['user_sig']; + break; - /** - * Род занятий (edit) - */ - case 'user_occ': - $occ = isset($_POST['user_occ']) ? (string) $_POST['user_occ'] : $pr_data['user_occ']; - $occ = htmlCHR($occ); - if ($submit && $occ != $pr_data['user_occ']) - { - $pr_data['user_occ'] = $occ; - $db_data['user_occ'] = (string) $occ; - } - $tp_data['USER_OCC'] = $pr_data['user_occ']; - break; + /** + * Род занятий (edit) + */ + case 'user_occ': + $occ = isset($_POST['user_occ']) ? (string)$_POST['user_occ'] : $pr_data['user_occ']; + $occ = htmlCHR($occ); + if ($submit && $occ != $pr_data['user_occ']) { + $pr_data['user_occ'] = $occ; + $db_data['user_occ'] = (string)$occ; + } + $tp_data['USER_OCC'] = $pr_data['user_occ']; + break; - /** - * Интересы - */ - case 'user_interests': - $interests = isset($_POST['user_interests']) ? (string) $_POST['user_interests'] : $pr_data['user_interests']; - $interests = htmlCHR($interests); - if ($submit && $interests != $pr_data['user_interests']) - { - $pr_data['user_interests'] = $interests; - $db_data['user_interests'] = (string) $interests; - } - $tp_data['USER_INTERESTS'] = $pr_data['user_interests']; - break; + /** + * Интересы + */ + case 'user_interests': + $interests = isset($_POST['user_interests']) ? (string)$_POST['user_interests'] : $pr_data['user_interests']; + $interests = htmlCHR($interests); + if ($submit && $interests != $pr_data['user_interests']) { + $pr_data['user_interests'] = $interests; + $db_data['user_interests'] = (string)$interests; + } + $tp_data['USER_INTERESTS'] = $pr_data['user_interests']; + break; - /** - * Skype - */ - case 'user_skype': - $skype = isset($_POST['user_skype']) ? (string) $_POST['user_skype'] : $pr_data['user_skype']; - if ($submit && $skype != $pr_data['user_skype']) - { - if ($skype != '' && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $skype)) - { - $errors[] = $lang['SKYPE_ERROR']; - } - $pr_data['user_skype'] = $skype; - $db_data['user_skype'] = (string) $skype; - } - $tp_data['USER_SKYPE'] = $pr_data['user_skype']; - break; + /** + * Skype + */ + case 'user_skype': + $skype = isset($_POST['user_skype']) ? (string)$_POST['user_skype'] : $pr_data['user_skype']; + if ($submit && $skype != $pr_data['user_skype']) { + if ($skype != '' && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $skype)) { + $errors[] = $lang['SKYPE_ERROR']; + } + $pr_data['user_skype'] = $skype; + $db_data['user_skype'] = (string)$skype; + } + $tp_data['USER_SKYPE'] = $pr_data['user_skype']; + break; - /** - * Twitter - */ - case 'user_twitter': - $twitter = isset($_POST['user_twitter']) ? (string) $_POST['user_twitter'] : $pr_data['user_twitter']; - if ($submit && $twitter != $pr_data['user_twitter']) - { - if ($twitter != '' && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $twitter)) - { - $errors[] = $lang['TWITTER_ERROR']; - } - $pr_data['user_twitter'] = $twitter; - $db_data['user_twitter'] = (string) $twitter; - } - $tp_data['USER_TWITTER'] = $pr_data['user_twitter']; - break; + /** + * Twitter + */ + case 'user_twitter': + $twitter = isset($_POST['user_twitter']) ? (string)$_POST['user_twitter'] : $pr_data['user_twitter']; + if ($submit && $twitter != $pr_data['user_twitter']) { + if ($twitter != '' && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $twitter)) { + $errors[] = $lang['TWITTER_ERROR']; + } + $pr_data['user_twitter'] = $twitter; + $db_data['user_twitter'] = (string)$twitter; + } + $tp_data['USER_TWITTER'] = $pr_data['user_twitter']; + break; - /** - * Выбор шаблона (edit) - */ - case 'tpl_name': - $templates = isset($_POST['tpl_name']) ? (string) $_POST['tpl_name'] : $pr_data['tpl_name']; - $templates = htmlCHR($templates); - if ($submit && $templates != $pr_data['tpl_name']) - { - $pr_data['tpl_name'] = $di->config->get('tpl_name'); - $db_data['tpl_name'] = (string) $di->config->get('tpl_name'); - foreach ($di->config->get('templates') as $folder => $name) - { - if ($templates == $folder) - { - $pr_data['tpl_name'] = $templates; - $db_data['tpl_name'] = (string) $templates; - } - } - } - $tp_data['TEMPLATES_SELECT'] = templates_select($pr_data['tpl_name'], 'tpl_name'); - break; + /** + * Выбор шаблона (edit) + */ + case 'tpl_name': + $templates = isset($_POST['tpl_name']) ? (string)$_POST['tpl_name'] : $pr_data['tpl_name']; + $templates = htmlCHR($templates); + if ($submit && $templates != $pr_data['tpl_name']) { + $pr_data['tpl_name'] = $di->config->get('tpl_name'); + $db_data['tpl_name'] = (string)$di->config->get('tpl_name'); + foreach ($di->config->get('templates') as $folder => $name) { + if ($templates == $folder) { + $pr_data['tpl_name'] = $templates; + $db_data['tpl_name'] = (string)$templates; + } + } + } + $tp_data['TEMPLATES_SELECT'] = templates_select($pr_data['tpl_name'], 'tpl_name'); + break; - /** - * default - */ - default: - trigger_error("invalid profile field: $field", E_USER_ERROR); - } + /** + * default + */ + default: + trigger_error("invalid profile field: $field", E_USER_ERROR); + } } // submit -if ($submit && !$errors) -{ - /** - * Создание нового профиля - */ - if ($mode == 'register') - { - if ($req_email_activation) - { - $user_actkey = make_rand_str(12); - $db_data['user_active'] = 0; - $db_data['user_actkey'] = $user_actkey; - } - else - { - $db_data['user_active'] = 1; - $db_data['user_actkey'] = ''; - } - $db_data['user_regdate'] = TIMENOW; +if ($submit && !$errors) { + /** + * Создание нового профиля + */ + if ($mode == 'register') { + if ($req_email_activation) { + $user_actkey = make_rand_str(12); + $db_data['user_active'] = 0; + $db_data['user_actkey'] = $user_actkey; + } else { + $db_data['user_active'] = 1; + $db_data['user_actkey'] = ''; + } + $db_data['user_regdate'] = TIMENOW; - if (!IS_ADMIN) $db_data['user_reg_ip'] = USER_IP; + if (!IS_ADMIN) $db_data['user_reg_ip'] = USER_IP; - if (!isset($db_data['tpl_name'])) $db_data['tpl_name'] = (string) $di->config->get('tpl_name'); + if (!isset($db_data['tpl_name'])) $db_data['tpl_name'] = (string)$di->config->get('tpl_name'); - $sql_args = DB()->build_array('INSERT', $db_data); + $sql_args = DB()->build_array('INSERT', $db_data); - DB()->query("INSERT INTO ". BB_USERS . $sql_args); - $new_user_id = DB()->sql_nextid(); + DB()->query("INSERT INTO " . BB_USERS . $sql_args); + $new_user_id = DB()->sql_nextid(); - if (IS_ADMIN) - { - set_pr_die_append_msg($new_user_id); - $message = $lang['ACCOUNT_ADDED']; - } - else - { - if ($req_email_activation) - { - $message = $lang['ACCOUNT_INACTIVE']; - $email_template = 'user_welcome_inactive'; - } - else - { - $message = $lang['ACCOUNT_ADDED']; - $email_template = 'user_welcome'; - } + if (IS_ADMIN) { + set_pr_die_append_msg($new_user_id); + $message = $lang['ACCOUNT_ADDED']; + } else { + if ($req_email_activation) { + $message = $lang['ACCOUNT_INACTIVE']; + $email_template = 'user_welcome_inactive'; + } else { + $message = $lang['ACCOUNT_ADDED']; + $email_template = 'user_welcome'; + } - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($username ." <{$email}>"); - $emailer->use_template($email_template, $user_lang); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>"); + $emailer->email_address($username . " <{$email}>"); + $emailer->use_template($email_template, $user_lang); - $emailer->assign_vars(array( - 'SITENAME' => $di->config->get('sitename'), - 'WELCOME_MSG' => sprintf($lang['WELCOME_SUBJECT'], $di->config->get('sitename')), - 'USERNAME' => html_entity_decode($username), - 'PASSWORD' => $new_pass, - 'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $new_user_id . '&act_key=' . $db_data['user_actkey']) - )); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('sitename'), + 'WELCOME_MSG' => sprintf($lang['WELCOME_SUBJECT'], $di->config->get('sitename')), + 'USERNAME' => html_entity_decode($username), + 'PASSWORD' => $new_pass, + 'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $new_user_id . '&act_key=' . $db_data['user_actkey']) + )); - $emailer->send(); - $emailer->reset(); - } + $emailer->send(); + $emailer->reset(); + } - bb_die($message); - } - /** - * Редактирование - */ - else - { - set_pr_die_append_msg($pr_data['user_id']); + bb_die($message); + } /** + * Редактирование + */ + else { + set_pr_die_append_msg($pr_data['user_id']); - // если что-то было изменено - if ($db_data) - { - if (!$pr_data['user_active']) - { - $user_actkey = make_rand_str(12); - $pr_data['user_actkey'] = $user_actkey; - $db_data['user_actkey'] = $user_actkey; + // если что-то было изменено + if ($db_data) { + if (!$pr_data['user_active']) { + $user_actkey = make_rand_str(12); + $pr_data['user_actkey'] = $user_actkey; + $db_data['user_actkey'] = $user_actkey; - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address($username ." <{$email}>"); - $emailer->use_template('user_activate', $pr_data['user_lang']); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>"); + $emailer->email_address($username . " <{$email}>"); + $emailer->use_template('user_activate', $pr_data['user_lang']); - $emailer->assign_vars(array( - 'SITENAME' => $di->config->get('sitename'), - 'USERNAME' => html_entity_decode($username), - 'U_ACTIVATE' => make_url("profile.php?mode=activate&u={$pr_data['user_id']}&act_key=$user_actkey"), - )); - $emailer->send(); - $emailer->reset(); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('sitename'), + 'USERNAME' => html_entity_decode($username), + 'U_ACTIVATE' => make_url("profile.php?mode=activate&u={$pr_data['user_id']}&act_key=$user_actkey"), + )); + $emailer->send(); + $emailer->reset(); - $message = $lang['PROFILE_UPDATED_INACTIVE']; - $user->session_end(); - } - else - { - meta_refresh('index.php' , 10); - $message = $lang['PROFILE_UPDATED']; - } + $message = $lang['PROFILE_UPDATED_INACTIVE']; + $user->session_end(); + } else { + meta_refresh('index.php', 10); + $message = $lang['PROFILE_UPDATED']; + } - $sql_args = DB()->build_array('UPDATE', $db_data); + $sql_args = DB()->build_array('UPDATE', $db_data); - DB()->query("UPDATE ". BB_USERS ." SET $sql_args WHERE user_id = {$pr_data['user_id']} LIMIT 1"); + DB()->query("UPDATE " . BB_USERS . " SET $sql_args WHERE user_id = {$pr_data['user_id']} LIMIT 1"); - if ($pr_data['user_id'] != $userdata['user_id']) - { - if ($pr_data['user_level'] == MOD && !empty($db_data['username'])) - { - $datastore->update('moderators'); - } - } + if ($pr_data['user_id'] != $userdata['user_id']) { + if ($pr_data['user_level'] == MOD && !empty($db_data['username'])) { + $datastore->update('moderators'); + } + } - cache_rm_user_sessions ($pr_data['user_id']); + cache_rm_user_sessions($pr_data['user_id']); - if ($adm_edit) - { - bb_die($lang['PROFILE_USER'] . ' '. profile_url($pr_data) .' '. $lang['GOOD_UPDATE']); - } - elseif (!$pr_data['user_active']) - { - bb_die($lang['PROFILE_UPDATED_INACTIVE']); - } - else - { - meta_refresh('index.php' , 10); - bb_die($lang['PROFILE_UPDATED']); - } - } - else - { - bb_die($lang['NOTHING_HAS_CHANGED']); - } - } + if ($adm_edit) { + bb_die($lang['PROFILE_USER'] . ' ' . profile_url($pr_data) . ' ' . $lang['GOOD_UPDATE']); + } elseif (!$pr_data['user_active']) { + bb_die($lang['PROFILE_UPDATED_INACTIVE']); + } else { + meta_refresh('index.php', 10); + bb_die($lang['PROFILE_UPDATED']); + } + } else { + bb_die($lang['NOTHING_HAS_CHANGED']); + } + } } $template->assign_vars($tp_data); $template->assign_vars(array( - 'PAGE_TITLE' => ($mode == 'editprofile') ? $lang['EDIT_PROFILE'] . ($adm_edit ? " :: {$pr_data['username']}" : '') : $lang['REGISTER'], - 'SHOW_REG_AGREEMENT' => ($mode == 'register' && !IS_ADMIN), - 'ERROR_MESSAGE' => ($errors) ? join('
        ', array_unique($errors)) : '', - 'MODE' => $mode, - 'EDIT_PROFILE' => ($mode == 'editprofile'), - 'ADM_EDIT' => $adm_edit, - 'SHOW_PASS' => ($adm_edit || ($mode == 'register' && IS_ADMIN)), - 'CAPTCHA_HTML' => ($need_captcha) ? bb_captcha('get') : '', + 'PAGE_TITLE' => ($mode == 'editprofile') ? $lang['EDIT_PROFILE'] . ($adm_edit ? " :: {$pr_data['username']}" : '') : $lang['REGISTER'], + 'SHOW_REG_AGREEMENT' => ($mode == 'register' && !IS_ADMIN), + 'ERROR_MESSAGE' => ($errors) ? join('
        ', array_unique($errors)) : '', + 'MODE' => $mode, + 'EDIT_PROFILE' => ($mode == 'editprofile'), + 'ADM_EDIT' => $adm_edit, + 'SHOW_PASS' => ($adm_edit || ($mode == 'register' && IS_ADMIN)), + 'CAPTCHA_HTML' => ($need_captcha) ? bb_captcha('get') : '', - 'LANGUAGE_SELECT' => language_select($pr_data['user_lang'], 'user_lang'), - 'TIMEZONE_SELECT' => tz_select($pr_data['user_timezone'], 'user_timezone'), - 'USER_TIMEZONE' => $pr_data['user_timezone'], + 'LANGUAGE_SELECT' => language_select($pr_data['user_lang'], 'user_lang'), + 'TIMEZONE_SELECT' => tz_select($pr_data['user_timezone'], 'user_timezone'), + 'USER_TIMEZONE' => $pr_data['user_timezone'], - 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], $di->config->get('avatars.max_width'), $di->config->get('avatars.max_height'), (round($di->config->get('avatars.max_size') / 1024))), - 'AVATAR_DISALLOWED' => bf($pr_data['user_opt'], 'user_opt', 'dis_avatar'), - 'AVATAR_DIS_EXPLAIN' => sprintf($lang['AVATAR_DISABLE'], $di->config->get('terms_and_conditions_url')), - 'AVATAR_IMG' => get_avatar($pr_data['user_id'], $pr_data['avatar_ext_id'], !bf($pr_data['user_opt'], 'user_opt', 'dis_avatar')), + 'AVATAR_EXPLAIN' => sprintf($lang['AVATAR_EXPLAIN'], $di->config->get('avatars.max_width'), $di->config->get('avatars.max_height'), (round($di->config->get('avatars.max_size') / 1024))), + 'AVATAR_DISALLOWED' => bf($pr_data['user_opt'], 'user_opt', 'dis_avatar'), + 'AVATAR_DIS_EXPLAIN' => sprintf($lang['AVATAR_DISABLE'], $di->config->get('terms_and_conditions_url')), + 'AVATAR_IMG' => get_avatar($pr_data['user_id'], $pr_data['avatar_ext_id'], !bf($pr_data['user_opt'], 'user_opt', 'dis_avatar')), - 'SIGNATURE_EXPLAIN' => sprintf($lang['SIGNATURE_EXPLAIN'], $di->config->get('max_sig_chars')), - 'SIG_DISALLOWED' => bf($pr_data['user_opt'], 'user_opt', 'dis_sig'), + 'SIGNATURE_EXPLAIN' => sprintf($lang['SIGNATURE_EXPLAIN'], $di->config->get('max_sig_chars')), + 'SIG_DISALLOWED' => bf($pr_data['user_opt'], 'user_opt', 'dis_sig'), - 'PR_USER_ID' => $pr_data['user_id'], - 'U_RESET_AUTOLOGIN' => LOGIN_URL . "?logout=1&reset_autologin=1&sid={$userdata['session_id']}", + 'PR_USER_ID' => $pr_data['user_id'], + 'U_RESET_AUTOLOGIN' => LOGIN_URL . "?logout=1&reset_autologin=1&sid={$userdata['session_id']}", )); -print_page('usercp_register.tpl'); \ No newline at end of file +print_page('usercp_register.tpl'); diff --git a/library/includes/ucp/sendpasswd.php b/library/includes/ucp/sendpasswd.php index 9e244bb89..e9d60675f 100644 --- a/library/includes/ucp/sendpasswd.php +++ b/library/includes/ucp/sendpasswd.php @@ -11,78 +11,66 @@ if ($di->config->get('emailer_disabled')) bb_die($lang['EMAILER_DISABLED']); $need_captcha = ($_GET['mode'] == 'sendpassword' && !IS_ADMIN && !$di->config->get('captcha.disabled')); -if (isset($_POST['submit'])) -{ - if ($need_captcha && !bb_captcha('check')) bb_die($lang['CAPTCHA_WRONG']); - $email = (!empty($_POST['email'])) ? trim(strip_tags(htmlspecialchars($_POST['email']))) : ''; - $sql = "SELECT * FROM " . BB_USERS . " WHERE user_email = '" . DB()->escape($email)."'"; - if ($result = DB()->sql_query($sql)) - { - if ( $row = DB()->sql_fetchrow($result) ) - { - if (!$row['user_active']) - { - bb_die($lang['NO_SEND_ACCOUNT_INACTIVE']); - } - if (in_array($row['user_level'], array(MOD, ADMIN))) - { - bb_die($lang['NO_SEND_ACCOUNT']); - } +if (isset($_POST['submit'])) { + if ($need_captcha && !bb_captcha('check')) bb_die($lang['CAPTCHA_WRONG']); + $email = (!empty($_POST['email'])) ? trim(strip_tags(htmlspecialchars($_POST['email']))) : ''; + $sql = "SELECT * FROM " . BB_USERS . " WHERE user_email = '" . DB()->escape($email) . "'"; + if ($result = DB()->sql_query($sql)) { + if ($row = DB()->sql_fetchrow($result)) { + if (!$row['user_active']) { + bb_die($lang['NO_SEND_ACCOUNT_INACTIVE']); + } + if (in_array($row['user_level'], array(MOD, ADMIN))) { + bb_die($lang['NO_SEND_ACCOUNT']); + } - $username = $row['username']; - $user_id = $row['user_id']; + $username = $row['username']; + $user_id = $row['user_id']; - $user_actkey = make_rand_str(12); - $user_password = make_rand_str(8); + $user_actkey = make_rand_str(12); + $user_password = make_rand_str(8); - $sql = "UPDATE " . BB_USERS . " + $sql = "UPDATE " . BB_USERS . " SET user_newpasswd = '$user_password', user_actkey = '$user_actkey' WHERE user_id = " . $row['user_id']; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update new password information'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update new password information'); + } - require(CLASS_DIR .'emailer.php'); - $emailer = new emailer($di->config->get('smtp_delivery')); + require(CLASS_DIR . 'emailer.php'); + $emailer = new emailer($di->config->get('smtp_delivery')); - $emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); - $emailer->email_address("$username <{$row['user_email']}>"); + $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>"); + $emailer->email_address("$username <{$row['user_email']}>"); - $emailer->use_template('user_activate_passwd', $row['user_lang']); + $emailer->use_template('user_activate_passwd', $row['user_lang']); - $emailer->assign_vars(array( - 'SITENAME' => $di->config->get('sitename'), - 'USERNAME' => $username, - 'PASSWORD' => $user_password, - 'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey) - )); - $emailer->send(); - $emailer->reset(); + $emailer->assign_vars(array( + 'SITENAME' => $di->config->get('sitename'), + 'USERNAME' => $username, + 'PASSWORD' => $user_password, + 'U_ACTIVATE' => make_url('profile.php?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey) + )); + $emailer->send(); + $emailer->reset(); - bb_die($lang['PASSWORD_UPDATED']); - } - else - { - bb_die($lang['NO_EMAIL_MATCH']); - } - } - else - { - bb_die('Could not obtain user information for sendpassword'); - } -} -else -{ - $email = $username = ''; + bb_die($lang['PASSWORD_UPDATED']); + } else { + bb_die($lang['NO_EMAIL_MATCH']); + } + } else { + bb_die('Could not obtain user information for sendpassword'); + } +} else { + $email = $username = ''; } $template->assign_vars(array( - 'USERNAME' => $username, - 'EMAIL' => $email, - 'CAPTCHA_HTML' => ($need_captcha) ? bb_captcha('get') : '', - 'S_HIDDEN_FIELDS' => '', - 'S_PROFILE_ACTION' => "profile.php?mode=sendpassword", + 'USERNAME' => $username, + 'EMAIL' => $email, + 'CAPTCHA_HTML' => ($need_captcha) ? bb_captcha('get') : '', + 'S_HIDDEN_FIELDS' => '', + 'S_PROFILE_ACTION' => "profile.php?mode=sendpassword", )); -print_page('usercp_sendpasswd.tpl'); \ No newline at end of file +print_page('usercp_sendpasswd.tpl'); diff --git a/library/includes/ucp/topic_watch.php b/library/includes/ucp/topic_watch.php index 1be7cb5c1..999adb60c 100644 --- a/library/includes/ucp/topic_watch.php +++ b/library/includes/ucp/topic_watch.php @@ -3,12 +3,11 @@ /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -if (empty($di->config->get('topic_notify_enabled'))) -{ - bb_die($lang['DISABLED']); +if (empty($di->config->get('topic_notify_enabled'))) { + bb_die($lang['DISABLED']); } -$page_cfg['use_tablesorter'] = true; +$page_cfg['use_tablesorter'] = true; $page_cfg['include_bbcode_js'] = true; $tracking_topics = get_tracks('topic'); @@ -16,35 +15,31 @@ $user_id = $userdata['user_id']; $start = isset($_GET['start']) ? abs(intval($_GET['start'])) : 0; $per_page = $di->config->get('topics_per_page'); -if (isset($_POST['topic_id_list'])) -{ - $topic_ids = implode(",", $_POST['topic_id_list']); - $sql = "DELETE FROM ". BB_TOPICS_WATCH ." WHERE topic_id IN(". $topic_ids .") AND user_id = $user_id"; - if (!($result = DB() ->sql_query($sql))) - { - bb_die('Could not delete topic watch information #1'); - } +if (isset($_POST['topic_id_list'])) { + $topic_ids = implode(",", $_POST['topic_id_list']); + $sql = "DELETE FROM " . BB_TOPICS_WATCH . " WHERE topic_id IN(" . $topic_ids . ") AND user_id = $user_id"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not delete topic watch information #1'); + } } $template->assign_vars(array( - 'PAGE_TITLE' => $lang['WATCHED_TOPICS'], - 'S_FORM_ACTION' => BB_ROOT .'profile.php?mode=watch', + 'PAGE_TITLE' => $lang['WATCHED_TOPICS'], + 'S_FORM_ACTION' => BB_ROOT . 'profile.php?mode=watch', )); -$sql = "SELECT COUNT(topic_id) as watch_count FROM ". BB_TOPICS_WATCH ." WHERE user_id = $user_id"; -if ( !($result = DB() ->sql_query($sql)) ) -{ - bb_die('Could not obtain watch topic information #2'); +$sql = "SELECT COUNT(topic_id) as watch_count FROM " . BB_TOPICS_WATCH . " WHERE user_id = $user_id"; +if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain watch topic information #2'); } -$row = DB() ->sql_fetchrow($result); -$watch_count = ( $row['watch_count'] ) ? $row['watch_count'] : 0; -DB() ->sql_freeresult($result); +$row = DB()->sql_fetchrow($result); +$watch_count = ($row['watch_count']) ? $row['watch_count'] : 0; +DB()->sql_freeresult($result); -if ($watch_count > 0) -{ - $sql = "SELECT w.*, t.*, f.*, u.*, u2.username as last_username, u2.user_id as last_user_id, +if ($watch_count > 0) { + $sql = "SELECT w.*, t.*, f.*, u.*, u2.username as last_username, u2.user_id as last_user_id, u2.user_level as last_user_level, u2.user_rank as last_user_rank - FROM ". BB_TOPICS_WATCH ." w, ". BB_TOPICS ." t, ". BB_USERS ." u, ". BB_FORUMS ." f, ". BB_POSTS ." p, " . BB_USERS . " u2 + FROM " . BB_TOPICS_WATCH . " w, " . BB_TOPICS . " t, " . BB_USERS . " u, " . BB_FORUMS . " f, " . BB_POSTS . " p, " . BB_USERS . " u2 WHERE w.topic_id = t.topic_id AND t.forum_id = f.forum_id AND p.post_id = t.topic_last_post_id @@ -53,51 +48,46 @@ if ($watch_count > 0) AND w.user_id = $user_id GROUP BY t.topic_last_post_time DESC LIMIT $start, $per_page"; - if (!($result = DB() ->sql_query($sql))) - { - bb_die('Could not obtain watch topic information #3'); - } - $watch = DB() ->sql_fetchrowset($result); + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not obtain watch topic information #3'); + } + $watch = DB()->sql_fetchrowset($result); - if ($watch) - { - for ( $i = 0; $i < count($watch); $i++ ) - { - $is_unread = is_unread($watch[$i]['topic_last_post_time'], $watch[$i]['topic_id'], $watch[$i]['forum_id']); + if ($watch) { + for ($i = 0; $i < count($watch); $i++) { + $is_unread = is_unread($watch[$i]['topic_last_post_time'], $watch[$i]['topic_id'], $watch[$i]['forum_id']); - $template->assign_block_vars('watch', array( - 'ROW_CLASS' => ( !($i % 2) ) ? 'row1' : 'row2', - 'POST_ID' => $watch[$i]['topic_first_post_id'], - 'TOPIC_ID' => $watch[$i]['topic_id'], - 'TOPIC_TITLE' => wbr(str_short($watch[$i]['topic_title'], 70)), - 'FULL_TOPIC_TITLE' => wbr($watch[$i]['topic_title']), - 'U_TOPIC' => TOPIC_URL . $watch[$i]['topic_id'], - 'FORUM_TITLE' => wbr($watch[$i]['forum_name']), - 'U_FORUM' => FORUM_URL . $watch[$i]['forum_id'], - 'REPLIES' => $watch[$i]['topic_replies'], - 'AUTHOR' => profile_url($watch[$i]), - 'LAST_POST' => bb_date($watch[$i]['topic_last_post_time']) .'
        '. profile_url(array('user_id' => $watch[$i]['last_user_id'], 'username' => $watch[$i]['last_username'], 'user_rank' => $watch[$i]['last_user_rank'])), - 'LAST_POST_ID' => $watch[$i]['topic_last_post_id'], - 'IS_UNREAD' => $is_unread, - 'TOPIC_ICON' => get_topic_icon($watch[$i], $is_unread), - 'PAGINATION' => ($watch[$i]['topic_status'] == TOPIC_MOVED) ? '' : build_topic_pagination(TOPIC_URL . $watch[$i]['topic_id'], $watch[$i]['topic_replies'], $di->config->get('posts_per_page')), - )); - } + $template->assign_block_vars('watch', array( + 'ROW_CLASS' => (!($i % 2)) ? 'row1' : 'row2', + 'POST_ID' => $watch[$i]['topic_first_post_id'], + 'TOPIC_ID' => $watch[$i]['topic_id'], + 'TOPIC_TITLE' => wbr(str_short($watch[$i]['topic_title'], 70)), + 'FULL_TOPIC_TITLE' => wbr($watch[$i]['topic_title']), + 'U_TOPIC' => TOPIC_URL . $watch[$i]['topic_id'], + 'FORUM_TITLE' => wbr($watch[$i]['forum_name']), + 'U_FORUM' => FORUM_URL . $watch[$i]['forum_id'], + 'REPLIES' => $watch[$i]['topic_replies'], + 'AUTHOR' => profile_url($watch[$i]), + 'LAST_POST' => bb_date($watch[$i]['topic_last_post_time']) . '
        ' . profile_url(array('user_id' => $watch[$i]['last_user_id'], 'username' => $watch[$i]['last_username'], 'user_rank' => $watch[$i]['last_user_rank'])), + 'LAST_POST_ID' => $watch[$i]['topic_last_post_id'], + 'IS_UNREAD' => $is_unread, + 'TOPIC_ICON' => get_topic_icon($watch[$i], $is_unread), + 'PAGINATION' => ($watch[$i]['topic_status'] == TOPIC_MOVED) ? '' : build_topic_pagination(TOPIC_URL . $watch[$i]['topic_id'], $watch[$i]['topic_replies'], $di->config->get('posts_per_page')), + )); + } - $template->assign_vars(array( - 'MATCHES' => (count($watch) == 1) ? sprintf($lang['FOUND_SEARCH_MATCH'], count($watch)) : sprintf($lang['FOUND_SEARCH_MATCHES'], count($watch)), - 'PAGINATION' => generate_pagination(BB_ROOT .'profile.php?mode=watch', $watch_count, $per_page, $start), - 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], ( floor( $start / $per_page ) + 1 ), ceil( $watch_count / $per_page )), - 'U_PER_PAGE' => BB_ROOT .'profile.php?mode=watch', - 'PER_PAGE' => $per_page, - )); - } - DB() ->sql_freeresult($result); -} -else -{ - meta_refresh('index.php', 3); - bb_die($lang['NO_WATCHED_TOPICS']); + $template->assign_vars(array( + 'MATCHES' => (count($watch) == 1) ? sprintf($lang['FOUND_SEARCH_MATCH'], count($watch)) : sprintf($lang['FOUND_SEARCH_MATCHES'], count($watch)), + 'PAGINATION' => generate_pagination(BB_ROOT . 'profile.php?mode=watch', $watch_count, $per_page, $start), + 'PAGE_NUMBER' => sprintf($lang['PAGE_OF'], (floor($start / $per_page) + 1), ceil($watch_count / $per_page)), + 'U_PER_PAGE' => BB_ROOT . 'profile.php?mode=watch', + 'PER_PAGE' => $per_page, + )); + } + DB()->sql_freeresult($result); +} else { + meta_refresh('index.php', 3); + bb_die($lang['NO_WATCHED_TOPICS']); } -print_page('usercp_topic_watch.tpl'); \ No newline at end of file +print_page('usercp_topic_watch.tpl'); diff --git a/library/includes/ucp/viewprofile.php b/library/includes/ucp/viewprofile.php index e7fea1d0d..a9a899038 100644 --- a/library/includes/ucp/viewprofile.php +++ b/library/includes/ucp/viewprofile.php @@ -5,57 +5,47 @@ if (!defined('BB_ROOT')) die(basename(__FILE__)); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require(INC_DIR .'bbcode.php'); +require(INC_DIR . 'bbcode.php'); $datastore->enqueue(array( - 'ranks', + 'ranks', )); -if (empty($_GET[POST_USERS_URL]) || $_GET[POST_USERS_URL] == GUEST_UID) -{ - bb_die($lang['NO_USER_ID_SPECIFIED']); +if (empty($_GET[POST_USERS_URL]) || $_GET[POST_USERS_URL] == GUEST_UID) { + bb_die($lang['NO_USER_ID_SPECIFIED']); } -if (!$profiledata = get_userdata($_GET[POST_USERS_URL])) -{ - bb_die($lang['NO_USER_ID_SPECIFIED']); +if (!$profiledata = get_userdata($_GET[POST_USERS_URL])) { + bb_die($lang['NO_USER_ID_SPECIFIED']); } -if (!$userdata['session_logged_in']) -{ - redirect(LOGIN_URL . "?redirect={$_SERVER['REQUEST_URI']}"); +if (!$userdata['session_logged_in']) { + redirect(LOGIN_URL . "?redirect={$_SERVER['REQUEST_URI']}"); } -if (!$ranks = $datastore->get('ranks')) -{ - $datastore->update('ranks'); - $ranks = $datastore->get('ranks'); +if (!$ranks = $datastore->get('ranks')) { + $datastore->update('ranks'); + $ranks = $datastore->get('ranks'); } -$poster_rank = $rank_image= $rank_style = $rank_select = ''; -if (($user_rank = $profiledata['user_rank']) && isset($ranks[$user_rank])) -{ - $rank_image = ($ranks[$user_rank]['rank_image']) ? '' : ''; - $poster_rank = $ranks[$user_rank]['rank_title']; - $rank_style = $ranks[$user_rank]['rank_style']; +$poster_rank = $rank_image = $rank_style = $rank_select = ''; +if (($user_rank = $profiledata['user_rank']) && isset($ranks[$user_rank])) { + $rank_image = ($ranks[$user_rank]['rank_image']) ? '' : ''; + $poster_rank = $ranks[$user_rank]['rank_title']; + $rank_style = $ranks[$user_rank]['rank_style']; } -if (IS_ADMIN) -{ - $rank_select = array($lang['NONE'] => 0); - foreach ($ranks as $row) - { - $rank_select[$row['rank_title']] = $row['rank_id']; - } - $rank_select = build_select('rank-sel', $rank_select, $user_rank); +if (IS_ADMIN) { + $rank_select = array($lang['NONE'] => 0); + foreach ($ranks as $row) { + $rank_select[$row['rank_title']] = $row['rank_id']; + } + $rank_select = build_select('rank-sel', $rank_select, $user_rank); } -if (bf($profiledata['user_opt'], 'user_opt', 'user_viewemail') || $profiledata['user_id'] == $userdata['user_id'] || IS_AM) -{ - $email_uri = ($di->config->get('board_email_form')) ? 'profile.php?mode=email&'. POST_USERS_URL .'='. $profiledata['user_id'] : 'mailto:'. $profiledata['user_email']; - $email = ''. $profiledata['user_email'] .''; -} -else -{ - $email = ''; +if (bf($profiledata['user_opt'], 'user_opt', 'user_viewemail') || $profiledata['user_id'] == $userdata['user_id'] || IS_AM) { + $email_uri = ($di->config->get('board_email_form')) ? 'profile.php?mode=email&' . POST_USERS_URL . '=' . $profiledata['user_id'] : 'mailto:' . $profiledata['user_email']; + $email = '' . $profiledata['user_email'] . ''; +} else { + $email = ''; } // @@ -66,161 +56,140 @@ $profile_user_id = ($profiledata['user_id'] == $userdata['user_id']); $signature = ($di->config->get('allow_sig') && $profiledata['user_sig']) ? $profiledata['user_sig'] : ''; -if(bf($profiledata['user_opt'], 'user_opt', 'dis_sig')) -{ - if($profile_user_id) - { - $signature = $lang['SIGNATURE_DISABLE']; - } - else - { - $signature = ''; - } -} -else if ($signature) -{ - $signature = bbcode2html($signature); +if (bf($profiledata['user_opt'], 'user_opt', 'dis_sig')) { + if ($profile_user_id) { + $signature = $lang['SIGNATURE_DISABLE']; + } else { + $signature = ''; + } +} else if ($signature) { + $signature = bbcode2html($signature); } $template->assign_vars(array( - 'PAGE_TITLE' => sprintf($lang['VIEWING_USER_PROFILE'], $profiledata['username']), - 'USERNAME' => $profiledata['username'], - 'PROFILE_USER_ID' => $profiledata['user_id'], - 'PROFILE_USER' => $profile_user_id, - 'USER_REGDATE' => bb_date($profiledata['user_regdate'], 'Y-m-d H:i', false), - 'POSTER_RANK' => ($poster_rank) ? "". $poster_rank ."" : $lang['USER'], - 'RANK_IMAGE' => $rank_image, - 'RANK_SELECT' => $rank_select, - 'POSTS' => $profiledata['user_posts'], - 'PM' => ''. $lang['SEND_PRIVATE_MESSAGE'] .'', - 'EMAIL' => $email, - 'WWW' => $profiledata['user_website'], - 'ICQ' => $profiledata['user_icq'], - 'LAST_VISIT_TIME' => ($profiledata['user_lastvisit']) ? (bf($profiledata['user_opt'], 'user_opt', 'user_viewonline') && !IS_ADMIN) ? $lang['HIDDEN_USER'] : bb_date($profiledata['user_lastvisit'], 'Y-m-d H:i', false) : $lang['NEVER'], - 'LAST_ACTIVITY_TIME' => ($profiledata['user_session_time']) ? (bf($profiledata['user_opt'], 'user_opt', 'user_viewonline') && !IS_ADMIN) ? $lang['HIDDEN_USER'] : bb_date($profiledata['user_session_time'], 'Y-m-d H:i', false) : $lang['NEVER'], + 'PAGE_TITLE' => sprintf($lang['VIEWING_USER_PROFILE'], $profiledata['username']), + 'USERNAME' => $profiledata['username'], + 'PROFILE_USER_ID' => $profiledata['user_id'], + 'PROFILE_USER' => $profile_user_id, + 'USER_REGDATE' => bb_date($profiledata['user_regdate'], 'Y-m-d H:i', false), + 'POSTER_RANK' => ($poster_rank) ? "" . $poster_rank . "" : $lang['USER'], + 'RANK_IMAGE' => $rank_image, + 'RANK_SELECT' => $rank_select, + 'POSTS' => $profiledata['user_posts'], + 'PM' => '' . $lang['SEND_PRIVATE_MESSAGE'] . '', + 'EMAIL' => $email, + 'WWW' => $profiledata['user_website'], + 'ICQ' => $profiledata['user_icq'], + 'LAST_VISIT_TIME' => ($profiledata['user_lastvisit']) ? (bf($profiledata['user_opt'], 'user_opt', 'user_viewonline') && !IS_ADMIN) ? $lang['HIDDEN_USER'] : bb_date($profiledata['user_lastvisit'], 'Y-m-d H:i', false) : $lang['NEVER'], + 'LAST_ACTIVITY_TIME' => ($profiledata['user_session_time']) ? (bf($profiledata['user_opt'], 'user_opt', 'user_viewonline') && !IS_ADMIN) ? $lang['HIDDEN_USER'] : bb_date($profiledata['user_session_time'], 'Y-m-d H:i', false) : $lang['NEVER'], - 'USER_ACTIVE' => $profiledata['user_active'], - 'LOCATION' => $profiledata['user_from'], - 'OCCUPATION' => $profiledata['user_occ'], - 'INTERESTS' => $profiledata['user_interests'], - 'SKYPE' => $profiledata['user_skype'], - 'TWITTER' => $profiledata['user_twitter'], - 'USER_POINTS' => $profiledata['user_points'], - 'GENDER' => ($di->config->get('gender')) ? $lang['GENDER_SELECT'][$profiledata['user_gender']] : '', - 'BIRTHDAY' => ($di->config->get('birthday_enabled') && $profiledata['user_birthday'] != '0000-00-00') ? $profiledata['user_birthday'] : '', - 'AGE' => ($di->config->get('birthday_enabled') && $profiledata['user_birthday'] != '0000-00-00') ? birthday_age($profiledata['user_birthday']) : '', + 'USER_ACTIVE' => $profiledata['user_active'], + 'LOCATION' => $profiledata['user_from'], + 'OCCUPATION' => $profiledata['user_occ'], + 'INTERESTS' => $profiledata['user_interests'], + 'SKYPE' => $profiledata['user_skype'], + 'TWITTER' => $profiledata['user_twitter'], + 'USER_POINTS' => $profiledata['user_points'], + 'GENDER' => ($di->config->get('gender')) ? $lang['GENDER_SELECT'][$profiledata['user_gender']] : '', + 'BIRTHDAY' => ($di->config->get('birthday_enabled') && $profiledata['user_birthday'] != '0000-00-00') ? $profiledata['user_birthday'] : '', + 'AGE' => ($di->config->get('birthday_enabled') && $profiledata['user_birthday'] != '0000-00-00') ? birthday_age($profiledata['user_birthday']) : '', - 'L_VIEWING_PROFILE' => sprintf($lang['VIEWING_USER_PROFILE'], $profiledata['username']), - 'L_MY_PROFILE' => sprintf($lang['VIEWING_MY_PROFILE'], 'profile.php?mode=editprofile'), + 'L_VIEWING_PROFILE' => sprintf($lang['VIEWING_USER_PROFILE'], $profiledata['username']), + 'L_MY_PROFILE' => sprintf($lang['VIEWING_MY_PROFILE'], 'profile.php?mode=editprofile'), - 'U_SEARCH_USER' => "search.php?search_author=1&uid={$profiledata['user_id']}", - 'U_SEARCH_TOPICS' => "search.php?uid={$profiledata['user_id']}&myt=1", - 'U_SEARCH_RELEASES' => "tracker.php?rid={$profiledata['user_id']}#results", + 'U_SEARCH_USER' => "search.php?search_author=1&uid={$profiledata['user_id']}", + 'U_SEARCH_TOPICS' => "search.php?uid={$profiledata['user_id']}&myt=1", + 'U_SEARCH_RELEASES' => "tracker.php?rid={$profiledata['user_id']}#results", - 'AVATAR_IMG' => get_avatar($profiledata['user_id'], $profiledata['avatar_ext_id'], !bf($profiledata['user_opt'], 'user_opt', 'dis_avatar')), + 'AVATAR_IMG' => get_avatar($profiledata['user_id'], $profiledata['avatar_ext_id'], !bf($profiledata['user_opt'], 'user_opt', 'dis_avatar')), - 'SIGNATURE' => $signature, - 'SHOW_PASSKEY' => (IS_ADMIN || $profile_user_id), - 'SHOW_ROLE' => (IS_AM || $profile_user_id || $profiledata['user_active']), - 'GROUP_MEMBERSHIP' => false, - 'TRAF_STATS' => !(IS_AM || $profile_user_id), + 'SIGNATURE' => $signature, + 'SHOW_PASSKEY' => (IS_ADMIN || $profile_user_id), + 'SHOW_ROLE' => (IS_AM || $profile_user_id || $profiledata['user_active']), + 'GROUP_MEMBERSHIP' => false, + 'TRAF_STATS' => !(IS_AM || $profile_user_id), )); -if (IS_ADMIN) -{ - $group_membership = array(); - $sql = " +if (IS_ADMIN) { + $group_membership = array(); + $sql = " SELECT COUNT(g.group_id) AS groups_cnt, g.group_single_user, ug.user_pending - FROM ". BB_USER_GROUP ." ug - LEFT JOIN ". BB_GROUPS ." g USING(group_id) + FROM " . BB_USER_GROUP . " ug + LEFT JOIN " . BB_GROUPS . " g USING(group_id) WHERE ug.user_id = {$profiledata['user_id']} GROUP BY ug.user_id, g.group_single_user, ug.user_pending ORDER BY NULL "; - if ($rowset = DB()->fetch_rowset($sql)) - { - $member = $pending = $single = 0; - foreach ($rowset as $row) - { - if (!$row['group_single_user'] && !$row['user_pending']) - { - $member = $row['groups_cnt']; - } - else if (!$row['group_single_user'] && $row['user_pending']) - { - $pending = $row['groups_cnt']; - } - else if ($row['group_single_user']) - { - $single = $row['groups_cnt']; - } - } - if ($member) $group_membership[] = $lang['PARTY'] ." $member"; - if ($pending) $group_membership[] = $lang['CANDIDATE'] ." $pending"; - if ($single) $group_membership[] = $lang['INDIVIDUAL']; - $group_membership = join(', ', $group_membership); - } - $template->assign_vars(array( - 'GROUP_MEMBERSHIP' => (bool) $group_membership, - 'GROUP_MEMBERSHIP_TXT' => $group_membership, - )); -} -else if (IS_MOD) -{ - $template->assign_vars(array( - 'SHOW_GROUP_MEMBERSHIP' => ($profiledata['user_level'] != USER), - )); + if ($rowset = DB()->fetch_rowset($sql)) { + $member = $pending = $single = 0; + foreach ($rowset as $row) { + if (!$row['group_single_user'] && !$row['user_pending']) { + $member = $row['groups_cnt']; + } else if (!$row['group_single_user'] && $row['user_pending']) { + $pending = $row['groups_cnt']; + } else if ($row['group_single_user']) { + $single = $row['groups_cnt']; + } + } + if ($member) $group_membership[] = $lang['PARTY'] . " $member"; + if ($pending) $group_membership[] = $lang['CANDIDATE'] . " $pending"; + if ($single) $group_membership[] = $lang['INDIVIDUAL']; + $group_membership = join(', ', $group_membership); + } + $template->assign_vars(array( + 'GROUP_MEMBERSHIP' => (bool)$group_membership, + 'GROUP_MEMBERSHIP_TXT' => $group_membership, + )); +} else if (IS_MOD) { + $template->assign_vars(array( + 'SHOW_GROUP_MEMBERSHIP' => ($profiledata['user_level'] != USER), + )); } // Show users torrent-profile -if (IS_AM || $profile_user_id || !bf($profiledata['user_opt'], 'user_opt', 'user_dls')) -{ - require(UCP_DIR .'viewtorrent.php'); +if (IS_AM || $profile_user_id || !bf($profiledata['user_opt'], 'user_opt', 'user_dls')) { + require(UCP_DIR . 'viewtorrent.php'); } // Ajax bt_userdata -if (IS_AM || $profile_user_id) -{ - show_bt_userdata($profiledata['user_id']); -} -else -{ - $template->assign_vars(array( - 'DOWN_TOTAL_BYTES' => false, - 'MIN_DL_BYTES' => false, - )); +if (IS_AM || $profile_user_id) { + show_bt_userdata($profiledata['user_id']); +} else { + $template->assign_vars(array( + 'DOWN_TOTAL_BYTES' => false, + 'MIN_DL_BYTES' => false, + )); } -if (IS_ADMIN) -{ - $ajax_user_opt = \Zend\Json\Json::encode(array( - 'dis_avatar' => bf($profiledata['user_opt'], 'user_opt', 'dis_avatar'), - 'dis_sig' => bf($profiledata['user_opt'], 'user_opt', 'dis_sig'), - 'dis_passkey' => bf($profiledata['user_opt'], 'user_opt', 'dis_passkey'), - 'dis_pm' => bf($profiledata['user_opt'], 'user_opt', 'dis_pm'), - 'dis_post' => bf($profiledata['user_opt'], 'user_opt', 'dis_post'), - 'dis_post_edit' => bf($profiledata['user_opt'], 'user_opt', 'dis_post_edit'), - 'dis_topic' => bf($profiledata['user_opt'], 'user_opt', 'dis_topic'), - )); +if (IS_ADMIN) { + $ajax_user_opt = \Zend\Json\Json::encode(array( + 'dis_avatar' => bf($profiledata['user_opt'], 'user_opt', 'dis_avatar'), + 'dis_sig' => bf($profiledata['user_opt'], 'user_opt', 'dis_sig'), + 'dis_passkey' => bf($profiledata['user_opt'], 'user_opt', 'dis_passkey'), + 'dis_pm' => bf($profiledata['user_opt'], 'user_opt', 'dis_pm'), + 'dis_post' => bf($profiledata['user_opt'], 'user_opt', 'dis_post'), + 'dis_post_edit' => bf($profiledata['user_opt'], 'user_opt', 'dis_post_edit'), + 'dis_topic' => bf($profiledata['user_opt'], 'user_opt', 'dis_topic'), + )); - $template->assign_vars(array( - 'EDITABLE_TPLS' => true, - 'AJAX_USER_OPT' => $ajax_user_opt, - 'U_MANAGE' => "profile.php?mode=editprofile&u={$profiledata['user_id']}", - 'U_PERMISSIONS' => "admin/admin_ug_auth.php?mode=user&u={$profiledata['user_id']}", - )); + $template->assign_vars(array( + 'EDITABLE_TPLS' => true, + 'AJAX_USER_OPT' => $ajax_user_opt, + 'U_MANAGE' => "profile.php?mode=editprofile&u={$profiledata['user_id']}", + 'U_PERMISSIONS' => "admin/admin_ug_auth.php?mode=user&u={$profiledata['user_id']}", + )); } $user_restrictions = array(); -if (bf($profiledata['user_opt'], 'user_opt', 'dis_avatar')) $user_restrictions[] = $lang['HIDE_AVATARS']; -if (bf($profiledata['user_opt'], 'user_opt', 'dis_sig')) $user_restrictions[] = $lang['SHOW_CAPTION']; -if (bf($profiledata['user_opt'], 'user_opt', 'dis_passkey')) $user_restrictions[] = $lang['DOWNLOAD_TORRENT']; -if (bf($profiledata['user_opt'], 'user_opt', 'dis_pm')) $user_restrictions[] = $lang['SEND_PM']; -if (bf($profiledata['user_opt'], 'user_opt', 'dis_post')) $user_restrictions[] = $lang['SEND_MESSAGE']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_avatar')) $user_restrictions[] = $lang['HIDE_AVATARS']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_sig')) $user_restrictions[] = $lang['SHOW_CAPTION']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_passkey')) $user_restrictions[] = $lang['DOWNLOAD_TORRENT']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_pm')) $user_restrictions[] = $lang['SEND_PM']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_post')) $user_restrictions[] = $lang['SEND_MESSAGE']; if (bf($profiledata['user_opt'], 'user_opt', 'dis_post_edit')) $user_restrictions[] = $lang['EDIT_POST']; -if (bf($profiledata['user_opt'], 'user_opt', 'dis_topic')) $user_restrictions[] = $lang['NEW_THREADS']; +if (bf($profiledata['user_opt'], 'user_opt', 'dis_topic')) $user_restrictions[] = $lang['NEW_THREADS']; $template->assign_var('USER_RESTRICTIONS', join('
      • ', $user_restrictions)); -print_page('usercp_viewprofile.tpl'); \ No newline at end of file +print_page('usercp_viewprofile.tpl'); diff --git a/library/includes/ucp/viewtorrent.php b/library/includes/ucp/viewtorrent.php index 9a49233be..c481add70 100644 --- a/library/includes/ucp/viewtorrent.php +++ b/library/includes/ucp/viewtorrent.php @@ -17,7 +17,7 @@ $sql = DB()->fetch_rowset(" f.forum_id, f.forum_name, t.topic_title, tor.tor_type, tor.size, sn.seeders, sn.leechers, tr.* - FROM ". BB_FORUMS ." f, ". BB_TOPICS ." t, ". BB_BT_TRACKER ." tr, ". BB_BT_TORRENTS ." tor, ". BB_BT_TRACKER_SNAP ." sn + FROM " . BB_FORUMS . " f, " . BB_TOPICS . " t, " . BB_BT_TRACKER . " tr, " . BB_BT_TORRENTS . " tor, " . BB_BT_TRACKER_SNAP . " sn WHERE tr.user_id = {$profiledata['user_id']} AND tr.topic_id = tor.topic_id AND sn.topic_id = tor.topic_id @@ -28,96 +28,84 @@ $sql = DB()->fetch_rowset(" ORDER BY f.forum_name, t.topic_title "); -foreach ($sql as $rowset) -{ - if ($rowset['releaser']) - { - $releasing[] = $rowset; - } - elseif ($rowset['seeder']) - { - $seeding[] = $rowset; - } - else - { - $leeching[] = $rowset; - } +foreach ($sql as $rowset) { + if ($rowset['releaser']) { + $releasing[] = $rowset; + } elseif ($rowset['seeder']) { + $seeding[] = $rowset; + } else { + $leeching[] = $rowset; + } } -if ($releasing) -{ - foreach ($releasing as $i => $row) - { - $topic_title = wbr($row['topic_title']); +if ($releasing) { + foreach ($releasing as $i => $row) { + $topic_title = wbr($row['topic_title']); - $template->assign_block_vars('released', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'FORUM_NAME' => htmlCHR($row['forum_name']), - 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", - 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], - 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], - 'TOR_TYPE' => is_gold($row['tor_type']), - 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, - 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, - 'SPEED_UP' => ($row['speed_up']) ? humn_size($row['speed_up'], 0, 'KB') .'/s' : '-', - )); + $template->assign_block_vars('released', array( + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'FORUM_NAME' => htmlCHR($row['forum_name']), + 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", + 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], + 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], + 'TOR_TYPE' => is_gold($row['tor_type']), + 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, + 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, + 'SPEED_UP' => ($row['speed_up']) ? humn_size($row['speed_up'], 0, 'KB') . '/s' : '-', + )); - $releasing_count++; - } + $releasing_count++; + } } -if ($seeding) -{ - foreach ($seeding as $i => $row) - { - $topic_title = wbr($row['topic_title']); +if ($seeding) { + foreach ($seeding as $i => $row) { + $topic_title = wbr($row['topic_title']); - $template->assign_block_vars('seed', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'FORUM_NAME' => htmlCHR($row['forum_name']), - 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", - 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], - 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], - 'TOR_TYPE' => is_gold($row['tor_type']), - 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, - 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, - 'SPEED_UP' => ($row['speed_up']) ? humn_size($row['speed_up'], 0, 'KB') .'/s' : '-', - )); + $template->assign_block_vars('seed', array( + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'FORUM_NAME' => htmlCHR($row['forum_name']), + 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", + 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], + 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], + 'TOR_TYPE' => is_gold($row['tor_type']), + 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, + 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, + 'SPEED_UP' => ($row['speed_up']) ? humn_size($row['speed_up'], 0, 'KB') . '/s' : '-', + )); - $seeding_count++; - } + $seeding_count++; + } } -if ($leeching) -{ - foreach ($leeching as $i => $row) - { - $compl_size = ($row['remain'] && $row['size'] && $row['size'] > $row['remain']) ? ($row['size'] - $row['remain']) : 0; - $compl_perc = ($compl_size) ? floor($compl_size * 100 / $row['size']) : 0; - $topic_title = wbr($row['topic_title']); +if ($leeching) { + foreach ($leeching as $i => $row) { + $compl_size = ($row['remain'] && $row['size'] && $row['size'] > $row['remain']) ? ($row['size'] - $row['remain']) : 0; + $compl_perc = ($compl_size) ? floor($compl_size * 100 / $row['size']) : 0; + $topic_title = wbr($row['topic_title']); - $template->assign_block_vars('leech', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'FORUM_NAME' => htmlCHR($row['forum_name']), - 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", - 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], - 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], - 'COMPL_PERC' => $compl_perc, - 'TOR_TYPE' => is_gold($row['tor_type']), - 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, - 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, - 'SPEED_DOWN' => ($row['speed_down']) ? humn_size($row['speed_down'], 0, 'KB') .'/s' : '-', - )); + $template->assign_block_vars('leech', array( + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'FORUM_NAME' => htmlCHR($row['forum_name']), + 'TOPIC_TITLE' => ($row['update_time']) ? $topic_title : "$topic_title", + 'U_VIEW_FORUM' => FORUM_URL . $row['forum_id'], + 'U_VIEW_TOPIC' => TOPIC_URL . $row['topic_id'], + 'COMPL_PERC' => $compl_perc, + 'TOR_TYPE' => is_gold($row['tor_type']), + 'TOPIC_SEEDERS' => ($row['seeders']) ? $row['seeders'] : 0, + 'TOPIC_LEECHERS' => ($row['leechers']) ? $row['leechers'] : 0, + 'SPEED_DOWN' => ($row['speed_down']) ? humn_size($row['speed_down'], 0, 'KB') . '/s' : '-', + )); - $leeching_count++; - } + $leeching_count++; + } } $template->assign_vars(array( - 'SHOW_SEARCH_DL' => IS_AM || $profile_user_id, - 'USERNAME' => $profiledata['username'], - 'L_RELEASINGS' => "{$lang['RELEASING']}: ". (($releasing_count) ? "$releasing_count" : '0'), - 'L_SEEDINGS' => "{$lang['SEEDING']}: ". (($seeding_count) ? "$seeding_count" : '0'), - 'L_LEECHINGS' => "{$lang['LEECHING']}: ". (($leeching_count) ? "$leeching_count" : '0'), - 'USER_DLS' => $releasing_count || $seeding_count || $leeching_count, -)); \ No newline at end of file + 'SHOW_SEARCH_DL' => IS_AM || $profile_user_id, + 'USERNAME' => $profiledata['username'], + 'L_RELEASINGS' => "{$lang['RELEASING']}: " . (($releasing_count) ? "$releasing_count" : '0'), + 'L_SEEDINGS' => "{$lang['SEEDING']}: " . (($seeding_count) ? "$seeding_count" : '0'), + 'L_LEECHINGS' => "{$lang['LEECHING']}: " . (($leeching_count) ? "$leeching_count" : '0'), + 'USER_DLS' => $releasing_count || $seeding_count || $leeching_count, +)); diff --git a/library/includes/viewtopic_torrent.php b/library/includes/viewtopic_torrent.php index b11c55747..098a02002 100644 --- a/library/includes/viewtopic_torrent.php +++ b/library/includes/viewtopic_torrent.php @@ -7,517 +7,446 @@ global $t_data, $poster_id, $is_auth, $dl_link_css, $dl_status_css, $lang, $user /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -$show_peers_limit = 300; +$show_peers_limit = 300; $max_peers_before_overflow = 20; -$peers_div_style_normal = 'padding: 3px;'; -$peers_div_style_overflow = "padding: 6px; height: 400px; overflow: auto; border: 1px inset;"; +$peers_div_style_normal = 'padding: 3px;'; +$peers_div_style_overflow = "padding: 6px; height: 400px; overflow: auto; border: 1px inset;"; $peers_cnt = $seed_count = $leech_count = 0; $seeders = $leechers = ''; $tor_info = []; $template->assign_vars([ - 'DL_BUTTONS' => true, - 'LEECH_COUNT' => false, - 'SEED_COUNT' => false, - 'SHOW_CPHOLD_OPT' => (IS_ADMIN || IS_CP_HOLDER), - 'SHOW_RATIO_WARN' => false, - 'TOR_CONTROLS' => false, - 'TOR_SPEED_DOWN' => false, - 'TOR_SPEED_UP' => false, + 'DL_BUTTONS' => true, + 'LEECH_COUNT' => false, + 'SEED_COUNT' => false, + 'SHOW_CPHOLD_OPT' => (IS_ADMIN || IS_CP_HOLDER), + 'SHOW_RATIO_WARN' => false, + 'TOR_CONTROLS' => false, + 'TOR_SPEED_DOWN' => false, + 'TOR_SPEED_UP' => false, ]); $page_cfg['show_tor_status_select'] = ($is_auth['auth_mod'] || IS_CP_HOLDER); // Define show peers mode (count only || full details) $s_mode = (isset($_GET['spmode']) && $_GET['spmode'] == 'full') ? 'full' : 'count'; -$bt_user_id = $userdata['user_id']; +$bt_user_id = $userdata['user_id']; $tor_file_size = humn_size($t_data['filesize']); -$tor_reged = (bool) $t_data['tracker_status']; +$tor_reged = (bool)$t_data['tracker_status']; $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'] || IS_CP_HOLDER)); -if ($tor_auth && $t_data['allow_reg_tracker'] && !$tor_reged && !IS_CP_HOLDER) -{ - $tr_reg_link = ''. $lang['BT_REG_ON_TRACKER'] .''; -} -else if ($is_auth['auth_mod'] && $tor_reged && !IS_CP_HOLDER) -{ - $tr_reg_link = ''. $lang['BT_UNREG_FROM_TRACKER'] .''; -} -else -{ - $tr_reg_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; +if ($tor_auth && $t_data['allow_reg_tracker'] && !$tor_reged && !IS_CP_HOLDER) { + $tr_reg_link = '' . $lang['BT_REG_ON_TRACKER'] . ''; +} else if ($is_auth['auth_mod'] && $tor_reged && !IS_CP_HOLDER) { + $tr_reg_link = '' . $lang['BT_UNREG_FROM_TRACKER'] . ''; +} else { + $tr_reg_link = ($tor_reged) ? $lang['BT_REG_YES'] : $lang['BT_REG_NO']; } -if ($tor_auth) -{ - $template->assign_vars(array( - 'TOR_CONTROLS' => ($is_auth['auth_mod'] || IS_CP_HOLDER), - 'TOR_ACTION' => 'torrent.php', - )); +if ($tor_auth) { + $template->assign_vars(array( + 'TOR_CONTROLS' => ($is_auth['auth_mod'] || IS_CP_HOLDER), + 'TOR_ACTION' => 'torrent.php', + )); - 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) -{ - $template->assign_vars(array( - 'SHOW_TOR_NOT_REGGED' => true, - 'TRACKER_REG_LINK' => $tr_reg_link, - )); -} -else -{ - $tor_info = DB()->fetch_row("SELECT * FROM ". BB_BT_TORRENTS ." WHERE topic_id = $topic_id LIMIT 1"); +if (!$tor_reged) { + $template->assign_vars(array( + 'SHOW_TOR_NOT_REGGED' => true, + 'TRACKER_REG_LINK' => $tr_reg_link, + )); +} else { + $tor_info = DB()->fetch_row("SELECT * FROM " . BB_BT_TORRENTS . " WHERE topic_id = $topic_id LIMIT 1"); } -if ($tor_reged && !$tor_info) -{ - DB()->query("UPDATE ". BB_TOPICS ." SET tracker_status = 0 WHERE topic_id = $topic_id LIMIT 1"); - bb_die('Torrent status fixed'); // TODO: перевести +if ($tor_reged && !$tor_info) { + DB()->query("UPDATE " . BB_TOPICS . " SET tracker_status = 0 WHERE topic_id = $topic_id LIMIT 1"); + bb_die('Torrent status fixed'); // TODO: перевести } -if ($tor_reged) -{ - $tor_size = (int) $tor_info['size']; +if ($tor_reged) { + $tor_size = (int)$tor_info['size']; - // 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 = $di->config->get('bt_min_ratio_allow_dl_tor'); - $min_ratio_warn = $di->config->get('bt_min_ratio_warning'); - $dl_allowed = true; - $user_ratio = 0; + // ratio limits + $min_ratio_dl = $di->config->get('bt_min_ratio_allow_dl_tor'); + $min_ratio_warn = $di->config->get('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 = $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 = $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 = $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_info['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_info['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, $di->config->get('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, $di->config->get('ratio_url_help')), + )); + } + } - if (!$dl_allowed) - { - $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_vars(array( - 'DOWNLOAD_NAME' => '[' . $di->config->get('server_name') . '].t' . $topic_id . '.torrent', - 'TOR_SILVER_GOLD' => $tor_info['tor_type'], + if (!$dl_allowed) { + $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_vars(array( + 'DOWNLOAD_NAME' => '[' . $di->config->get('server_name') . '].t' . $topic_id . '.torrent', + 'TOR_SILVER_GOLD' => $tor_info['tor_type'], - 'TOR_FROZEN' => (!IS_AM) ? ($di->config->get('tor_frozen.' . $tor_info['tor_status']) && !($di->config->get('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' => $di->config->get('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' => $di->config->get('tor_comment') && !IS_GUEST && in_array($tor_info['tor_status'], $di->config->get('tor_reply')) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, + 'TOR_FROZEN' => (!IS_AM) ? ($di->config->get('tor_frozen.' . $tor_info['tor_status']) && !($di->config->get('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' => $di->config->get('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' => $di->config->get('tor_comment') && !IS_GUEST && in_array($tor_info['tor_status'], $di->config->get('tor_reply')) && $userdata['user_id'] == $tor_info['poster_id'] && $t_data['topic_status'] != TOPIC_LOCKED, - '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' => declension($t_data['attach_dl_cnt'], 'times'), - 'REGED_TIME' => bb_date($tor_info['reg_time']), + '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' => declension($t_data['attach_dl_cnt'], 'times'), + 'REGED_TIME' => bb_date($tor_info['reg_time']), - 'SHOW_TOR_REGGED' => true, - 'TRACKER_REG_LINK' => $tr_reg_link, - 'AUTH_MOD' => $is_auth['auth_mod'], - 'TOR_SIZE' => humn_size($tor_size), - 'TOR_LONGEVITY' => delta_time($tor_info['reg_time']), - 'TOR_COMPLETED' => declension($tor_info['complete_count'], 'times'), - )); - } + 'SHOW_TOR_REGGED' => true, + 'TRACKER_REG_LINK' => $tr_reg_link, + 'AUTH_MOD' => $is_auth['auth_mod'], + '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 ($tor_info['tor_status'] == TOR_CLOSED_CPHOLD) - { - $template->assign_vars(array( - 'TOR_CLOSED_BY_CPHOLD' => true, - 'TOR_CONTROLS' => false, - 'DL_BUTTONS' => false, - 'CPHOLD_UID' => $tor_info['tor_status_uid'], - 'CPHOLD_NAME' => $tor_status_username, - 'CAN_OPEN_CH_RELEASE' => ($is_auth['auth_mod'] || IS_CP_HOLDER), - )); - } - else - { - // Sorting order in full mode - if ($s_mode == 'full') - { - $full_mode_order = 'tr.remain'; - $full_mode_sort_dir = 'ASC'; + // Show peers + if ($tor_info['tor_status'] == TOR_CLOSED_CPHOLD) { + $template->assign_vars(array( + 'TOR_CLOSED_BY_CPHOLD' => true, + 'TOR_CONTROLS' => false, + 'DL_BUTTONS' => false, + 'CPHOLD_UID' => $tor_info['tor_status_uid'], + 'CPHOLD_NAME' => $tor_status_username, + 'CAN_OPEN_CH_RELEASE' => ($is_auth['auth_mod'] || IS_CP_HOLDER), + )); + } else { + // 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'; + } else if (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 = $topic_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 + } 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 WHERE tr.topic_id = $topic_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 = $topic_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 ."=$topic_id&spmode=full#seeders"; + if (!defined('SEEDER_EXIST')) { + define('SEEDER_EXIST', true); + $seed_order_action = "viewtopic.php?" . POST_TOPIC_URL . "=$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' : '-'; - $template->assign_block_vars("$x_full.$x_row", array( - '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( + '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 ($di->config->get('bt_allow_spmode_change') && $s_mode != 'full') -{ - $template->assign_vars(array( - 'PEERS_FULL_LINK' => true, - 'SPMODE_FULL_HREF' => "viewtopic.php?". POST_TOPIC_URL ."=$topic_id&spmode=full#seeders", - )); +if ($di->config->get('bt_allow_spmode_change') && $s_mode != 'full') { + $template->assign_vars(array( + 'PEERS_FULL_LINK' => true, + 'SPMODE_FULL_HREF' => "viewtopic.php?" . POST_TOPIC_URL . "=$topic_id&spmode=full#seeders", + )); } $template->assign_vars(array( - 'SHOW_DL_LIST_LINK' => (($di->config->get('bt_show_dl_list') || $di->config->get('allow_dl_list_names_mode')) && $t_data['tracker_status']), - 'SHOW_TOR_ACT' => ($tor_reged && (!$di->config->get('tor_no_tor_act.' . $tor_info['tor_status']) || IS_AM)), - 'S_MODE_COUNT' => ($s_mode == 'count'), - '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' => $di->config->get('tor_help_links'), - 'CALL_SEED' => ($di->config->get('callseed') && $tor_reged && !$di->config->get('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' => (($di->config->get('bt_show_dl_list') || $di->config->get('allow_dl_list_names_mode')) && $t_data['tracker_status']), + 'SHOW_TOR_ACT' => ($tor_reged && (!$di->config->get('tor_no_tor_act.' . $tor_info['tor_status']) || IS_AM)), + 'S_MODE_COUNT' => ($s_mode == 'count'), + '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' => $di->config->get('tor_help_links'), + 'CALL_SEED' => ($di->config->get('callseed') && $tor_reged && !$di->config->get('tor_no_tor_act.' . $tor_info['tor_status']) && $seed_count < 3 && $tor_info['call_seed_time'] < (TIMENOW - 86400)), +)); diff --git a/library/language/en/main.php b/library/language/en/main.php index 7b0473e61..5ed23aa1c 100644 --- a/library/language/en/main.php +++ b/library/language/en/main.php @@ -510,9 +510,9 @@ $lang['ALWAYS_NOTIFY_EXPLAIN'] = 'Sends an e-mail when someone replies to a topi $lang['BOARD_LANG'] = 'Board language'; $lang['GENDER'] = 'Gender'; $lang['GENDER_SELECT'] = array( - 0 => 'Unknown', - 1 => 'Male', - 2 => 'Female' + 0 => 'Unknown', + 1 => 'Male', + 2 => 'Female' ); $lang['MODULE_OFF'] = 'Module is disabled!'; @@ -1045,18 +1045,18 @@ $lang['TOR_STATUS_SELECT_ACTION'] = 'Select status'; $lang['TOR_STATUS_NOT_SELECT'] = 'You have not selected status.'; $lang['TOR_STATUS_SELECT_ALL'] = 'All statuses'; $lang['TOR_STATUS_NAME'] = array( - TOR_NOT_APPROVED => 'not checked', - TOR_CLOSED => 'closed', - TOR_APPROVED => 'checked', - TOR_NEED_EDIT => 'not formalized until', - TOR_NO_DESC => 'not formalized', - TOR_DUP => 'repeat', - TOR_CLOSED_CPHOLD => 'closed right', - TOR_CONSUMED => 'absorbed', - TOR_DOUBTFUL => 'doubtful', - TOR_CHECKING => 'verified', - TOR_TMP => 'temporary', - TOR_PREMOD => 'pre-moderation', + TOR_NOT_APPROVED => 'not checked', + TOR_CLOSED => 'closed', + TOR_APPROVED => 'checked', + TOR_NEED_EDIT => 'not formalized until', + TOR_NO_DESC => 'not formalized', + TOR_DUP => 'repeat', + TOR_CLOSED_CPHOLD => 'closed right', + TOR_CONSUMED => 'absorbed', + TOR_DOUBTFUL => 'doubtful', + TOR_CHECKING => 'verified', + TOR_TMP => 'temporary', + TOR_PREMOD => 'pre-moderation', ); $lang['TOR_STATUS_FAILED'] = 'Such status does not exist!'; $lang['TORRENT_FAILED'] = 'Distribution was not found!'; @@ -1301,19 +1301,19 @@ $lang['DECLENSION']['REPLIES'] = array('reply', 'replies'); $lang['DECLENSION']['TIMES'] = array('time', 'times'); $lang['DELTA_TIME']['INTERVALS'] = array( - 'seconds' => array('second', 'seconds'), - 'minutes' => array('minute', 'minutes'), - 'hours' => array('hour', 'hours'), - 'mday' => array('day', 'days'), - 'mon' => array('month', 'months'), - 'year' => array('year', 'years'), + 'seconds' => array('second', 'seconds'), + 'minutes' => array('minute', 'minutes'), + 'hours' => array('hour', 'hours'), + 'mday' => array('day', 'days'), + 'mon' => array('month', 'months'), + 'year' => array('year', 'years'), ); $lang['DELTA_TIME']['FORMAT'] = '%1$s %2$s'; // 5(%1) minutes(%2) -$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; -$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; -$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; -$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; +$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; +$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; +$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; +$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; $lang['AUTH_TYPES'][AUTH_ADMIN] = $lang['AUTH_ADMINISTRATORS']; $lang['NEW_USER_REG_DISABLED'] = 'Sorry, registration is disabled at this time'; @@ -1414,7 +1414,7 @@ $lang['EMAILER_DISABLED'] = 'Sorry, this feature is temporarily not working'; $lang['TERMS_ON'] = 'I agree with these terms and conditions'; $lang['TERMS_OFF'] = 'I do not agree to these terms'; $lang['JAVASCRIPT_ON_REGISTER'] = 'To register, heads necessary to enable JavaScript'; -$lang['REGISTERED_IN_TIME'] = "At the moment registration is closed

        You can register from 01:00 to 17:00 MSK (now ". date('H:i') ." MSK)

        We apologize for this inconvenience"; +$lang['REGISTERED_IN_TIME'] = "At the moment registration is closed

        You can register from 01:00 to 17:00 MSK (now " . date('H:i') . " MSK)

        We apologize for this inconvenience"; $lang['AUTOCOMPLETE'] = 'Password generate'; $lang['YOUR_NEW_PASSWORD'] = 'Your are new password:'; $lang['REGENERATE'] = 'Regenerate'; @@ -1548,7 +1548,7 @@ $lang['ACTIONS_LOG'] = 'Report on action'; //Welcome page $lang['IDX_BROWSER_NSP_FRAME'] = 'Sorry, your browser doesn\'t seem to support frames'; -$lang['IDX_CLEAR_CACHE'] ='Clear Cache:'; +$lang['IDX_CLEAR_CACHE'] = 'Clear Cache:'; $lang['IDX_CLEAR_DATASTORE'] = 'Datastore'; $lang['IDX_CLEAR_TEMPLATES'] = 'Templates'; $lang['IDX_CLEAR_NEWNEWS'] = 'Net news'; @@ -1580,7 +1580,7 @@ $lang['USERS_PER_DAY'] = 'Users per day'; $lang['BOARD_STARTED'] = 'Board started'; $lang['AVATAR_DIR_SIZE'] = 'Avatar directory size'; $lang['DATABASE_SIZE'] = 'Database size'; -$lang['GZIP_COMPRESSION'] ='Gzip compression'; +$lang['GZIP_COMPRESSION'] = 'Gzip compression'; $lang['NOT_AVAILABLE'] = 'Not available'; // Clear Cache @@ -2307,12 +2307,12 @@ $lang['CRON_EDIT_HEAD_EDIT'] = 'Edit job'; $lang['CRON_EDIT_HEAD_ADD'] = 'Add job'; $lang['CRON_SCRIPT_EXPL'] = 'name of the script from "includes/cron/jobs/"';; $lang['SCHEDULE'] = array( - 'select' => '» Select start', - 'hourly' => 'hourly', - 'daily' => 'daily', - 'weekly' => 'weekly', - 'monthly' => 'monthly', - 'interval' => 'interval' + 'select' => '» Select start', + 'hourly' => 'hourly', + 'daily' => 'daily', + 'weekly' => 'weekly', + 'monthly' => 'monthly', + 'interval' => 'interval' ); $lang['NOSELECT'] = 'No select'; $lang['RUN_DAY'] = 'Run day'; @@ -2441,18 +2441,18 @@ $lang['CALLSEED_MSG_SPAM'] = 'Request has already been once successfully sent (P $lang['CALLSEED_HAVE_SEED'] = 'Topic does not require help (Seeders: %d)'; $lang['LOG_ACTION']['LOG_TYPE'] = array( - 'mod_topic_delete' => 'Topic:
        deleted', - 'mod_topic_move' => 'Topic:
        moved', - 'mod_topic_lock' => 'Topic:
        closed', - 'mod_topic_unlock' => 'Topic:
        opened', - 'mod_topic_split' => 'Topic:
        split', - 'mod_post_delete' => 'Post:
        deleted', - 'adm_user_delete' => 'User:
        deleted', - 'adm_user_ban' => 'User:
        ban', - 'adm_user_unban' => 'User:
        unban', + 'mod_topic_delete' => 'Topic:
        deleted', + 'mod_topic_move' => 'Topic:
        moved', + 'mod_topic_lock' => 'Topic:
        closed', + 'mod_topic_unlock' => 'Topic:
        opened', + 'mod_topic_split' => 'Topic:
        split', + 'mod_post_delete' => 'Post:
        deleted', + 'adm_user_delete' => 'User:
        deleted', + 'adm_user_ban' => 'User:
        ban', + 'adm_user_unban' => 'User:
        unban', ); -$lang['ACTS_LOG_ALL_ACTIONS'] = 'All actions'; +$lang['ACTS_LOG_ALL_ACTIONS'] = 'All actions'; $lang['ACTS_LOG_SEARCH_OPTIONS'] = 'Actions Log: Search options'; $lang['ACTS_LOG_FORUM'] = 'Forum'; $lang['ACTS_LOG_ACTION'] = 'Action'; @@ -2589,26 +2589,26 @@ $lang['MC_FAQ'] = 'Entered text will be displayed under this message'; $lang['MC_COMMENT_PM_SUBJECT'] = "%s in your message"; $lang['MC_COMMENT_PM_MSG'] = "Hello, [b]%s[/b]\nModerator left in your message [url=%s][b]%s[/b][/url][quote]\n%s\n[/quote]"; $lang['MC_COMMENT'] = array( - 0 => array( - 'title' => '', - 'type' => 'Delete comment', - ), - 1 => array( - 'title' => 'Comment from %s', - 'type' => 'Comment', - ), - 2 => array( - 'title' => 'Information from %s', - 'type' => 'Information', - ), - 3 => array( - 'title' => 'Warning from %s', - 'type' => 'Warning', - ), - 4 => array( - 'title' => 'Violation from %s', - 'type' => 'Violation', - ), + 0 => array( + 'title' => '', + 'type' => 'Delete comment', + ), + 1 => array( + 'title' => 'Comment from %s', + 'type' => 'Comment', + ), + 2 => array( + 'title' => 'Information from %s', + 'type' => 'Information', + ), + 3 => array( + 'title' => 'Warning from %s', + 'type' => 'Warning', + ), + 4 => array( + 'title' => 'Violation from %s', + 'type' => 'Violation', + ), ); $lang['SITEMAP'] = 'Sitemap'; @@ -2649,14 +2649,14 @@ $lang['TERMS_EMPTY_TEXT'] = '[align=center]The text of this page is edited at: [ $lang['TERMS_EXPLAIN'] = 'On this page, you can specify the text of the basic rules of the resource is displayed to users.'; $lang['TR_STATS'] = array( - 0 => 'inactive users in 30 days', - 1 => 'inactive users for 90 days', - 2 => 'medium size distributions on the tracker (many megabytes)', - 3 => 'how many total hands on the tracker', - 4 => 'how many live hands (there is at least 1 led)', - 5 => 'how many hands where that seeding more than 5 seeds', - 6 => 'how many of us uploaders (those who filled at least 1 hand)', - 7 => 'how many uploaders over the last 30 days', + 0 => 'inactive users in 30 days', + 1 => 'inactive users for 90 days', + 2 => 'medium size distributions on the tracker (many megabytes)', + 3 => 'how many total hands on the tracker', + 4 => 'how many live hands (there is at least 1 led)', + 5 => 'how many hands where that seeding more than 5 seeds', + 6 => 'how many of us uploaders (those who filled at least 1 hand)', + 7 => 'how many uploaders over the last 30 days', ); $lang['NEW_POLL_START'] = 'Poll enabled'; @@ -2688,16 +2688,16 @@ $lang['UPLOAD_ERROR_DIMENSIONS'] = 'Image dimensions exceed the maximum allowabl $lang['UPLOAD_ERROR_NOT_IMAGE'] = 'The uploaded file is not an image'; $lang['UPLOAD_ERROR_NOT_ALLOWED'] = 'Extension %s for downloads is not allowed'; $lang['UPLOAD_ERRORS'] = array( - UPLOAD_ERR_INI_SIZE => 'you have exceeded the maximum file size for the server', - UPLOAD_ERR_FORM_SIZE => 'you have exceeded the maximum file upload size', - UPLOAD_ERR_PARTIAL => 'the file was partially downloaded', - UPLOAD_ERR_NO_FILE => 'file was not uploaded', - UPLOAD_ERR_NO_TMP_DIR => 'temporary directory not found', - UPLOAD_ERR_CANT_WRITE => 'write error', - UPLOAD_ERR_EXTENSION => 'upload stopped by extension', + UPLOAD_ERR_INI_SIZE => 'you have exceeded the maximum file size for the server', + UPLOAD_ERR_FORM_SIZE => 'you have exceeded the maximum file upload size', + UPLOAD_ERR_PARTIAL => 'the file was partially downloaded', + UPLOAD_ERR_NO_FILE => 'file was not uploaded', + UPLOAD_ERR_NO_TMP_DIR => 'temporary directory not found', + UPLOAD_ERR_CANT_WRITE => 'write error', + UPLOAD_ERR_EXTENSION => 'upload stopped by extension', ); // Captcha $lang['CAPTCHA'] = 'Check that you are not a robot'; $lang['CAPTCHA_WRONG'] = 'You could not confirm that you are not a robot'; -$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha not being fully configured

        If you haven\'t already generated the keys, you can do it on https://www.google.com/recaptcha/admin.
        After you generate the keys, you need to put them at the file library/config.php.

        '; \ No newline at end of file +$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha not being fully configured

        If you haven\'t already generated the keys, you can do it on https://www.google.com/recaptcha/admin.
        After you generate the keys, you need to put them at the file library/config.php.

        '; diff --git a/library/language/ru/main.php b/library/language/ru/main.php index 088576a38..cadf0e4a7 100644 --- a/library/language/ru/main.php +++ b/library/language/ru/main.php @@ -510,9 +510,9 @@ $lang['ALWAYS_NOTIFY_EXPLAIN'] = 'Когда кто-нибудь ответит $lang['BOARD_LANG'] = 'Язык'; $lang['GENDER'] = 'Пол'; $lang['GENDER_SELECT'] = array( - 0 => 'Не указан', - 1 => 'Мужской', - 2 => 'Женский' + 0 => 'Не указан', + 1 => 'Мужской', + 2 => 'Женский' ); $lang['MODULE_OFF'] = 'Модуль отключен!'; @@ -1045,18 +1045,18 @@ $lang['TOR_STATUS_SELECT_ACTION'] = 'Выберите статус'; $lang['TOR_STATUS_NOT_SELECT'] = 'Вы не выбрали статус.'; $lang['TOR_STATUS_SELECT_ALL'] = 'Все статусы'; $lang['TOR_STATUS_NAME'] = array( - TOR_NOT_APPROVED => 'не проверено', - TOR_CLOSED => 'закрыто', - TOR_APPROVED => 'проверено', - TOR_NEED_EDIT => 'недооформлено', - TOR_NO_DESC => 'неоформлено', - TOR_DUP => 'повтор', - TOR_CLOSED_CPHOLD => 'закрыто правообладателем', - TOR_CONSUMED => 'поглощено', - TOR_DOUBTFUL => 'сомнительно', - TOR_CHECKING => 'проверяется', - TOR_TMP => 'временная', - TOR_PREMOD => 'премодерация', + TOR_NOT_APPROVED => 'не проверено', + TOR_CLOSED => 'закрыто', + TOR_APPROVED => 'проверено', + TOR_NEED_EDIT => 'недооформлено', + TOR_NO_DESC => 'неоформлено', + TOR_DUP => 'повтор', + TOR_CLOSED_CPHOLD => 'закрыто правообладателем', + TOR_CONSUMED => 'поглощено', + TOR_DOUBTFUL => 'сомнительно', + TOR_CHECKING => 'проверяется', + TOR_TMP => 'временная', + TOR_PREMOD => 'премодерация', ); $lang['TOR_STATUS_FAILED'] = 'Такого статуса не существует!'; $lang['TORRENT_FAILED'] = 'Раздача не найдена!'; @@ -1301,19 +1301,19 @@ $lang['DECLENSION']['REPLIES'] = array('ответ', 'ответа', 'ответ $lang['DECLENSION']['TIMES'] = array('раз', 'раза', 'раз'); $lang['DELTA_TIME']['INTERVALS'] = array( - 'seconds' => array('секунда', 'секунды', 'секунд'), - 'minutes' => array('минута', 'минуты', 'минут'), - 'hours' => array('час', 'часа', 'часов'), - 'mday' => array('день', 'дня', 'дней'), - 'mon' => array('месяц', 'месяца', 'месяцев'), - 'year' => array('год', 'года', 'лет'), + 'seconds' => array('секунда', 'секунды', 'секунд'), + 'minutes' => array('минута', 'минуты', 'минут'), + 'hours' => array('час', 'часа', 'часов'), + 'mday' => array('день', 'дня', 'дней'), + 'mon' => array('месяц', 'месяца', 'месяцев'), + 'year' => array('год', 'года', 'лет'), ); $lang['DELTA_TIME']['FORMAT'] = '%1$s %2$s'; // 5(%1) минут(%2) -$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; -$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; -$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; -$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; +$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; +$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; +$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; +$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; $lang['AUTH_TYPES'][AUTH_ADMIN] = $lang['AUTH_ADMINISTRATORS']; $lang['NEW_USER_REG_DISABLED'] = 'Регистрация новых пользователей временно отключена'; @@ -1414,7 +1414,7 @@ $lang['EMAILER_DISABLED'] = 'Извините, эта функция време $lang['TERMS_ON'] = 'Я согласен с этими условиями'; $lang['TERMS_OFF'] = 'Я не согласен с этими условиями'; $lang['JAVASCRIPT_ON_REGISTER'] = 'Для регистрации необходимо включить JavaScript'; -$lang['REGISTERED_IN_TIME'] = "В данный момент регистрация закрыта

        вы можете зарегистрироваться с 01:00 до 17:00 MSK (сейчас ". date('H:i') ." MSK)

        Приносим извинения за это временное неудобство"; +$lang['REGISTERED_IN_TIME'] = "В данный момент регистрация закрыта

        вы можете зарегистрироваться с 01:00 до 17:00 MSK (сейчас " . date('H:i') . " MSK)

        Приносим извинения за это временное неудобство"; $lang['AUTOCOMPLETE'] = 'Сгенерировать пароль'; $lang['YOUR_NEW_PASSWORD'] = 'Ваш пароль: '; $lang['REGENERATE'] = 'Перегенерировать'; @@ -1548,7 +1548,7 @@ $lang['ACTIONS_LOG'] = 'Отчет по действиям'; //Welcome page $lang['IDX_BROWSER_NSP_FRAME'] = 'Простите, но ваш браузер не поддерживает фреймы.'; -$lang['IDX_CLEAR_CACHE'] ='Очистить кеш:'; +$lang['IDX_CLEAR_CACHE'] = 'Очистить кеш:'; $lang['IDX_CLEAR_DATASTORE'] = 'Данные'; $lang['IDX_CLEAR_TEMPLATES'] = 'Шаблоны'; $lang['IDX_CLEAR_NEWNEWS'] = 'Новости'; @@ -1580,7 +1580,7 @@ $lang['USERS_PER_DAY'] = 'Пользователей в день'; $lang['BOARD_STARTED'] = 'Дата запуска'; $lang['AVATAR_DIR_SIZE'] = 'Размер директории с аватарами'; $lang['DATABASE_SIZE'] = 'Объем БД'; -$lang['GZIP_COMPRESSION'] ='сжатие Gzip'; +$lang['GZIP_COMPRESSION'] = 'сжатие Gzip'; $lang['NOT_AVAILABLE'] = 'Недоступно'; // Clear Cache @@ -2307,12 +2307,12 @@ $lang['CRON_EDIT_HEAD_EDIT'] = 'Редактировать задачу'; $lang['CRON_EDIT_HEAD_ADD'] = 'Добавить задачу'; $lang['CRON_SCRIPT_EXPL'] = 'название в папке "includes/cron/jobs/"'; $lang['SCHEDULE'] = array( - 'select' => '» Выберите запуск', - 'hourly' => 'ежечасно', - 'daily' => 'ежедневно', - 'weekly' => 'еженедельно', - 'monthly' => 'ежемесячно', - 'interval' => 'интервал' + 'select' => '» Выберите запуск', + 'hourly' => 'ежечасно', + 'daily' => 'ежедневно', + 'weekly' => 'еженедельно', + 'monthly' => 'ежемесячно', + 'interval' => 'интервал' ); $lang['NOSELECT'] = 'Не указан'; $lang['RUN_DAY'] = 'День запуска'; @@ -2441,15 +2441,15 @@ $lang['CALLSEED_MSG_SPAM'] = 'Запрос уже был отправлен (в $lang['CALLSEED_HAVE_SEED'] = 'Раздача не нуждается в помощи (Сидеров: %d)'; $lang['LOG_ACTION']['LOG_TYPE'] = array( - 'mod_topic_delete' => 'Топик:
        удален', - 'mod_topic_move' => 'Топик:
        перенесен', - 'mod_topic_lock' => 'Топик:
        закрыт', - 'mod_topic_unlock' => 'Топик:
        открыт', - 'mod_topic_split' => 'Топик:
        разделен', - 'mod_post_delete' => 'Пост:
        удален', - 'adm_user_delete' => 'Юзер:
        удален', - 'adm_user_ban' => 'Юзер:
        забанен', - 'adm_user_unban' => 'Юзер:
        разбанен' + 'mod_topic_delete' => 'Топик:
        удален', + 'mod_topic_move' => 'Топик:
        перенесен', + 'mod_topic_lock' => 'Топик:
        закрыт', + 'mod_topic_unlock' => 'Топик:
        открыт', + 'mod_topic_split' => 'Топик:
        разделен', + 'mod_post_delete' => 'Пост:
        удален', + 'adm_user_delete' => 'Юзер:
        удален', + 'adm_user_ban' => 'Юзер:
        забанен', + 'adm_user_unban' => 'Юзер:
        разбанен' ); $lang['ACTS_LOG_ALL_ACTIONS'] = 'Все действия'; @@ -2589,26 +2589,26 @@ $lang['MC_FAQ'] = 'Введенный Вами текст будет отобр $lang['MC_COMMENT_PM_SUBJECT'] = "%s в Вашем сообщении"; $lang['MC_COMMENT_PM_MSG'] = "Здравствуйте, [b]%s[/b]\nМодератор оставил в Вашем сообщении [url=%s][b]%s[/b][/url][quote]\n%s\n[/quote]"; $lang['MC_COMMENT'] = array( - 0 => array( - 'title' => '', - 'type' => 'Удалить комментарий', - ), - 1 => array( - 'title' => 'Комментарий от %s', - 'type' => 'Комментарий', - ), - 2 => array( - 'title' => 'Информация от %s', - 'type' => 'Информация', - ), - 3 => array( - 'title' => 'Предупреждение от %s', - 'type' => 'Предупреждение', - ), - 4 => array( - 'title' => 'Нарушение от %s', - 'type' => 'Нарушение', - ), + 0 => array( + 'title' => '', + 'type' => 'Удалить комментарий', + ), + 1 => array( + 'title' => 'Комментарий от %s', + 'type' => 'Комментарий', + ), + 2 => array( + 'title' => 'Информация от %s', + 'type' => 'Информация', + ), + 3 => array( + 'title' => 'Предупреждение от %s', + 'type' => 'Предупреждение', + ), + 4 => array( + 'title' => 'Нарушение от %s', + 'type' => 'Нарушение', + ), ); $lang['SITEMAP'] = 'Карта сайта (sitemap)'; @@ -2649,14 +2649,14 @@ $lang['TERMS_EMPTY_TEXT'] = '[align=center]Текст этой страницы $lang['TERMS_EXPLAIN'] = 'На данной странице вы можете указать текст основных правил ресурса, выводящихся пользователям.'; $lang['TR_STATS'] = array( - 0 => 'неактивные пользователи в течение 30 дней', - 1 => 'неактивные пользователи в течение 90 дней', - 2 => 'средний размер раздачи на трекере (сколько мегабайт)', - 3 => 'сколько у нас всего раздач на трекере', - 4 => 'сколько живых раздач (есть хотя бы 1 сид)', - 5 => 'сколько раздач где которые сидируются больше 5 сидами', - 6 => 'сколько у нас аплоадеров (те, кто залили хотя бы 1 раздачу)', - 7 => 'сколько аплоадеров за последние 30 дней', + 0 => 'неактивные пользователи в течение 30 дней', + 1 => 'неактивные пользователи в течение 90 дней', + 2 => 'средний размер раздачи на трекере (сколько мегабайт)', + 3 => 'сколько у нас всего раздач на трекере', + 4 => 'сколько живых раздач (есть хотя бы 1 сид)', + 5 => 'сколько раздач где которые сидируются больше 5 сидами', + 6 => 'сколько у нас аплоадеров (те, кто залили хотя бы 1 раздачу)', + 7 => 'сколько аплоадеров за последние 30 дней', ); $lang['NEW_POLL_START'] = 'Опрос включен'; @@ -2688,16 +2688,16 @@ $lang['UPLOAD_ERROR_DIMENSIONS'] = 'Размеры изображения пре $lang['UPLOAD_ERROR_NOT_IMAGE'] = 'Загруженный файл не является изображением'; $lang['UPLOAD_ERROR_NOT_ALLOWED'] = 'Расширение %s для загружаемых файлов не разрешено'; $lang['UPLOAD_ERRORS'] = array( - UPLOAD_ERR_INI_SIZE => 'превышен максимальный размер файлов для сервера', - UPLOAD_ERR_FORM_SIZE => 'превышен максимальный размер загружаемого файла', - UPLOAD_ERR_PARTIAL => 'файл был загружен частично', - UPLOAD_ERR_NO_FILE => 'файл не был загружен', - UPLOAD_ERR_NO_TMP_DIR => 'временная директория не найдена', - UPLOAD_ERR_CANT_WRITE => 'ошибка записи', - UPLOAD_ERR_EXTENSION => 'загрузка остановлена из-за расширения', + UPLOAD_ERR_INI_SIZE => 'превышен максимальный размер файлов для сервера', + UPLOAD_ERR_FORM_SIZE => 'превышен максимальный размер загружаемого файла', + UPLOAD_ERR_PARTIAL => 'файл был загружен частично', + UPLOAD_ERR_NO_FILE => 'файл не был загружен', + UPLOAD_ERR_NO_TMP_DIR => 'временная директория не найдена', + UPLOAD_ERR_CANT_WRITE => 'ошибка записи', + UPLOAD_ERR_EXTENSION => 'загрузка остановлена из-за расширения', ); // Captcha $lang['CAPTCHA'] = 'Проверка, что вы не робот'; $lang['CAPTCHA_WRONG'] = 'Вы не смогли подтвердить, что вы не робот'; -$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha настроена не полностью

        Если вы еще не сгенерировали ключи, вы можете это сделать на странице https://www.google.com/recaptcha/admin.
        После того, как вы сгенерируете ключи, нужно прописать их в файл library/config.php.

        '; \ No newline at end of file +$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha настроена не полностью

        Если вы еще не сгенерировали ключи, вы можете это сделать на странице https://www.google.com/recaptcha/admin.
        После того, как вы сгенерируете ключи, нужно прописать их в файл library/config.php.

        '; diff --git a/library/language/uk/main.php b/library/language/uk/main.php index 926224fae..d56f8128e 100644 --- a/library/language/uk/main.php +++ b/library/language/uk/main.php @@ -401,7 +401,7 @@ $lang['SAVEBOX'] = 'Збережені'; $lang['SENTBOX'] = 'Надіслані'; $lang['FLAG'] = 'Прапор'; $lang['SUBJECT'] = 'Тема'; -$lang['FROM']='Від кого'; +$lang['FROM'] = 'Від кого'; $lang['TO'] = 'Кому'; $lang['DATE'] = 'Дата'; $lang['MARK'] = 'Оцінка'; @@ -510,9 +510,9 @@ $lang['ALWAYS_NOTIFY_EXPLAIN'] = 'Коли хто-небудь відповіс $lang['BOARD_LANG'] = 'Мова'; $lang['GENDER'] = 'Стать'; $lang['GENDER_SELECT'] = array( - 0 => 'Не вказана', - 1 => 'Чоловіча', - 2 => 'Жіноча' + 0 => 'Не вказана', + 1 => 'Чоловіча', + 2 => 'Жіноча' ); $lang['MODULE_OFF'] = 'Модуль відключений!'; @@ -1045,18 +1045,18 @@ $lang['TOR_STATUS_SELECT_ACTION'] = 'Виберіть статус'; $lang['TOR_STATUS_NOT_SELECT'] = 'Ви не вибрали статус.'; $lang['TOR_STATUS_SELECT_ALL'] = 'Всі статуси'; $lang['TOR_STATUS_NAME'] = array( - TOR_NOT_APPROVED => 'не перевірено', - TOR_CLOSED => 'закрито', - TOR_APPROVED => 'перевірено', - TOR_NEED_EDIT => 'недооформлено', - TOR_NO_DESC => 'неоформлено', - TOR_DUP => 'повтор', - TOR_CLOSED_CPHOLD => 'закрито правовласником', - TOR_CONSUMED => 'поглинена', - TOR_DOUBTFUL => 'сумнівна', - TOR_CHECKING => 'перевіряється', - TOR_TMP => 'тимчасова', - TOR_PREMOD => 'премодерація', + TOR_NOT_APPROVED => 'не перевірено', + TOR_CLOSED => 'закрито', + TOR_APPROVED => 'перевірено', + TOR_NEED_EDIT => 'недооформлено', + TOR_NO_DESC => 'неоформлено', + TOR_DUP => 'повтор', + TOR_CLOSED_CPHOLD => 'закрито правовласником', + TOR_CONSUMED => 'поглинена', + TOR_DOUBTFUL => 'сумнівна', + TOR_CHECKING => 'перевіряється', + TOR_TMP => 'тимчасова', + TOR_PREMOD => 'премодерація', ); $lang['TOR_STATUS_FAILED'] = 'Такого статусу не існує!'; $lang['TORRENT_FAILED'] = 'Роздача не знайдено!'; @@ -1301,19 +1301,19 @@ $lang['DECLENSION']['REPLIES'] = array('відповідь', 'відповіді $lang['DECLENSION']['TIMES'] = array('раз', 'рази', 'раз'); $lang['DELTA_TIME']['INTERVALS'] = array( - 'seconds' => array('секунда', 'секунди', 'секунд'), - 'minutes' => array('хвилина', 'хвилини', 'хвилин'), - 'hours' => array('година', 'години', 'годин'), - 'mday' => array('день', 'дня', 'днів'), - 'mon' => array('місяць', 'місяця', 'місяців'), - 'year' => array('рік', 'року', 'років'), + 'seconds' => array('секунда', 'секунди', 'секунд'), + 'minutes' => array('хвилина', 'хвилини', 'хвилин'), + 'hours' => array('година', 'години', 'годин'), + 'mday' => array('день', 'дня', 'днів'), + 'mon' => array('місяць', 'місяця', 'місяців'), + 'year' => array('рік', 'року', 'років'), ); $lang['DELTA_TIME']['FORMAT'] = '%1$s %2$s'; // 5(%1) минут(%2) -$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; -$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; -$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; -$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; +$lang['AUTH_TYPES'][AUTH_ALL] = $lang['AUTH_ANONYMOUS_USERS']; +$lang['AUTH_TYPES'][AUTH_REG] = $lang['AUTH_REGISTERED_USERS']; +$lang['AUTH_TYPES'][AUTH_ACL] = $lang['AUTH_USERS_GRANTED_ACCESS']; +$lang['AUTH_TYPES'][AUTH_MOD] = $lang['AUTH_MODERATORS']; $lang['AUTH_TYPES'][AUTH_ADMIN] = $lang['AUTH_ADMINISTRATORS']; $lang['NEW_USER_REG_DISABLED'] = 'Реєстрація нових користувачів тимчасово відключена'; @@ -1414,7 +1414,7 @@ $lang['EMAILER_DISABLED'] = 'Вибачте, ця функція тимчасо $lang['TERMS_ON'] = 'Я згоден з цими умовами'; $lang['TERMS_OFF'] = 'Я не згоден з цими умовами'; $lang['JAVASCRIPT_ON_REGISTER'] = 'Для реєстрації необхідно включити JavaScript'; -$lang['REGISTERED_IN_TIME'] = "В даний момент реєстрація закрита

        ви можете зареєструватися з 01:00 до 17:00 Kiev (зараз ". date('H:i') ." Kiev)

        Приносимо вибачення за це тимчасові незручності"; +$lang['REGISTERED_IN_TIME'] = "В даний момент реєстрація закрита

        ви можете зареєструватися з 01:00 до 17:00 Kiev (зараз " . date('H:i') . " Kiev)

        Приносимо вибачення за це тимчасові незручності"; $lang['AUTOCOMPLETE'] = 'Згенерувати пароль'; $lang['YOUR_NEW_PASSWORD'] = 'Ваш пароль: '; $lang['REGENERATE'] = 'Перегенерувати'; @@ -1548,7 +1548,7 @@ $lang['ACTIONS_LOG'] = 'Звіт по діям'; //Welcome page $lang['IDX_BROWSER_NSP_FRAME'] = 'Вибачте, але ваш браузер не підтримує фрейми.'; -$lang['IDX_CLEAR_CACHE'] ='Очистити кеш:'; +$lang['IDX_CLEAR_CACHE'] = 'Очистити кеш:'; $lang['IDX_CLEAR_DATASTORE'] = 'Дані'; $lang['IDX_CLEAR_TEMPLATES'] = 'Шаблони'; $lang['IDX_CLEAR_NEWNEWS'] = 'Новини'; @@ -1580,7 +1580,7 @@ $lang['USERS_PER_DAY'] = 'Користувачів'; $lang['BOARD_STARTED'] = 'Дата запуску'; $lang['AVATAR_DIR_SIZE'] = 'Розмір директорії з аватарами'; $lang['DATABASE_SIZE'] = "Об'єм БД"; -$lang['GZIP_COMPRESSION'] ='стискання Gzip'; +$lang['GZIP_COMPRESSION'] = 'стискання Gzip'; $lang['NOT_AVAILABLE'] = 'Недоступне'; // Clear Cache @@ -2307,12 +2307,12 @@ $lang['CRON_EDIT_HEAD_EDIT'] = 'Редагувати завдання'; $lang['CRON_EDIT_HEAD_ADD'] = 'Додати завдання'; $lang['CRON_SCRIPT_EXPL'] = 'назва в папці "includes/cron/jobs/"'; $lang['SCHEDULE'] = array( - 'select' => '» Оберить запуск', - 'hourly' => 'щогодини', - 'daily' => 'щодня', - 'weekly' => 'щотижня', - 'monthly' => 'щомісяця', - 'interval' => 'інтервал' + 'select' => '» Оберить запуск', + 'hourly' => 'щогодини', + 'daily' => 'щодня', + 'weekly' => 'щотижня', + 'monthly' => 'щомісяця', + 'interval' => 'інтервал' ); $lang['NOSELECT'] = 'Не вказано'; $lang['RUN_DAY'] = 'День запуску'; @@ -2436,20 +2436,20 @@ $lang['CALLSEED'] = 'Покликати, кто завантажил'; $lang['CALLSEED_EXPLAIN'] = 'Приймати повідомлення з проханням повернутися на роздачу'; $lang['CALLSEED_SUBJECT'] = 'Допоможіть завантажити %s'; $lang['CALLSEED_TEXT'] = 'Привіт![br]Ваша допомога необхідна в роздачі [url=%s]%s[/url][br]Якщо ви вирішили допомогти, але вже видалили торрент-файл, можете завантажити його [url=%s]здесь[/url][br][br]Сподіваюся на вашу допомогу!'; -$lang['CALLSEED_MSG_OK'] = 'Повідомлення успішно відправлено всім скачавшим даний реліз'; +$lang['CALLSEED_MSG_OK'] = 'Повідомлення успішно відправлено всім скачавшим даний реліз'; $lang['CALLSEED_MSG_SPAM'] = 'Запит вже одного разу успішно надісланий (можливо не Вами)

        Наступна можливість відіслати запит буде через %s.'; -$lang['CALLSEED_HAVE_SEED'] = 'Роздача не потребує допомоги (Сидерів: %d)'; +$lang['CALLSEED_HAVE_SEED'] = 'Роздача не потребує допомоги (Сидерів: %d)'; $lang['LOG_ACTION']['LOG_TYPE'] = array( - 'mod_topic_delete' => 'Топік:
        видалений', - 'mod_topic_move' => 'Топік:
        перенесений', - 'mod_topic_lock' => 'Топік:
        закритий', - 'mod_topic_unlock' => 'Топік:
        відкритий', - 'mod_topic_split' => 'Топік:
        розділений', - 'mod_post_delete' => 'Пост:
        видалений', - 'adm_user_delete' => 'Юзер:
        видалений', - 'adm_user_ban' => 'Юзер:
        забанен', - 'adm_user_unban' => 'Юзер:
        разбанен' + 'mod_topic_delete' => 'Топік:
        видалений', + 'mod_topic_move' => 'Топік:
        перенесений', + 'mod_topic_lock' => 'Топік:
        закритий', + 'mod_topic_unlock' => 'Топік:
        відкритий', + 'mod_topic_split' => 'Топік:
        розділений', + 'mod_post_delete' => 'Пост:
        видалений', + 'adm_user_delete' => 'Юзер:
        видалений', + 'adm_user_ban' => 'Юзер:
        забанен', + 'adm_user_unban' => 'Юзер:
        разбанен' ); $lang['ACTS_LOG_ALL_ACTIONS'] = 'Всі дії'; @@ -2589,26 +2589,26 @@ $lang['MC_FAQ'] = 'Доданий Вами текст буде відображ $lang['MC_COMMENT_PM_SUBJECT'] = "%s у Вашому повідомленні"; $lang['MC_COMMENT_PM_MSG'] = "Здрастуйте, [b]%s[/b]\nМодератор залишив у Вашому повідомленні [url=%s][b]%s[/b][/url][quote]\n%s\n[/quote] "; $lang['MC_COMMENT'] = array( - 0 => array( - 'title' => '', - 'type' => 'Видалити коментар', - ), - 1 => array( - 'title' => 'Коментар від %s', - 'type' => 'Коментар', - ), - 2 => array( - 'title' => 'Информація від %s', - 'type' => 'Информація', - ), - 3 => array( - 'title' => 'Попередження від %s', - 'type' => 'Попередження', - ), - 4 => array( - 'title' => 'Порушення від %s', - 'type' => 'Порушення', - ), + 0 => array( + 'title' => '', + 'type' => 'Видалити коментар', + ), + 1 => array( + 'title' => 'Коментар від %s', + 'type' => 'Коментар', + ), + 2 => array( + 'title' => 'Информація від %s', + 'type' => 'Информація', + ), + 3 => array( + 'title' => 'Попередження від %s', + 'type' => 'Попередження', + ), + 4 => array( + 'title' => 'Порушення від %s', + 'type' => 'Порушення', + ), ); $lang['SITEMAP'] = 'Карта сайту (sitemap)'; @@ -2649,14 +2649,14 @@ $lang['TERMS_EMPTY_TEXT'] = '[align=center]Текст цієї сторінки $lang['TERMS_EXPLAIN'] = 'На цій сторінці ви можете вказати текст основних правил ресурсу, які виводяться користувачам.'; $lang['TR_STATS'] = array( - 0 => 'неактивні користувачі протягом 30 днів', - 1 => 'неактивні користувачі протягом 90 днів', - 2 => 'середній розмір роздачі на трекері (скільки мегабайт)', - 3 => 'скільки у нас всього роздачі на трекері', - 4 => 'скільки живих роздач (є хоча б 1 сід)', - 5 => 'скільки роздач де які сидируются більше 5 сидами', - 6 => 'скільки у нас аплоадеров (ті, хто залили хоча б 1 роздачу)', - 7 => 'скільки аплоадеров за останні 30 днів', + 0 => 'неактивні користувачі протягом 30 днів', + 1 => 'неактивні користувачі протягом 90 днів', + 2 => 'середній розмір роздачі на трекері (скільки мегабайт)', + 3 => 'скільки у нас всього роздачі на трекері', + 4 => 'скільки живих роздач (є хоча б 1 сід)', + 5 => 'скільки роздач де які сидируются більше 5 сидами', + 6 => 'скільки у нас аплоадеров (ті, хто залили хоча б 1 роздачу)', + 7 => 'скільки аплоадеров за останні 30 днів', ); $lang['NEW_POLL_START'] = 'Опитування включений'; @@ -2688,16 +2688,16 @@ $lang['UPLOAD_ERROR_DIMENSIONS'] = 'Розміри зображення пере $lang['UPLOAD_ERROR_NOT_IMAGE'] = 'Завантажений файл не є зображенням'; $lang['UPLOAD_ERROR_NOT_ALLOWED'] = 'Розширення %s для файлів, що завантажуються не дозволено'; $lang['UPLOAD_ERRORS'] = array( - UPLOAD_ERR_INI_SIZE => 'перевищено максимальний розмір файлів для сервера', - UPLOAD_ERR_FORM_SIZE => 'перевищено максимальний розмір завантажуваного файлу', - UPLOAD_ERR_PARTIAL => 'файл був завантажений частково', - UPLOAD_ERR_NO_FILE => 'файл не був завантажений', - UPLOAD_ERR_NO_TMP_DIR => 'тимчасова директорія не знайдено', - UPLOAD_ERR_CANT_WRITE => 'помилка запису', - UPLOAD_ERR_EXTENSION => 'завантаження зупинено через розширення', + UPLOAD_ERR_INI_SIZE => 'перевищено максимальний розмір файлів для сервера', + UPLOAD_ERR_FORM_SIZE => 'перевищено максимальний розмір завантажуваного файлу', + UPLOAD_ERR_PARTIAL => 'файл був завантажений частково', + UPLOAD_ERR_NO_FILE => 'файл не був завантажений', + UPLOAD_ERR_NO_TMP_DIR => 'тимчасова директорія не знайдено', + UPLOAD_ERR_CANT_WRITE => 'помилка запису', + UPLOAD_ERR_EXTENSION => 'завантаження зупинено через розширення', ); // Captcha $lang['CAPTCHA'] = 'Перевірка, що ви не робот'; $lang['CAPTCHA_WRONG'] = 'Ви не змогли підтвердити, що ви не робот'; -$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha налаштована не повністю

        Якщо ви ще не згенерували ключі, ви можете це зробити на сторінці https://www.google.com/recaptcha/admin.
        Після того, як ви сгенеріруете ключі, потрібно прописати їх у файл library/config.php.

        '; \ No newline at end of file +$lang['CAPTCHA_SETTINGS'] = '

        ReCaptcha налаштована не повністю

        Якщо ви ще не згенерували ключі, ви можете це зробити на сторінці https://www.google.com/recaptcha/admin.
        Після того, як ви сгенеріруете ключі, потрібно прописати їх у файл library/config.php.

        '; diff --git a/login.php b/login.php index 3f6aacc85..7bbc99f6d 100644 --- a/login.php +++ b/login.php @@ -16,43 +16,34 @@ array_deep($_POST, 'trim'); $user->session_start(); // Logout -if (!empty($_GET['logout'])) -{ - if (!IS_GUEST) - { - $user->session_end(); - } - redirect("index.php"); +if (!empty($_GET['logout'])) { + if (!IS_GUEST) { + $user->session_end(); + } + redirect("index.php"); } $redirect_url = "index.php"; $login_errors = array(); // Requested redirect -if (preg_match('/^redirect=([a-z0-9\.#\/\?&=\+\-_]+)/si', $_SERVER['QUERY_STRING'], $matches)) -{ - $redirect_url = $matches[1]; +if (preg_match('/^redirect=([a-z0-9\.#\/\?&=\+\-_]+)/si', $_SERVER['QUERY_STRING'], $matches)) { + $redirect_url = $matches[1]; - if (!strstr($redirect_url, '?') && $first_amp = strpos($redirect_url, '&')) - { - $redirect_url[$first_amp] = '?'; - } -} -elseif (!empty($_POST['redirect'])) -{ - $redirect_url = str_replace('&', '&', htmlspecialchars($_POST['redirect'])); -} -elseif (!empty($_SERVER['HTTP_REFERER']) && ($parts = parse_url($_SERVER['HTTP_REFERER']))) -{ - $redirect_url = (isset($parts['path']) ? $parts['path'] : "index.php") . (isset($parts['query']) ? '?'. $parts['query'] : ''); + if (!strstr($redirect_url, '?') && $first_amp = strpos($redirect_url, '&')) { + $redirect_url[$first_amp] = '?'; + } +} elseif (!empty($_POST['redirect'])) { + $redirect_url = str_replace('&', '&', htmlspecialchars($_POST['redirect'])); +} elseif (!empty($_SERVER['HTTP_REFERER']) && ($parts = parse_url($_SERVER['HTTP_REFERER']))) { + $redirect_url = (isset($parts['path']) ? $parts['path'] : "index.php") . (isset($parts['query']) ? '?' . $parts['query'] : ''); } $redirect_url = str_replace('&admin=1', '', $redirect_url); $redirect_url = str_replace('?admin=1', '', $redirect_url); -if (!$redirect_url || strstr(urldecode($redirect_url), "\n") || strstr(urldecode($redirect_url), "\r") || strstr(urldecode($redirect_url), ';url')) -{ - $redirect_url = "index.php"; +if (!$redirect_url || strstr(urldecode($redirect_url), "\n") || strstr(urldecode($redirect_url), "\r") || strstr(urldecode($redirect_url), ';url')) { + $redirect_url = "index.php"; } $redirect_url = str_replace("&sid={$user->data['session_id']}", '', $redirect_url); @@ -67,72 +58,63 @@ $login_password = isset($_POST['login_password']) ? $_POST['login_password'] : ' // Проверка на неверную комбинацию логин/пароль $need_captcha = false; -if (!$mod_admin_login) -{ - $need_captcha = $cache->has('l_err_'. USER_IP); - if ($need_captcha < $di->config->get('invalid_logins')) $need_captcha = false; +if (!$mod_admin_login) { + $need_captcha = $cache->has('l_err_' . USER_IP); + if ($need_captcha < $di->config->get('invalid_logins')) $need_captcha = false; } // login -if (isset($_POST['login'])) -{ - if (!$mod_admin_login) - { - if (!IS_GUEST) - { - redirect('index.php'); - } - if ($login_username == '' || $login_password == '') - { - $login_errors[] = $lang['ENTER_PASSWORD']; - } - } +if (isset($_POST['login'])) { + if (!$mod_admin_login) { + if (!IS_GUEST) { + redirect('index.php'); + } + if ($login_username == '' || $login_password == '') { + $login_errors[] = $lang['ENTER_PASSWORD']; + } + } - // Captcha - if ($need_captcha && !bb_captcha('check') && !$di->config->get('captcha.disabled')) - { - $login_errors[] = $lang['CAPTCHA_WRONG']; - } + // Captcha + if ($need_captcha && !bb_captcha('check') && !$di->config->get('captcha.disabled')) { + $login_errors[] = $lang['CAPTCHA_WRONG']; + } - if (!$login_errors) - { - if ($user->login($_POST, $mod_admin_login)) - { - $redirect_url = (defined('FIRST_LOGON')) ? $di->config->get('first_logon_redirect_url') : $redirect_url; - // Удаление при введении правильной комбинации логин/пароль - $cache->delete('l_err_'. USER_IP); + if (!$login_errors) { + if ($user->login($_POST, $mod_admin_login)) { + $redirect_url = (defined('FIRST_LOGON')) ? $di->config->get('first_logon_redirect_url') : $redirect_url; + // Удаление при введении правильной комбинации логин/пароль + $cache->delete('l_err_' . USER_IP); - if ($redirect_url == '/' . LOGIN_URL || $redirect_url == LOGIN_URL) $redirect_url = 'index.php'; - redirect($redirect_url); - } + if ($redirect_url == '/' . LOGIN_URL || $redirect_url == LOGIN_URL) $redirect_url = 'index.php'; + redirect($redirect_url); + } - $login_errors[] = $lang['ERROR_LOGIN']; + $login_errors[] = $lang['ERROR_LOGIN']; - if (!$mod_admin_login) { - $login_err = $cache->get('l_err_' . USER_IP); - if ($login_err > $di->config->get('invalid_logins')) $need_captcha = true; - $cache->set('l_err_' . USER_IP, ($login_err + 1), 3600); - } else { - $need_captcha = false; - } - } + if (!$mod_admin_login) { + $login_err = $cache->get('l_err_' . USER_IP); + if ($login_err > $di->config->get('invalid_logins')) $need_captcha = true; + $cache->set('l_err_' . USER_IP, ($login_err + 1), 3600); + } else { + $need_captcha = false; + } + } } // Login page -if (IS_GUEST || $mod_admin_login) -{ - $template->assign_vars(array( - 'LOGIN_USERNAME' => htmlCHR($login_username), - 'LOGIN_PASSWORD' => htmlCHR($login_password), - 'ERROR_MESSAGE' => join('
        ', $login_errors), - 'ADMIN_LOGIN' => $mod_admin_login, - 'REDIRECT_URL' => htmlCHR($redirect_url), - 'CAPTCHA_HTML' => ($need_captcha && !$di->config->get('captcha.disabled')) ? bb_captcha('get') : '', - 'PAGE_TITLE' => $lang['LOGIN'], - 'S_LOGIN_ACTION' => LOGIN_URL, - )); +if (IS_GUEST || $mod_admin_login) { + $template->assign_vars(array( + 'LOGIN_USERNAME' => htmlCHR($login_username), + 'LOGIN_PASSWORD' => htmlCHR($login_password), + 'ERROR_MESSAGE' => join('
        ', $login_errors), + 'ADMIN_LOGIN' => $mod_admin_login, + 'REDIRECT_URL' => htmlCHR($redirect_url), + 'CAPTCHA_HTML' => ($need_captcha && !$di->config->get('captcha.disabled')) ? bb_captcha('get') : '', + 'PAGE_TITLE' => $lang['LOGIN'], + 'S_LOGIN_ACTION' => LOGIN_URL, + )); - print_page('login.tpl'); + print_page('login.tpl'); } -redirect($redirect_url); \ No newline at end of file +redirect($redirect_url); diff --git a/memberlist.php b/memberlist.php index b786398f4..6d23c4b5e 100644 --- a/memberlist.php +++ b/memberlist.php @@ -2,7 +2,7 @@ define('BB_SCRIPT', 'memberlist'); define('BB_ROOT', './'); -require(BB_ROOT .'common.php'); +require(BB_ROOT . 'common.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -12,54 +12,50 @@ $page_cfg['use_tablesorter'] = true; $user->session_start(array('req_login' => true)); $start = abs(intval(request_var('start', 0))); -$mode = (string) request_var('mode', 'joined'); +$mode = (string)request_var('mode', 'joined'); $sort_order = (request_var('order', 'ASC') == 'ASC') ? 'ASC' : 'DESC'; -$username = request_var('username', ''); +$username = request_var('username', ''); $paginationusername = $username; // // Memberlist sorting // $mode_types_text = array( - $lang['SORT_JOINED'], - $lang['SORT_USERNAME'], - $lang['SORT_LOCATION'], - $lang['SORT_POSTS'], - $lang['SORT_EMAIL'], - $lang['SORT_WEBSITE'], - $lang['SORT_TOP_TEN'] + $lang['SORT_JOINED'], + $lang['SORT_USERNAME'], + $lang['SORT_LOCATION'], + $lang['SORT_POSTS'], + $lang['SORT_EMAIL'], + $lang['SORT_WEBSITE'], + $lang['SORT_TOP_TEN'] ); $mode_types = array( - 'joined', - 'username', - 'location', - 'posts', - 'email', - 'website', - 'topten' + 'joined', + 'username', + 'location', + 'posts', + 'email', + 'website', + 'topten' ); // '; -for ($i=0, $cnt=count($mode_types_text); $i < $cnt; $i++) -{ - $selected = ( $mode == $mode_types[$i] ) ? ' selected="selected"' : ''; - $select_sort_mode .= ''; +for ($i = 0, $cnt = count($mode_types_text); $i < $cnt; $i++) { + $selected = ($mode == $mode_types[$i]) ? ' selected="selected"' : ''; + $select_sort_mode .= ''; } $select_sort_mode .= ''; // '; -if ($sort_order == 'ASC') -{ - $select_sort_order .= ''; -} -else -{ - $select_sort_order .= ''; +if ($sort_order == 'ASC') { + $select_sort_order .= ''; +} else { + $select_sort_order .= ''; } $select_sort_order .= ''; @@ -67,39 +63,38 @@ $select_sort_order .= ''; // Generate page // $template->assign_vars(array( - 'S_MODE_SELECT' => $select_sort_mode, - 'S_ORDER_SELECT' => $select_sort_order, - 'S_MODE_ACTION' => "memberlist.php", - 'S_USERNAME' => $paginationusername, + 'S_MODE_SELECT' => $select_sort_mode, + 'S_ORDER_SELECT' => $select_sort_order, + 'S_MODE_ACTION' => "memberlist.php", + 'S_USERNAME' => $paginationusername, )); -switch( $mode ) -{ - case 'joined': - $order_by = "user_id $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'username': - $order_by = "username $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'location': - $order_by = "user_from $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'posts': - $order_by = "user_posts $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'email': - $order_by = "user_email $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'website': - $order_by = "user_website $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - break; - case 'topten': - $order_by = "user_posts $sort_order LIMIT 10"; - break; - default: - $order_by = "user_regdate $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); - $mode = 'joined'; - break; +switch ($mode) { + case 'joined': + $order_by = "user_id $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'username': + $order_by = "username $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'location': + $order_by = "user_from $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'posts': + $order_by = "user_posts $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'email': + $order_by = "user_email $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'website': + $order_by = "user_website $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + break; + case 'topten': + $order_by = "user_posts $sort_order LIMIT 10"; + break; + default: + $order_by = "user_regdate $sort_order LIMIT $start, " . $di->config->get('topics_per_page'); + $mode = 'joined'; + break; } // per-letter selection @@ -112,129 +107,107 @@ $select_letter = $letter_sql = ''; $by_letter_req = isset($_REQUEST['letter']) ? strtolower(trim($_REQUEST['letter'])) : false; -if ($by_letter_req) -{ - if ($by_letter_req === 'all') - { - $by_letter = 'all'; - $letter_sql = ''; - } - else if ($by_letter_req === 'others') - { - $by_letter = 'others'; - $letter_sql = "username REGEXP '^[!-@\\[-`].*$'"; - } - else if ($letter_req = preg_replace("#[^$letters_range]#ui", '', iconv('windows-1251', 'UTF-8', $by_letter_req[0]))) - { - $by_letter = DB()->escape($letter_req); - $letter_sql = "LOWER(username) LIKE '$by_letter%'"; - } +if ($by_letter_req) { + if ($by_letter_req === 'all') { + $by_letter = 'all'; + $letter_sql = ''; + } else if ($by_letter_req === 'others') { + $by_letter = 'others'; + $letter_sql = "username REGEXP '^[!-@\\[-`].*$'"; + } else if ($letter_req = preg_replace("#[^$letters_range]#ui", '', iconv('windows-1251', 'UTF-8', $by_letter_req[0]))) { + $by_letter = DB()->escape($letter_req); + $letter_sql = "LOWER(username) LIKE '$by_letter%'"; + } } // ENG -for ($i=ord('A'), $cnt=ord('Z'); $i <= $cnt; $i++) -{ - $select_letter .= ($by_letter == chr($i)) ? ''. chr($i) .' ' : ''. chr($i) .' '; +for ($i = ord('A'), $cnt = ord('Z'); $i <= $cnt; $i++) { + $select_letter .= ($by_letter == chr($i)) ? '' . chr($i) . ' ' : '' . chr($i) . ' '; } // RUS $select_letter .= ': '; -for ($i=224, $cnt=255; $i <= $cnt; $i++) -{ - $select_letter .= ($by_letter == iconv('windows-1251', 'UTF-8', chr($i))) ? ''. iconv('windows-1251', 'UTF-8', chr($i-32)) .' ' : ''. iconv('windows-1251', 'UTF-8', chr($i-32)) .' '; +for ($i = 224, $cnt = 255; $i <= $cnt; $i++) { + $select_letter .= ($by_letter == iconv('windows-1251', 'UTF-8', chr($i))) ? '' . iconv('windows-1251', 'UTF-8', chr($i - 32)) . ' ' : '' . iconv('windows-1251', 'UTF-8', chr($i - 32)) . ' '; } $select_letter .= ': '; -$select_letter .= ($by_letter == 'others') ? ''. $lang['OTHERS'] .' ' : ''. $lang['OTHERS'] .' '; +$select_letter .= ($by_letter == 'others') ? '' . $lang['OTHERS'] . ' ' : '' . $lang['OTHERS'] . ' '; $select_letter .= ': '; -$select_letter .= ($by_letter == 'all') ? ''. $lang['ALL'] .'' : ''. $lang['ALL'] .''; +$select_letter .= ($by_letter == 'all') ? '' . $lang['ALL'] . '' : '' . $lang['ALL'] . ''; $template->assign_vars(array( - 'S_LETTER_SELECT' => $select_letter, - 'S_LETTER_HIDDEN' => '', + 'S_LETTER_SELECT' => $select_letter, + 'S_LETTER_HIDDEN' => '', )); // per-letter selection end -$sql = "SELECT username, user_id, user_rank, user_opt, user_posts, user_regdate, user_from, user_website, user_email FROM ". BB_USERS ." WHERE user_id NOT IN(". EXCLUDED_USERS .")"; -if ( $username ) -{ - $username = preg_replace('/\*/', '%', clean_username($username)); - $letter_sql = "username LIKE '". DB()->escape($username) ."'"; +$sql = "SELECT username, user_id, user_rank, user_opt, user_posts, user_regdate, user_from, user_website, user_email FROM " . BB_USERS . " WHERE user_id NOT IN(" . EXCLUDED_USERS . ")"; +if ($username) { + $username = preg_replace('/\*/', '%', clean_username($username)); + $letter_sql = "username LIKE '" . DB()->escape($username) . "'"; } $sql .= ($letter_sql) ? " AND $letter_sql" : ''; $sql .= " ORDER BY $order_by"; -if ($result = DB()->fetch_rowset($sql)) -{ - foreach($result as $i => $row) - { - $user_id = $row['user_id']; - $from = $row['user_from']; - $joined = bb_date($row['user_regdate'], $di->config->get('date_format')); - $posts = $row['user_posts']; - $pm = ($di->config->get('text_buttons')) ? ''. $lang['SEND_PM_TXTB'] .'' : '' . $lang['SEND_PRIVATE_MESSAGE'] . ''; +if ($result = DB()->fetch_rowset($sql)) { + foreach ($result as $i => $row) { + $user_id = $row['user_id']; + $from = $row['user_from']; + $joined = bb_date($row['user_regdate'], $di->config->get('date_format')); + $posts = $row['user_posts']; + $pm = ($di->config->get('text_buttons')) ? '' . $lang['SEND_PM_TXTB'] . '' : '' . $lang['SEND_PRIVATE_MESSAGE'] . ''; - if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || IS_ADMIN) - { - $email_uri = ($di->config->get('board_email_form')) ? ("profile.php?mode=email&". POST_USERS_URL ."=$user_id") : 'mailto:'. $row['user_email']; - $email = ''. $row['user_email'] .''; - } - else - { - $email = ''; - } + if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || IS_ADMIN) { + $email_uri = ($di->config->get('board_email_form')) ? ("profile.php?mode=email&" . POST_USERS_URL . "=$user_id") : 'mailto:' . $row['user_email']; + $email = '' . $row['user_email'] . ''; + } else { + $email = ''; + } - if ($row['user_website']) - { - $www = ($di->config->get('text_buttons')) ? ''. $lang['VISIT_WEBSITE_TXTB'] .'' : '' . $lang['VISIT_WEBSITE'] . ''; - } - else - { - $www = ''; - } + if ($row['user_website']) { + $www = ($di->config->get('text_buttons')) ? '' . $lang['VISIT_WEBSITE_TXTB'] . '' : '' . $lang['VISIT_WEBSITE'] . ''; + } else { + $www = ''; + } - $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('memberrow', array( - 'ROW_NUMBER' => $i + ( $start + 1 ), - 'ROW_CLASS' => $row_class, - 'USER' => profile_url($row), - 'FROM' => $from, - 'JOINED_RAW' => $row['user_regdate'], - 'JOINED' => $joined, - 'POSTS' => $posts, - 'PM' => $pm, - 'EMAIL' => $email, - 'WWW' => $www, - 'U_VIEWPROFILE' => PROFILE_URL . $user_id, - )); - } -} -else -{ - $template->assign_block_vars('no_username', array( - 'NO_USER_ID_SPECIFIED' => $lang['NO_USER_ID_SPECIFIED'], - )); + $row_class = !($i % 2) ? 'row1' : 'row2'; + $template->assign_block_vars('memberrow', array( + 'ROW_NUMBER' => $i + ($start + 1), + 'ROW_CLASS' => $row_class, + 'USER' => profile_url($row), + 'FROM' => $from, + 'JOINED_RAW' => $row['user_regdate'], + 'JOINED' => $joined, + 'POSTS' => $posts, + 'PM' => $pm, + 'EMAIL' => $email, + 'WWW' => $www, + 'U_VIEWPROFILE' => PROFILE_URL . $user_id, + )); + } +} else { + $template->assign_block_vars('no_username', array( + 'NO_USER_ID_SPECIFIED' => $lang['NO_USER_ID_SPECIFIED'], + )); } $paginationurl = "memberlist.php?mode=$mode&order=$sort_order&letter=$by_letter"; if ($paginationusername) $paginationurl .= "&username=$paginationusername"; -if ( $mode != 'topten' || $di->config->get('topics_per_page') < 10 ) -{ - $sql = "SELECT COUNT(*) AS total FROM ". BB_USERS; - $sql .= ($letter_sql) ? " WHERE $letter_sql" : ''; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Error getting total users'); - } - if ($total = DB()->sql_fetchrow($result)) - { - $total_members = $total['total']; - generate_pagination($paginationurl, $total_members, $di->config->get('topics_per_page'), $start). ' '; - } - DB()->sql_freeresult($result); +if ($mode != 'topten' || $di->config->get('topics_per_page') < 10) { + $sql = "SELECT COUNT(*) AS total FROM " . BB_USERS; + $sql .= ($letter_sql) ? " WHERE $letter_sql" : ''; + if (!$result = DB()->sql_query($sql)) { + bb_die('Error getting total users'); + } + if ($total = DB()->sql_fetchrow($result)) { + $total_members = $total['total']; + generate_pagination($paginationurl, $total_members, $di->config->get('topics_per_page'), $start) . ' '; + } + DB()->sql_freeresult($result); } $template->assign_vars(array( - 'PAGE_TITLE' => $lang['USERS'], + 'PAGE_TITLE' => $lang['USERS'], )); -print_page('memberlist.tpl'); \ No newline at end of file +print_page('memberlist.tpl'); diff --git a/messages/ru.php b/messages/ru.php index fe7f6405b..a3ba7c710 100644 --- a/messages/ru.php +++ b/messages/ru.php @@ -6,7 +6,7 @@ */ return [ - 'Style guide' => 'Гид по стилю', - 'Send' => 'Отправить', - 'Hello, %name%' => 'Добро пожаловать, %name%', -]; \ No newline at end of file + 'Style guide' => 'Гид по стилю', + 'Send' => 'Отправить', + 'Hello, %name%' => 'Добро пожаловать, %name%', +]; diff --git a/modcp.php b/modcp.php index 581361c41..f85d8e609 100644 --- a/modcp.php +++ b/modcp.php @@ -2,10 +2,10 @@ define('BB_SCRIPT', 'modcp'); define('BB_ROOT', './'); -require(BB_ROOT .'common.php'); -require(INC_DIR .'bbcode.php'); -require(INC_DIR .'functions_post.php'); -require_once(INC_DIR .'functions_admin.php'); +require(BB_ROOT . 'common.php'); +require(INC_DIR . 'bbcode.php'); +require(INC_DIR . 'functions_post.php'); +require_once(INC_DIR . 'functions_admin.php'); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); @@ -13,51 +13,45 @@ $di = \TorrentPier\Di::getInstance(); // // Functions // -function return_msg_mcp ($status_msg) +function return_msg_mcp($status_msg) { - global $topic_id, $req_topics, $forum_id, $lang, $mode; + global $topic_id, $req_topics, $forum_id, $lang, $mode; - if (count($req_topics) == 1) - { - $topic_id = $req_topics[0]; - } + if (count($req_topics) == 1) { + $topic_id = $req_topics[0]; + } - $message = $status_msg; - $message .= '

        '; + $message = $status_msg; + $message .= '

        '; - if ($topic_id && $mode != 'delete') - { - $message .= sprintf($lang['CLICK_RETURN_TOPIC'], '', ''); - $message .= '

        '; - } - elseif (count($req_topics) != 1) - { - $message .= sprintf($lang['CLICK_RETURN_MODCP'], '', ''); - $message .= '

        '; - } + if ($topic_id && $mode != 'delete') { + $message .= sprintf($lang['CLICK_RETURN_TOPIC'], '', ''); + $message .= '

        '; + } elseif (count($req_topics) != 1) { + $message .= sprintf($lang['CLICK_RETURN_MODCP'], '', ''); + $message .= '

        '; + } - $message .= sprintf($lang['CLICK_RETURN_FORUM'], '', ''); + $message .= sprintf($lang['CLICK_RETURN_FORUM'], '', ''); - return $message; + return $message; } -function validate_topics ($forum_id, &$req_topics, &$topic_titles) +function validate_topics($forum_id, &$req_topics, &$topic_titles) { - $valid_topics = $valid_titles = array(); + $valid_topics = $valid_titles = array(); - if ($topic_csv = get_id_csv($req_topics)) - { - $sql = "SELECT topic_id, topic_title FROM ". BB_TOPICS ." WHERE topic_id IN($topic_csv) AND forum_id = $forum_id"; + if ($topic_csv = get_id_csv($req_topics)) { + $sql = "SELECT topic_id, topic_title FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) AND forum_id = $forum_id"; - foreach (DB()->fetch_rowset($sql) as $row) - { - $valid_topics[] = $row['topic_id']; - $valid_titles[] = $row['topic_title']; - } - } + foreach (DB()->fetch_rowset($sql) as $row) { + $valid_topics[] = $row['topic_id']; + $valid_titles[] = $row['topic_title']; + } + } - $req_topics = $valid_topics; - $topic_titles = $valid_titles; + $req_topics = $valid_topics; + $topic_titles = $valid_titles; } /** @@ -65,142 +59,114 @@ function validate_topics ($forum_id, &$req_topics, &$topic_titles) * @param $mod_action * @return bool */ -function validate_mode_condition($request_index, $mod_action='') { - if (!$mod_action) { - $mod_action = $request_index; - } - return (isset($_REQUEST[$request_index]) || (isset($_POST['mod_action']) && $_POST['mod_action'] === $mod_action)); +function validate_mode_condition($request_index, $mod_action = '') +{ + if (!$mod_action) { + $mod_action = $request_index; + } + return (isset($_REQUEST[$request_index]) || (isset($_POST['mod_action']) && $_POST['mod_action'] === $mod_action)); } // Obtain initial vars $forum_id = isset($_REQUEST['f']) ? $_REQUEST['f'] : 0; $topic_id = isset($_REQUEST['t']) ? $_REQUEST['t'] : 0; -$post_id = isset($_REQUEST['p']) ? $_REQUEST['p'] : 0; +$post_id = isset($_REQUEST['p']) ? $_REQUEST['p'] : 0; $start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; $confirmed = isset($_POST['confirm']); $mode = $topic_title = ''; -if (isset($_REQUEST['mode'])) -{ - $mode = (string) $_REQUEST['mode']; -} -else -{ - if (validate_mode_condition('delete', 'topic_delete')) - { - $mode = 'delete'; - } - elseif (validate_mode_condition('move', 'topic_move')) - { - $mode = 'move'; - } - elseif (validate_mode_condition('lock', 'topic_lock')) - { - $mode = 'lock'; - } - elseif (validate_mode_condition('unlock', 'topic_unlock')) - { - $mode = 'unlock'; - } - elseif (validate_mode_condition('post_pin')) - { - $mode = 'post_pin'; - } - elseif (validate_mode_condition('post_unpin')) - { - $mode = 'post_unpin'; - } +if (isset($_REQUEST['mode'])) { + $mode = (string)$_REQUEST['mode']; +} else { + if (validate_mode_condition('delete', 'topic_delete')) { + $mode = 'delete'; + } elseif (validate_mode_condition('move', 'topic_move')) { + $mode = 'move'; + } elseif (validate_mode_condition('lock', 'topic_lock')) { + $mode = 'lock'; + } elseif (validate_mode_condition('unlock', 'topic_unlock')) { + $mode = 'unlock'; + } elseif (validate_mode_condition('post_pin')) { + $mode = 'post_pin'; + } elseif (validate_mode_condition('post_unpin')) { + $mode = 'post_unpin'; + } } // Obtain relevant data -if ($topic_id) -{ - $sql = " +if ($topic_id) { + $sql = " SELECT f.forum_id, f.forum_name, f.forum_topics, f.self_moderated, t.topic_first_post_id, t.topic_poster - FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f + FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f WHERE t.topic_id = $topic_id AND f.forum_id = t.forum_id LIMIT 1 "; - if (!$topic_row = DB()->fetch_row($sql)) - { - bb_die('Topic post not exist'); - } + if (!$topic_row = DB()->fetch_row($sql)) { + bb_die('Topic post not exist'); + } - $forum_id = $topic_row['forum_id']; - $forum_name = $topic_row['forum_name']; - $forum_topics = (!$topic_row['forum_topics']) ? 1 : $topic_row['forum_topics']; -} -elseif ($forum_id) -{ - $sql = "SELECT forum_name, forum_topics FROM ". BB_FORUMS ." WHERE forum_id = $forum_id LIMIT 1"; + $forum_id = $topic_row['forum_id']; + $forum_name = $topic_row['forum_name']; + $forum_topics = (!$topic_row['forum_topics']) ? 1 : $topic_row['forum_topics']; +} elseif ($forum_id) { + $sql = "SELECT forum_name, forum_topics FROM " . BB_FORUMS . " WHERE forum_id = $forum_id LIMIT 1"; - if (!$topic_row = DB()->fetch_row($sql)) - { - bb_die('Forum not exist'); - } + if (!$topic_row = DB()->fetch_row($sql)) { + bb_die('Forum not exist'); + } - $forum_name = $topic_row['forum_name']; - $forum_topics = (!$topic_row['forum_topics']) ? 1 : $topic_row['forum_topics']; -} -else -{ - bb_die('Invalid request'); + $forum_name = $topic_row['forum_name']; + $forum_topics = (!$topic_row['forum_topics']) ? 1 : $topic_row['forum_topics']; +} else { + bb_die('Invalid request'); } // Start session management $user->session_start(array('req_login' => true)); // Check if user did or did not confirm. If they did not, forward them to the last page they were on -if (isset($_POST['cancel']) || IS_GUEST) -{ - $redirect = 'index.php'; +if (isset($_POST['cancel']) || IS_GUEST) { + $redirect = 'index.php'; - if ($topic_id || $forum_id) - { - $redirect = ($topic_id) ? TOPIC_URL . $topic_id : FORUM_URL . $forum_id; - } - redirect($redirect); + if ($topic_id || $forum_id) { + $redirect = ($topic_id) ? TOPIC_URL . $topic_id : FORUM_URL . $forum_id; + } + redirect($redirect); } // Start auth check $is_auth = auth(AUTH_ALL, $forum_id, $userdata); $is_moderator = (IS_AM); -if ($mode == 'ip') -{ - // Moderator can view IP in all forums - $is_auth['auth_mod'] = $is_moderator; -} -elseif ($mode == 'move' && !$is_auth['auth_mod']) -{ - // User can move his own topic if this forum is "self_moderated" - if ($topic_id && $topic_row['self_moderated'] && $topic_row['topic_poster'] == $userdata['user_id']) - { - $is_auth['auth_mod'] = true; +if ($mode == 'ip') { + // Moderator can view IP in all forums + $is_auth['auth_mod'] = $is_moderator; +} elseif ($mode == 'move' && !$is_auth['auth_mod']) { + // User can move his own topic if this forum is "self_moderated" + if ($topic_id && $topic_row['self_moderated'] && $topic_row['topic_poster'] == $userdata['user_id']) { + $is_auth['auth_mod'] = true; - $_POST['insert_bot_msg'] = 1; - unset($_POST['topic_id_list']); - unset($_POST['move_leave_shadow']); - } + $_POST['insert_bot_msg'] = 1; + unset($_POST['topic_id_list']); + unset($_POST['move_leave_shadow']); + } } // Exit if user not authorized -if (!$is_auth['auth_mod']) -{ - bb_die($lang['NOT_MODERATOR']); +if (!$is_auth['auth_mod']) { + bb_die($lang['NOT_MODERATOR']); } // Redirect to login page if not admin session -if ($is_moderator && !$userdata['session_admin']) -{ - $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : $_SERVER['REQUEST_URI']; - redirect(LOGIN_URL . "?redirect=$redirect&admin=1"); +if ($is_moderator && !$userdata['session_admin']) { + $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : $_SERVER['REQUEST_URI']; + redirect(LOGIN_URL . "?redirect=$redirect&admin=1"); } // @@ -208,642 +174,572 @@ if ($is_moderator && !$userdata['session_admin']) // $req_topics = $topic_csv = $topic_titles = $hidden_fields = array(); -switch ($mode) -{ - case 'delete': - case 'move': - case 'lock': - case 'unlock': - case 'set_download': - case 'unset_download': - case 'post_pin': - case 'post_unpin': +switch ($mode) { + case 'delete': + case 'move': + case 'lock': + case 'unlock': + case 'set_download': + case 'unset_download': + case 'post_pin': + case 'post_unpin': - if (empty($_POST['topic_id_list']) && empty($topic_id)) - { - bb_die($lang['NONE_SELECTED']); - } + if (empty($_POST['topic_id_list']) && empty($topic_id)) { + bb_die($lang['NONE_SELECTED']); + } - $req_topics = isset($_POST['topic_id_list']) ? $_POST['topic_id_list'] : $topic_id; - validate_topics($forum_id, $req_topics, $topic_titles); + $req_topics = isset($_POST['topic_id_list']) ? $_POST['topic_id_list'] : $topic_id; + validate_topics($forum_id, $req_topics, $topic_titles); - if (!$req_topics || !($topic_csv = get_id_csv($req_topics))) - { - bb_die($lang['NONE_SELECTED']); - } + if (!$req_topics || !($topic_csv = get_id_csv($req_topics))) { + bb_die($lang['NONE_SELECTED']); + } - $hidden_fields = array( - 'sid' => $userdata['session_id'], - 'mode' => $mode, - 'f' => $forum_id, - 't' => $topic_id, - ); - foreach ($req_topics as $req_topic_id) - { - $hidden_fields['topic_id_list'][] = $req_topic_id; - } + $hidden_fields = array( + 'sid' => $userdata['session_id'], + 'mode' => $mode, + 'f' => $forum_id, + 't' => $topic_id, + ); + foreach ($req_topics as $req_topic_id) { + $hidden_fields['topic_id_list'][] = $req_topic_id; + } - break; + break; } // // Perform action or show confirm message // -switch ($mode) -{ - case 'delete': +switch ($mode) { + case 'delete': - if (!$is_auth['auth_delete']) - { - bb_die(sprintf($lang['SORRY_AUTH_DELETE'], $is_auth['auth_delete_type'])); - } + if (!$is_auth['auth_delete']) { + bb_die(sprintf($lang['SORRY_AUTH_DELETE'], $is_auth['auth_delete_type'])); + } - if ($confirmed) - { - $result = topic_delete($req_topics, $forum_id); + if ($confirmed) { + $result = topic_delete($req_topics, $forum_id); - //Обновление кеша новостей на главной - $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); - if (isset($news_forums[$forum_id]) && $di->config->get('show_latest_news') && $result) - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } + //Обновление кеша новостей на главной + $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); + if (isset($news_forums[$forum_id]) && $di->config->get('show_latest_news') && $result) { + $datastore->enqueue('latest_news'); + $datastore->update('latest_news'); + } - $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); - if (isset($net_forums[$forum_id]) && $di->config->get('show_network_news') && $result) - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } + $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); + if (isset($net_forums[$forum_id]) && $di->config->get('show_network_news') && $result) { + $datastore->enqueue('network_news'); + $datastore->update('network_news'); + } - $msg = ($result) ? $lang['TOPICS_REMOVED'] : $lang['NO_TOPICS_REMOVED']; - bb_die(return_msg_mcp($msg)); - } - else - { - print_confirmation(array( - 'QUESTION' => $lang['CONFIRM_DELETE_TOPIC'], - 'ITEMS_LIST' => join("\n
      • \n
      • \n", $topic_titles), - 'FORM_ACTION' => "modcp.php", - 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - )); - } - break; + $msg = ($result) ? $lang['TOPICS_REMOVED'] : $lang['NO_TOPICS_REMOVED']; + bb_die(return_msg_mcp($msg)); + } else { + print_confirmation(array( + 'QUESTION' => $lang['CONFIRM_DELETE_TOPIC'], + 'ITEMS_LIST' => join("\n
      • \n
      • \n", $topic_titles), + 'FORM_ACTION' => "modcp.php", + 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + )); + } + break; - case 'move': + case 'move': - if ($confirmed) - { - $new_forum_id = (int) $_POST['new_forum']; - $result = topic_move($req_topics, $new_forum_id, $forum_id, isset($_POST['move_leave_shadow']), isset($_POST['insert_bot_msg'])); + if ($confirmed) { + $new_forum_id = (int)$_POST['new_forum']; + $result = topic_move($req_topics, $new_forum_id, $forum_id, isset($_POST['move_leave_shadow']), isset($_POST['insert_bot_msg'])); - //Обновление кеша новостей на главной - $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); - if ((isset($news_forums[$forum_id]) || isset($news_forums[$new_forum_id])) && $di->config->get('show_latest_news') && $result) - { - $datastore->enqueue('latest_news'); - $datastore->update('latest_news'); - } + //Обновление кеша новостей на главной + $news_forums = array_flip(explode(',', $di->config->get('latest_news_forum_id'))); + if ((isset($news_forums[$forum_id]) || isset($news_forums[$new_forum_id])) && $di->config->get('show_latest_news') && $result) { + $datastore->enqueue('latest_news'); + $datastore->update('latest_news'); + } - $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); - if ((isset($net_forums[$forum_id]) || isset($net_forums[$new_forum_id])) && $di->config->get('show_network_news') && $result) - { - $datastore->enqueue('network_news'); - $datastore->update('network_news'); - } + $net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); + if ((isset($net_forums[$forum_id]) || isset($net_forums[$new_forum_id])) && $di->config->get('show_network_news') && $result) { + $datastore->enqueue('network_news'); + $datastore->update('network_news'); + } - $msg = ($result) ? $lang['TOPICS_MOVED'] : $lang['NO_TOPICS_MOVED']; - bb_die(return_msg_mcp($msg)); - } - else - { - if (IS_ADMIN) - { - $forum_select_mode = 'admin'; - } - else - { - $not_auth_forums_csv = $user->get_not_auth_forums(AUTH_VIEW); - $forum_select_mode = explode(',', $not_auth_forums_csv); - } + $msg = ($result) ? $lang['TOPICS_MOVED'] : $lang['NO_TOPICS_MOVED']; + bb_die(return_msg_mcp($msg)); + } else { + if (IS_ADMIN) { + $forum_select_mode = 'admin'; + } else { + $not_auth_forums_csv = $user->get_not_auth_forums(AUTH_VIEW); + $forum_select_mode = explode(',', $not_auth_forums_csv); + } - $forum_select = get_forum_select($forum_select_mode, 'new_forum', $forum_id); + $forum_select = get_forum_select($forum_select_mode, 'new_forum', $forum_id); - $template->assign_vars(array( - 'TPL_MODCP_MOVE' => true, - 'SHOW_LEAVESHADOW' => $is_moderator, - 'SHOW_BOT_OPTIONS' => $is_moderator, + $template->assign_vars(array( + 'TPL_MODCP_MOVE' => true, + 'SHOW_LEAVESHADOW' => $is_moderator, + 'SHOW_BOT_OPTIONS' => $is_moderator, - 'MESSAGE_TITLE' => $lang['CONFIRM'], - 'MESSAGE_TEXT' => $lang['CONFIRM_MOVE_TOPIC'], - 'TOPIC_TITLES' => join("\n
      • \n
      • \n", $topic_titles), + 'MESSAGE_TITLE' => $lang['CONFIRM'], + 'MESSAGE_TEXT' => $lang['CONFIRM_MOVE_TOPIC'], + 'TOPIC_TITLES' => join("\n
      • \n
      • \n", $topic_titles), - 'S_FORUM_SELECT' => $forum_select, - 'S_MODCP_ACTION' => "modcp.php", - 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - )); + 'S_FORUM_SELECT' => $forum_select, + 'S_MODCP_ACTION' => "modcp.php", + 'S_HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + )); - $template->set_filenames(array('body' => 'modcp.tpl')); - } - break; + $template->set_filenames(array('body' => 'modcp.tpl')); + } + break; - case 'lock': - case 'unlock': - $lock = ($mode == 'lock'); - $new_topic_status = ($lock) ? TOPIC_LOCKED : TOPIC_UNLOCKED; + case 'lock': + case 'unlock': + $lock = ($mode == 'lock'); + $new_topic_status = ($lock) ? TOPIC_LOCKED : TOPIC_UNLOCKED; - $sql = " + $sql = " SELECT topic_id, topic_title - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) AND forum_id = $forum_id - AND topic_status != ". TOPIC_MOVED ." + AND topic_status != " . TOPIC_MOVED . " AND topic_status != $new_topic_status "; - $topic_csv = array(); + $topic_csv = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $topic_csv[] = $row['topic_id']; - $log_topics[$row['topic_id']] = $row['topic_title']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topic_csv[] = $row['topic_id']; + $log_topics[$row['topic_id']] = $row['topic_title']; + } - if (!$topic_csv = get_id_csv($topic_csv)) - { - bb_die($lang['NONE_SELECTED']); - } + if (!$topic_csv = get_id_csv($topic_csv)) { + bb_die($lang['NONE_SELECTED']); + } - DB()->query(" - UPDATE ". BB_TOPICS ." SET + DB()->query(" + UPDATE " . BB_TOPICS . " SET topic_status = $new_topic_status WHERE topic_id IN($topic_csv) "); - // Log action - $type = ($lock) ? 'mod_topic_lock' : 'mod_topic_unlock'; + // Log action + $type = ($lock) ? 'mod_topic_lock' : 'mod_topic_unlock'; - foreach ($log_topics as $topic_id => $topic_title) - { - $log_action->mod($type, array( - 'forum_id' => $forum_id, - 'topic_id' => $topic_id, - 'topic_title' => $topic_title, - )); - } + foreach ($log_topics as $topic_id => $topic_title) { + $log_action->mod($type, array( + 'forum_id' => $forum_id, + 'topic_id' => $topic_id, + 'topic_title' => $topic_title, + )); + } - $msg = ($lock) ? $lang['TOPICS_LOCKED'] : $lang['TOPICS_UNLOCKED']; - bb_die(return_msg_mcp($msg)); + $msg = ($lock) ? $lang['TOPICS_LOCKED'] : $lang['TOPICS_UNLOCKED']; + bb_die(return_msg_mcp($msg)); - break; + break; - // Set or unset topics DL-type - case 'set_download': - case 'unset_download': - $set_download = ($mode == 'set_download'); - $new_dl_type = ($set_download) ? 1 : 0; + // Set or unset topics DL-type + case 'set_download': + case 'unset_download': + $set_download = ($mode == 'set_download'); + $new_dl_type = ($set_download) ? 1 : 0; - DB()->query(" - UPDATE ". BB_TOPICS ." SET + DB()->query(" + UPDATE " . BB_TOPICS . " SET tracker_status = $new_dl_type WHERE topic_id IN($topic_csv) AND forum_id = $forum_id AND topic_moved_id = 0 "); - if ($mode == 'unset_download') - { - clear_dl_list($topic_csv); - } + if ($mode == 'unset_download') { + clear_dl_list($topic_csv); + } - $msg = ($set_download) ? $lang['TOPICS_DOWN_SETS'] : $lang['TOPICS_DOWN_UNSETS']; - bb_die(return_msg_mcp($msg)); + $msg = ($set_download) ? $lang['TOPICS_DOWN_SETS'] : $lang['TOPICS_DOWN_UNSETS']; + bb_die(return_msg_mcp($msg)); - break; + break; - case 'split': - //mpd - $delete_posts = isset($_POST['delete_posts']); - $split = (isset($_POST['split_type_all']) || isset($_POST['split_type_beyond'])); - $posts = (isset($_POST['post_id_list'])) ? $_POST['post_id_list'] : array(); - $start = /* (isset($_POST['start'])) ? intval($_POST['start']) : */ 0; - $topic_first_post_id = (isset($topic_row['topic_first_post_id'])) ? $topic_row['topic_first_post_id'] : ''; + case 'split': + //mpd + $delete_posts = isset($_POST['delete_posts']); + $split = (isset($_POST['split_type_all']) || isset($_POST['split_type_beyond'])); + $posts = (isset($_POST['post_id_list'])) ? $_POST['post_id_list'] : array(); + $start = /* (isset($_POST['start'])) ? intval($_POST['start']) : */ + 0; + $topic_first_post_id = (isset($topic_row['topic_first_post_id'])) ? $topic_row['topic_first_post_id'] : ''; - $post_id_sql = $req_post_id_sql = array(); + $post_id_sql = $req_post_id_sql = array(); - if (($split || $delete_posts) && ($posts && $topic_id && $forum_id && $topic_first_post_id) && $confirmed) - { - foreach ($posts as $post_id) - { - if ($pid = intval($post_id)) - { - $req_post_id_sql[] = $pid; - } - } - if ($req_post_id_sql = join(',', $req_post_id_sql)) - { - $sql = "SELECT post_id - FROM ". BB_POSTS ." + if (($split || $delete_posts) && ($posts && $topic_id && $forum_id && $topic_first_post_id) && $confirmed) { + foreach ($posts as $post_id) { + if ($pid = intval($post_id)) { + $req_post_id_sql[] = $pid; + } + } + if ($req_post_id_sql = join(',', $req_post_id_sql)) { + $sql = "SELECT post_id + FROM " . BB_POSTS . " WHERE post_id IN($req_post_id_sql) AND post_id != $topic_first_post_id AND topic_id = $topic_id AND forum_id = $forum_id"; - if (!$result = DB()->sql_query($sql)) - { - bb_die('Could not get post id information'); - } - if ($rowset = DB()->sql_fetchrowset($result)) - { - foreach ($rowset as $rid => $row) - { - $post_id_sql[] = $row['post_id']; - } - $post_id_sql = join(',', $post_id_sql); - } - } - } + if (!$result = DB()->sql_query($sql)) { + bb_die('Could not get post id information'); + } + if ($rowset = DB()->sql_fetchrowset($result)) { + foreach ($rowset as $rid => $row) { + $post_id_sql[] = $row['post_id']; + } + $post_id_sql = join(',', $post_id_sql); + } + } + } - if ($post_id_sql && $split) - //mpd end - { - $sql = "SELECT post_id, poster_id, topic_id, post_time + if ($post_id_sql && $split) //mpd end + { + $sql = "SELECT post_id, poster_id, topic_id, post_time FROM " . BB_POSTS . " WHERE post_id IN ($post_id_sql) ORDER BY post_time ASC"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get post information'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get post information'); + } - if ($row = DB()->sql_fetchrow($result)) - { - $first_poster = $row['poster_id']; - $topic_id = $row['topic_id']; - $post_time = $row['post_time']; + if ($row = DB()->sql_fetchrow($result)) { + $first_poster = $row['poster_id']; + $topic_id = $row['topic_id']; + $post_time = $row['post_time']; - $user_id_sql = ''; - $post_id_sql = ''; - do - { - $user_id_sql .= (($user_id_sql != '') ? ', ' : '') . intval($row['poster_id']); - $post_id_sql .= (($post_id_sql != '') ? ', ' : '') . intval($row['post_id']); - } - while ($row = DB()->sql_fetchrow($result)); + $user_id_sql = ''; + $post_id_sql = ''; + do { + $user_id_sql .= (($user_id_sql != '') ? ', ' : '') . intval($row['poster_id']); + $post_id_sql .= (($post_id_sql != '') ? ', ' : '') . intval($row['post_id']); + } while ($row = DB()->sql_fetchrow($result)); - $post_subject = clean_title($_POST['subject']); - if (empty($post_subject)) - { - bb_die($lang['EMPTY_SUBJECT']); - } + $post_subject = clean_title($_POST['subject']); + if (empty($post_subject)) { + bb_die($lang['EMPTY_SUBJECT']); + } - $new_forum_id = intval($_POST['new_forum_id']); - $topic_time = TIMENOW; + $new_forum_id = intval($_POST['new_forum_id']); + $topic_time = TIMENOW; - $sql = 'SELECT forum_id FROM ' . BB_FORUMS . ' WHERE forum_id = ' . $new_forum_id; - if ( !($result = DB()->sql_query($sql)) ) - { - bb_die('Could not select from forums table'); - } + $sql = 'SELECT forum_id FROM ' . BB_FORUMS . ' WHERE forum_id = ' . $new_forum_id; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not select from forums table'); + } - if (!DB()->sql_fetchrow($result)) - { - bb_die('New forum does not exist'); - } + if (!DB()->sql_fetchrow($result)) { + bb_die('New forum does not exist'); + } - DB()->sql_freeresult($result); + DB()->sql_freeresult($result); - $first_post_id = min(explode(',', $post_id_sql)); + $first_post_id = min(explode(',', $post_id_sql)); - $sql = "INSERT INTO " . BB_TOPICS . " (topic_title, topic_poster, topic_time, forum_id, topic_status, topic_type, topic_first_post_id) + $sql = "INSERT INTO " . BB_TOPICS . " (topic_title, topic_poster, topic_time, forum_id, topic_status, topic_type, topic_first_post_id) VALUES ('" . DB()->escape($post_subject) . "', $first_poster, " . $topic_time . ", $new_forum_id, " . TOPIC_UNLOCKED . ", " . POST_NORMAL . ", $first_post_id)"; - if (!(DB()->sql_query($sql))) - { - bb_die('Could not insert new topic'); - } + if (!(DB()->sql_query($sql))) { + bb_die('Could not insert new topic'); + } - $new_topic_id = DB()->sql_nextid(); + $new_topic_id = DB()->sql_nextid(); - // Update topic watch table, switch users whose posts - // have moved, over to watching the new topic - $sql = "UPDATE " . BB_TOPICS_WATCH . " + // Update topic watch table, switch users whose posts + // have moved, over to watching the new topic + $sql = "UPDATE " . BB_TOPICS_WATCH . " SET topic_id = $new_topic_id WHERE topic_id = $topic_id AND user_id IN ($user_id_sql)"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update topics watch table'); - } + if (!DB()->sql_query($sql)) { + bb_die('Could not update topics watch table'); + } - $sql_where = (!empty($_POST['split_type_beyond'])) ? " post_time >= $post_time AND topic_id = $topic_id" : "post_id IN ($post_id_sql)"; + $sql_where = (!empty($_POST['split_type_beyond'])) ? " post_time >= $post_time AND topic_id = $topic_id" : "post_id IN ($post_id_sql)"; - $sql = "UPDATE " . BB_POSTS . " SET topic_id = $new_topic_id, forum_id = $new_forum_id WHERE $sql_where"; - if (!DB()->sql_query($sql)) - { - bb_die('Could not update posts table'); - } + $sql = "UPDATE " . BB_POSTS . " SET topic_id = $new_topic_id, forum_id = $new_forum_id WHERE $sql_where"; + if (!DB()->sql_query($sql)) { + bb_die('Could not update posts table'); + } - //bot - if (isset($_POST['after_split_to_old'])) - { - insert_post('after_split_to_old', $topic_id, $forum_id, '', $new_topic_id, trim($_POST['subject'])); - } - if (isset($_POST['after_split_to_new'])) - { - insert_post('after_split_to_new', $new_topic_id, $new_forum_id, $forum_id, $new_topic_id, '', $topic_id); - } + //bot + if (isset($_POST['after_split_to_old'])) { + insert_post('after_split_to_old', $topic_id, $forum_id, '', $new_topic_id, trim($_POST['subject'])); + } + if (isset($_POST['after_split_to_new'])) { + insert_post('after_split_to_new', $new_topic_id, $new_forum_id, $forum_id, $new_topic_id, '', $topic_id); + } - sync('topic', array($topic_id, $new_topic_id)); - sync('forum', array($forum_id, $new_forum_id)); + sync('topic', array($topic_id, $new_topic_id)); + sync('forum', array($forum_id, $new_forum_id)); - //bot - $message = $lang['TOPIC_SPLIT'] .'

        '. $lang['TOPIC_SPLIT_OLD'] .''; - $message .= '  ::  '. $lang['TOPIC_SPLIT_NEW'] .''; + //bot + $message = $lang['TOPIC_SPLIT'] . '

        ' . $lang['TOPIC_SPLIT_OLD'] . ''; + $message .= '  ::  ' . $lang['TOPIC_SPLIT_NEW'] . ''; - // Log action - $log_action->mod('mod_topic_split', array( - 'forum_id' => $forum_id, - 'forum_id_new' => $new_forum_id, - 'topic_id' => $topic_id, - 'topic_title' => get_topic_title($topic_id), - 'topic_id_new' => $new_topic_id, - 'topic_title_new' => htmlCHR($_POST['subject']), - )); + // Log action + $log_action->mod('mod_topic_split', array( + 'forum_id' => $forum_id, + 'forum_id_new' => $new_forum_id, + 'topic_id' => $topic_id, + 'topic_title' => get_topic_title($topic_id), + 'topic_id_new' => $new_topic_id, + 'topic_title_new' => htmlCHR($_POST['subject']), + )); - bb_die($message); - } - } - elseif ($post_id_sql && $delete_posts) - { - if (!$is_auth['auth_delete']) - { - bb_die(sprintf($lang['SORRY_AUTH_DELETE'], $is_auth['auth_delete_type'])); - } + bb_die($message); + } + } elseif ($post_id_sql && $delete_posts) { + if (!$is_auth['auth_delete']) { + bb_die(sprintf($lang['SORRY_AUTH_DELETE'], $is_auth['auth_delete_type'])); + } - // Delete posts - $result = post_delete(explode(',', $post_id_sql)); + // Delete posts + $result = post_delete(explode(',', $post_id_sql)); - $msg = ($result) ? $lang['DELETE_POSTS_SUCCESFULLY'] : 'No posts were removed'; - bb_die(return_msg_mcp($msg)); - } - else - { - $sql = "SELECT u.username, p.*, pt.post_text, p.post_username + $msg = ($result) ? $lang['DELETE_POSTS_SUCCESFULLY'] : 'No posts were removed'; + bb_die(return_msg_mcp($msg)); + } else { + $sql = "SELECT u.username, p.*, pt.post_text, p.post_username FROM " . BB_POSTS . " p, " . BB_USERS . " u, " . BB_POSTS_TEXT . " pt WHERE p.topic_id = $topic_id AND p.poster_id = u.user_id AND p.post_id = pt.post_id ORDER BY p.post_time ASC"; - if ( !($result = DB()->sql_query($sql)) ) - { - bb_die('Could not get topic / post information'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get topic / post information'); + } - $s_hidden_fields = ''; + $s_hidden_fields = ''; - if (($total_posts = DB()->num_rows($result)) > 0) - { - $postrow = DB()->sql_fetchrowset($result); + if (($total_posts = DB()->num_rows($result)) > 0) { + $postrow = DB()->sql_fetchrowset($result); - $template->assign_vars(array( - 'FORUM_NAME' => htmlCHR($forum_name), - 'U_VIEW_FORUM' => FORUM_URL . $forum_id, - 'S_SPLIT_ACTION' => 'modcp.php', - 'S_HIDDEN_FIELDS' => $s_hidden_fields, - 'S_FORUM_SELECT' => get_forum_select('admin', 'new_forum_id', $forum_id), - )); + $template->assign_vars(array( + 'FORUM_NAME' => htmlCHR($forum_name), + 'U_VIEW_FORUM' => FORUM_URL . $forum_id, + 'S_SPLIT_ACTION' => 'modcp.php', + 'S_HIDDEN_FIELDS' => $s_hidden_fields, + 'S_FORUM_SELECT' => get_forum_select('admin', 'new_forum_id', $forum_id), + )); - for ($i = 0; $i < $total_posts; $i++) - { - $post_id = $postrow[$i]['post_id']; - $poster_id = $postrow[$i]['poster_id']; - $poster = $postrow[$i]['username']; + for ($i = 0; $i < $total_posts; $i++) { + $post_id = $postrow[$i]['post_id']; + $poster_id = $postrow[$i]['poster_id']; + $poster = $postrow[$i]['username']; - $post_date = bb_date($postrow[$i]['post_time']); + $post_date = bb_date($postrow[$i]['post_time']); - $message = $postrow[$i]['post_text']; + $message = $postrow[$i]['post_text']; - // - // If the board has HTML off but the post has HTML - // on then we process it, else leave it alone - // - $message = bbcode2html($message); + // + // If the board has HTML off but the post has HTML + // on then we process it, else leave it alone + // + $message = bbcode2html($message); - $row_class = !($i % 2) ? 'row1' : 'row2'; + $row_class = !($i % 2) ? 'row1' : 'row2'; - $template->assign_block_vars('postrow', array( - 'ROW_CLASS' => $row_class, - 'POSTER_NAME' => wbr($poster), - 'POST_DATE' => $post_date, - 'MESSAGE' => $message, - 'CHECKBOX' => (defined('BEGIN_CHECKBOX')) ? TRUE : FALSE, - 'POST_ID' => $post_id, - 'ROW_ID' => $i, - 'CB_ID' => 'cb_'. $i, - )); + $template->assign_block_vars('postrow', array( + 'ROW_CLASS' => $row_class, + 'POSTER_NAME' => wbr($poster), + 'POST_DATE' => $post_date, + 'MESSAGE' => $message, + 'CHECKBOX' => (defined('BEGIN_CHECKBOX')) ? TRUE : FALSE, + 'POST_ID' => $post_id, + 'ROW_ID' => $i, + 'CB_ID' => 'cb_' . $i, + )); - if ($post_id == $topic_first_post_id) - { - define('BEGIN_CHECKBOX', TRUE); - } - } - } - } - $template->set_filenames(array('body' => 'modcp_split.tpl')); - break; + if ($post_id == $topic_first_post_id) { + define('BEGIN_CHECKBOX', TRUE); + } + } + } + } + $template->set_filenames(array('body' => 'modcp_split.tpl')); + break; - case 'ip': - $anon = GUEST_UID; + case 'ip': + $anon = GUEST_UID; - $rdns_ip_num = ( isset($_GET['rdns']) ) ? $_GET['rdns'] : ""; + $rdns_ip_num = (isset($_GET['rdns'])) ? $_GET['rdns'] : ""; - if (!$post_id) - { - bb_die($lang['NO_SUCH_POST']); - } + if (!$post_id) { + bb_die($lang['NO_SUCH_POST']); + } - // Look up relevant data for this post - $sql = "SELECT * FROM " . BB_POSTS . " WHERE post_id = $post_id AND forum_id = $forum_id"; - if (!($result = DB()->sql_query($sql))) - { - bb_die('Could not get poster IP information'); - } + // Look up relevant data for this post + $sql = "SELECT * FROM " . BB_POSTS . " WHERE post_id = $post_id AND forum_id = $forum_id"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get poster IP information'); + } - if (!($post_row = DB()->sql_fetchrow($result))) - { - bb_die($lang['NO_SUCH_POST']); - } + if (!($post_row = DB()->sql_fetchrow($result))) { + bb_die($lang['NO_SUCH_POST']); + } - $ip_this_post = decode_ip($post_row['poster_ip']); - $ip_this_post = ($rdns_ip_num == $ip_this_post) ? gethostbyaddr($ip_this_post) : $ip_this_post; + $ip_this_post = decode_ip($post_row['poster_ip']); + $ip_this_post = ($rdns_ip_num == $ip_this_post) ? gethostbyaddr($ip_this_post) : $ip_this_post; - $poster_id = $post_row['poster_id']; + $poster_id = $post_row['poster_id']; - $template->assign_vars(array( - 'TPL_MODCP_IP' => true, - 'IP' => $ip_this_post, - 'U_LOOKUP_IP' => "modcp.php?mode=ip&" . POST_POST_URL . "=$post_id&" . POST_TOPIC_URL . "=$topic_id&rdns=$ip_this_post&sid=" . $userdata['session_id'], - )); + $template->assign_vars(array( + 'TPL_MODCP_IP' => true, + 'IP' => $ip_this_post, + 'U_LOOKUP_IP' => "modcp.php?mode=ip&" . POST_POST_URL . "=$post_id&" . POST_TOPIC_URL . "=$topic_id&rdns=$ip_this_post&sid=" . $userdata['session_id'], + )); - // - // Get other IP's this user has posted under - // - $where_sql = ($poster_id == $anon) ? "post_username = '{$post_row['post_username']}'" : "poster_id = $poster_id"; + // + // Get other IP's this user has posted under + // + $where_sql = ($poster_id == $anon) ? "post_username = '{$post_row['post_username']}'" : "poster_id = $poster_id"; - $sql = "SELECT poster_ip, COUNT(*) AS postings FROM " . BB_POSTS . " WHERE $where_sql GROUP BY poster_ip ORDER BY postings DESC LIMIT 100"; - if ( !($result = DB()->sql_query($sql)) ) - { - bb_die('Could not get IP information for this user'); - } + $sql = "SELECT poster_ip, COUNT(*) AS postings FROM " . BB_POSTS . " WHERE $where_sql GROUP BY poster_ip ORDER BY postings DESC LIMIT 100"; + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get IP information for this user'); + } - if ( $row = DB()->sql_fetchrow($result) ) - { - $i = 0; - do - { - if ( $row['poster_ip'] == $post_row['poster_ip'] ) - { - $template->assign_vars(array( - 'POSTS' => $row['postings'], - )); - continue; - } + if ($row = DB()->sql_fetchrow($result)) { + $i = 0; + do { + if ($row['poster_ip'] == $post_row['poster_ip']) { + $template->assign_vars(array( + 'POSTS' => $row['postings'], + )); + continue; + } - $ip = decode_ip($row['poster_ip']); - $ip = ( $rdns_ip_num == $row['poster_ip'] || $rdns_ip_num == 'all') ? gethostbyaddr($ip) : $ip; + $ip = decode_ip($row['poster_ip']); + $ip = ($rdns_ip_num == $row['poster_ip'] || $rdns_ip_num == 'all') ? gethostbyaddr($ip) : $ip; - $template->assign_block_vars('iprow', array( - 'ROW_CLASS' => !($i % 2) ? 'row4' : 'row5', - 'IP' => $ip, - 'POSTS' => $row['postings'], - 'U_LOOKUP_IP' => "modcp.php?mode=ip&" . POST_POST_URL . "=$post_id&" . POST_TOPIC_URL . "=$topic_id&rdns=" . $row['poster_ip'] . "&sid=" . $userdata['session_id'], - )); + $template->assign_block_vars('iprow', array( + 'ROW_CLASS' => !($i % 2) ? 'row4' : 'row5', + 'IP' => $ip, + 'POSTS' => $row['postings'], + 'U_LOOKUP_IP' => "modcp.php?mode=ip&" . POST_POST_URL . "=$post_id&" . POST_TOPIC_URL . "=$topic_id&rdns=" . $row['poster_ip'] . "&sid=" . $userdata['session_id'], + )); - $i++; - } - while ( $row = DB()->sql_fetchrow($result) ); - } + $i++; + } while ($row = DB()->sql_fetchrow($result)); + } - // - // Get other users who've posted under this IP - // - $sql = "SELECT + // + // Get other users who've posted under this IP + // + $sql = "SELECT u.user_id, IF(u.user_id = $anon, p.post_username, u.username) AS username, COUNT(*) as postings - FROM " . BB_USERS ." u, " . BB_POSTS . " p + FROM " . BB_USERS . " u, " . BB_POSTS . " p WHERE p.poster_id = u.user_id AND p.poster_ip = '" . $post_row['poster_ip'] . "' GROUP BY u.user_id, p.post_username ORDER BY postings DESC LIMIT 100"; - if ( !($result = DB()->sql_query($sql)) ) - { - bb_die('Could not get posters information based on IP'); - } + if (!($result = DB()->sql_query($sql))) { + bb_die('Could not get posters information based on IP'); + } - if ( $row = DB()->sql_fetchrow($result) ) - { - $i = 0; - do - { - $id = $row['user_id']; - $username = (!$row['username']) ? $lang['GUEST'] : $row['username']; + if ($row = DB()->sql_fetchrow($result)) { + $i = 0; + do { + $id = $row['user_id']; + $username = (!$row['username']) ? $lang['GUEST'] : $row['username']; - $template->assign_block_vars('userrow', array( - 'ROW_CLASS' => !($i % 2) ? 'row4' : 'row5', - 'USERNAME' => wbr($username), - 'POSTS' => $row['postings'], - 'U_PROFILE' => ($id == GUEST_UID) ? "modcp.php?mode=ip&p=$post_id&t=$topic_id" : PROFILE_URL . $id, - 'U_SEARCHPOSTS' => "search.php?search_author=1&uid=$id", - )); + $template->assign_block_vars('userrow', array( + 'ROW_CLASS' => !($i % 2) ? 'row4' : 'row5', + 'USERNAME' => wbr($username), + 'POSTS' => $row['postings'], + 'U_PROFILE' => ($id == GUEST_UID) ? "modcp.php?mode=ip&p=$post_id&t=$topic_id" : PROFILE_URL . $id, + 'U_SEARCHPOSTS' => "search.php?search_author=1&uid=$id", + )); - $i++; - } - while ( $row = DB()->sql_fetchrow($result) ); - } + $i++; + } while ($row = DB()->sql_fetchrow($result)); + } - $template->set_filenames(array('body' => 'modcp.tpl')); - break; + $template->set_filenames(array('body' => 'modcp.tpl')); + break; - case 'post_pin': - case 'post_unpin': - $pin = ($mode == 'post_pin'); - $new_topic_status = ($pin) ? 1 : 0; + case 'post_pin': + case 'post_unpin': + $pin = ($mode == 'post_pin'); + $new_topic_status = ($pin) ? 1 : 0; - if (count($topic_csv)) - { - $sql = " + if (count($topic_csv)) { + $sql = " SELECT topic_id, topic_title - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id IN($topic_csv) AND forum_id = $forum_id - AND topic_show_first_post != ". TOPIC_MOVED ." + AND topic_show_first_post != " . TOPIC_MOVED . " AND topic_show_first_post != $new_topic_status "; - $topic_csv = array(); + $topic_csv = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $topic_csv[] = $row['topic_id']; - $log_topics[$row['topic_id']] = $row['topic_title']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topic_csv[] = $row['topic_id']; + $log_topics[$row['topic_id']] = $row['topic_title']; + } - if (!$topic_csv = get_id_csv($topic_csv)) - { - bb_die($lang['NONE_SELECTED']); - } + if (!$topic_csv = get_id_csv($topic_csv)) { + bb_die($lang['NONE_SELECTED']); + } - DB()->query(" - UPDATE ". BB_TOPICS ." SET + DB()->query(" + UPDATE " . BB_TOPICS . " SET topic_show_first_post = $new_topic_status WHERE topic_id IN($topic_csv) "); - $msg = ($pin) ? $lang['POST_PINNED'] : $lang['POST_UNPINNED']; - bb_die(return_msg_mcp($msg)); - } - elseif ($topic_id) - { - $sql = " + $msg = ($pin) ? $lang['POST_PINNED'] : $lang['POST_UNPINNED']; + bb_die(return_msg_mcp($msg)); + } elseif ($topic_id) { + $sql = " SELECT topic_id, topic_title - FROM ". BB_TOPICS ." + FROM " . BB_TOPICS . " WHERE topic_id = $topic_id AND forum_id = $forum_id - AND topic_show_first_post != ". TOPIC_MOVED ." + AND topic_show_first_post != " . TOPIC_MOVED . " AND topic_show_first_post != $new_topic_status LIMIT 1 "; - $topic_csv = array(); + $topic_csv = array(); - foreach (DB()->fetch_rowset($sql) as $row) - { - $topic_csv[] = $row['topic_id']; - $log_topics[$row['topic_id']] = $row['topic_title']; - } + foreach (DB()->fetch_rowset($sql) as $row) { + $topic_csv[] = $row['topic_id']; + $log_topics[$row['topic_id']] = $row['topic_title']; + } - if (!$topic_csv = get_id_csv($topic_csv)) - { - bb_die($lang['NONE_SELECTED']); - } + if (!$topic_csv = get_id_csv($topic_csv)) { + bb_die($lang['NONE_SELECTED']); + } - DB()->query(" - UPDATE ". BB_TOPICS ." SET + DB()->query(" + UPDATE " . BB_TOPICS . " SET topic_show_first_post = $new_topic_status WHERE topic_id IN($topic_csv) "); - $msg = ($pin) ? $lang['POST_PINNED'] : $lang['POST_UNPINNED']; - bb_die(return_msg_mcp($msg)); - } - break; + $msg = ($pin) ? $lang['POST_PINNED'] : $lang['POST_UNPINNED']; + bb_die(return_msg_mcp($msg)); + } + break; - default: - bb_die('invalid action'); - break; + default: + bb_die('invalid action'); + break; } $template->assign_vars(array('PAGE_TITLE' => $lang['MOD_CP'])); @@ -852,4 +748,4 @@ require(PAGE_HEADER); $template->pparse('body'); -require(PAGE_FOOTER); \ No newline at end of file +require(PAGE_FOOTER); diff --git a/poll.php b/poll.php index ebba4cbc9..76ad844d1 100644 --- a/poll.php +++ b/poll.php @@ -12,244 +12,218 @@ $cache = $di->cache; $user->session_start(array('req_login' => true)); -$mode = (string) $_POST['mode']; -$topic_id = (int) $_POST['topic_id']; -$forum_id = (int) $_POST['forum_id']; -$vote_id = (int) $_POST['vote_id']; +$mode = (string)$_POST['mode']; +$topic_id = (int)$_POST['topic_id']; +$forum_id = (int)$_POST['forum_id']; +$vote_id = (int)$_POST['vote_id']; $return_topic_url = TOPIC_URL . $topic_id; -$return_topic_url .= !empty($_POST['start']) ? "&start=". intval($_POST['start']) : ''; +$return_topic_url .= !empty($_POST['start']) ? "&start=" . intval($_POST['start']) : ''; set_die_append_msg($forum_id, $topic_id); $poll = new bb_poll(); // проверка валидности $topic_id -if (!$topic_id) -{ - bb_die('Invalid topic_id'); +if (!$topic_id) { + bb_die('Invalid topic_id'); } -if (!$t_data = DB()->fetch_row("SELECT * FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1")) -{ - bb_die('Topic not found'); +if (!$t_data = DB()->fetch_row("SELECT * FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1")) { + bb_die('Topic not found'); } // проверка прав -if ($mode != 'poll_vote') -{ - if ($t_data['topic_poster'] != $userdata['user_id']) - { - if (!IS_AM) bb_die($lang['NOT_AUTHORISED']); - } +if ($mode != 'poll_vote') { + if ($t_data['topic_poster'] != $userdata['user_id']) { + if (!IS_AM) bb_die($lang['NOT_AUTHORISED']); + } } // проверка на возможность вносить изменения -if ($mode == 'poll_delete') -{ - if ($t_data['topic_time'] < TIMENOW - $di->config->get('poll_max_days') * 86400) - { - bb_die(sprintf($lang['NEW_POLL_DAYS'], $di->config->get('poll_max_days'))); - } - if (!IS_ADMIN && ($t_data['topic_vote'] != POLL_FINISHED)) - { - bb_die($lang['CANNOT_DELETE_POLL']); - } +if ($mode == 'poll_delete') { + if ($t_data['topic_time'] < TIMENOW - $di->config->get('poll_max_days') * 86400) { + bb_die(sprintf($lang['NEW_POLL_DAYS'], $di->config->get('poll_max_days'))); + } + if (!IS_ADMIN && ($t_data['topic_vote'] != POLL_FINISHED)) { + bb_die($lang['CANNOT_DELETE_POLL']); + } } -switch ($mode) -{ - // голосование - case 'poll_vote': - if (!$t_data['topic_vote']) - { - bb_die($lang['POST_HAS_NO_POLL']); - } - if ($t_data['topic_status'] == TOPIC_LOCKED) - { - bb_die($lang['TOPIC_LOCKED_SHORT']); - } - if (!poll_is_active($t_data)) - { - bb_die($lang['NEW_POLL_ENDED']); - } - if (!$vote_id) - { - bb_die($lang['NO_VOTE_OPTION']); - } - if (DB()->fetch_row("SELECT 1 FROM ". BB_POLL_USERS ." WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']} LIMIT 1")) - { - bb_die($lang['ALREADY_VOTED']); - } +switch ($mode) { + // голосование + case 'poll_vote': + if (!$t_data['topic_vote']) { + bb_die($lang['POST_HAS_NO_POLL']); + } + if ($t_data['topic_status'] == TOPIC_LOCKED) { + bb_die($lang['TOPIC_LOCKED_SHORT']); + } + if (!poll_is_active($t_data)) { + bb_die($lang['NEW_POLL_ENDED']); + } + if (!$vote_id) { + bb_die($lang['NO_VOTE_OPTION']); + } + if (DB()->fetch_row("SELECT 1 FROM " . BB_POLL_USERS . " WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']} LIMIT 1")) { + bb_die($lang['ALREADY_VOTED']); + } - DB()->query(" - UPDATE ". BB_POLL_VOTES ." SET + DB()->query(" + UPDATE " . BB_POLL_VOTES . " SET vote_result = vote_result + 1 WHERE topic_id = $topic_id AND vote_id = $vote_id LIMIT 1 "); - if (DB()->affected_rows() != 1) - { - bb_die($lang['NO_VOTE_OPTION']); - } + if (DB()->affected_rows() != 1) { + bb_die($lang['NO_VOTE_OPTION']); + } - DB()->query("INSERT IGNORE INTO ". BB_POLL_USERS ." (topic_id, user_id, vote_ip, vote_dt) VALUES ($topic_id, {$userdata['user_id']}, '". USER_IP ."', ". TIMENOW .")"); + DB()->query("INSERT IGNORE INTO " . BB_POLL_USERS . " (topic_id, user_id, vote_ip, vote_dt) VALUES ($topic_id, {$userdata['user_id']}, '" . USER_IP . "', " . TIMENOW . ")"); - $cache->delete('poll_' . $topic_id); + $cache->delete('poll_' . $topic_id); - bb_die($lang['VOTE_CAST']); - break; + bb_die($lang['VOTE_CAST']); + break; - // возобновить возможность голосовать - case 'poll_start': - if (!$t_data['topic_vote']) - { - bb_die($lang['POST_HAS_NO_POLL']); - } - DB()->query("UPDATE ". BB_TOPICS ." SET topic_vote = 1 WHERE topic_id = $topic_id LIMIT 1"); - bb_die($lang['NEW_POLL_START']); - break; + // возобновить возможность голосовать + case 'poll_start': + if (!$t_data['topic_vote']) { + bb_die($lang['POST_HAS_NO_POLL']); + } + DB()->query("UPDATE " . BB_TOPICS . " SET topic_vote = 1 WHERE topic_id = $topic_id LIMIT 1"); + bb_die($lang['NEW_POLL_START']); + break; - // завершить опрос - case 'poll_finish': - if (!$t_data['topic_vote']) - { - bb_die($lang['POST_HAS_NO_POLL']); - } - DB()->query("UPDATE ". BB_TOPICS ." SET topic_vote = ". POLL_FINISHED ." WHERE topic_id = $topic_id LIMIT 1"); - bb_die($lang['NEW_POLL_END']); - break; + // завершить опрос + case 'poll_finish': + if (!$t_data['topic_vote']) { + bb_die($lang['POST_HAS_NO_POLL']); + } + DB()->query("UPDATE " . BB_TOPICS . " SET topic_vote = " . POLL_FINISHED . " WHERE topic_id = $topic_id LIMIT 1"); + bb_die($lang['NEW_POLL_END']); + break; - // удаление - case 'poll_delete': - if (!$t_data['topic_vote']) - { - bb_die($lang['POST_HAS_NO_POLL']); - } - $poll->delete_poll($topic_id); - bb_die($lang['NEW_POLL_DELETE']); - break; + // удаление + case 'poll_delete': + if (!$t_data['topic_vote']) { + bb_die($lang['POST_HAS_NO_POLL']); + } + $poll->delete_poll($topic_id); + bb_die($lang['NEW_POLL_DELETE']); + break; - // добавление - case 'poll_add': - if ($t_data['topic_vote']) - { - bb_die($lang['NEW_POLL_ALREADY']); - } - $poll->build_poll_data($_POST); - if ($poll->err_msg) - { - bb_die($poll->err_msg); - } - $poll->insert_votes_into_db($topic_id); - bb_die($lang['NEW_POLL_ADDED']); - break; + // добавление + case 'poll_add': + if ($t_data['topic_vote']) { + bb_die($lang['NEW_POLL_ALREADY']); + } + $poll->build_poll_data($_POST); + if ($poll->err_msg) { + bb_die($poll->err_msg); + } + $poll->insert_votes_into_db($topic_id); + bb_die($lang['NEW_POLL_ADDED']); + break; - // редакторование - case 'poll_edit': - if (!$t_data['topic_vote']) - { - bb_die($lang['POST_HAS_NO_POLL']); - } - $poll->build_poll_data($_POST); - if ($poll->err_msg) - { - bb_die($poll->err_msg); - } - $poll->insert_votes_into_db($topic_id); - $cache->delete('poll_' . $topic_id); - bb_die($lang['NEW_POLL_RESULTS']); - break; + // редакторование + case 'poll_edit': + if (!$t_data['topic_vote']) { + bb_die($lang['POST_HAS_NO_POLL']); + } + $poll->build_poll_data($_POST); + if ($poll->err_msg) { + bb_die($poll->err_msg); + } + $poll->insert_votes_into_db($topic_id); + $cache->delete('poll_' . $topic_id); + bb_die($lang['NEW_POLL_RESULTS']); + break; - default: - bb_die('Invalid mode: '. htmlCHR($mode)); + default: + bb_die('Invalid mode: ' . htmlCHR($mode)); } // Functions class bb_poll { - var $err_msg = ''; - var $poll_votes = array(); - var $max_votes = 0; + var $err_msg = ''; + var $poll_votes = array(); + var $max_votes = 0; - function bb_poll () - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function bb_poll() + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - $this->max_votes = $di->config->get('max_poll_options'); - } + $this->max_votes = $di->config->get('max_poll_options'); + } - function build_poll_data ($posted_data) - { - $poll_caption = (string) $posted_data['poll_caption']; - $poll_votes = (string) $posted_data['poll_votes']; - $this->poll_votes = array(); + function build_poll_data($posted_data) + { + $poll_caption = (string)$posted_data['poll_caption']; + $poll_votes = (string)$posted_data['poll_votes']; + $this->poll_votes = array(); - if (!$poll_caption = str_compact($poll_caption)) - { - global $lang; - return $this->err_msg = $lang['EMPTY_POLL_TITLE']; - } - $this->poll_votes[] = $poll_caption; // заголовок имеет vote_id = 0 + if (!$poll_caption = str_compact($poll_caption)) { + global $lang; + return $this->err_msg = $lang['EMPTY_POLL_TITLE']; + } + $this->poll_votes[] = $poll_caption; // заголовок имеет vote_id = 0 - foreach (explode("\n", $poll_votes) as $vote) - { - if (!$vote = str_compact($vote)) - { - continue; - } - $this->poll_votes[] = $vote; - } + foreach (explode("\n", $poll_votes) as $vote) { + if (!$vote = str_compact($vote)) { + continue; + } + $this->poll_votes[] = $vote; + } - // проверять на "< 3" -- 2 варианта ответа + заголовок - if (count($this->poll_votes) < 3 || count($this->poll_votes) > $this->max_votes + 1) - { - global $lang; - return $this->err_msg = sprintf($lang['NEW_POLL_VOTES'], $this->max_votes); - } + // проверять на "< 3" -- 2 варианта ответа + заголовок + if (count($this->poll_votes) < 3 || count($this->poll_votes) > $this->max_votes + 1) { + global $lang; + return $this->err_msg = sprintf($lang['NEW_POLL_VOTES'], $this->max_votes); + } - return false; - } + return false; + } - function insert_votes_into_db ($topic_id) - { - $this->delete_votes_data($topic_id); + function insert_votes_into_db($topic_id) + { + $this->delete_votes_data($topic_id); - $sql_ary = array(); - foreach ($this->poll_votes as $vote_id => $vote_text) - { - $sql_ary[] = array( - 'topic_id' => (int) $topic_id, - 'vote_id' => (int) $vote_id, - 'vote_text' => (string) $vote_text, - 'vote_result' => (int) 0, - ); - } - $sql_args = DB()->build_array('MULTI_INSERT', $sql_ary); + $sql_ary = array(); + foreach ($this->poll_votes as $vote_id => $vote_text) { + $sql_ary[] = array( + 'topic_id' => (int)$topic_id, + 'vote_id' => (int)$vote_id, + 'vote_text' => (string)$vote_text, + 'vote_result' => (int)0, + ); + } + $sql_args = DB()->build_array('MULTI_INSERT', $sql_ary); - DB()->query("REPLACE INTO ". BB_POLL_VOTES . $sql_args); + DB()->query("REPLACE INTO " . BB_POLL_VOTES . $sql_args); - DB()->query("UPDATE ". BB_TOPICS ." SET topic_vote = 1 WHERE topic_id = $topic_id LIMIT 1"); - } + DB()->query("UPDATE " . BB_TOPICS . " SET topic_vote = 1 WHERE topic_id = $topic_id LIMIT 1"); + } - function delete_poll ($topic_id) - { - DB()->query("UPDATE ". BB_TOPICS ." SET topic_vote = 0 WHERE topic_id = $topic_id LIMIT 1"); - $this->delete_votes_data($topic_id); - } + function delete_poll($topic_id) + { + DB()->query("UPDATE " . BB_TOPICS . " SET topic_vote = 0 WHERE topic_id = $topic_id LIMIT 1"); + $this->delete_votes_data($topic_id); + } - function delete_votes_data ($topic_id) - { - /** @var \TorrentPier\Di $di */ - $di = \TorrentPier\Di::getInstance(); + function delete_votes_data($topic_id) + { + /** @var \TorrentPier\Di $di */ + $di = \TorrentPier\Di::getInstance(); - /** @var \TorrentPier\Cache\Adapter $cache */ - $cache = $di->cache; + /** @var \TorrentPier\Cache\Adapter $cache */ + $cache = $di->cache; - DB()->query("DELETE FROM " . BB_POLL_VOTES . " WHERE topic_id = $topic_id"); - DB()->query("DELETE FROM " . BB_POLL_USERS . " WHERE topic_id = $topic_id"); + DB()->query("DELETE FROM " . BB_POLL_VOTES . " WHERE topic_id = $topic_id"); + DB()->query("DELETE FROM " . BB_POLL_USERS . " WHERE topic_id = $topic_id"); - $cache->delete('poll_' . $topic_id); - } -} \ No newline at end of file + $cache->delete('poll_' . $topic_id); + } +} diff --git a/posting.php b/posting.php index 31374d188..68e02b17f 100644 --- a/posting.php +++ b/posting.php @@ -2,28 +2,28 @@ define('BB_SCRIPT', 'posting'); define('BB_ROOT', './'); -require(BB_ROOT ."common.php"); +require(BB_ROOT . "common.php"); /** @var \TorrentPier\Di $di */ $di = \TorrentPier\Di::getInstance(); -require(INC_DIR .'bbcode.php'); -require(INC_DIR .'functions_post.php'); +require(INC_DIR . 'bbcode.php'); +require(INC_DIR . 'functions_post.php'); // Start session management $user->session_start(); $page_cfg['load_tpl_vars'] = ['post_icons']; -$submit = $di->request->request->has('post'); -$preview = $di->request->request->has('preview'); -$delete = $di->request->request->has('delete'); +$submit = $di->request->request->has('post'); +$preview = $di->request->request->has('preview'); +$delete = $di->request->request->has('delete'); $forum_id = $di->request->request->getInt(POST_FORUM_URL); $topic_id = $di->request->request->getInt(POST_TOPIC_URL); -$post_id = $di->request->request->getInt(POST_POST_URL); +$post_id = $di->request->request->getInt(POST_POST_URL); -$mode = (string) $_REQUEST['mode']; +$mode = (string)$_REQUEST['mode']; $confirm = isset($_POST['confirm']); @@ -35,10 +35,9 @@ $topic_type = in_array($topic_type, [POST_NORMAL, POST_STICKY, POST_ANNOUNCE]) ? $selected_rg = $switch_rg_sig = $switch_poster_rg_sig = 0; -if ($mode == 'smilies') -{ - generate_smilies('window'); - exit; +if ($mode == 'smilies') { + generate_smilies('window'); + exit; } $tracking_topics = get_tracks('topic'); @@ -48,230 +47,197 @@ set_die_append_msg($forum_id, $topic_id); // What auth type do we need to check? $is_auth = array(); -switch ($mode) -{ - case 'newtopic': - case 'new_rel': - if (bf($userdata['user_opt'], 'user_opt', 'dis_topic')) - { - bb_die($lang['RULES_POST_CANNOT']); - } - if ($topic_type == POST_ANNOUNCE) - { - $is_auth_type = 'auth_announce'; - } - elseif ($topic_type == POST_STICKY) - { - $is_auth_type = 'auth_sticky'; - } - else - { - $is_auth_type = 'auth_post'; - } - break; +switch ($mode) { + case 'newtopic': + case 'new_rel': + if (bf($userdata['user_opt'], 'user_opt', 'dis_topic')) { + bb_die($lang['RULES_POST_CANNOT']); + } + if ($topic_type == POST_ANNOUNCE) { + $is_auth_type = 'auth_announce'; + } elseif ($topic_type == POST_STICKY) { + $is_auth_type = 'auth_sticky'; + } else { + $is_auth_type = 'auth_post'; + } + break; - case 'reply': - case 'quote': - if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) - { - bb_die($lang['RULES_REPLY_CANNOT']); - } - $is_auth_type = 'auth_reply'; - break; + case 'reply': + case 'quote': + if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) { + bb_die($lang['RULES_REPLY_CANNOT']); + } + $is_auth_type = 'auth_reply'; + break; - case 'editpost': - if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) - { - bb_die($lang['RULES_EDIT_CANNOT']); - } - $is_auth_type = 'auth_edit'; - break; + case 'editpost': + if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) { + bb_die($lang['RULES_EDIT_CANNOT']); + } + $is_auth_type = 'auth_edit'; + break; - case 'delete': - $is_auth_type = 'auth_delete'; - break; + case 'delete': + $is_auth_type = 'auth_delete'; + break; - default: - bb_simple_die($lang['NO_POST_MODE']); - break; + default: + bb_simple_die($lang['NO_POST_MODE']); + break; } // Various lookups to find topic_id, forum_id, post_id etc $error_msg = ''; $post_data = array(); -switch ($mode) -{ - case 'newtopic': - case 'new_rel': - if (!$forum_id) bb_simple_die($lang['FORUM_NOT_EXIST']); - $sql = "SELECT * FROM ". BB_FORUMS ." WHERE forum_id = $forum_id LIMIT 1"; - break; +switch ($mode) { + case 'newtopic': + case 'new_rel': + if (!$forum_id) bb_simple_die($lang['FORUM_NOT_EXIST']); + $sql = "SELECT * FROM " . BB_FORUMS . " WHERE forum_id = $forum_id LIMIT 1"; + break; - case 'reply': - if (!$topic_id) bb_simple_die($lang['NO_TOPIC_ID']); - $sql = "SELECT f.*, t.* - FROM ". BB_FORUMS ." f, ". BB_TOPICS ." t + case 'reply': + if (!$topic_id) bb_simple_die($lang['NO_TOPIC_ID']); + $sql = "SELECT f.*, t.* + FROM " . BB_FORUMS . " f, " . BB_TOPICS . " t WHERE t.topic_id = $topic_id AND f.forum_id = t.forum_id LIMIT 1"; - break; + break; - case 'quote': - case 'editpost': - case 'delete': - if (!$post_id) bb_simple_die($lang['NO_POST_ID']); + case 'quote': + case 'editpost': + case 'delete': + if (!$post_id) bb_simple_die($lang['NO_POST_ID']); - $select_sql = 'SELECT f.*, t.*, p.*'; - $select_sql .= (!$submit) ? ', pt.*, u.username, u.user_id' : ''; + $select_sql = 'SELECT f.*, t.*, p.*'; + $select_sql .= (!$submit) ? ', pt.*, u.username, u.user_id' : ''; - $from_sql = "FROM ". BB_POSTS ." p, ". BB_TOPICS ." t, ". BB_FORUMS ." f"; - $from_sql .= (!$submit) ? ", " . BB_POSTS_TEXT . " pt, " . BB_USERS . " u" : ''; + $from_sql = "FROM " . BB_POSTS . " p, " . BB_TOPICS . " t, " . BB_FORUMS . " f"; + $from_sql .= (!$submit) ? ", " . BB_POSTS_TEXT . " pt, " . BB_USERS . " u" : ''; - $where_sql = " + $where_sql = " WHERE p.post_id = $post_id AND t.topic_id = p.topic_id AND f.forum_id = p.forum_id "; - $where_sql .= (!$submit) ? " + $where_sql .= (!$submit) ? " AND pt.post_id = p.post_id AND u.user_id = p.poster_id " : ''; - $sql = "$select_sql $from_sql $where_sql LIMIT 1"; - break; + $sql = "$select_sql $from_sql $where_sql LIMIT 1"; + break; - default: - bb_simple_die($lang['NO_VALID_MODE']); + default: + bb_simple_die($lang['NO_VALID_MODE']); } -if ($post_info = DB()->fetch_row($sql)) -{ - $forum_id = $post_info['forum_id']; - $forum_name = $post_info['forum_name']; +if ($post_info = DB()->fetch_row($sql)) { + $forum_id = $post_info['forum_id']; + $forum_name = $post_info['forum_name']; - set_die_append_msg($forum_id); + set_die_append_msg($forum_id); - $is_auth = auth(AUTH_ALL, $forum_id, $userdata, $post_info); + $is_auth = auth(AUTH_ALL, $forum_id, $userdata, $post_info); - if ($post_info['forum_status'] == FORUM_LOCKED && !$is_auth['auth_mod']) - { - bb_die($lang['FORUM_LOCKED']); - } - elseif ($mode != 'newtopic' && $mode != 'new_rel' && $post_info['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) - { - bb_die($lang['TOPIC_LOCKED']); - } + if ($post_info['forum_status'] == FORUM_LOCKED && !$is_auth['auth_mod']) { + bb_die($lang['FORUM_LOCKED']); + } elseif ($mode != 'newtopic' && $mode != 'new_rel' && $post_info['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) { + bb_die($lang['TOPIC_LOCKED']); + } - if ($mode == 'editpost' || $mode == 'delete') - { - $topic_id = $post_info['topic_id']; + if ($mode == 'editpost' || $mode == 'delete') { + $topic_id = $post_info['topic_id']; - $post_data['poster_post'] = ($post_info['poster_id'] == $userdata['user_id']); - $post_data['first_post'] = ($post_info['topic_first_post_id'] == $post_id); - $post_data['last_post'] = ($post_info['topic_last_post_id'] == $post_id); - $post_data['last_topic'] = ($post_info['forum_last_post_id'] == $post_id); - $post_data['topic_type'] = $post_info['topic_type']; - $post_data['poster_id'] = $post_info['poster_id']; + $post_data['poster_post'] = ($post_info['poster_id'] == $userdata['user_id']); + $post_data['first_post'] = ($post_info['topic_first_post_id'] == $post_id); + $post_data['last_post'] = ($post_info['topic_last_post_id'] == $post_id); + $post_data['last_topic'] = ($post_info['forum_last_post_id'] == $post_id); + $post_data['topic_type'] = $post_info['topic_type']; + $post_data['poster_id'] = $post_info['poster_id']; - $selected_rg = $post_info['poster_rg_id']; - $switch_rg_sig = ($post_info['attach_rg_sig']) ? true : false; + $selected_rg = $post_info['poster_rg_id']; + $switch_rg_sig = ($post_info['attach_rg_sig']) ? true : false; - // Can this user edit/delete the post? - if ($post_info['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) - { - $auth_err = ($delete || $mode == 'delete') ? $lang['DELETE_OWN_POSTS'] : $lang['EDIT_OWN_POSTS']; - } - elseif (!$post_data['last_post'] && !$is_auth['auth_mod'] && ($mode == 'delete' || $delete)) - { - $auth_err = $lang['CANNOT_DELETE_REPLIED']; - } + // Can this user edit/delete the post? + if ($post_info['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) { + $auth_err = ($delete || $mode == 'delete') ? $lang['DELETE_OWN_POSTS'] : $lang['EDIT_OWN_POSTS']; + } elseif (!$post_data['last_post'] && !$is_auth['auth_mod'] && ($mode == 'delete' || $delete)) { + $auth_err = $lang['CANNOT_DELETE_REPLIED']; + } - if (isset($auth_err)) bb_die($auth_err); - } - else - { - if ($mode == 'quote') - { - $topic_id = $post_info['topic_id']; - } - if ($mode == 'newtopic') - { - $post_data['topic_type'] = POST_NORMAL; - } - $post_data['first_post'] = ($mode == 'newtopic'); - $post_data['last_post'] = false; - } -} -else -{ - bb_die($lang['NO_SUCH_POST']); + if (isset($auth_err)) bb_die($auth_err); + } else { + if ($mode == 'quote') { + $topic_id = $post_info['topic_id']; + } + if ($mode == 'newtopic') { + $post_data['topic_type'] = POST_NORMAL; + } + $post_data['first_post'] = ($mode == 'newtopic'); + $post_data['last_post'] = false; + } +} else { + bb_die($lang['NO_SUCH_POST']); } $attach_allowed_ext = ($post_info['allow_reg_tracker']) ? $di->config->get('tor_forums_allowed_ext') : $di->config->get('gen_forums_allowed_ext'); -if (!$is_auth[$is_auth_type]) -{ - if (!IS_GUEST) - { - bb_die(sprintf($lang['SORRY_'. strtoupper($is_auth_type)], $is_auth[$is_auth_type .'_type'])); - } +if (!$is_auth[$is_auth_type]) { + if (!IS_GUEST) { + bb_die(sprintf($lang['SORRY_' . strtoupper($is_auth_type)], $is_auth[$is_auth_type . '_type'])); + } - switch ($mode) - { - case 'newtopic': - $redirect = "mode=newtopic&f=$forum_id"; - break; - case 'new_rel': - $redirect = "mode=new_rel&f=$forum_id"; - break; - case 'reply': - $redirect = "mode=reply&t=$topic_id"; - break; - case 'quote': - case 'editpost': - $redirect = "mode=quote&p=$post_id"; - break; - default: - $redirect = ''; - } - redirect(LOGIN_URL . "?redirect=/". POSTING_URL ."?$redirect"); + switch ($mode) { + case 'newtopic': + $redirect = "mode=newtopic&f=$forum_id"; + break; + case 'new_rel': + $redirect = "mode=new_rel&f=$forum_id"; + break; + case 'reply': + $redirect = "mode=reply&t=$topic_id"; + break; + case 'quote': + case 'editpost': + $redirect = "mode=quote&p=$post_id"; + break; + default: + $redirect = ''; + } + redirect(LOGIN_URL . "?redirect=/" . POSTING_URL . "?$redirect"); } -if ($mode == 'new_rel') -{ - if ($tor_status = join(',', $di->config->get('tor_cannot_new'))) - { - $sql = DB()->fetch_rowset("SELECT t.topic_title, t.topic_id, tor.tor_status - FROM ". BB_BT_TORRENTS ." tor, ". BB_TOPICS ." t +if ($mode == 'new_rel') { + if ($tor_status = join(',', $di->config->get('tor_cannot_new'))) { + $sql = DB()->fetch_rowset("SELECT t.topic_title, t.topic_id, tor.tor_status + FROM " . BB_BT_TORRENTS . " tor, " . BB_TOPICS . " t WHERE poster_id = {$userdata['user_id']} AND tor.topic_id = t.topic_id AND tor.tor_status IN ($tor_status) ORDER BY tor.reg_time "); - $topics = ''; - foreach ($sql as $row) { - $topics .= $di->config->get('tor_icons.' . $row['tor_status']) . '' . $row['topic_title'] . '
        '; - } - if ($topics) bb_die($topics . $lang['UNEXECUTED_RELEASE']); - } - require(INC_DIR .'posting_tpl.php'); - exit; + $topics = ''; + foreach ($sql as $row) { + $topics .= $di->config->get('tor_icons.' . $row['tor_status']) . '' . $row['topic_title'] . '
        '; + } + if ($topics) bb_die($topics . $lang['UNEXECUTED_RELEASE']); + } + require(INC_DIR . 'posting_tpl.php'); + exit; } // Notify -if ($submit || $preview) -{ - $notify_user = (int) !empty($_POST['notify']); -} -else -{ - $notify_user = bf($userdata['user_opt'], 'user_opt', 'user_notify'); +if ($submit || $preview) { + $notify_user = (int)!empty($_POST['notify']); +} else { + $notify_user = bf($userdata['user_opt'], 'user_opt', 'user_notify'); - if (!IS_GUEST && $mode != 'newtopic' && !$notify_user) - { - $notify_user = (int) DB()->fetch_row("SELECT topic_id FROM ". BB_TOPICS_WATCH ." WHERE topic_id = $topic_id AND user_id = ". $userdata['user_id']); - } + if (!IS_GUEST && $mode != 'newtopic' && !$notify_user) { + $notify_user = (int)DB()->fetch_row("SELECT topic_id FROM " . BB_TOPICS_WATCH . " WHERE topic_id = $topic_id AND user_id = " . $userdata['user_id']); + } } $update_post_time = !empty($_POST['update_post_time']); @@ -279,436 +245,380 @@ $update_post_time = !empty($_POST['update_post_time']); // если за время пока вы писали ответ, в топике появились новые сообщения, перед тем как ваше сообщение будет отправлено, выводится предупреждение с обзором этих сообщений $topic_has_new_posts = false; -if (!IS_GUEST && $mode != 'newtopic' && ($submit || $preview || $mode == 'quote' || $mode == 'reply') && isset($_COOKIE[COOKIE_TOPIC])) -{ - if ($topic_last_read = max(intval($tracking_topics[$topic_id]), intval($tracking_forums[$forum_id]))) - { - $sql = "SELECT p.*, pt.post_text, u.username, u.user_rank - FROM ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt, ". BB_USERS ." u - WHERE p.topic_id = ". (int) $topic_id ." +if (!IS_GUEST && $mode != 'newtopic' && ($submit || $preview || $mode == 'quote' || $mode == 'reply') && isset($_COOKIE[COOKIE_TOPIC])) { + if ($topic_last_read = max(intval($tracking_topics[$topic_id]), intval($tracking_forums[$forum_id]))) { + $sql = "SELECT p.*, pt.post_text, u.username, u.user_rank + FROM " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt, " . BB_USERS . " u + WHERE p.topic_id = " . (int)$topic_id . " AND u.user_id = p.poster_id AND pt.post_id = p.post_id AND p.post_time > $topic_last_read ORDER BY p.post_time - LIMIT ". $di->config->get('posts_per_page'); + LIMIT " . $di->config->get('posts_per_page'); - if ($rowset = DB()->fetch_rowset($sql)) - { - $topic_has_new_posts = true; + if ($rowset = DB()->fetch_rowset($sql)) { + $topic_has_new_posts = true; - foreach ($rowset as $i => $row) - { - $template->assign_block_vars('new_posts', array( - 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', - 'POSTER' => profile_url($row), - 'POSTER_NAME_JS' => addslashes($row['username']), - 'POST_DATE' => bb_date($row['post_time'], $di->config->get('post_date_format')), - 'MESSAGE' => get_parsed_post($row), - )); - } - $template->assign_vars(array( - 'TPL_SHOW_NEW_POSTS' => true, - )); + foreach ($rowset as $i => $row) { + $template->assign_block_vars('new_posts', array( + 'ROW_CLASS' => !($i % 2) ? 'row1' : 'row2', + 'POSTER' => profile_url($row), + 'POSTER_NAME_JS' => addslashes($row['username']), + 'POST_DATE' => bb_date($row['post_time'], $di->config->get('post_date_format')), + 'MESSAGE' => get_parsed_post($row), + )); + } + $template->assign_vars(array( + 'TPL_SHOW_NEW_POSTS' => true, + )); - set_tracks(COOKIE_TOPIC, $tracking_topics, $topic_id); - unset($rowset); - } - } + set_tracks(COOKIE_TOPIC, $tracking_topics, $topic_id); + unset($rowset); + } + } } // Confirm deletion -if ($mode == 'delete' && !$confirm) -{ - if (isset($_POST['cancel'])) - { - redirect(POST_URL . "$post_id#$post_id"); - } - $hidden_fields = array( - 'p' => $post_id, - 'mode' => 'delete', - ); - print_confirmation(array( - 'QUESTION' => $lang['CONFIRM_DELETE'], - 'FORM_ACTION' => POSTING_URL, - 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), - )); -} -elseif ( ($submit || $confirm) && !$topic_has_new_posts ) -{ - // - // Submit post (newtopic, edit, reply, etc.) - // - $return_message = ''; - $return_meta = ''; +if ($mode == 'delete' && !$confirm) { + if (isset($_POST['cancel'])) { + redirect(POST_URL . "$post_id#$post_id"); + } + $hidden_fields = array( + 'p' => $post_id, + 'mode' => 'delete', + ); + print_confirmation(array( + 'QUESTION' => $lang['CONFIRM_DELETE'], + 'FORM_ACTION' => POSTING_URL, + 'HIDDEN_FIELDS' => build_hidden_fields($hidden_fields), + )); +} elseif (($submit || $confirm) && !$topic_has_new_posts) { + // + // Submit post (newtopic, edit, reply, etc.) + // + $return_message = ''; + $return_meta = ''; - switch ($mode) - { - case 'editpost': - case 'newtopic': - case 'reply': - $username = (!empty($_POST['username'])) ? clean_username($_POST['username']) : ''; - $subject = (!empty($_POST['subject'])) ? clean_title($_POST['subject']) : ''; - $message = (!empty($_POST['message'])) ? prepare_message($_POST['message']) : ''; - $attach_rg_sig = (isset($_POST['attach_rg_sig']) && isset($_POST['poster_rg']) && $_POST['poster_rg'] != -1) ? 1 : 0; - $poster_rg_id = (isset($_POST['poster_rg']) && $_POST['poster_rg'] != -1) ? (int)$_POST['poster_rg'] : 0; + switch ($mode) { + case 'editpost': + case 'newtopic': + case 'reply': + $username = (!empty($_POST['username'])) ? clean_username($_POST['username']) : ''; + $subject = (!empty($_POST['subject'])) ? clean_title($_POST['subject']) : ''; + $message = (!empty($_POST['message'])) ? prepare_message($_POST['message']) : ''; + $attach_rg_sig = (isset($_POST['attach_rg_sig']) && isset($_POST['poster_rg']) && $_POST['poster_rg'] != -1) ? 1 : 0; + $poster_rg_id = (isset($_POST['poster_rg']) && $_POST['poster_rg'] != -1) ? (int)$_POST['poster_rg'] : 0; - prepare_post($mode, $post_data, $error_msg, $username, $subject, $message); + prepare_post($mode, $post_data, $error_msg, $username, $subject, $message); - if (!$error_msg) - { - $topic_type = ( isset($post_data['topic_type']) && $topic_type != $post_data['topic_type'] && !$is_auth['auth_sticky'] && !$is_auth['auth_announce'] ) ? $post_data['topic_type'] : $topic_type; + if (!$error_msg) { + $topic_type = (isset($post_data['topic_type']) && $topic_type != $post_data['topic_type'] && !$is_auth['auth_sticky'] && !$is_auth['auth_announce']) ? $post_data['topic_type'] : $topic_type; - submit_post($mode, $post_data, $return_message, $return_meta, $forum_id, $topic_id, $post_id, $topic_type, DB()->escape($username), DB()->escape($subject), DB()->escape($message), $update_post_time, $poster_rg_id, $attach_rg_sig); + submit_post($mode, $post_data, $return_message, $return_meta, $forum_id, $topic_id, $post_id, $topic_type, DB()->escape($username), DB()->escape($subject), DB()->escape($message), $update_post_time, $poster_rg_id, $attach_rg_sig); - $post_url = POST_URL ."$post_id#$post_id"; - $post_msg = ($mode == 'editpost') ? $lang['EDITED']: $lang['STORED']; - $onclick = ($mode == 'editpost') ? 'onclick="return post2url(this.href);"': ''; - $return_message .= $post_msg .'

        - '. $lang['POST_RETURN'] .' + $post_url = POST_URL . "$post_id#$post_id"; + $post_msg = ($mode == 'editpost') ? $lang['EDITED'] : $lang['STORED']; + $onclick = ($mode == 'editpost') ? 'onclick="return post2url(this.href);"' : ''; + $return_message .= $post_msg . '

        + ' . $lang['POST_RETURN'] . ' '; - } - break; + } + break; - case 'delete': - require_once(INC_DIR .'functions_admin.php'); - delete_post($mode, $post_data, $return_message, $return_meta, $forum_id, $topic_id, $post_id); - break; - } + case 'delete': + require_once(INC_DIR . 'functions_admin.php'); + delete_post($mode, $post_data, $return_message, $return_meta, $forum_id, $topic_id, $post_id); + break; + } - if (!$error_msg) - { - if (!in_array($mode, array('editpost', 'delete'))) - { - $user_id = ( $mode == 'reply' || $mode == 'newtopic' ) ? $userdata['user_id'] : $post_data['poster_id']; - update_post_stats($mode, $post_data, $forum_id, $topic_id, $post_id, $user_id); - } + if (!$error_msg) { + if (!in_array($mode, array('editpost', 'delete'))) { + $user_id = ($mode == 'reply' || $mode == 'newtopic') ? $userdata['user_id'] : $post_data['poster_id']; + update_post_stats($mode, $post_data, $forum_id, $topic_id, $post_id, $user_id); + } - if (!$error_msg) - { - user_notification($mode, $post_data, $post_info['topic_title'], $forum_id, $topic_id, $notify_user); - } + if (!$error_msg) { + user_notification($mode, $post_data, $post_info['topic_title'], $forum_id, $topic_id, $notify_user); + } - if ($mode == 'newtopic' || $mode == 'reply') - { - set_tracks(COOKIE_TOPIC, $tracking_topics, $topic_id); - } + if ($mode == 'newtopic' || $mode == 'reply') { + set_tracks(COOKIE_TOPIC, $tracking_topics, $topic_id); + } - // новая тема или редактирование 1-го сообщения и нет уже прикрепленного файла - $can_attach_file = (($mode == 'newtopic' || ($post_data['first_post'] && $mode == 'editpost')) && empty($post_info['attach_ext_id'])); + // новая тема или редактирование 1-го сообщения и нет уже прикрепленного файла + $can_attach_file = (($mode == 'newtopic' || ($post_data['first_post'] && $mode == 'editpost')) && empty($post_info['attach_ext_id'])); - if ($can_attach_file && !empty($_FILES['attach']['name'])) - { - require(INC_DIR .'functions_upload.php'); - $upload = new upload_common(); + if ($can_attach_file && !empty($_FILES['attach']['name'])) { + require(INC_DIR . 'functions_upload.php'); + $upload = new upload_common(); - if ($upload->init($di->config->get('attach'), $_FILES['attach']) && $upload->store('attach', array('topic_id' => $topic_id))) - { - DB()->query(" - UPDATE ". BB_TOPICS ." SET - attach_ext_id = ". (int) $upload->file_ext_id .", - filesize = ". (int) $upload->file_size ." + if ($upload->init($di->config->get('attach'), $_FILES['attach']) && $upload->store('attach', array('topic_id' => $topic_id))) { + DB()->query(" + UPDATE " . BB_TOPICS . " SET + attach_ext_id = " . (int)$upload->file_ext_id . ", + filesize = " . (int)$upload->file_size . " WHERE topic_id = $topic_id LIMIT 1 "); - if ($upload->file_ext_id == 8) - { - require_once(INC_DIR .'functions_torrent.php'); - if ($di->config->get('premod')) - { + if ($upload->file_ext_id == 8) { + require_once(INC_DIR . 'functions_torrent.php'); + if ($di->config->get('premod')) { // Получение списка id форумов начиная с parent $forum_parent = $forum_id; if ($post_info['forum_parent']) $forum_parent = $post_info['forum_parent']; - $count_rowset = DB()->fetch_rowset("SELECT forum_id FROM ". BB_FORUMS ." WHERE forum_parent = $forum_parent"); + $count_rowset = DB()->fetch_rowset("SELECT forum_id FROM " . BB_FORUMS . " WHERE forum_parent = $forum_parent"); $sub_forums = array(); - foreach ($count_rowset as $count_row) - { + foreach ($count_rowset as $count_row) { if ($count_row['forum_id'] != $forum_id) $sub_forums[] = $count_row['forum_id']; } $sub_forums[] = $forum_id; $sub_forums = join(',', $sub_forums); // Подсчет проверенных релизов в форумах раздела - $count_checked_releases = DB()->fetch_row("SELECT COUNT(*) AS checked_releases FROM ". BB_BT_TORRENTS ." WHERE poster_id = ". $userdata['user_id'] ." AND forum_id IN($sub_forums) AND tor_status IN(". TOR_APPROVED .",". TOR_DOUBTFUL .",". TOR_TMP .") LIMIT 1", 'checked_releases'); - if ($count_checked_releases || IS_AM) - { + $count_checked_releases = DB()->fetch_row("SELECT COUNT(*) AS checked_releases FROM " . BB_BT_TORRENTS . " WHERE poster_id = " . $userdata['user_id'] . " AND forum_id IN($sub_forums) AND tor_status IN(" . TOR_APPROVED . "," . TOR_DOUBTFUL . "," . TOR_TMP . ") LIMIT 1", 'checked_releases'); + if ($count_checked_releases || IS_AM) { tracker_register($topic_id, 'newtopic', TOR_NOT_APPROVED); - } - else - { + } else { tracker_register($topic_id, 'newtopic', TOR_PREMOD); } - } - else tracker_register($topic_id, 'newtopic', TOR_NOT_APPROVED); - } - } - else - { - $return_to_edit_link = 'Вернуться к редактированию сообщения'; //TODO: перевести - $return_message = ' - '. join('
        ', $upload->errors) ."
        + } else tracker_register($topic_id, 'newtopic', TOR_NOT_APPROVED); + } + } else { + $return_to_edit_link = 'Вернуться к редактированию сообщения'; //TODO: перевести + $return_message = ' + ' . join('
        ', $upload->errors) . "


        $return_to_edit_link



        $return_message "; - } - } + } + } - // Update atom feed - update_atom('topic', $topic_id); + // Update atom feed + update_atom('topic', $topic_id); - if ($mode == 'reply' && $post_info['topic_status'] == TOPIC_LOCKED) - { - $locked_warn = ' + if ($mode == 'reply' && $post_info['topic_status'] == TOPIC_LOCKED) { + $locked_warn = '
        - '. $lang['LOCKED_WARN'] .' + ' . $lang['LOCKED_WARN'] . '



        '; - $return_message = $locked_warn . $return_message; - } + $return_message = $locked_warn . $return_message; + } - bb_die($return_message); - } + bb_die($return_message); + } } -if ($preview || $error_msg || ($submit && $topic_has_new_posts)) -{ - $username = ( !empty($_POST['username']) ) ? clean_username($_POST['username']) : ''; - $subject = ( !empty($_POST['subject']) ) ? clean_title($_POST['subject']) : ''; - $message = ( !empty($_POST['message']) ) ? prepare_message($_POST['message']) : ''; +if ($preview || $error_msg || ($submit && $topic_has_new_posts)) { + $username = (!empty($_POST['username'])) ? clean_username($_POST['username']) : ''; + $subject = (!empty($_POST['subject'])) ? clean_title($_POST['subject']) : ''; + $message = (!empty($_POST['message'])) ? prepare_message($_POST['message']) : ''; - if ($preview) - { - $preview_subject = $subject; - $preview_username = $username; - $preview_message = htmlCHR($message, false, ENT_NOQUOTES); - $preview_message = bbcode2html($preview_message); + if ($preview) { + $preview_subject = $subject; + $preview_username = $username; + $preview_message = htmlCHR($message, false, ENT_NOQUOTES); + $preview_message = bbcode2html($preview_message); - $template->assign_vars(array( - 'TPL_PREVIEW_POST' => true, - 'TOPIC_TITLE' => wbr($preview_subject), - 'POST_SUBJECT' => $preview_subject, - 'POSTER_NAME' => $preview_username, - 'POST_DATE' => bb_date(TIMENOW), - 'PREVIEW_MSG' => $preview_message, - )); - } -} -else -{ - // User default entry point - if ( $mode == 'newtopic' ) - { - $username = ($userdata['session_logged_in']) ? $userdata['username'] : ''; - $subject = $message = ''; - } - elseif ( $mode == 'reply' ) - { - $username = ( $userdata['session_logged_in'] ) ? $userdata['username'] : ''; - $subject = $message = ''; - } - elseif ( $mode == 'quote' || $mode == 'editpost' ) - { - $subject = ( $post_data['first_post'] ) ? $post_info['topic_title'] : ''; - $message = $post_info['post_text']; + $template->assign_vars(array( + 'TPL_PREVIEW_POST' => true, + 'TOPIC_TITLE' => wbr($preview_subject), + 'POST_SUBJECT' => $preview_subject, + 'POSTER_NAME' => $preview_username, + 'POST_DATE' => bb_date(TIMENOW), + 'PREVIEW_MSG' => $preview_message, + )); + } +} else { + // User default entry point + if ($mode == 'newtopic') { + $username = ($userdata['session_logged_in']) ? $userdata['username'] : ''; + $subject = $message = ''; + } elseif ($mode == 'reply') { + $username = ($userdata['session_logged_in']) ? $userdata['username'] : ''; + $subject = $message = ''; + } elseif ($mode == 'quote' || $mode == 'editpost') { + $subject = ($post_data['first_post']) ? $post_info['topic_title'] : ''; + $message = $post_info['post_text']; - if ( $mode == 'quote' ) - { - if (!defined('WORD_LIST_OBTAINED')) - { - $orig_word = array(); - $replace_word = array(); - obtain_word_list($orig_word, $replace_word); - define('WORD_LIST_OBTAINED', TRUE); - } + if ($mode == 'quote') { + if (!defined('WORD_LIST_OBTAINED')) { + $orig_word = array(); + $replace_word = array(); + obtain_word_list($orig_word, $replace_word); + define('WORD_LIST_OBTAINED', TRUE); + } - if ($post_info['post_attachment'] && !IS_AM) $message = $post_info['topic_title']; - $quote_username = ($post_info['post_username'] != '') ? $post_info['post_username'] : $post_info['username']; - $message = '[quote="'. $quote_username .'"][qpost='. $post_info['post_id'] .']' . $message . '[/quote]'; + if ($post_info['post_attachment'] && !IS_AM) $message = $post_info['topic_title']; + $quote_username = ($post_info['post_username'] != '') ? $post_info['post_username'] : $post_info['username']; + $message = '[quote="' . $quote_username . '"][qpost=' . $post_info['post_id'] . ']' . $message . '[/quote]'; - // 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)) - { - $subject = (!empty($subject)) ? preg_replace($orig_word, $replace_word, $subject) : ''; - $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; - } + if (!empty($orig_word)) { + $subject = (!empty($subject)) ? preg_replace($orig_word, $replace_word, $subject) : ''; + $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; + } - if ( !preg_match('/^Re:/', $subject) && strlen($subject) > 0 ) - { - $subject = 'Re: ' . $subject; - } + if (!preg_match('/^Re:/', $subject) && strlen($subject) > 0) { + $subject = 'Re: ' . $subject; + } - $mode = 'reply'; - } - else - { - $username = ( $post_info['user_id'] == GUEST_UID && !empty($post_info['post_username']) ) ? $post_info['post_username'] : ''; - } - } + $mode = 'reply'; + } else { + $username = ($post_info['user_id'] == GUEST_UID && !empty($post_info['post_username'])) ? $post_info['post_username'] : ''; + } + } } -if ($error_msg) -{ - $template->assign_vars(array( - 'ERROR_MESSAGE' => $error_msg, - )); +if ($error_msg) { + $template->assign_vars(array( + 'ERROR_MESSAGE' => $error_msg, + )); } -if (IS_GUEST || ($mode == 'editpost' && $post_info['poster_id'] == GUEST_UID)) -{ - $template->assign_var('POSTING_USERNAME'); +if (IS_GUEST || ($mode == 'editpost' && $post_info['poster_id'] == GUEST_UID)) { + $template->assign_var('POSTING_USERNAME'); } // Notify checkbox -if (!IS_GUEST) -{ - if ($mode != 'editpost' || ($mode == 'editpost' && $post_info['poster_id'] != GUEST_UID)) - { - $template->assign_var('SHOW_NOTIFY_CHECKBOX'); - } +if (!IS_GUEST) { + if ($mode != 'editpost' || ($mode == 'editpost' && $post_info['poster_id'] != GUEST_UID)) { + $template->assign_var('SHOW_NOTIFY_CHECKBOX'); + } } // Topic type selection $topic_type_toggle = ''; -if ( $mode == 'newtopic' || ( $mode == 'editpost' && $post_data['first_post'] ) ) -{ - $template->assign_block_vars('switch_type_toggle', array()); +if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) { + $template->assign_block_vars('switch_type_toggle', array()); - if( $is_auth['auth_sticky'] ) - { - $topic_type_toggle .= '
      • ' . $val . '
        ' . str_replace(array("{$this->selected_db}.", ',', ';'), array('', ', ', ';
        '), $val) . '