Basic reformat all .php files to PSR-2. Requires manual verification.

This commit is contained in:
Yuriy Pikhtarev 2016-09-27 22:36:35 +03:00
commit 8776f12e86
No known key found for this signature in database
GPG key ID: 3A9B5A757B48ECC6
154 changed files with 24662 additions and 28312 deletions

View file

@ -1,148 +1,136 @@
<?php
if (!empty($setmodules))
{
$module['GENERAL']['CONFIGURATION'] = basename(__FILE__) .'?mode=config';
$module['MODS']['CONFIGURATION'] = basename(__FILE__) .'?mode=config_mods';
return;
if (!empty($setmodules)) {
$module['GENERAL']['CONFIGURATION'] = basename(__FILE__) . '?mode=config';
$module['MODS']['CONFIGURATION'] = basename(__FILE__) . '?mode=config_mods';
return;
}
require('./pagestart.php');
require(INC_DIR .'functions_selects.php');
require(INC_DIR . 'functions_selects.php');
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$return_links = array(
'index' => '<br /><br />'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'),
'config' => '<br /><br />'. sprintf($lang['CLICK_RETURN_CONFIG'], '<a href="admin_board.php?mode=config">', '</a>'),
'config_mods' => '<br /><br />'. sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '<a href="admin_board.php?mode=config_mods">', '</a>')
'index' => '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'),
'config' => '<br /><br />' . sprintf($lang['CLICK_RETURN_CONFIG'], '<a href="admin_board.php?mode=config">', '</a>'),
'config_mods' => '<br /><br />' . sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '<a href="admin_board.php?mode=config_mods">', '</a>')
);
//
// 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');
print_page('admin_board.tpl', 'admin');

View file

@ -1,148 +1,140 @@
<?php
if (!empty($setmodules))
{
$module['TP']['FORUM_CONFIG'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['TP']['FORUM_CONFIG'] = basename(__FILE__);
return;
}
require('./pagestart.php');
$max_forum_name_len = 30;
$max_forum_rows = 25;
$max_forum_rows = 25;
require(INC_DIR .'functions_admin_torrent.php');
require(INC_DIR . 'functions_admin_torrent.php');
$submit = isset($_POST['submit']);
$submit = isset($_POST['submit']);
$confirm = isset($_POST['confirm']);
$cfg = array();
// All config names with default values
$default_cfg_str = array(
'bt_announce_url' => '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'] .'<br /><br />'. sprintf($lang['RETURN_CONFIG'], '<a href="admin_bt_forum_cfg.php">', '</a>') .'<br /><br />'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
bb_die($lang['CONFIG_UPD'] . '<br /><br />' . sprintf($lang['RETURN_CONFIG'], '<a href="admin_bt_forum_cfg.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
// 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 .= '<option value="'. $forum['forum_id'] .'" '. $selected .'>&nbsp;' . (($forum['forum_parent']) ? HTML_SF_SPACER : '') . htmlCHR($forum_name) ."</option>\n";
}
$$field_name .= '<option value="' . $forum['forum_id'] . '" ' . $selected . '>&nbsp;' . (($forum['forum_parent']) ? HTML_SF_SPACER : '') . htmlCHR($forum_name) . "</option>\n";
}
}
foreach ($db_fields_bool as $field_name => $field_def_val)
{
$$field_name = '<select name="'. $field_name ."[]\" multiple=\"multiple\" size=\"$forum_rows\">". $$field_name .'</select>';
$template->assign_vars(array('S_'. strtoupper($field_name) => $$field_name));
foreach ($db_fields_bool as $field_name => $field_def_val) {
$$field_name = '<select name="' . $field_name . "[]\" multiple=\"multiple\" size=\"$forum_rows\">" . $$field_name . '</select>';
$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) ? '<u>'. $lang['BT_SHOW_PEERS_MODE_COUNT'] .'</u>' : $lang['BT_SHOW_PEERS_MODE_COUNT'],
'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? '<u>'. $lang['BT_SHOW_PEERS_MODE_NAMES'] .'</u>' : $lang['BT_SHOW_PEERS_MODE_NAMES'],
'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? '<u>'. $lang['BT_SHOW_PEERS_MODE_FULL'] .'</u>' : $lang['BT_SHOW_PEERS_MODE_FULL'],
'L_BT_SHOW_PEERS_MODE_COUNT' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_COUNT) ? '<u>' . $lang['BT_SHOW_PEERS_MODE_COUNT'] . '</u>' : $lang['BT_SHOW_PEERS_MODE_COUNT'],
'L_BT_SHOW_PEERS_MODE_NAMES' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_NAMES) ? '<u>' . $lang['BT_SHOW_PEERS_MODE_NAMES'] . '</u>' : $lang['BT_SHOW_PEERS_MODE_NAMES'],
'L_BT_SHOW_PEERS_MODE_FULL' => ($cfg['bt_show_peers_mode'] == SHOW_PEERS_FULL) ? '<u>' . $lang['BT_SHOW_PEERS_MODE_FULL'] . '</u>' : $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');
print_page('admin_bt_forum_cfg.tpl', 'admin');

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
if (IS_SUPER_ADMIN) $module['TP']['TRACKER_CONFIG'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['TP']['TRACKER_CONFIG'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -12,56 +11,56 @@ $di = \TorrentPier\Di::getInstance();
if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']);
require(INC_DIR .'functions_admin_torrent.php');
require(INC_DIR . 'functions_admin_torrent.php');
$submit = isset($_POST['submit']);
$confirmed = isset($_POST['confirm']);
$submit = isset($_POST['submit']);
$confirmed = isset($_POST['confirm']);
// All config names with default values
$default_cfg_str = array(
'off_reason' => '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');
print_page('admin_bt_tracker_cfg.tpl', 'admin');

View file

@ -1,227 +1,198 @@
<?php
if (!empty($setmodules))
{
if (IS_SUPER_ADMIN) $module['TP']['CRON'] = basename(__FILE__) . '?mode=list';
return;
if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['TP']['CRON'] = basename(__FILE__) . '?mode=list';
return;
}
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$job_id = isset($_GET['id']) ? (int) $_GET['id'] : '';
$submit = isset($_POST['submit']);
$job_id = isset($_GET['id']) ? (int)$_GET['id'] : '';
$submit = isset($_POST['submit']);
$jobs = isset($_POST['select']) ? implode(',', $_POST['select']) : '';
$cron_action = isset($_POST['cron_action']) ? $_POST['cron_action'] : '';
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 ($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'] ? '<img src="../styles/images/icon_run.gif" alt="'. $lang['YES'] .'" />' : '<img src="../styles/images/icon_delete.gif" alt="'. $lang['NO'] .'" />',
'CRON_TITLE' => $row['cron_title'],
'CRON_SCRIPT' => $row['cron_script'],
'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '<b class="leech">'. $lang['NOSELECT'] .'</b>',
'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'] ? '<img src="../styles/images/icon_run.gif" alt="' . $lang['YES'] . '" />' : '<img src="../styles/images/icon_delete.gif" alt="' . $lang['NO'] . '" />',
'CRON_TITLE' => $row['cron_title'],
'CRON_SCRIPT' => $row['cron_script'],
'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '<b class="leech">' . $lang['NOSELECT'] . '</b>',
'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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_JOBS'], '<a href="admin_cron.php?mode=list">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
break;
case 'delete':
delete_jobs($job_id);
bb_die($lang['JOB_REMOVED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_JOBS'], '<a href="admin_cron.php?mode=list">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
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');
print_page('admin_cron.tpl', 'admin');

View file

@ -1,57 +1,47 @@
<?php
if (!empty($setmodules))
{
$module['USERS']['DISALLOW'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['USERS']['DISALLOW'] = basename(__FILE__);
return;
}
require('./pagestart.php');
$message = '';
if (isset($_POST['add_name']))
{
include(INC_DIR .'functions_validate.php');
if (isset($_POST['add_name'])) {
include(INC_DIR . 'functions_validate.php');
$disallowed_user = ( isset($_POST['disallowed_user']) ) ? trim($_POST['disallowed_user']) : trim($_GET['disallowed_user']);
$disallowed_user = (isset($_POST['disallowed_user'])) ? trim($_POST['disallowed_user']) : trim($_GET['disallowed_user']);
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'];
}
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 .= '<br /><br />'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '<a href="admin_disallow.php">', '</a>') . '<br /><br />'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message .= '<br /><br />' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '<a href="admin_disallow.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] .'<br /><br />'. sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '<a href="admin_disallow.php">', '</a>') .'<br /><br />'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message .= $lang['DISALLOWED_DELETED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_DISALLOWADMIN'], '<a href="admin_disallow.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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 = '<select name="disallowed_id">';
if (count($disallowed) <= 0)
{
$disallow_select .= '<option value="">' . $lang['NO_DISALLOWED'] . '</option>';
}
else
{
for ($i = 0; $i < count($disallowed); $i++)
{
$disallow_select .= '<option value="' . $disallowed[$i]['disallow_id'] . '">' . $disallowed[$i]['disallow_username'] . '</option>';
}
if (count($disallowed) <= 0) {
$disallow_select .= '<option value="">' . $lang['NO_DISALLOWED'] . '</option>';
} else {
for ($i = 0; $i < count($disallowed); $i++) {
$disallow_select .= '<option value="' . $disallowed[$i]['disallow_id'] . '">' . $disallowed[$i]['disallow_username'] . '</option>';
}
}
$disallow_select .= '</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');
print_page('admin_disallow.tpl', 'admin');

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['FORUMS']['PRUNE'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['FORUMS']['PRUNE'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -11,50 +10,44 @@ $all_forums = -1;
$pruned_total = 0;
$prune_performed = false;
if (isset($_REQUEST['submit']))
{
if (!($var =& $_REQUEST['f']) || !($f_selected = get_id_ary($var)))
{
bb_die('Forum not selected');
}
if (!($var =& $_REQUEST['prunedays']) || !($prunedays = abs(intval($var))))
{
bb_die($lang['NOT_DAYS']);
}
if (isset($_REQUEST['submit'])) {
if (!($var =& $_REQUEST['f']) || !($f_selected = get_id_ary($var))) {
bb_die('Forum not selected');
}
if (!($var =& $_REQUEST['prunedays']) || !($prunedays = abs(intval($var)))) {
bb_die($lang['NOT_DAYS']);
}
$prunetime = TIMENOW - 86400*$prunedays;
$forum_csv = in_array($all_forums, $f_selected) ? $all_forums : join(',', $f_selected);
$prunetime = TIMENOW - 86400 * $prunedays;
$forum_csv = in_array($all_forums, $f_selected) ? $all_forums : join(',', $f_selected);
$where_sql = ($forum_csv != $all_forums) ? "WHERE forum_id IN($forum_csv)" : '';
$where_sql = ($forum_csv != $all_forums) ? "WHERE forum_id IN($forum_csv)" : '';
$sql = "SELECT forum_id, forum_name FROM ". BB_FORUMS ." $where_sql";
$sql = "SELECT forum_id, forum_name FROM " . BB_FORUMS . " $where_sql";
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;
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');
print_page('admin_forum_prune.tpl', 'admin');

View file

@ -1,134 +1,121 @@
<?php
if (!empty($setmodules))
{
$module['FORUMS']['PERMISSIONS'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['FORUMS']['PERMISSIONS'] = basename(__FILE__);
return;
}
require('./pagestart.php');
$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',
);
// View Read Reply Edit Delete Vote Poll PostAttach DownAttach PostTopic Sticky Announce
$simple_auth_ary = array(
/* 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]
/* 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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="'."admin_forumauth.php".'">', "</a>"));
$datastore->update('cat_forums');
bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="' . "admin_forumauth.php" . '">', "</a>"));
} // 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 = '<select name="simpleauth">';
if (empty($adv)) {
$simple_auth = '<select name="simpleauth">';
for($j = 0; $j < count($simple_auth_types); $j++)
{
$selected = ( $matched_type == $j ) ? ' selected="selected"' : '';
$simple_auth .= '<option value="' . $j . '"' . $selected . '>' . $simple_auth_types[$j] . '</option>';
}
for ($j = 0; $j < count($simple_auth_types); $j++) {
$selected = ($matched_type == $j) ? ' selected="selected"' : '';
$simple_auth .= '<option value="' . $j . '"' . $selected . '>' . $simple_auth_types[$j] . '</option>';
}
$simple_auth .= '</select>';
$simple_auth .= '</select>';
$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] = '&nbsp;<select name="' . $forum_auth_fields[$j] . '">';
$s_column_span++;
} else {
//
// Output values of individual
// fields
//
for ($j = 0; $j < count($forum_auth_fields); $j++) {
$custom_auth[$j] = '&nbsp;<select name="' . $forum_auth_fields[$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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . strtoupper($forum_auth_levels[$k])] . '</OPTION>';
}
$custom_auth[$j] .= '</select>&nbsp;';
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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . strtoupper($forum_auth_levels[$k])] . '</OPTION>';
}
$custom_auth[$j] .= '</select>&nbsp;';
$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&amp;adv=$adv_mode";
$switch_mode_text = ( empty($adv) ) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE'];
$u_switch_mode = '<a href="' . $switch_mode . '">' . $switch_mode_text . '</a>';
$adv_mode = (empty($adv)) ? '1' : '0';
$switch_mode = "admin_forumauth.php?f=$forum_id&amp;adv=$adv_mode";
$switch_mode_text = (empty($adv)) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE'];
$u_switch_mode = '<a href="' . $switch_mode . '">' . $switch_mode_text . '</a>';
$s_hidden_fields = '<input type="hidden" name="' . POST_FORUM_URL . '" value="' . $forum_id . '">';
$s_hidden_fields = '<input type="hidden" name="' . POST_FORUM_URL . '" value="' . $forum_id . '">';
$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');
print_page('admin_forumauth.tpl', 'admin');

View file

@ -1,174 +1,151 @@
<?php
if (!empty($setmodules))
{
$module['FORUMS']['PERMISSIONS_LIST'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['FORUMS']['PERMISSIONS_LIST'] = basename(__FILE__);
return;
}
require('./pagestart.php');
// View Read Post Reply Edit Delete Sticky Announce Vote Poll PostAttach Download
$simple_auth_ary = array(
/* 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]
/* 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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="admin_forumauth_list.php">', "</a>"));
$datastore->update('cat_forums');
bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="admin_forumauth_list.php">', "</a>"));
} // 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; $i<count($forum_auth_fields); $i++)
{
$template->assign_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; $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' => '<a class="'.(($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen').'" href="admin_forumauth.php?'. POST_FORUM_URL .'='. $forum_rows[$j]['forum_id'] .'">'. htmlCHR($forum_rows[$j]['forum_name']) .'</a>',
'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' => '<a class="' . (($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen') . '" href="admin_forumauth.php?' . POST_FORUM_URL . '=' . $forum_rows[$j]['forum_id'] . '">' . htmlCHR($forum_rows[$j]['forum_name']) . '</a>',
'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'],
));
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
//
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; $i<count($forum_auth_fields); $i++)
{
$template->assign_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; $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' => '<a class="'.(($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen').'" href="admin_forumauth.php?'. POST_FORUM_URL .'='. $forum_rows[$j]['forum_id'] .'">'. htmlCHR($forum_rows[$j]['forum_name']) .'</a>',
'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' => '<a class="' . (($forum_rows[$j]['forum_parent']) ? 'genmed' : 'gen') . '" href="admin_forumauth.php?' . POST_FORUM_URL . '=' . $forum_rows[$j]['forum_id'] . '">' . htmlCHR($forum_rows[$j]['forum_name']) . '</a>',
'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'],
));
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)]))
);
}
}
}
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] = '<select name="' . $forum_auth_fields[$j] . '">';
//
// 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] = '<select name="' . $forum_auth_fields[$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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . $forum_auth_levels[$k]] . '</option>';
}
$custom_auth[$j] .= '</select>';
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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . $forum_auth_levels[$k]] . '</option>';
}
$custom_auth[$j] .= '</select>';
$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 = '<input type="hidden" name="' . POST_CAT_URL . '" value="' . $cat_id . '">';
//
// finally pass any remaining items to the template
//
$s_hidden_fields = '<input type="hidden" name="' . POST_CAT_URL . '" value="' . $cat_id . '">';
$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');
print_page('admin_forumauth_list.tpl', 'admin');

File diff suppressed because it is too large Load diff

View file

@ -1,186 +1,160 @@
<?php
if (!empty($setmodules))
{
$module['GROUPS']['MANAGE'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['GROUPS']['MANAGE'] = basename(__FILE__);
return;
}
require('./pagestart.php');
require(INC_DIR .'functions_group.php');
require(INC_DIR . 'functions_group.php');
$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : 0;
$mode = isset($_REQUEST['mode']) ? strval($_REQUEST['mode']) : '';
$mode = isset($_REQUEST['mode']) ? strval($_REQUEST['mode']) : '';
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';
}
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 = '
<input type="hidden" name="mode" value="'. $mode .'" />
<input type="hidden" name="'. POST_GROUPS_URL .'" value="'. $group_id .'" />
// Ok, now we know everything about them, let's show the page.
$s_hidden_fields = '
<input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="' . POST_GROUPS_URL . '" value="' . $group_id . '" />
';
$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'] .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message = $lang['DELETED_GROUP'] . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message = $lang['UPDATED_GROUP'] . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message = $lang['ADDED_NEW_GROUP'] . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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');
print_page('admin_groups.tpl', 'admin');

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['USERS']['ACTIONS_LOG'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['USERS']['ACTIONS_LOG'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -11,53 +10,52 @@ require('./pagestart.php');
$di = \TorrentPier\Di::getInstance();
$datastore->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');
print_page('admin_log.tpl', 'admin');

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['MODS']['MASS_EMAIL'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['MODS']['MASS_EMAIL'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -12,94 +11,86 @@ $di = \TorrentPier\Di::getInstance();
set_time_limit(1200);
$subject = (string) trim(request_var('subject', ''));
$message = (string) request_var('message', '');
$group_id = (int) request_var(POST_GROUPS_URL, 0);
$subject = (string)trim(request_var('subject', ''));
$message = (string)request_var('message', '');
$group_id = (int)request_var(POST_GROUPS_URL, 0);
$errors = $user_id_sql = array();
if (isset($_POST['submit']))
{
if (!$subject) $errors[] = $lang['EMPTY_SUBJECT'];
if (!$message) $errors[] = $lang['EMPTY_MESSAGE'];
if (!$group_id) $errors[] = $lang['GROUP_NOT_EXIST'];
if (isset($_POST['submit'])) {
if (!$subject) $errors[] = $lang['EMPTY_SUBJECT'];
if (!$message) $errors[] = $lang['EMPTY_MESSAGE'];
if (!$group_id) $errors[] = $lang['GROUP_NOT_EXIST'];
if (!$errors)
{
$sql = DB()->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('<br />', array_unique($errors)) : '',
'ERROR_MESSAGE' => ($errors) ? join('<br />', 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');
print_page('admin_mass_email.tpl', 'admin');

View file

@ -1,10 +1,9 @@
<?php
if (!empty($setmodules))
{
$module['GENERAL']['PHP_INFO'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['GENERAL']['PHP_INFO'] = basename(__FILE__);
return;
}
require('./pagestart.php');
phpinfo();
phpinfo();

View file

@ -1,254 +1,209 @@
<?php
if (!empty($setmodules))
{
$module['USERS']['RANKS'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['USERS']['RANKS'] = basename(__FILE__);
return;
}
require('./pagestart.php');
$_POST['special_rank'] = 1;
$_POST['min_posts'] = -1;
if (isset($_GET['mode']) || isset($_POST['mode']))
{
$mode = isset($_GET['mode']) ? $_GET['mode'] : $_POST['mode'];
}
else
{
//
// These could be entered via a form button
//
if (isset($_POST['add']))
{
$mode = 'add';
}
elseif (isset($_POST['save']))
{
$mode = 'save';
}
else
{
$mode = '';
}
if (isset($_GET['mode']) || isset($_POST['mode'])) {
$mode = isset($_GET['mode']) ? $_GET['mode'] : $_POST['mode'];
} else {
//
// These could be entered via a form button
//
if (isset($_POST['add'])) {
$mode = 'add';
} elseif (isset($_POST['save'])) {
$mode = 'save';
} else {
$mode = '';
}
}
if ($mode != '')
{
if ($mode == 'edit' || $mode == 'add')
{
//
// They want to add a new rank, show the form.
//
$rank_id = (isset($_GET['id'])) ? intval($_GET['id']) : 0;
if ($mode != '') {
if ($mode == 'edit' || $mode == 'add') {
//
// They want to add a new rank, show the form.
//
$rank_id = (isset($_GET['id'])) ? intval($_GET['id']) : 0;
$s_hidden_fields = '';
$s_hidden_fields = '';
if ($mode == 'edit')
{
if (empty($rank_id))
{
bb_die($lang['MUST_SELECT_RANK']);
}
if ($mode == 'edit') {
if (empty($rank_id)) {
bb_die($lang['MUST_SELECT_RANK']);
}
$sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_id = $rank_id";
if (!$result = DB()->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 .= '<input type="hidden" name="id" value="'. $rank_id .'" />';
}
else
{
$rank_info['rank_special'] = 0;
}
$rank_info = DB()->sql_fetchrow($result);
$s_hidden_fields .= '<input type="hidden" name="id" value="' . $rank_id . '" />';
} else {
$rank_info['rank_special'] = 0;
}
$s_hidden_fields .= '<input type="hidden" name="mode" value="save" />';
$s_hidden_fields .= '<input type="hidden" name="mode" value="save" />';
$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']) ? '<img src="../'. $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']) ? '<img src="../' . $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 .= '<br /><br />' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '<a href="admin_ranks.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message .= '<br /><br />' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '<a href="admin_ranks.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '<a href="admin_ranks.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_RANKADMIN'], '<a href="admin_ranks.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
} 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']) ? '<img src="../'. $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']) ? '<img src="../' . $rank_rows[$i]['rank_image'] . '" />' : '',
'SPECIAL_RANK' => $rank_is_special,
'RANK_MIN' => $rank_min,
'U_RANK_EDIT' => "admin_ranks.php?mode=edit&amp;id=$rank_id",
'U_RANK_DELETE' => "admin_ranks.php?mode=delete&amp;id=$rank_id",
));
}
'U_RANK_EDIT' => "admin_ranks.php?mode=edit&amp;id=$rank_id",
'U_RANK_DELETE' => "admin_ranks.php?mode=delete&amp;id=$rank_id",
));
}
}
print_page('admin_ranks.tpl', 'admin');
print_page('admin_ranks.tpl', 'admin');

View file

@ -1,48 +1,45 @@
<?php
if (!empty($setmodules))
{
if (IS_SUPER_ADMIN) $module['GENERAL']['REBUILD_SEARCH_INDEX'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['GENERAL']['REBUILD_SEARCH_INDEX'] = basename(__FILE__);
return;
}
require('./pagestart.php');
if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']);
require(INC_DIR .'bbcode.php');
require(INC_DIR . 'bbcode.php');
define('REBUILD_SEARCH_ABORTED', 0); // when the user aborted the processing
define('REBUILD_SEARCH_ABORTED', 0); // when the user aborted the processing
define('REBUILD_SEARCH_PROCESSED', 1); // when a batch of posts has been processed
define('REBUILD_SEARCH_COMPLETED', 2); // when all the db posts have been processed
//
// Define initial vars
//
$def_post_limit = 50;
$def_post_limit = 50;
$def_refresh_rate = 3;
$def_time_limit = ($sys_time_limit = ini_get('max_execution_time')) ? $sys_time_limit : 30;
$def_time_limit = ($sys_time_limit = ini_get('max_execution_time')) ? $sys_time_limit : 30;
$last_session_data = get_rebuild_session_details('last', 'all');
$last_session_id = (int) $last_session_data['rebuild_session_id'];
$max_post_id = get_latest_post_id();
$start_time = TIMENOW;
$last_session_id = (int)$last_session_data['rebuild_session_id'];
$max_post_id = get_latest_post_id();
$start_time = TIMENOW;
$mode = (string) $_REQUEST['mode'];
$mode = (string)$_REQUEST['mode'];
// check if the user has choosen to stop processing
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 ."
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']) .'<br /><br />'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '<a href="admin_rebuild_search.php">', '</a>'));
bb_die(sprintf($lang['REBUILD_SEARCH_ABORTED'], $last_session_data['end_post_id']) . '<br /><br />' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '<a href="admin_rebuild_search.php">', '</a>'));
}
// 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 .= '<br />' . 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 .= '<br />' . 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 .= '<br />' . 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 .= '<br />' . 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'] .'<br /><br />'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '<a href="admin_rebuild_search.php">', '</a>'));
}
if ($mode == 'submit') {
if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) {
bb_die($lang['WRONG_INPUT'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '<a href="admin_rebuild_search.php">', '</a>'));
}
}
// 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 .= '<br />' . $lang['ALL_TABLES_OPTIMIZED'];
}
$processing_messages .= '<br />' . $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 = '<input type="hidden" name="post_limit_stored" value="'.$post_limit_hidden.'" />';
$s_hidden_fields .= '<input type="hidden" name="total_posts_stored" value="'.$total_posts.'" />';
$s_hidden_fields = '<input type="hidden" name="post_limit_stored" value="' . $post_limit_hidden . '" />';
$s_hidden_fields .= '<input type="hidden" name="total_posts_stored" value="' . $total_posts . '" />';
$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 .= '<br />'.$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 .= '<br />' . $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),
));
}
}
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),
));
}
}

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['MODS']['SITEMAP'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['MODS']['SITEMAP'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -14,18 +13,18 @@ $di = \TorrentPier\Di::getInstance();
$cache = $di->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('<a href="admin_sitemap.php">' . $lang['GO_BACK'] . '</a>');
if (bb_update_config(array('static_sitemap' => request_var('static_sitemap', '')))) {
// TODO: delete only necessary cache
$cache->flush();
}
bb_die('<a href="admin_sitemap.php">' . $lang['GO_BACK'] . '</a>');
}
$s_mess = $lang['SITEMAP_CREATED'].': <b>'. bb_date($di->config->get('sitemap_time'), $di->config->get('post_date_format')) .'</b> '. $lang['SITEMAP_AVAILABLE'] .': <a href="'. make_url('sitemap.xml') .'" target="_blank">'. make_url('sitemap.xml') .'</a>';
$s_mess = $lang['SITEMAP_CREATED'] . ': <b>' . bb_date($di->config->get('sitemap_time'), $di->config->get('post_date_format')) . '</b> ' . $lang['SITEMAP_AVAILABLE'] . ': <a href="' . make_url('sitemap.xml') . '" target="_blank">' . make_url('sitemap.xml') . '</a>';
$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');
print_page('admin_sitemap.tpl', 'admin');

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['GENERAL']['SMILIES'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['GENERAL']['SMILIES'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -11,363 +10,307 @@ require('./pagestart.php');
$di = \TorrentPier\Di::getInstance();
// Check to see what mode we should operate in
if (isset($_POST['mode']) || isset($_GET['mode']))
{
$mode = ( isset($_POST['mode']) ) ? $_POST['mode'] : $_GET['mode'];
$mode = htmlspecialchars($mode);
}
else
{
$mode = '';
if (isset($_POST['mode']) || isset($_GET['mode'])) {
$mode = (isset($_POST['mode'])) ? $_POST['mode'] : $_GET['mode'];
$mode = htmlspecialchars($mode);
} else {
$mode = '';
}
$delimeter = '=+:';
$delimeter = '=+:';
// Read a listing of uploaded smilies for use in the add or edit smliey code
$dir = opendir(BB_ROOT . $di->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('<', '&lt;', $smile_data[$j]);
$smile_data[$j] = str_replace('>', '&gt;', $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('<', '&lt;', $smile_data[$j]);
$smile_data[$j] = str_replace('>', '&gt;', $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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
else
{
// Display the script to get the smile_pak cfg file
$smile_paks_select = '<select name="smile_pak"><option value="">' . $lang['SELECT_PAK'] . '</option>';
while (list($key, $value) = each($smiley_paks))
{
if (!empty($value))
{
$smile_paks_select .= '<option>' . $value . '</option>';
}
}
$smile_paks_select .= '</select>';
bb_die($lang['SMILEY_IMPORT_SUCCESS'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
} else {
// Display the script to get the smile_pak cfg file
$smile_paks_select = '<select name="smile_pak"><option value="">' . $lang['SELECT_PAK'] . '</option>';
while (list($key, $value) = each($smiley_paks)) {
if (!empty($value)) {
$smile_paks_select .= '<option>' . $value . '</option>';
}
}
$smile_paks_select .= '</select>';
$hidden_vars = '<input type="hidden" name="mode" value="import">';
$hidden_vars = '<input type="hidden" name="mode" value="import">';
$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'], '<a href="admin_smilies.php?export_pack=send">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
else if (isset($_POST['add']) || isset($_GET['add']))
{
$filename_list = '';
for ($i = 0; $i < count($smiley_images); $i++)
{
$filename_list .= '<option value="'. $smiley_images[$i] .'">'. $smiley_images[$i] .'</option>';
}
bb_die(sprintf($lang['EXPORT_SMILES'], '<a href="admin_smilies.php?export_pack=send">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
} else if (isset($_POST['add']) || isset($_GET['add'])) {
$filename_list = '';
for ($i = 0; $i < count($smiley_images); $i++) {
$filename_list .= '<option value="' . $smiley_images[$i] . '">' . $smiley_images[$i] . '</option>';
}
$s_hidden_fields = '<input type="hidden" name="mode" value="savenew" />';
$s_hidden_fields = '<input type="hidden" name="mode" value="savenew" />';
$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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
break;
bb_die($lang['SMILEY_DEL_SUCCESS'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
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 .= '<option value="' . $smiley_images[$i] . '"' . $smiley_selected . '>' . $smiley_images[$i] . '</option>';
}
$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 .= '<option value="' . $smiley_images[$i] . '"' . $smiley_selected . '>' . $smiley_images[$i] . '</option>';
}
$s_hidden_fields = '<input type="hidden" name="mode" value="save" /><input type="hidden" name="smile_id" value="'. $smile_data['smilies_id'] .'" />';
$s_hidden_fields = '<input type="hidden" name="mode" value="save" /><input type="hidden" name="smile_id" value="' . $smile_data['smilies_id'] . '" />';
$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('<', '&lt;', $smile_code);
$smile_code = str_replace('>', '&gt;', $smile_code);
// Convert < and > to proper htmlentities for parsing
$smile_code = str_replace('<', '&lt;', $smile_code);
$smile_code = str_replace('>', '&gt;', $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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
break;
bb_die($lang['SMILEY_EDIT_SUCCESS'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
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('<', '&lt;', $smile_code);
$smile_code = str_replace('>', '&gt;', $smile_code);
// Convert < and > to proper htmlentities for parsing
$smile_code = str_replace('<', '&lt;', $smile_code);
$smile_code = str_replace('>', '&gt;', $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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_SMILEADMIN'], '<a href="admin_smilies.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
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('&lt;', '<', $smilies[$i]['code']);
$smilies[$i]['code'] = str_replace('&gt;', '>', $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('&lt;', '<', $smilies[$i]['code']);
$smilies[$i]['code'] = str_replace('&gt;', '>', $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&amp;id=". $smilies[$i]['smilies_id'],
'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&amp;id=". $smilies[$i]['smilies_id'],
));
}
'U_SMILEY_EDIT' => "admin_smilies.php?mode=edit&amp;id=" . $smilies[$i]['smilies_id'],
'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&amp;id=" . $smilies[$i]['smilies_id'],
));
}
}
print_page('admin_smilies.tpl', 'admin');
print_page('admin_smilies.tpl', 'admin');

View file

@ -1,28 +1,26 @@
<?php
if (!empty($setmodules))
{
$module['GENERAL']['TERMS'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['GENERAL']['TERMS'] = basename(__FILE__);
return;
}
require('./pagestart.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
require(INC_DIR .'bbcode.php');
require(INC_DIR . 'bbcode.php');
if (isset($_POST['post']) && $di->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');
print_page('admin_terms.tpl', 'admin');

View file

@ -1,465 +1,415 @@
<?php
if (!empty($setmodules))
{
$module['USERS']['PERMISSIONS'] = basename(__FILE__) .'?mode=user';
$module['GROUPS']['PERMISSIONS'] = basename(__FILE__) .'?mode=group';
return;
if (!empty($setmodules)) {
$module['USERS']['PERMISSIONS'] = basename(__FILE__) . '?mode=user';
$module['GROUPS']['PERMISSIONS'] = basename(__FILE__) . '?mode=group';
return;
}
require('./pagestart.php');
$max_forum_name_length = 50;
require(INC_DIR .'functions_group.php');
require(INC_DIR . 'functions_group.php');
$yes_sign = '&radic;';
$no_sign = 'x';
$no_sign = 'x';
$group_id = (int) $_REQUEST['g'];
$user_id = (int) $_REQUEST['u'];
$cat_id = (int) $_REQUEST['c'];
$mode = (string) $_REQUEST['mode'];
$submit = isset($_POST['submit']);
$group_id = (int)$_REQUEST['g'];
$user_id = (int)$_REQUEST['u'];
$cat_id = (int)$_REQUEST['c'];
$mode = (string)$_REQUEST['mode'];
$submit = isset($_POST['submit']);
$group_data = array();
$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',
);
if ($submit && $mode == 'user')
{
$this_user_level = null;
if ($submit && $mode == 'user') {
$this_user_level = null;
// Obtain relevant data for this user
if (!$row = get_userdata($user_id))
{
bb_die($lang['NO_SUCH_USER']);
}
$this_user_level = $row['user_level'];
// Obtain relevant data for this user
if (!$row = get_userdata($user_id)) {
bb_die($lang['NO_SUCH_USER']);
}
$this_user_level = $row['user_level'];
// Get "single_user" group_id for this user
$sql = "SELECT g.group_id
FROM ". BB_USER_GROUP ." ug, ". BB_GROUPS ." g
// Get "single_user" group_id for this user
$sql = "SELECT g.group_id
FROM " . BB_USER_GROUP . " ug, " . BB_GROUPS . " g
WHERE ug.user_id = $user_id
AND g.group_id = ug.group_id
AND g.group_single_user = 1";
if ($row = DB()->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'] .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '<a href="admin_ug_auth.php?mode=' . $mode . '">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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<br /><br />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<br /><br />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'] .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_USERAUTH'], '<a href="admin_ug_auth.php?mode=' . $mode . '">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] .'<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH'];
$message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode=' . $mode . '">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] .'<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$l_auth_return = $lang['CLICK_RETURN_GROUPAUTH'];
$message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode=' . $mode . '">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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&amp;u=$user_id";
if (!$forums = $datastore->get('cat_forums')) {
$datastore->update('cat_forums');
$forums = $datastore->get('cat_forums');
}
$base_url = basename(__FILE__) . "?mode=user&amp;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&amp;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&amp;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<br />", $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<br />", $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 = '
<input type="hidden" name="mode" value="'. $mode .'" />
<input type="hidden" name="'. POST_USERS_URL .'" value="'. $user_id .'" />
$s_hidden_fields = '
<input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="' . POST_USERS_URL . '" value="' . $user_id . '" />
';
$s_user_type = ($this_userdata['user_level'] == ADMIN) ? '
$s_user_type = ($this_userdata['user_level'] == ADMIN) ? '
<select name="userlevel">
<option value="admin" selected="selected">'. $lang['RANK_ADMIN'] .'</option>
<option value="user">'. $lang['USER'] .'</option>
<option value="admin" selected="selected">' . $lang['RANK_ADMIN'] . '</option>
<option value="user">' . $lang['USER'] . '</option>
</select>
' : '
<select name="userlevel">
<option value="admin">'. $lang['RANK_ADMIN'] .'</option>
<option value="user" selected="selected">'. $lang['USER'] .'</option>
<option value="admin">' . $lang['RANK_ADMIN'] . '</option>
<option value="user" selected="selected">' . $lang['USER'] . '</option>
</select>
';
$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&amp;g=$group_id";
if (!$forums = $datastore->get('cat_forums')) {
$datastore->update('cat_forums');
$forums = $datastore->get('cat_forums');
}
$base_url = basename(__FILE__) . "?mode=group&amp;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&amp;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&amp;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<br />", $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<br />", $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 = '
<input type="hidden" name="mode" value="'. $mode .'" />
<input type="hidden" name="g" value="'. $group_id .'" />
$s_hidden_fields = '
<input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="g" value="' . $group_id . '" />
';
$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 = '<input type="hidden" name="mode" value="'. $mode .'" />';
$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" />';
$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&amp;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&amp;c=all" : '',
));
print_page('admin_ug_auth.tpl', 'admin');
print_page('admin_ug_auth.tpl', 'admin');

View file

@ -1,362 +1,295 @@
<?php
if (!empty($setmodules))
{
$module['USERS']['BAN_MANAGEMENT'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['USERS']['BAN_MANAGEMENT'] = basename(__FILE__);
return;
}
require('./pagestart.php');
if (isset($_POST['submit']))
{
$user_bansql = '';
$email_bansql = '';
$ip_bansql = '';
if (isset($_POST['submit'])) {
$user_bansql = '';
$email_bansql = '';
$ip_bansql = '';
$user_list = array();
if (!empty($_POST['username']))
{
$this_userdata = get_userdata($_POST['username'], true);
if (!$this_userdata)
{
bb_die($lang['NO_USER_ID_SPECIFIED']);
}
$user_list = array();
if (!empty($_POST['username'])) {
$this_userdata = get_userdata($_POST['username'], true);
if (!$this_userdata) {
bb_die($lang['NO_USER_ID_SPECIFIED']);
}
$user_list[] = $this_userdata['user_id'];
}
$user_list[] = $this_userdata['user_id'];
}
$ip_list = array();
if (isset($_POST['ban_ip']))
{
$ip_list_temp = explode(',', $_POST['ban_ip']);
$ip_list = array();
if (isset($_POST['ban_ip'])) {
$ip_list_temp = explode(',', $_POST['ban_ip']);
for ($i = 0; $i < count($ip_list_temp); $i++)
{
if (preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/', trim($ip_list_temp[$i]), $ip_range_explode))
{
$ip_1_counter = $ip_range_explode[1];
$ip_1_end = $ip_range_explode[5];
for ($i = 0; $i < count($ip_list_temp); $i++) {
if (preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/', trim($ip_list_temp[$i]), $ip_range_explode)) {
$ip_1_counter = $ip_range_explode[1];
$ip_1_end = $ip_range_explode[5];
while ( $ip_1_counter <= $ip_1_end )
{
$ip_2_counter = ( $ip_1_counter == $ip_range_explode[1] ) ? $ip_range_explode[2] : 0;
$ip_2_end = ( $ip_1_counter < $ip_1_end ) ? 254 : $ip_range_explode[6];
while ($ip_1_counter <= $ip_1_end) {
$ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
$ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
if ( $ip_2_counter == 0 && $ip_2_end == 254 )
{
$ip_2_counter = 255;
$ip_2_fragment = 255;
if ($ip_2_counter == 0 && $ip_2_end == 254) {
$ip_2_counter = 255;
$ip_2_fragment = 255;
$ip_list[] = encode_ip("$ip_1_counter.255.255.255");
}
$ip_list[] = encode_ip("$ip_1_counter.255.255.255");
}
while ( $ip_2_counter <= $ip_2_end )
{
$ip_3_counter = ( $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1] ) ? $ip_range_explode[3] : 0;
$ip_3_end = ( $ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end ) ? 254 : $ip_range_explode[7];
while ($ip_2_counter <= $ip_2_end) {
$ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
$ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
if ( $ip_3_counter == 0 && $ip_3_end == 254 )
{
$ip_3_counter = 255;
$ip_3_fragment = 255;
if ($ip_3_counter == 0 && $ip_3_end == 254) {
$ip_3_counter = 255;
$ip_3_fragment = 255;
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.255.255");
}
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.255.255");
}
while ( $ip_3_counter <= $ip_3_end )
{
$ip_4_counter = ( $ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1] ) ? $ip_range_explode[4] : 0;
$ip_4_end = ( $ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end ) ? 254 : $ip_range_explode[8];
while ($ip_3_counter <= $ip_3_end) {
$ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
$ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
if ( $ip_4_counter == 0 && $ip_4_end == 254 )
{
$ip_4_counter = 255;
$ip_4_fragment = 255;
if ($ip_4_counter == 0 && $ip_4_end == 254) {
$ip_4_counter = 255;
$ip_4_fragment = 255;
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.255");
}
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.255");
}
while ( $ip_4_counter <= $ip_4_end )
{
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter");
$ip_4_counter++;
}
$ip_3_counter++;
}
$ip_2_counter++;
}
$ip_1_counter++;
}
}
else if (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i])))
{
$ip = gethostbynamel(trim($ip_list_temp[$i]));
while ($ip_4_counter <= $ip_4_end) {
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter");
$ip_4_counter++;
}
$ip_3_counter++;
}
$ip_2_counter++;
}
$ip_1_counter++;
}
} else if (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i]))) {
$ip = gethostbynamel(trim($ip_list_temp[$i]));
for ($j = 0; $j < count($ip); $j++)
{
if (!empty($ip[$j]))
{
$ip_list[] = encode_ip($ip[$j]);
}
}
}
else if (preg_match('/^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$/', trim($ip_list_temp[$i])))
{
$ip_list[] = encode_ip(str_replace('*', '255', trim($ip_list_temp[$i])));
}
}
}
for ($j = 0; $j < count($ip); $j++) {
if (!empty($ip[$j])) {
$ip_list[] = encode_ip($ip[$j]);
}
}
} else if (preg_match('/^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$/', trim($ip_list_temp[$i]))) {
$ip_list[] = encode_ip(str_replace('*', '255', trim($ip_list_temp[$i])));
}
}
}
$email_list = array();
if (isset($_POST['ban_email']))
{
$email_list_temp = explode(',', $_POST['ban_email']);
$email_list = array();
if (isset($_POST['ban_email'])) {
$email_list_temp = explode(',', $_POST['ban_email']);
for ($i = 0; $i < count($email_list_temp); $i++)
{
if (preg_match('/^(([a-z0-9&\'\.\-_\+])|(\*))+@(([a-z0-9\-])|(\*))+\.([a-z0-9\-]+\.)*?[a-z]+$/is', trim($email_list_temp[$i])))
{
$email_list[] = trim($email_list_temp[$i]);
}
}
}
for ($i = 0; $i < count($email_list_temp); $i++) {
if (preg_match('/^(([a-z0-9&\'\.\-_\+])|(\*))+@(([a-z0-9\-])|(\*))+\.([a-z0-9\-]+\.)*?[a-z]+$/is', trim($email_list_temp[$i]))) {
$email_list[] = trim($email_list_temp[$i]);
}
}
}
$sql = "SELECT * FROM " . BB_BANLIST;
if (!($result = DB()->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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_BANADMIN'], '<a href="admin_user_ban.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
else
{
$template->assign_vars(array(
'S_BANLIST_ACTION' => 'admin_user_ban.php',
));
bb_die($lang['BAN_UPDATE_SUCESSFUL'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_BANADMIN'], '<a href="admin_user_ban.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
} 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 .= '<option value="' . $user_list[$i]['ban_id'] . '">' . $user_list[$i]['username'] . '</option>';
$userban_count++;
}
$select_userlist = '';
for ($i = 0; $i < count($user_list); $i++) {
$select_userlist .= '<option value="' . $user_list[$i]['ban_id'] . '">' . $user_list[$i]['username'] . '</option>';
$userban_count++;
}
if ($select_userlist == '')
{
$select_userlist = '<option value="-1">' . $lang['NO_BANNED_USERS'] . '</option>';
}
if ($select_userlist == '') {
$select_userlist = '<option value="-1">' . $lang['NO_BANNED_USERS'] . '</option>';
}
$select_userlist = '<select name="unban_user[]" multiple="multiple" size="5">' . $select_userlist . '</select>';
$select_userlist = '<select name="unban_user[]" multiple="multiple" size="5">' . $select_userlist . '</select>';
$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 .= '<option value="' . $ban_id . '">' . $ban_ip . '</option>';
$ipban_count++;
}
else if (!empty($banlist[$i]['ban_email']))
{
$ban_email = $banlist[$i]['ban_email'];
$select_emaillist .= '<option value="' . $ban_id . '">' . $ban_email . '</option>';
$emailban_count++;
}
}
if (!empty($banlist[$i]['ban_ip'])) {
$ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip']));
$select_iplist .= '<option value="' . $ban_id . '">' . $ban_ip . '</option>';
$ipban_count++;
} else if (!empty($banlist[$i]['ban_email'])) {
$ban_email = $banlist[$i]['ban_email'];
$select_emaillist .= '<option value="' . $ban_id . '">' . $ban_email . '</option>';
$emailban_count++;
}
}
if ($select_iplist == '')
{
$select_iplist = '<option value="-1">' . $lang['NO_BANNED_IP'] . '</option>';
}
if ($select_iplist == '') {
$select_iplist = '<option value="-1">' . $lang['NO_BANNED_IP'] . '</option>';
}
if ($select_emaillist == '')
{
$select_emaillist = '<option value="-1">' . $lang['NO_BANNED_EMAIL'] . '</option>';
}
if ($select_emaillist == '') {
$select_emaillist = '<option value="-1">' . $lang['NO_BANNED_EMAIL'] . '</option>';
}
$select_iplist = '<select name="unban_ip[]" multiple="multiple" size="15">' . $select_iplist . '</select>';
$select_emaillist = '<select name="unban_email[]" multiple="multiple" size="10">' . $select_emaillist . '</select>';
$select_iplist = '<select name="unban_ip[]" multiple="multiple" size="15">' . $select_iplist . '</select>';
$select_emaillist = '<select name="unban_email[]" multiple="multiple" size="10">' . $select_emaillist . '</select>';
$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');
print_page('admin_user_ban.tpl', 'admin');

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,8 @@
<?php
if (!empty($setmodules))
{
$module['GENERAL']['WORD_CENSOR'] = basename(__FILE__);
return;
if (!empty($setmodules)) {
$module['GENERAL']['WORD_CENSOR'] = basename(__FILE__);
return;
}
require('./pagestart.php');
@ -13,151 +12,123 @@ $di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->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 .= '<input type="hidden" name="id" value="' . $word_id . '" />';
$word = $word_info['word'];
$replacement = $word_info['replacement'];
}
else
{
bb_die($lang['NO_WORD_SELECTED']);
}
}
$word_info = DB()->sql_fetchrow($result);
$s_hidden_fields .= '<input type="hidden" name="id" value="' . $word_id . '" />';
$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 .= '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
$cache->delete('censored');
$message .= '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}
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'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
} 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&amp;id=$word_id",
'U_WORD_DELETE' => "admin_words.php?mode=delete&amp;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&amp;id=$word_id",
'U_WORD_DELETE' => "admin_words.php?mode=delete&amp;id=$word_id",
));
}
}
print_page('admin_words.tpl', 'admin');
print_page('admin_words.tpl', 'admin');

View file

@ -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[] = '<span title="'. $name .'">'. humn_size($dbsize) .'</span>';
}
}
$dbsize = implode('&nbsp;|&nbsp;', $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[] = '<span title="' . $name . '">' . humn_size($dbsize) . '</span>';
}
}
$dbsize = implode('&nbsp;|&nbsp;', $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');
print_page('index.tpl', 'admin');

View file

@ -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");
}
if (!$userdata['session_admin']) {
$redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1);
redirect("login.php?redirect=$redirect");
}

View file

@ -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 '<html><body><head></head>';
echo '
<br /><br />
<table border="1" cellspacing="0" cellpadding="6" align="center">';
foreach ($sql as $i => $query)
{
$row = mysql_fetch_row(DB()->query($query)); // TODO: deprecated
echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>";
foreach ($sql as $i => $query) {
$row = mysql_fetch_row(DB()->query($query)); // TODO: deprecated
echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>";
}
echo '</table>';
echo '<div align="center"><pre>';
if ($l = sys('la'))
{
$l = explode(' ', $l);
for ($i=0; $i < 3; $i++)
{
$l[$i] = round($l[$i], 1);
}
echo "\n\n<b>loadavg: </b>$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\n<b>loadavg: </b>$l[0] $l[1] $l[2]\n\n";
}
echo 'gen time: <b>'. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ."</b> sec\n";
echo 'gen time: <b>' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . "</b> sec\n";
echo '</pre></div>';
echo '</body></html>';
echo '</body></html>';

View file

@ -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 '<html><body><head></head>';
@ -95,7 +95,7 @@ echo "\n
<td align=center>
$stat[tor_all] / <b>$stat[tor_active]</b> / $stat[tor_with_seeder]
&nbsp;
[ ". humn_size($stat['torrents_size']) ." ]
[ " . humn_size($stat['torrents_size']) . " ]
</td></tr>
\n";
@ -104,36 +104,34 @@ echo "\n
<td align=center>
$stat[p_all] / <b>$stat[p_within_ann]</b>
&nbsp;
[ 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 ]
</td></tr>
\n";
echo "\n<tr><td align=center> peers: in last ". join(' / ', $peers_in_last_minutes) ." min</td>\n";
echo "\n<td align=center>". join(' / ', $peers_in_last_min) ."</td></tr>\n";
echo "\n<tr><td align=center> peers: in last " . join(' / ', $peers_in_last_minutes) . " min</td>\n";
echo "\n<td align=center>" . join(' / ', $peers_in_last_min) . "</td></tr>\n";
echo "\n<tr><td align=center> peers in last $peers_in_last_sec_limit sec <br /> [ per second, DESC order --> ] <br /> last peer: $stat[last_peer_time] seconds ago <br /> ". date("j M H:i:s [T O]") ." </td>\n";
echo '<td align=center style="font-size: 13px; font-family: \'Courier New\',Courier,monospace;"><pre> '. join(' ', $peers_in_last_sec) ."</pre></td></tr>\n";
echo "\n<tr><td align=center> peers in last $peers_in_last_sec_limit sec <br /> [ per second, DESC order --> ] <br /> last peer: $stat[last_peer_time] seconds ago <br /> " . date("j M H:i:s [T O]") . " </td>\n";
echo '<td align=center style="font-size: 13px; font-family: \'Courier New\',Courier,monospace;"><pre> ' . join(' ', $peers_in_last_sec) . "</pre></td></tr>\n";
echo '</table>';
echo '<div align="center"><pre>';
if ($l = sys('la'))
{
$l = explode(' ', $l);
for ($i=0; $i < 3; $i++)
{
$l[$i] = round($l[$i], 1);
}
echo "\n\n<b>loadavg: </b>$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\n<b>loadavg: </b>$l[0] $l[1] $l[2]\n\n";
}
echo 'gen time: <b>'. sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) ."</b> sec\n";
echo 'gen time: <b>' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . "</b> sec\n";
echo '</pre></div>';
echo '</body></html>';
DB()->query("DROP TEMPORARY TABLE ". TMP_TRACKER_TABLE);
DB()->query("DROP TEMPORARY TABLE " . TMP_TRACKER_TABLE);
bb_exit();
bb_exit();

659
ajax.php
View file

@ -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');
}
}
function sitemap()
{
require(AJAX_DIR . 'sitemap.php');
}
}

View file

@ -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;
exit;

View file

@ -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');
}
}
$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');
}
}

View file

@ -1,3 +1,3 @@
<?php
require('./announce.php');
require('./announce.php');

View file

@ -2,34 +2,32 @@
define('IN_TRACKER', true);
define('BB_ROOT', './../');
require(BB_ROOT .'common.php');
require(BB_ROOT . 'common.php');
if (!$tr_cfg['scrape']) msg_die('Please disable SCRAPE!');
// 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'];
}
if (!isset($_GET['info_hash']) || strlen($_GET['info_hash']) != 20)
{
msg_die('Invalid info_hash');
if (!isset($_GET['info_hash']) || strlen($_GET['info_hash']) != 20) {
msg_die('Invalid info_hash');
}
$info_hash = $_GET['info_hash'];
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([
'min interval' => (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;
exit;

View file

@ -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;
}

View file

@ -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));
}
}
}

View file

@ -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
],
]
];

View file

@ -1,6 +1,6 @@
<?php
define('START_CRON', true);
define('BB_ROOT', dirname ( __FILE__ ) . '/');
define('BB_ROOT', dirname(__FILE__) . '/');
require(BB_ROOT. 'common.php');
require(BB_ROOT . 'common.php');

View file

@ -7,52 +7,39 @@ require_once __DIR__ . '/common.php';
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
$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');
$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('&amp;', '&', 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");
redirect("index.php");

943
group.php

File diff suppressed because it is too large Load diff

View file

@ -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 = '<input type="hidden" name="'. POST_GROUPS_URL .'" value="'. $group_id .'" />';
$s_hidden_fields = '<input type="hidden" name="' . POST_GROUPS_URL . '" value="' . $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",
$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);
}

505
index.php
View file

@ -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][] = '<a href="'. PROFILE_URL . $user_id .'">'. $mod['name_users'][$user_id] .'</a>';
}
}
foreach ($mod['mod_groups'] as $forum_id => $group_ids)
{
foreach ($group_ids as $group_id)
{
$moderators[$forum_id][] = '<a href="'. GROUP_URL . $group_id .'">'. $mod['name_groups'][$group_id] .'</a>';
}
}
if (!empty($mod)) {
foreach ($mod['mod_users'] as $forum_id => $user_ids) {
foreach ($user_ids as $user_id) {
$moderators[$forum_id][] = '<a href="' . PROFILE_URL . $user_id . '">' . $mod['name_users'][$user_id] . '</a>';
}
}
foreach ($mod['mod_groups'] as $forum_id => $group_ids) {
foreach ($group_ids as $group_id) {
$moderators[$forum_id][] = '<a href="' . GROUP_URL . $group_id . '">' . $mod['name_groups'][$group_id] . '</a>';
}
}
}
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']}&amp;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']}&amp;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) .' <span class="small">('. birthday_age($week['user_birthday']-1) .')</span>';
}
$week_all = ($week_all) ? '&nbsp;<a class="txtb" href="#" onclick="ajax.exec({action: \'index_data\', mode: \'birthday_week\'}); return false;" title="'. $lang['ALL'] .'">...</a>' : '';
$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) . ' <span class="small">(' . birthday_age($week['user_birthday'] - 1) . ')</span>';
}
$week_all = ($week_all) ? '&nbsp;<a class="txtb" href="#" onclick="ajax.exec({action: \'index_data\', mode: \'birthday_week\'}); return false;" title="' . $lang['ALL'] . '">...</a>' : '';
$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) .' <span class="small">('. birthday_age($today['user_birthday']) .')</span>';
}
$today_all = ($today_all) ? '&nbsp;<a class="txtb" href="#" onclick="ajax.exec({action: \'index_data\', mode: \'birthday_today\'}); return false;" title="'. $lang['ALL'] .'">...</a>' : '';
$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) . ' <span class="small">(' . birthday_age($today['user_birthday']) . ')</span>';
}
$today_all = ($today_all) ? '&nbsp;<a class="txtb" href="#" onclick="ajax.exec({action: \'index_data\', mode: \'birthday_today\'}); return false;" title="' . $lang['ALL'] . '">...</a>' : '';
$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');
print_page('index.tpl');

View file

@ -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
?><!DOCTYPE html>
<html dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<link rel="stylesheet" href="styles/templates/default/css/main.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Content-Style-Type" content="text/css"/>
<link rel="stylesheet" href="styles/templates/default/css/main.css" type="text/css">
</head>
<body>
<style type="text/css">
#infobox-wrap { width: 760px; }
#infobox-body {
background: #FFFFFF; color: #000000; padding: 1em;
height: 400px; overflow: auto; border: 1px inset #000000;
}
#infobox-body p { margin-top: 1em; margin-bottom: 1em; }
#infobox-wrap {
width: 760px;
}
#infobox-body {
background: #FFFFFF;
color: #000000;
padding: 1em;
height: 400px;
overflow: auto;
border: 1px inset #000000;
}
#infobox-body p {
margin-top: 1em;
margin-bottom: 1em;
}
</style>
<br />
<br/>
<div id="infobox-wrap" class="bCenter row1">
<fieldset class="pad_6">
<legend class="med bold mrg_2 warnColor1"><?php echo mb_strtoupper($info['title'], 'UTF-8'); ?></legend>
<div class="bCenter">
<?php require($require); ?>
</div>
</fieldset>
<p class="gen tRight pad_6"><a href="javascript:window.close();" class="gen">[ <?php echo $lang['LOCK']; ?> ]</a></p>
<fieldset class="pad_6">
<legend class="med bold mrg_2 warnColor1"><?php echo mb_strtoupper($info['title'], 'UTF-8'); ?></legend>
<div class="bCenter">
<?php require($require); ?>
</div>
</fieldset>
<p class="gen tRight pad_6"><a href="javascript:window.close();" class="gen">[ <?php echo $lang['LOCK']; ?> ]</a>
</p>
</div><!--/infobox-wrap-->
</body>
</html>
</html>

View file

@ -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 = '<img src="'. $di->config->get('avatars.upload_path') . $di->config->get('avatars.no_avatar') .'" alt="'. $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 = '<img src="' . $di->config->get('avatars.upload_path') . $di->config->get('avatars.no_avatar') . '" alt="' . $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;
$this->response['avatar_html'] = $response;

View file

@ -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) .' <b> '. $lang['TOR_STATUS_NAME'][$new_status]. '</b> &middot; '. profile_url($userdata) .' &middot; <i>'. delta_time(TIMENOW) . $lang['TOR_BACK']. '</i>';
$this->response['status'] = $di->config->get('tor_icons.' . $new_status) . ' <b> ' . $lang['TOR_STATUS_NAME'][$new_status] . '</b> &middot; ' . profile_url($userdata) . ' &middot; <i>' . delta_time(TIMENOW) . $lang['TOR_BACK'] . '</i>';
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;
$this->response['topic_id'] = $topic_id;

View file

@ -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;
$this->response['url'] = $url;
$this->response['title'] = $title;

View file

@ -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'];
$this->response['resp_html'] = $lang['SAVED'];

View file

@ -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) ? '<span class="'. $ranks[$rank_id]['rank_style'] .'">'. $ranks[$rank_id]['rank_title'] .'</span>' : '';
$user_rank = ($rank_id) ? '<span class="' . $ranks[$rank_id]['rank_style'] . '">' . $ranks[$rank_id]['rank_title'] . '</span>' : '';
$this->response['html'] = ($rank_id) ? $lang['AWARDED_RANK'] . "<b> $user_rank </b>" : $lang['SHOT_RANK'];
$this->response['rank_name'] = ($rank_id) ? $user_rank : $lang['USER'];

View file

@ -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");
DB()->query("UPDATE " . BB_GROUPS . " SET $mode = $value_sql WHERE group_id = $group_id LIMIT 1");

View file

@ -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'];
$this->response['edit_id'] = $this->request['edit_id'];

View file

@ -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']);
$this->response['passkey'] = $passkey;
} else $this->ajax_die($lang['NOT_AUTHORISED']);

View file

@ -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 .= "&amp;u=$user_id";
$link = '<a href="'. $href .'" class="'. $class .'" target="_blank">'. htmlCHR($row['group_name']) .'</a>';
$html[] = $link;
}
else
{
// скрытая группа и сам юзер не является ее членом
if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view'])
{
continue;
}
if ($row['group_moderator'] == $user->id)
{
$class .= ' selfMod';
$href .= "&amp;u=$user_id"; // сам юзер модератор этой группы
}
$link = '<a href="'. $href .'" class="'. $class .'" target="_blank">'. htmlCHR($row['group_name']) .'</a>';
$html[] = $link;
}
}
if ($html)
{
$this->response['group_list_html'] = '<ul><li>'. join('</li><li>', $html) .'</li></ul>';
}
else
{
$this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN'];
}
break;
if (IS_ADMIN) {
$href .= "&amp;u=$user_id";
$link = '<a href="' . $href . '" class="' . $class . '" target="_blank">' . htmlCHR($row['group_name']) . '</a>';
$html[] = $link;
} else {
// скрытая группа и сам юзер не является ее членом
if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) {
continue;
}
if ($row['group_moderator'] == $user->id) {
$class .= ' selfMod';
$href .= "&amp;u=$user_id"; // сам юзер модератор этой группы
}
$link = '<a href="' . $href . '" class="' . $class . '" target="_blank">' . htmlCHR($row['group_name']) . '</a>';
$html[] = $link;
}
}
if ($html) {
$this->response['group_list_html'] = '<ul><li>' . join('</li><li>', $html) . '</li></ul>';
} else {
$this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN'];
}
break;
default:
$this->ajax_die("invalid mode: $mode");
}
default:
$this->ajax_die("invalid mode: $mode");
}

View file

@ -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) .' <span class="small">('. birthday_age($week['user_birthday']) .')</span>';
}
$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) . ' <span class="small">(' . birthday_age($week['user_birthday']) . ')</span>';
}
$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) .' <span class="small">('. birthday_age($today['user_birthday']) .')</span>';
}
$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) . ' <span class="small">(' . birthday_age($today['user_birthday']) . ')</span>';
}
$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[] = '<a href="'. PROFILE_URL . $user_id .'">'. $mod['name_users'][$user_id] .'</a>';
}
}
if (isset($mod['mod_users'][$forum_id])) {
foreach ($mod['mod_users'][$forum_id] as $user_id) {
$moderators[] = '<a href="' . PROFILE_URL . $user_id . '">' . $mod['name_users'][$user_id] . '</a>';
}
}
if (isset($mod['mod_groups'][$forum_id]))
{
foreach ($mod['mod_groups'][$forum_id] as $group_id)
{
$moderators[] = '<a href="'. "group.php?". POST_GROUPS_URL ."=". $group_id .'">'. $mod['name_groups'][$group_id] .'</a>';
}
}
if (isset($mod['mod_groups'][$forum_id])) {
foreach ($mod['mod_groups'][$forum_id] as $group_id) {
$moderators[] = '<a href="' . "group.php?" . POST_GROUPS_URL . "=" . $group_id . '">' . $mod['name_groups'][$group_id] . '</a>';
}
}
$html = ':&nbsp;';
$html .= ($moderators) ? join(', ', $moderators) : $lang['NONE'];
unset($moderators, $mod);
$datastore->rm('moderators');
break;
$html = ':&nbsp;';
$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) ? '<b class="gen">'. get_bt_ratio($btu) .'</b>' : $lang['IT_WILL_BE_DOWN'] .' <b>'. humn_size(MIN_DL_FOR_RATIO) .'</b>';
$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) ? '<b class="gen">' . get_bt_ratio($btu) . '</b>' : $lang['IT_WILL_BE_DOWN'] . ' <b>' . humn_size(MIN_DL_FOR_RATIO) . '</b>';
$html = '
$html = '
<tr class="row3">
<th style="padding: 0;"></th>
<th>'. $lang['DOWNLOADED'] .'</th>
<th>'. $lang['UPLOADED'] .'</th>
<th>'. $lang['RELEASED'] .'</th>
<th>'. $lang['BONUS'] .'</th>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<th>'. $lang['SEED_BONUS'] .'</th>' : '';
$html .= '</tr>
<th>' . $lang['DOWNLOADED'] . '</th>
<th>' . $lang['UPLOADED'] . '</th>
<th>' . $lang['RELEASED'] . '</th>
<th>' . $lang['BONUS'] . '</th>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<th>' . $lang['SEED_BONUS'] . '</th>' : '';
$html .= '</tr>
<tr class="row1">
<td>'. $lang['TOTAL_TRAF'] .'</td>
<td id="u_down_total"><span class="editable bold leechmed">'. humn_size($btu['u_down_total']) .'</span></td>
<td id="u_up_total"><span class="editable bold seedmed">' .humn_size($btu['u_up_total']) .'</span></td>
<td id="u_up_release"><span class="editable bold seedmed">'. humn_size($btu['u_up_release']) .'</span></td>
<td id="u_up_bonus"><span class="editable bold seedmed">'. humn_size($btu['u_up_bonus']) .'</span></td>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<td id="user_points"><span class="editable bold points">'. $profiledata['user_points'] .'</b></td>' : '';
$html .= '</tr>
<td>' . $lang['TOTAL_TRAF'] . '</td>
<td id="u_down_total"><span class="editable bold leechmed">' . humn_size($btu['u_down_total']) . '</span></td>
<td id="u_up_total"><span class="editable bold seedmed">' . humn_size($btu['u_up_total']) . '</span></td>
<td id="u_up_release"><span class="editable bold seedmed">' . humn_size($btu['u_up_release']) . '</span></td>
<td id="u_up_bonus"><span class="editable bold seedmed">' . humn_size($btu['u_up_bonus']) . '</span></td>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<td id="user_points"><span class="editable bold points">' . $profiledata['user_points'] . '</b></td>' : '';
$html .= '</tr>
<tr class="row5">
<td colspan="1">'. $lang['SPEED'] .'</td>
<td colspan="2">'. $lang['DL_DL_SPEED'] .': '. $speed_down .'</span></td>
<td colspan="2">'. $lang['DL_UL_SPEED'] .': '. $speed_up .'</span></td>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<td colspan="1"></td>' : '';
$html .= '</tr>';
<td colspan="1">' . $lang['SPEED'] . '</td>
<td colspan="2">' . $lang['DL_DL_SPEED'] . ': ' . $speed_down . '</span></td>
<td colspan="2">' . $lang['DL_UL_SPEED'] . ': ' . $speed_up . '</span></td>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<td colspan="1"></td>' : '';
$html .= '</tr>';
$this->response['user_ratio'] = '
<th><a href="'. $di->config->get('ratio_url_help') .'" class="bold">'. $lang['USER_RATIO'] .'</a>:</th>
<td>'. $user_ratio .'</td>
$this->response['user_ratio'] = '
<th><a href="' . $di->config->get('ratio_url_help') . '" class="bold">' . $lang['USER_RATIO'] . '</a>:</th>
<td>' . $user_ratio . '</td>
';
break;
break;
}
$this->response['html'] = $html;
$this->response['mode'] = $mode;
$this->response['mode'] = $mode;

View file

@ -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'] = '<span class="seed bold">'. $lang['ALL_CACHE_CLEARED'] .'</span>';
$this->response['cache_html'] = '<span class="seed bold">' . $lang['ALL_CACHE_CLEARED'] . '</span>';
break;
break;
case 'clear_datastore':
case 'clear_datastore':
global $datastore;
global $datastore;
$datastore->clean();
$datastore->clean();
$this->response['datastore_html'] = '<span class="seed bold">'. $lang['DATASTORE_CLEARED'] .'</span>';
$this->response['datastore_html'] = '<span class="seed bold">' . $lang['DATASTORE_CLEARED'] . '</span>';
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'] = '<span class="seed bold">'. $lang['ALL_TEMPLATE_CLEARED'] .'</span>';
$this->response['template_cache_html'] = '<span class="seed bold">' . $lang['ALL_TEMPLATE_CLEARED'] . '</span>';
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'] = '<span class="seed bold">'. $lang['INDEXER'] .'</span>';
$this->response['indexer_html'] = '<span class="seed bold">' . $lang['INDEXER'] . '</span>';
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'] = '<span class="seed bold">'. $lang['USER_LEVELS_UPDATED'] .'</span>';
$this->response['update_user_level_html'] = '<span class="seed bold">' . $lang['USER_LEVELS_UPDATED'] . '</span>';
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'] = '<span class="seed bold">'. $lang['TOPICS_DATA_SYNCHRONIZED'] .'</span>';
$this->response['sync_topics_html'] = '<span class="seed bold">' . $lang['TOPICS_DATA_SYNCHRONIZED'] . '</span>';
break;
break;
case 'sync_user_posts':
case 'sync_user_posts':
sync('user_posts', 'all');
sync('user_posts', 'all');
$this->response['sync_user_posts_html'] = '<span class="seed bold">'. $lang['USER_POSTS_COUNT_SYNCHRONIZED'] .'</span>';
$this->response['sync_user_posts_html'] = '<span class="seed bold">' . $lang['USER_POSTS_COUNT_SYNCHRONIZED'] . '</span>';
break;
break;
case 'unlock_cron':
case 'unlock_cron':
cron_enable_board();
cron_enable_board();
$this->response['unlock_cron_html'] = '<span class="seed bold">'. $lang['ADMIN_UNLOCKED'] .'</span>';
$this->response['unlock_cron_html'] = '<span class="seed bold">' . $lang['ADMIN_UNLOCKED'] . '</span>';
break;
break;
}
$this->response['mode'] = $mode;
$this->response['mode'] = $mode;

View file

@ -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);
$this->response['url'] = html_entity_decode(make_url('/') . PROFILE_URL . $user_id);

View file

@ -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 = '<a href="'. $di->config->get('whois_info') . $user_reg_ip .'" class="gen" target="_blank">'. $user_reg_ip .'</a>';
$last_ip = '<a href="'. $di->config->get('whois_info') . $user_last_ip .'" class="gen" target="_blank">'. $user_last_ip .'</a>';
}
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 = '<a href="' . $di->config->get('whois_info') . $user_reg_ip . '" class="gen" target="_blank">' . $user_reg_ip . '</a>';
$last_ip = '<a href="' . $di->config->get('whois_info') . $user_last_ip . '" class="gen" target="_blank">' . $user_last_ip . '</a>';
}
$this->response['ip_list_html'] = '
$this->response['ip_list_html'] = '
<br /><table class="mod_ip bCenter borderless" cellspacing="1">
<tr class="row5" >
<td>'. $lang['REG_IP'] .'</td>
<td class="tCenter">'. $reg_ip .'</td>
<td><div>'. $link_reg_ip .'</div></td>
<td>' . $lang['REG_IP'] . '</td>
<td class="tCenter">' . $reg_ip . '</td>
<td><div>' . $link_reg_ip . '</div></td>
</tr>
<tr class="row4">
<td>'. $lang['LAST_IP'] .'</td>
<td class="tCenter">'. $last_ip .'</td>
<td><div>'. $link_last_ip .'</div></td>
<td>' . $lang['LAST_IP'] . '</td>
<td class="tCenter">' . $last_ip . '</td>
<td><div>' . $link_last_ip . '</div></td>
</tr>
</table><br />
';
break;
}
break;
}

View file

@ -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;
$this->response['mc_text'] = bbcode2html($mc_text);
$this->response['mc_class'] = $mc_class;

View file

@ -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), '<img class="smile" src="'. $di->config->get('smilies_path'));
if ($count_smilies > $di->config->get('max_smilies'))
{
$this->ajax_die(sprintf($lang['MAX_SMILIES_PER_POST'], $di->config->get('max_smilies')));
}
}
DB()->query("UPDATE ". BB_POSTS_TEXT ." SET post_text = '". DB()->escape($text) ."' WHERE post_id = $post_id LIMIT 1");
if ($post['topic_last_post_id'] != $post['post_id'] && $userdata['user_id'] == $post['poster_id'])
{
DB()->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), '<img class="smile" src="' . $di->config->get('smilies_path'));
if ($count_smilies > $di->config->get('max_smilies')) {
$this->ajax_die(sprintf($lang['MAX_SMILIES_PER_POST'], $di->config->get('max_smilies')));
}
}
DB()->query("UPDATE " . BB_POSTS_TEXT . " SET post_text = '" . DB()->escape($text) . "' WHERE post_id = $post_id LIMIT 1");
if ($post['topic_last_post_id'] != $post['post_id'] && $userdata['user_id'] == $post['poster_id']) {
DB()->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 = '<input type="hidden" name="mode" value="editpost" />';
$hidden_form .= '<input type="hidden" name="'. POST_POST_URL .'" value="'. $post_id .'" />';
$hidden_form .= '<input type="hidden" name="subject" value="'. $post['topic_title'] .'" />';
$hidden_form = '<input type="hidden" name="mode" value="editpost" />';
$hidden_form .= '<input type="hidden" name="' . POST_POST_URL . '" value="' . $post_id . '" />';
$hidden_form .= '<input type="hidden" name="subject" value="' . $post['topic_title'] . '" />';
$this->response['text'] = '
<form action="'. POSTING_URL .'" method="post" name="post">
'. $hidden_form .'
$this->response['text'] = '
<form action="' . POSTING_URL . '" method="post" name="post">
' . $hidden_form . '
<div class="buttons mrg_4">
<input type="button" value="B" name="codeB" title="'. $lang['BOLD'] .'" style="font-weight: bold; width: 25px;" />
<input type="button" value="i" name="codeI" title="'. $lang['ITALIC'] .'" style="width: 25px; font-style: italic;" />
<input type="button" value="u" name="codeU" title="'. $lang['UNDERLINE'] .'" style="width: 25px; text-decoration: underline;" />
<input type="button" value="s" name="codeS" title="'. $lang['STRIKEOUT'] .'" style="width: 25px; text-decoration: line-through;" />&nbsp;&nbsp;
<input type="button" value="'. $lang['QUOTE'] .'" name="codeQuote" title="'. $lang['QUOTE_TITLE'] .'" style="width: 57px;" />
<input type="button" value="Img" name="codeImg" title="'. $lang['IMG_TITLE'] .'" style="width: 40px;" />
<input type="button" value="'. $lang['URL'] .'" name="codeUrl" title="'. $lang['URL_TITLE'] .'" style="width: 63px; text-decoration: underline;" />&nbsp;
<input type="button" value="'. $lang['CODE'] .'" name="codeCode" title="'. $lang['CODE_TITLE'] .'" style="width: 43px;" />
<input type="button" value="'. $lang['LIST'] .'" name="codeList" title="'. $lang['LIST_TITLE'] .'" style="width: 60px;" />
<input type="button" value="1." name="codeOpt" title="'. $lang['LIST_ITEM'] .'" style="width: 30px;" />&nbsp;
<input type="button" value="'. $lang['QUOTE_SEL'] .'" name="quoteselected" title="'. $lang['QUOTE_SELECTED'] .'" onclick="bbcode.onclickQuoteSel();" />&nbsp;
<input type="button" value="B" name="codeB" title="' . $lang['BOLD'] . '" style="font-weight: bold; width: 25px;" />
<input type="button" value="i" name="codeI" title="' . $lang['ITALIC'] . '" style="width: 25px; font-style: italic;" />
<input type="button" value="u" name="codeU" title="' . $lang['UNDERLINE'] . '" style="width: 25px; text-decoration: underline;" />
<input type="button" value="s" name="codeS" title="' . $lang['STRIKEOUT'] . '" style="width: 25px; text-decoration: line-through;" />&nbsp;&nbsp;
<input type="button" value="' . $lang['QUOTE'] . '" name="codeQuote" title="' . $lang['QUOTE_TITLE'] . '" style="width: 57px;" />
<input type="button" value="Img" name="codeImg" title="' . $lang['IMG_TITLE'] . '" style="width: 40px;" />
<input type="button" value="' . $lang['URL'] . '" name="codeUrl" title="' . $lang['URL_TITLE'] . '" style="width: 63px; text-decoration: underline;" />&nbsp;
<input type="button" value="' . $lang['CODE'] . '" name="codeCode" title="' . $lang['CODE_TITLE'] . '" style="width: 43px;" />
<input type="button" value="' . $lang['LIST'] . '" name="codeList" title="' . $lang['LIST_TITLE'] . '" style="width: 60px;" />
<input type="button" value="1." name="codeOpt" title="' . $lang['LIST_ITEM'] . '" style="width: 30px;" />&nbsp;
<input type="button" value="' . $lang['QUOTE_SEL'] . '" name="quoteselected" title="' . $lang['QUOTE_SELECTED'] . '" onclick="bbcode.onclickQuoteSel();" />&nbsp;
</div>
<textarea id="message-'. $post_id .'" class="editor mrg_4" name="message" rows="18" cols="92">'. $post['post_text'] .'</textarea>
<textarea id="message-' . $post_id . '" class="editor mrg_4" name="message" rows="18" cols="92">' . $post['post_text'] . '</textarea>
<div class="mrg_4 tCenter">
<input title="Alt+Enter" name="preview" type="submit" value="'. $lang['PREVIEW'] .'">
<input type="button" onclick="edit_post('. $post_id .');" value="'. $lang['CANCEL'] .'">
<input type="button" onclick="edit_post('. $post_id .', \'editor\', $(\'#message-'. $post_id .'\').val()); return false;" class="bold" value="'. $lang['SUBMIT'] .'">
<input title="Alt+Enter" name="preview" type="submit" value="' . $lang['PREVIEW'] . '">
<input type="button" onclick="edit_post(' . $post_id . ');" value="' . $lang['CANCEL'] . '">
<input type="button" onclick="edit_post(' . $post_id . ', \'editor\', $(\'#message-' . $post_id . '\').val()); return false;" class="bold" value="' . $lang['SUBMIT'] . '">
</div><hr>
<script type="text/javascript">
var bbcode = new BBCode("message-'. $post_id .'");
var bbcode = new BBCode("message-' . $post_id . '");
var ctrl = "ctrl";
bbcode.addTag("codeB", "b", null, "B", ctrl);
@ -226,106 +193,92 @@ switch($this->request['type'])
bbcode.addTag("codeOpt", "*", "", "0", ctrl);
</script>
</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), '<img class="smile" src="'. $di->config->get('smilies_path'));
if ($count_smilies > $di->config->get('max_smilies'))
{
$this->ajax_die(sprintf($lang['MAX_SMILIES_PER_POST'], $di->config->get('max_smilies')));
}
}
if ($di->config->get('max_smilies')) {
$count_smilies = substr_count(bbcode2html($message), '<img class="smile" src="' . $di->config->get('smilies_path'));
if ($count_smilies > $di->config->get('max_smilies')) {
$this->ajax_die(sprintf($lang['MAX_SMILIES_PER_POST'], $di->config->get('max_smilies')));
}
}
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) ."')");
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;
}
default:
$this->ajax_die('empty type');
break;
}

View file

@ -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'].': <b>'.bb_date(TIMENOW, $di->config->get('post_date_format')).'</b> '.$lang['SITEMAP_AVAILABLE'].': <a href="'.make_url('sitemap.xml').'" target="_blank">'.make_url('sitemap.xml').'</a>';
} else {
$html .= $lang['SITEMAP_NOT_CREATED'];
}
break;
switch ($mode) {
case 'create':
$map->create();
if (file_exists(SITEMAP_DIR . 'sitemap.xml')) {
$html .= $lang['SITEMAP_CREATED'] . ': <b>' . bb_date(TIMENOW, $di->config->get('post_date_format')) . '</b> ' . $lang['SITEMAP_AVAILABLE'] . ': <a href="' . make_url('sitemap.xml') . '" target="_blank">' . make_url('sitemap.xml') . '</a>';
} 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 .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: <font style="color: green;">'.$lang['SITEMAP_SENT'].'</font>';
} else {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Google: <font style="color: red;">'.$lang['SITEMAP_ERROR'].'</font> URL: <a href="http://google.com/webmasters/sitemaps/ping?sitemap='.urlencode($map_link).'" target="_blank">http://google.com/webmasters/sitemaps/ping?sitemap='.$map_link.'</a>';
}
if (strpos($map->send_url("http://google.com/webmasters/sitemaps/ping?sitemap=", $map_link), "successfully added") !== false) {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Google: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Google: <font style="color: red;">' . $lang['SITEMAP_ERROR'] . '</font> URL: <a href="http://google.com/webmasters/sitemaps/ping?sitemap=' . urlencode($map_link) . '" target="_blank">http://google.com/webmasters/sitemaps/ping?sitemap=' . $map_link . '</a>';
}
if (strpos($map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link), "OK") !== false) {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: <font style="color: green;">'.$lang['SITEMAP_SENT'].'</font>';
} else {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Yandex: <font style="color: red;">'.$lang['SITEMAP_ERROR'].'</font> URL: <a href="http://ping.blogs.yandex.ru/ping?sitemap='.urlencode($map_link).'" target="_blank">http://ping.blogs.yandex.ru/ping?sitemap='.$map_link.'</a>';
}
if (strpos($map->send_url("http://ping.blogs.yandex.ru/ping?sitemap=", $map_link), "OK") !== false) {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Yandex: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Yandex: <font style="color: red;">' . $lang['SITEMAP_ERROR'] . '</font> URL: <a href="http://ping.blogs.yandex.ru/ping?sitemap=' . urlencode($map_link) . '" target="_blank">http://ping.blogs.yandex.ru/ping?sitemap=' . $map_link . '</a>';
}
if ($map->send_url("http://www.bing.com/ping?sitemap=", $map_link)) {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: <font style="color: green;">'.$lang['SITEMAP_SENT'].'</font>';
} else {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Bing: <font style="color: red;">'.$lang['SITEMAP_ERROR'].'</font> URL: <a href="http://www.bing.com/ping?sitemap='.urlencode($map_link).'" target="_blank">http://www.bing.com/ping?sitemap='.$map_link.'</a>';
}
if ($map->send_url("http://www.bing.com/ping?sitemap=", $map_link)) {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Bing: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Bing: <font style="color: red;">' . $lang['SITEMAP_ERROR'] . '</font> URL: <a href="http://www.bing.com/ping?sitemap=' . urlencode($map_link) . '" target="_blank">http://www.bing.com/ping?sitemap=' . $map_link . '</a>';
}
if (strpos($map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link), "Thanks for the ping") !== false) {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: <font style="color: green;">'.$lang['SITEMAP_SENT'].'</font>';
} else {
$html .= '<br />'.$lang['SITEMAP_NOTIFY_SEARCH'].' Weblogs: <font style="color: red;">'.$lang['SITEMAP_ERROR'].'</font> URL: <a href="http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url='.urlencode($map_link).'" target="_blank">http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url='.$map_link.'</a>';
}
break;
if (strpos($map->send_url("http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=", $map_link), "Thanks for the ping") !== false) {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Weblogs: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else {
$html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Weblogs: <font style="color: red;">' . $lang['SITEMAP_ERROR'] . '</font> URL: <a href="http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=' . urlencode($map_link) . '" target="_blank">http://rpc.weblogs.com/pingSiteForm?name=InfraBlog&url=' . $map_link . '</a>';
}
break;
}
$this->response['html'] = $html;
$this->response['mode'] = $mode;
$this->response['mode'] = $mode;

View file

@ -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;
$this->response['mode'] = $mode;
$this->response['timestamp'] = TIMENOW;

View file

@ -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 = '<img src="./styles/images/good.gif">';
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 = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_A_NAME'] .'</span>';
}
elseif($err = validate_username($username))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $err .'</span>';
}
break;
if (empty($username)) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_A_NAME'] . '</span>';
} elseif ($err = validate_username($username)) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>';
}
break;
case 'check_email':
$email = (string) $this->request['email'];
case 'check_email':
$email = (string)$this->request['email'];
if (empty($email))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_E_MAIL'] .'</span>';
}
elseif($err = validate_email($email))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $err .'</span>';
}
break;
if (empty($email)) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_E_MAIL'] . '</span>';
} elseif ($err = validate_email($email)) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>';
}
break;
case 'check_pass':
$pass = (string) $this->request['pass'];
$pass_confirm = (string) $this->request['pass_confirm'];
if (empty($pass) || empty($pass_confirm))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_PASS'] .'</span>';
}
else
{
if ($pass != $pass_confirm)
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_PASS_ERR'] .'</span>';
}
else
{
if (mb_strlen($pass, 'UTF-8') > 20)
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) .'</span>';
}
elseif (mb_strlen($pass, 'UTF-8') < 5)
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) .'</span>';
}
else
{
$text = (IS_GUEST) ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK'];
$html = '<img src="./styles/images/good.gif"> <span class="seedmed bold">'. $text .'</span>';
}
}
}
break;
case 'check_pass':
$pass = (string)$this->request['pass'];
$pass_confirm = (string)$this->request['pass_confirm'];
if (empty($pass) || empty($pass_confirm)) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS'] . '</span>';
} else {
if ($pass != $pass_confirm) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS_ERR'] . '</span>';
} else {
if (mb_strlen($pass, 'UTF-8') > 20) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) . '</span>';
} elseif (mb_strlen($pass, 'UTF-8') < 5) {
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) . '</span>';
} else {
$text = (IS_GUEST) ? $lang['CHOOSE_PASS_REG_OK'] : $lang['CHOOSE_PASS_OK'];
$html = '<img src="./styles/images/good.gif"> <span class="seedmed bold">' . $text . '</span>';
}
}
}
break;
}
$this->response['html'] = $html;
$this->response['mode'] = $mode;
$this->response['mode'] = $mode;

View file

@ -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);
$this->response['post_id'] = $post_id;
$this->response['topic_id'] = $topic_id;
$this->response['post_html'] = get_parsed_post($post_data);

View file

@ -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 "<div class=\"tor-root-dir\">{$this->root_dir}</div>$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 "<div class=\"tor-root-dir\">{$this->root_dir}</div>$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 = '<a title="'.$lang['DC_MAGNET'].'" href="dchub:magnet:?kt='.$name.'&xl='.$length.'"><img src="'. $images['icon_dc_magnet'] .'" width="10" height="10" border="0" /></a>';
$magnet_ext = '<a title="'.$lang['DC_MAGNET_EXT'].'" href="dchub:magnet:?kt=.'.substr(strrchr($name, '.'), 1).'&xl='.$length.'"><img src="'. $images['icon_dc_magnet_ext'] .'" width="10" height="10" border="0" /></a>';
}
if ($di->config->get('magnet_links_enabled')) {
$magnet_name = '<a title="' . $lang['DC_MAGNET'] . '" href="dchub:magnet:?kt=' . $name . '&xl=' . $length . '"><img src="' . $images['icon_dc_magnet'] . '" width="10" height="10" border="0" /></a>';
$magnet_ext = '<a title="' . $lang['DC_MAGNET_EXT'] . '" href="dchub:magnet:?kt=.' . substr(strrchr($name, '.'), 1) . '&xl=' . $length . '"><img src="' . $images['icon_dc_magnet_ext'] . '" width="10" height="10" border="0" /></a>';
}
return "$name <i>$length</i> $magnet_name $magnet_ext";
}
return "$name <i>$length</i> $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('&#91;', '&#93;', '&lt;', '&gt;', '&#039;'), $dirname);
return str_replace(array('[', ']', '<', '>', "'"), array('&#91;', '&#93;', '&lt;', '&gt;', '&#039;'), $dirname);
}
if ($bnc_error) $tor_filelist = '<b style="color: #993300;">'.$lang['ERROR_BUILD'].'</b><br /><br />'.$tor_filelist;
if ($bnc_error) $tor_filelist = '<b style="color: #993300;">' . $lang['ERROR_BUILD'] . '</b><br /><br />' . $tor_filelist;
$this->response['html'] = $tor_filelist;
$this->response['html'] = $tor_filelist;

File diff suppressed because it is too large Load diff

View file

@ -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); // премодерация
define('TOR_CONSUMED', 7); // поглощено
define('TOR_DOUBTFUL', 8); // сомнительно
define('TOR_CHECKING', 9); // проверяется
define('TOR_TMP', 10); // временная
define('TOR_PREMOD', 11); // премодерация

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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("#(?<!\r)\n#s", "\n", $this->msg), $this->extra_headers);
}
$result = mail($to, $this->subject, preg_replace("#(?<!\r)\n#s", "\n", $this->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;
}
}
return $start . $str . $end;
}
}

View file

@ -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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static();
$map .= $this->get_forum();
$map .= $this->get_topic();
$map .= "</urlset>";
function build_map()
{
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static();
$map .= $this->get_forum();
$map .= $this->get_topic();
$map .= "</urlset>";
return $map;
}
return $map;
}
function build_index ($count) {
$lm = date('c');
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap1.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
for ($i = 0; $i < $count; $i++) {
$t = $i + 2;
$map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap{$t}.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
}
$map .= "</sitemapindex>";
function build_index($count)
{
$lm = date('c');
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap1.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
for ($i = 0; $i < $count; $i++) {
$t = $i + 2;
$map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap{$t}.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
}
$map .= "</sitemapindex>";
return $map;
}
return $map;
}
function build_stat () {
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static();
$map .= $this->get_forum();
$map .= "</urlset>";
function build_stat()
{
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static();
$map .= $this->get_forum();
$map .= "</urlset>";
return $map;
}
return $map;
}
function build_map_topic ($n) {
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_topic($n);
$map .= "</urlset>";
function build_map_topic($n)
{
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_topic($n);
$map .= "</urlset>";
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<url>\n";
$xml .= "\t\t<loc>$loc</loc>\n";
$xml .= "\t\t<lastmod>$lm</lastmod>\n";
$xml .= "\t\t<priority>" . $this->priority . "</priority>\n";
$xml .= "\t</url>\n";
function get_xml($loc, $lm)
{
$xml = "\t<url>\n";
$xml .= "\t\t<loc>$loc</loc>\n";
$xml .= "\t\t<lastmod>$lm</lastmod>\n";
$xml .= "\t\t<priority>" . $this->priority . "</priority>\n";
$xml .= "\t</url>\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);
}
}
$params['sitemap_time'] = TIMENOW;
bb_update_config($params);
}
}

View file

@ -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;
}
}
// определение имени сервера
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;
}
}

File diff suppressed because it is too large Load diff

View file

@ -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');
}

View file

@ -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');
}
if (defined('IN_CRON')) {
bb_log(date('H:i:s - ') . getmypid() . ' --x- ALL jobs FINISHED *************************************************' . LOG_LF, CRON_LOG_DIR . 'cron_check');
}

View file

@ -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');
}
}
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');
}
}

View file

@ -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)");
}
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)");
}

View file

@ -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
");
");

View file

@ -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) ."
");
DELETE FROM " . BB_LOG . "
WHERE log_time < " . (TIMENOW - 86400 * $log_days_keep) . "
");

View file

@ -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
");
");

View file

@ -2,4 +2,4 @@
if (!defined('BB_ROOT')) die(basename(__FILE__));
$datastore->update('cat_forums');
$datastore->update('cat_forums');

View file

@ -2,4 +2,4 @@
if (!defined('BB_ROOT')) die(basename(__FILE__));
$datastore->update('stats');
$datastore->update('stats');

View file

@ -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();
DB()->unlock();

View file

@ -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']));
}
}
foreach (DB()->fetch_rowset($sql) as $row) {
topic_delete('prune', $row['forum_id'], (TIMENOW - 86400 * $row['prune_days']));
}
}

View file

@ -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);
}
sleep(3);
}

View file

@ -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
");
}
}

View file

@ -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)
");
");

View file

@ -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);
}
$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);
}

View file

@ -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);
DB()->query("DROP TABLE IF EXISTS " . NEW_BB_BT_LAST_USERSTAT . ", " . OLD_BB_BT_LAST_USERSTAT);

View file

@ -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");
}
// Drop tmp table
DB()->query("DROP TEMPORARY TABLE tmp_complete_count");
}

View file

@ -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)
");
}
}

View file

@ -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);
DB()->expect_slow_query(10);

View file

@ -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");
}
DB()->query("DROP TEMPORARY TABLE IF EXISTS tmp_bonus");
}

View file

@ -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);
DB()->query("TRUNCATE TABLE " . BUF_LAST_SEEDER);

View file

@ -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);
}
}
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);
}
}

View file

@ -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');
}
}
function is_installed()
{
return function_exists('apc_fetch');
}
}

View file

@ -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);
}
$this->store('network_news', $data);
}

View file

@ -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);
$this->store('moderators', $data);

View file

@ -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);
$this->store('ranks', $ranks);

View file

@ -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'][] = ' <img class="smile" src="'. $di->config->get('smilies_path') .'/'. $smile['smile_url'] .'" alt="'. $smile['emoticon'] .'" align="absmiddle" border="0" />';
$smilies['smile'][] = $smile;
foreach ($rowset as $smile) {
$smilies['orig'][] = '#(?<=^|\W)' . preg_quote($smile['code'], '#') . '(?=$|\W)#';
$smilies['repl'][] = ' <img class="smile" src="' . $di->config->get('smilies_path') . '/' . $smile['smile_url'] . '" alt="' . $smile['emoticon'] . '" align="absmiddle" border="0" />';
$smilies['smile'][] = $smile;
}
$this->store('smile_replacements', $smilies);
$this->store('smile_replacements', $smilies);

View file

@ -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);
$this->store('stats', $data);

View file

@ -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';
}
}
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';
}
}

View file

@ -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 = "<?php\n";
$filecache .= "if (!defined('BB_ROOT')) die(basename(__FILE__));\n";
$filecache .= '$filecache = ' . var_export($var, true) . ";\n";
$filecache .= '?>';
$filecache = "<?php\n";
$filecache .= "if (!defined('BB_ROOT')) die(basename(__FILE__));\n";
$filecache .= '$filecache = ' . var_export($var, true) . ";\n";
$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;
}
}
}
}
$this->data[$item] = $filecache;
}
}
}
}

View file

@ -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');
}
}
function is_installed()
{
return class_exists('Memcache');
}
}

View file

@ -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');
}
}
function is_installed()
{
return class_exists('Redis');
}
}

Some files were not shown because too many files have changed in this diff Show more