Merge pull request #103 from Exile37/coding-style-psr-2

New coding standart: PSR-2
This commit is contained in:
Yuriy Pikhtarev 2016-10-04 00:03:43 +03:00 committed by GitHub
commit 3a1085fd0b
165 changed files with 28284 additions and 29633 deletions

View file

@ -1,56 +1,54 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{ $module['GENERAL']['CONFIGURATION'] = basename(__FILE__) . '?mode=config';
$module['GENERAL']['CONFIGURATION'] = basename(__FILE__) .'?mode=config'; $module['MODS']['CONFIGURATION'] = basename(__FILE__) . '?mode=config_mods';
$module['MODS']['CONFIGURATION'] = basename(__FILE__) .'?mode=config_mods';
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
require(INC_DIR .'functions_selects.php'); require(INC_DIR . 'functions_selects.php');
$mode = isset($_GET['mode']) ? $_GET['mode'] : ''; $mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$return_links = array( $return_links = array(
'index' => '<br /><br />'. sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</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' => '<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>') 'config_mods' => '<br /><br />' . sprintf($lang['CLICK_RETURN_CONFIG_MODS'], '<a href="admin_board.php?mode=config_mods">', '</a>')
); );
// /**
// Pull all config data * Pull all config data
// */
$sql = "SELECT * FROM " . BB_CONFIG; $sql = "SELECT * FROM " . BB_CONFIG;
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not query config information in admin_board'); bb_die('Could not query config information in admin_board');
} } else {
else while ($row = DB()->sql_fetchrow($result)) {
{
while ($row = DB()->sql_fetchrow($result))
{
$config_name = $row['config_name']; $config_name = $row['config_name'];
$config_value = $row['config_value']; $config_value = $row['config_value'];
$default_config[$config_name] = $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 (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) {
{ if ($config_name == 'seed_bonus_points' ||
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])); $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])); bb_update_config(array($config_name => $new[$config_name]));
} }
} }
if (isset($_POST['submit'])) if (isset($_POST['submit'])) {
{
bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']); bb_die($lang['CONFIG_UPDATED'] . $return_links[$mode] . $return_links['index']);
} }
} }
switch ($mode) switch ($mode) {
{
case 'config_mods': case 'config_mods':
$template->assign_vars(array( $template->assign_vars(array(
'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods', 'S_CONFIG_ACTION' => 'admin_board.php?mode=config_mods',
@ -81,14 +79,14 @@ switch ($mode)
'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'], 'SEED_BONUS_USER_REGDATE' => $new['seed_bonus_user_regdate'],
)); ));
if ($new['seed_bonus_points'] && $new['seed_bonus_release']) if ($new['seed_bonus_points'] && $new['seed_bonus_release']) {
{
$seed_bonus = unserialize($new['seed_bonus_points']); $seed_bonus = unserialize($new['seed_bonus_points']);
$seed_release = unserialize($new['seed_bonus_release']); $seed_release = unserialize($new['seed_bonus_release']);
foreach ($seed_bonus as $i => $row) foreach ($seed_bonus as $i => $row) {
{ if (!$row || !$seed_release[$i]) {
if (!$row || !$seed_release[$i]) continue; continue;
}
$template->assign_block_vars('seed_bonus', array( $template->assign_block_vars('seed_bonus', array(
'RELEASE' => $seed_release[$i], 'RELEASE' => $seed_release[$i],
@ -97,14 +95,14 @@ switch ($mode)
} }
} }
if ($new['bonus_upload'] && $new['bonus_upload_price']) if ($new['bonus_upload'] && $new['bonus_upload_price']) {
{
$upload_row = unserialize($new['bonus_upload']); $upload_row = unserialize($new['bonus_upload']);
$price_row = unserialize($new['bonus_upload_price']); $price_row = unserialize($new['bonus_upload_price']);
foreach ($upload_row as $i => $row) foreach ($upload_row as $i => $row) {
{ if (!$row || !$price_row[$i]) {
if (!$row || !$price_row[$i]) continue; continue;
}
$template->assign_block_vars('bonus_upload', array( $template->assign_block_vars('bonus_upload', array(
'UP' => $row, 'UP' => $row,
@ -123,7 +121,7 @@ switch ($mode)
'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']), 'CONFIG_SITE_DESCRIPTION' => htmlCHR($new['site_desc']),
'DISABLE_BOARD' => ($new['board_disable']) ? true : false, 'DISABLE_BOARD' => ($new['board_disable']) ? true : false,
'ALLOW_AUTOLOGIN' => ($new['allow_autologin']) ? true : false, 'ALLOW_AUTOLOGIN' => ($new['allow_autologin']) ? true : false,
'AUTOLOGIN_TIME' => (int) $new['max_autologin_time'], 'AUTOLOGIN_TIME' => (int)$new['max_autologin_time'],
'MAX_POLL_OPTIONS' => $new['max_poll_options'], 'MAX_POLL_OPTIONS' => $new['max_poll_options'],
'FLOOD_INTERVAL' => $new['flood_interval'], 'FLOOD_INTERVAL' => $new['flood_interval'],
'TOPICS_PER_PAGE' => $new['topics_per_page'], 'TOPICS_PER_PAGE' => $new['topics_per_page'],

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['TP']['FORUM_CONFIG'] = basename(__FILE__); $module['TP']['FORUM_CONFIG'] = basename(__FILE__);
return; return;
} }
@ -10,14 +9,16 @@ require('./pagestart.php');
$max_forum_name_len = 30; $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']); $confirm = isset($_POST['confirm']);
$cfg = array(); $cfg = [];
// All config names with default values /**
* All config names with default values
*/
$default_cfg_str = array( $default_cfg_str = array(
'bt_announce_url' => 'http://demo.torrentpier.me/bt/', 'bt_announce_url' => 'http://demo.torrentpier.me/bt/',
); );
@ -58,14 +59,16 @@ $db_fields_bool = array(
'self_moderated' => 0, // Users can move theirs topic to another forum 'self_moderated' => 0, // Users can move theirs topic to another forum
); );
// Get config /**
* Get config
*/
$cfg = bb_get_config(BB_CONFIG, true, false); $cfg = bb_get_config(BB_CONFIG, true, false);
// Submit new config /**
if ($submit && $confirm) * Submit new config
{ */
foreach ($db_fields_bool as $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_table_bool(BB_FORUMS, 'forum_id', $field_name, $field_def_val);
} }
@ -75,63 +78,58 @@ if ($submit && $confirm)
$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 template vars
set_tpl_vars ($default_cfg_str, $cfg); set_tpl_vars($default_cfg_str, $cfg);
set_tpl_vars_lang ($default_cfg_str); set_tpl_vars_lang($default_cfg_str);
set_tpl_vars_bool ($default_cfg_bool, $cfg); set_tpl_vars_bool($default_cfg_bool, $cfg);
set_tpl_vars_lang ($default_cfg_bool); set_tpl_vars_lang($default_cfg_bool);
set_tpl_vars ($default_cfg_num, $cfg); set_tpl_vars($default_cfg_num, $cfg);
set_tpl_vars_lang ($default_cfg_num); set_tpl_vars_lang($default_cfg_num);
set_tpl_vars_lang ($db_fields_bool); set_tpl_vars_lang($db_fields_bool);
// Get Forums list // Get Forums list
$sql = "SELECT f.* $sql = "SELECT f.*
FROM ". BB_CATEGORIES ." c, ". BB_FORUMS ." f FROM " . BB_CATEGORIES . " c, " . BB_FORUMS . " f
WHERE f.cat_id = c.cat_id WHERE f.cat_id = c.cat_id
ORDER BY c.cat_order, f.forum_order"; ORDER BY c.cat_order, f.forum_order";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not obtain forum names'); bb_die('Could not obtain forum names');
} }
$rowset = DB()->sql_fetchrowset($result); $rowset = DB()->sql_fetchrowset($result);
$forum_rows = min($max_forum_rows, count($rowset)); $forum_rows = min($max_forum_rows, count($rowset));
foreach ($db_fields_bool as $field_name => $field_def_val) foreach ($db_fields_bool as $field_name => $field_def_val) {
{
$$field_name = ''; $$field_name = '';
} }
foreach ($rowset as $rid => $forum) foreach ($rowset as $rid => $forum) {
{ foreach ($db_fields_bool as $field_name => $field_def_val) {
foreach ($db_fields_bool as $field_name => $field_def_val)
{
$forum_name = $forum['forum_name']; $forum_name = $forum['forum_name'];
$selected = ($forum[$field_name]) ? ' selected="selected"' : ''; $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) foreach ($db_fields_bool as $field_name => $field_def_val) {
{ $$field_name = '<select name="' . $field_name . "[]\" multiple=\"multiple\" size=\"$forum_rows\">" . $$field_name . '</select>';
$$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('S_'. strtoupper($field_name) => $$field_name));
} }
$template->assign_vars(array( $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_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_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_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_COUNT_VAL' => SHOW_PEERS_COUNT,
'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES, 'BT_SHOW_PEERS_MODE_NAMES_VAL' => SHOW_PEERS_NAMES,

View file

@ -1,8 +1,9 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{ if (IS_SUPER_ADMIN) {
if (IS_SUPER_ADMIN) $module['TP']['TRACKER_CONFIG'] = basename(__FILE__); $module['TP']['TRACKER_CONFIG'] = basename(__FILE__);
}
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
@ -10,14 +11,18 @@ require('./pagestart.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']); if (!IS_SUPER_ADMIN) {
bb_die($lang['NOT_ADMIN']);
}
require(INC_DIR .'functions_admin_torrent.php'); require(INC_DIR . 'functions_admin_torrent.php');
$submit = isset($_POST['submit']); $submit = isset($_POST['submit']);
$confirmed = isset($_POST['confirm']); $confirmed = isset($_POST['confirm']);
// All config names with default values /**
* All config names with default values
*/
$default_cfg_str = array( $default_cfg_str = array(
'off_reason' => 'Tracker is disabled', 'off_reason' => 'Tracker is disabled',
'browser_redirect_url' => 'http://demo.torrentpier.me/', 'browser_redirect_url' => 'http://demo.torrentpier.me/',
@ -43,15 +48,17 @@ $default_cfg_num = array(
'limit_leech_ips' => 0, 'limit_leech_ips' => 0,
); );
// Set template vars /**
set_tpl_vars ($default_cfg_str, $tr_cfg); * Set template vars
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_bool($default_cfg_bool, $tr_cfg);
set_tpl_vars_lang ($default_cfg_bool); set_tpl_vars_lang($default_cfg_bool);
set_tpl_vars ($default_cfg_num, $tr_cfg); set_tpl_vars($default_cfg_num, $tr_cfg);
set_tpl_vars_lang ($default_cfg_num); set_tpl_vars_lang($default_cfg_num);
$template->assign_vars(array( $template->assign_vars(array(
'IGNORE_REPORTED_IP' => $di->config->get('ignore_reported_ip'), 'IGNORE_REPORTED_IP' => $di->config->get('ignore_reported_ip'),

View file

@ -1,43 +1,44 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{ if (IS_SUPER_ADMIN) {
if (IS_SUPER_ADMIN) $module['TP']['CRON'] = basename(__FILE__) . '?mode=list'; $module['TP']['CRON'] = basename(__FILE__) . '?mode=list';
}
return; return;
} }
$mode = isset($_GET['mode']) ? $_GET['mode'] : ''; $mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$job_id = isset($_GET['id']) ? (int) $_GET['id'] : ''; $job_id = isset($_GET['id']) ? (int)$_GET['id'] : '';
$submit = isset($_POST['submit']); $submit = isset($_POST['submit']);
$jobs = isset($_POST['select']) ? implode(',', $_POST['select']) : ''; $jobs = isset($_POST['select']) ? implode(',', $_POST['select']) : '';
$cron_action = isset($_POST['cron_action']) ? $_POST['cron_action'] : ''; $cron_action = isset($_POST['cron_action']) ? $_POST['cron_action'] : '';
if ($mode == 'run' && !$job_id) if ($mode == 'run' && !$job_id) {
{
define('BB_ROOT', './../'); define('BB_ROOT', './../');
require(BB_ROOT.'common.php'); require(BB_ROOT . 'common.php');
$user->session_start(); $user->session_start();
redirect('admin/'.basename(__FILE__) . '?mode=list'); redirect('admin/' . basename(__FILE__) . '?mode=list');
} else {
require('./pagestart.php');
} }
else require('./pagestart.php');
if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']); if (!IS_SUPER_ADMIN) {
bb_die($lang['NOT_ADMIN']);
}
require(INC_DIR .'functions_admin_torrent.php'); require(INC_DIR . 'functions_admin_torrent.php');
require(INC_DIR .'functions_admin_cron.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) foreach ($sql as $row) {
{
$config_name = $row['config_name']; $config_name = $row['config_name'];
$config_value = $row['config_value']; $config_value = $row['config_value'];
$default_config[$config_name] = $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 (isset($_POST['submit']) && $row['config_value'] != $new[$config_name]) {
{
bb_update_config(array($config_name => $new[$config_name])); bb_update_config(array($config_name => $new[$config_name]));
} }
} }
@ -47,21 +48,19 @@ $template->assign_vars(array(
'CRON_CHECK_INTERVAL' => $new['cron_check_interval'], 'CRON_CHECK_INTERVAL' => $new['cron_check_interval'],
)); ));
switch ($mode) switch ($mode) {
{
case 'list': case 'list':
$sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." ORDER BY cron_id"); $sql = DB()->fetch_rowset("SELECT * FROM " . BB_CRON . " ORDER BY cron_id");
foreach ($sql as $i => $row) foreach ($sql as $i => $row) {
{
$template->assign_block_vars('list', array( $template->assign_block_vars('list', array(
'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1', 'ROW_CLASS' => !($i % 2) ? 'row2' : 'row1',
'JOB_ID' => $i + 1, 'JOB_ID' => $i + 1,
'CRON_ID' => $row['cron_id'], '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_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_TITLE' => $row['cron_title'],
'CRON_SCRIPT' => $row['cron_script'], 'CRON_SCRIPT' => $row['cron_script'],
'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '<b class="leech">'. $lang['NOSELECT'] .'</b>', 'SCHEDULE' => $row['schedule'] ? $lang['SCHEDULE'][$row['schedule']] : '<b class="leech">' . $lang['NOSELECT'] . '</b>',
'RUN_DAY' => $row['run_day'], 'RUN_DAY' => $row['run_day'],
'LAST_RUN' => $row['last_run'], 'LAST_RUN' => $row['last_run'],
'NEXT_RUN' => $row['next_run'], 'NEXT_RUN' => $row['next_run'],
@ -76,8 +75,7 @@ switch ($mode)
)); ));
//detect cron status //detect cron status
if (file_exists('../triggers/cron_running')) if (file_exists('../triggers/cron_running')) {
{
$template->assign_vars(array( $template->assign_vars(array(
'CRON_RUNNING' => true, 'CRON_RUNNING' => true,
)); ));
@ -85,23 +83,21 @@ switch ($mode)
break; break;
case 'repair': case 'repair':
if (file_exists('../triggers/cron_running')) if (file_exists('../triggers/cron_running')) {
{
rename("../triggers/cron_running", "../triggers/cron_allowed"); rename("../triggers/cron_running", "../triggers/cron_allowed");
} }
redirect('admin/'.basename(__FILE__) . '?mode=list'); redirect('admin/' . basename(__FILE__) . '?mode=list');
break; break;
case 'run': case 'run':
run_jobs($job_id); run_jobs($job_id);
redirect('admin/'.basename(__FILE__) . '?mode=list'); redirect('admin/' . basename(__FILE__) . '?mode=list');
break; break;
case 'edit': case 'edit':
$sql = DB()->fetch_rowset("SELECT * FROM ". BB_CRON ." WHERE cron_id = $job_id"); $sql = DB()->fetch_rowset("SELECT * FROM " . BB_CRON . " WHERE cron_id = $job_id");
foreach ($sql as $row) foreach ($sql as $row) {
{
$template->assign_vars(array( $template->assign_vars(array(
'CRON_ID' => $row['cron_id'], 'CRON_ID' => $row['cron_id'],
'CRON_ACTIVE' => $row['cron_active'], 'CRON_ACTIVE' => $row['cron_active'],
@ -123,14 +119,12 @@ switch ($mode)
} }
$run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0);
for ($i = 1; $i <= 28; $i++) for ($i = 1; $i <= 28; $i++) {
{
$run_day[$i] = $i; $run_day[$i] = $i;
} }
$schedule = array($lang['SCHEDULE']['select'] => 0); $schedule = array($lang['SCHEDULE']['select'] => 0);
foreach ($lang['SCHEDULE'] as $type => $key) foreach ($lang['SCHEDULE'] as $type => $key) {
{
$schedule[$key] = $type; $schedule[$key] = $type;
} }
@ -146,14 +140,12 @@ switch ($mode)
case 'add': case 'add':
$run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0); $run_day = array($lang['DELTA_TIME']['INTERVALS']['mday'][0] => 0);
for ($i = 1; $i <= 28; $i++) for ($i = 1; $i <= 28; $i++) {
{
$run_day[$i] = $i; $run_day[$i] = $i;
} }
$schedule = array(); $schedule = array();
foreach ($lang['SCHEDULE'] as $type => $key) foreach ($lang['SCHEDULE'] as $type => $key) {
{
$schedule[$key] = $type; $schedule[$key] = $type;
} }
@ -186,40 +178,27 @@ switch ($mode)
break; break;
} }
if ($submit) if ($submit) {
{ if ($_POST['mode'] == 'list') {
if ($_POST['mode'] == 'list') if ($cron_action == 'run' && $jobs) {
{
if ($cron_action == 'run' && $jobs)
{
run_jobs($jobs); run_jobs($jobs);
} } elseif ($cron_action == 'delete' && $jobs) {
else if ($cron_action == 'delete' && $jobs)
{
delete_jobs($jobs); delete_jobs($jobs);
} } elseif (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) {
else if (($cron_action == 'disable' || $cron_action == 'enable') && $jobs)
{
toggle_active($jobs, $cron_action); toggle_active($jobs, $cron_action);
} }
redirect('admin/'.basename(__FILE__) . '?mode=list'); redirect('admin/' . basename(__FILE__) . '?mode=list');
} } elseif (validate_cron_post($_POST) == 1) {
else if (validate_cron_post($_POST) == 1) if ($_POST['mode'] == 'edit') {
{
if ($_POST['mode'] == 'edit')
{
update_cron_job($_POST); update_cron_job($_POST);
} } elseif ($_POST['mode'] == 'add') {
else if ($_POST['mode'] == 'add')
{
insert_cron_job($_POST); insert_cron_job($_POST);
} else {
bb_die('Mode error');
} }
else bb_die('Mode error');
redirect('admin/'.basename(__FILE__) . '?mode=list'); redirect('admin/' . basename(__FILE__) . '?mode=list');
} } else {
else
{
bb_die(validate_cron_post($_POST)); bb_die(validate_cron_post($_POST));
} }
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['USERS']['DISALLOW'] = basename(__FILE__); $module['USERS']['DISALLOW'] = basename(__FILE__);
return; return;
} }
@ -9,78 +8,62 @@ require('./pagestart.php');
$message = ''; $message = '';
if (isset($_POST['add_name'])) if (isset($_POST['add_name'])) {
{ include(INC_DIR . 'functions_validate.php');
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 == '') if ($disallowed_user == '') {
{
bb_die($lang['FIELDS_EMPTY']); bb_die($lang['FIELDS_EMPTY']);
} }
if( !validate_username($disallowed_user) ) if (!validate_username($disallowed_user)) {
{
$message = $lang['DISALLOWED_ALREADY']; $message = $lang['DISALLOWED_ALREADY'];
} } else {
else
{
$sql = "INSERT INTO " . BB_DISALLOW . " (disallow_username) VALUES('" . DB()->escape($disallowed_user) . "')"; $sql = "INSERT INTO " . BB_DISALLOW . " (disallow_username) VALUES('" . DB()->escape($disallowed_user) . "')";
$result = DB()->sql_query( $sql ); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not add disallowed user'); bb_die('Could not add disallowed user');
} }
$message = $lang['DISALLOW_SUCCESSFUL']; $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); bb_die($message);
} } elseif (isset($_POST['delete_name'])) {
elseif (isset($_POST['delete_name'])) $disallowed_id = (isset($_POST['disallowed_id'])) ? intval($_POST['disallowed_id']) : intval($_GET['disallowed_id']);
{
$disallowed_id = (isset($_POST['disallowed_id']) ) ? intval( $_POST['disallowed_id'] ) : intval( $_GET['disallowed_id']);
$sql = "DELETE FROM " . BB_DISALLOW . " WHERE disallow_id = $disallowed_id"; $sql = "DELETE FROM " . BB_DISALLOW . " WHERE disallow_id = $disallowed_id";
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not removed disallowed user'); 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);
} }
// /**
// Grab the current list of disallowed usernames... * Grab the current list of disallowed usernames
// */
$sql = "SELECT * FROM " . BB_DISALLOW; $sql = "SELECT * FROM " . BB_DISALLOW;
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not get disallowed users'); bb_die('Could not get disallowed users');
} }
$disallowed = DB()->sql_fetchrowset($result); $disallowed = DB()->sql_fetchrowset($result);
// /**
// Ok now generate the info for the template, which will be put out no matter * Now generate the info for the template, which will be put out no matter what mode we are in
// what mode we are in. */
//
$disallow_select = '<select name="disallowed_id">'; $disallow_select = '<select name="disallowed_id">';
if (count($disallowed) <= 0) if (count($disallowed) <= 0) {
{
$disallow_select .= '<option value="">' . $lang['NO_DISALLOWED'] . '</option>'; $disallow_select .= '<option value="">' . $lang['NO_DISALLOWED'] . '</option>';
} } else {
else for ($i = 0; $i < count($disallowed); $i++) {
{
for ($i = 0; $i < count($disallowed); $i++)
{
$disallow_select .= '<option value="' . $disallowed[$i]['disallow_id'] . '">' . $disallowed[$i]['disallow_username'] . '</option>'; $disallow_select .= '<option value="' . $disallowed[$i]['disallow_id'] . '">' . $disallowed[$i]['disallow_username'] . '</option>';
} }
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['FORUMS']['PRUNE'] = basename(__FILE__); $module['FORUMS']['PRUNE'] = basename(__FILE__);
return; return;
} }
@ -11,26 +10,22 @@ $all_forums = -1;
$pruned_total = 0; $pruned_total = 0;
$prune_performed = false; $prune_performed = false;
if (isset($_REQUEST['submit'])) if (isset($_REQUEST['submit'])) {
{ if (!($var =& $_REQUEST['f']) || !($f_selected = get_id_ary($var))) {
if (!($var =& $_REQUEST['f']) || !($f_selected = get_id_ary($var)))
{
bb_die('Forum not selected'); bb_die('Forum not selected');
} }
if (!($var =& $_REQUEST['prunedays']) || !($prunedays = abs(intval($var)))) if (!($var =& $_REQUEST['prunedays']) || !($prunedays = abs(intval($var)))) {
{
bb_die($lang['NOT_DAYS']); bb_die($lang['NOT_DAYS']);
} }
$prunetime = TIMENOW - 86400*$prunedays; $prunetime = TIMENOW - 86400 * $prunedays;
$forum_csv = in_array($all_forums, $f_selected) ? $all_forums : join(',', $f_selected); $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) foreach (DB()->fetch_rowset($sql) as $i => $row) {
{
$pruned_topics = topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types'])); $pruned_topics = topic_delete('prune', $row['forum_id'], $prunetime, !empty($_POST['prune_all_topic_types']));
$pruned_total += $pruned_topics; $pruned_total += $pruned_topics;
$prune_performed = true; $prune_performed = true;
@ -41,12 +36,10 @@ if (isset($_REQUEST['submit']))
'PRUNED_TOPICS' => $pruned_topics, 'PRUNED_TOPICS' => $pruned_topics,
)); ));
} }
if (!$prune_performed) if (!$prune_performed) {
{
bb_die($lang['NONE_SELECTED']); bb_die($lang['NONE_SELECTED']);
} }
if (!$pruned_total) if (!$pruned_total) {
{
bb_die($lang['NO_SEARCH_MATCH']); bb_die($lang['NO_SEARCH_MATCH']);
} }
} }

View file

@ -1,13 +1,12 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['FORUMS']['PERMISSIONS'] = basename(__FILE__); $module['FORUMS']['PERMISSIONS'] = basename(__FILE__);
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
$forum_auth_fields = array( $forum_auth_fields = [
'auth_view', 'auth_view',
'auth_read', 'auth_read',
'auth_reply', 'auth_reply',
@ -20,105 +19,86 @@ $forum_auth_fields = array(
'auth_post', 'auth_post',
'auth_sticky', 'auth_sticky',
'auth_announce', 'auth_announce',
); ];
// View Read Reply Edit Delete Vote Poll PostAttach DownAttach PostTopic Sticky Announce // View Read Reply Edit Delete Vote Poll PostAttach DownAttach PostTopic Sticky Announce
$simple_auth_ary = array( $simple_auth_ary = [
/* 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 0 => [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 1 => [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] 2 => [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 3 => [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] 4 => [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 5 => [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] 6 => [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( $simple_auth_types = [
$lang['PUBLIC'], $lang['PUBLIC'],
$lang['REGISTERED'], $lang['REGISTERED'],
$lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']',
$lang['PRIVATE'], $lang['PRIVATE'],
$lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']',
$lang['MODERATORS'], $lang['MODERATORS'],
$lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']',
); ];
$field_names = array(); $field_names = [];
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$field_names[$auth_type] = $lang[strtoupper($auth_type)]; $field_names[$auth_type] = $lang[strtoupper($auth_type)];
} }
$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); $forum_auth_levels = ['ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'];
$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); $forum_auth_const = [AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN];
if ($_REQUEST[POST_FORUM_URL]) if ($_REQUEST[POST_FORUM_URL]) {
{ $forum_id = (int)$_REQUEST[POST_FORUM_URL];
$forum_id = (int) $_REQUEST[POST_FORUM_URL];
$forum_sql = "WHERE forum_id = $forum_id"; $forum_sql = "WHERE forum_id = $forum_id";
} } else {
else
{
unset($forum_id); unset($forum_id);
$forum_sql = ''; $forum_sql = '';
} }
if( isset($_GET['adv']) ) if (isset($_GET['adv'])) {
{
$adv = intval($_GET['adv']); $adv = intval($_GET['adv']);
} } else {
else
{
unset($adv); unset($adv);
} }
// /**
// Start program proper * Start program proper
// */
if( isset($_POST['submit']) ) if (isset($_POST['submit'])) {
{
$sql = ''; $sql = '';
if(!empty($forum_id)) if (!empty($forum_id)) {
{ if (isset($_POST['simpleauth'])) {
if(isset($_POST['simpleauth']))
{
$simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])];
for($i = 0; $i < count($simple_ary); $i++) for ($i = 0; $i < count($simple_ary); $i++) {
{ $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i];
$sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i];
} }
if (is_array($simple_ary)) if (is_array($simple_ary)) {
{
$sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id";
} }
} } else {
else for ($i = 0; $i < count($forum_auth_fields); $i++) {
{
for ($i = 0; $i < count($forum_auth_fields); $i++)
{
$value = intval($_POST[$forum_auth_fields[$i]]); $value = intval($_POST[$forum_auth_fields[$i]]);
if ($forum_auth_fields[$i] == 'auth_vote') if ($forum_auth_fields[$i] == 'auth_vote') {
{ if ($_POST['auth_vote'] == AUTH_ALL) {
if ($_POST['auth_vote'] == AUTH_ALL)
{
$value = AUTH_REG; $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 ($sql != '') {
{ if (!DB()->sql_query($sql)) {
if (!DB()->sql_query($sql))
{
bb_die('Could not update auth table'); bb_die('Could not update auth table');
} }
} }
@ -128,48 +108,37 @@ if( isset($_POST['submit']) )
} }
$datastore->update('cat_forums'); $datastore->update('cat_forums');
bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="'."admin_forumauth.php".'">', "</a>")); bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="' . "admin_forumauth.php" . '">', "</a>"));
}
} // End of submit /**
* Get required information
*/
$forum_rows = DB()->fetch_rowset("SELECT * FROM " . BB_FORUMS . " $forum_sql");
// if (empty($forum_id)) {
// Get required information, either all forums if
// no id was specified or just the requsted if it
// was
//
$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 // Output the selection table if no forum id was specified
$template->assign_vars(array( $template->assign_vars(array(
'TPL_AUTH_SELECT_FORUM' => true, 'TPL_AUTH_SELECT_FORUM' => true,
'S_AUTH_ACTION' => 'admin_forumauth.php', 'S_AUTH_ACTION' => 'admin_forumauth.php',
'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80), 'S_AUTH_SELECT' => get_forum_select('admin', 'f', null, 80),
)); ));
} else {
}
else
{
// Output the authorisation details if an id was specified // Output the authorisation details if an id was specified
$forum_name = $forum_rows[0]['forum_name']; $forum_name = $forum_rows[0]['forum_name'];
reset($simple_auth_ary); reset($simple_auth_ary);
while (list($key, $auth_levels) = each($simple_auth_ary)) while (list($key, $auth_levels) = each($simple_auth_ary)) {
{
$matched = 1; $matched = 1;
for ($k = 0; $k < count($auth_levels); $k++) for ($k = 0; $k < count($auth_levels); $k++) {
{
$matched_type = $key; $matched_type = $key;
if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) if ($forum_rows[0][$forum_auth_fields[$k]] != $auth_levels[$k]) {
{
$matched = 0; $matched = 0;
} }
} }
if ( $matched ) if ($matched) {
{
break; break;
} }
} }
@ -178,20 +147,17 @@ else
// If we didn't get a match above then we // If we didn't get a match above then we
// automatically switch into 'advanced' mode // automatically switch into 'advanced' mode
// //
if ( !isset($adv) && !$matched ) if (!isset($adv) && !$matched) {
{
$adv = 1; $adv = 1;
} }
$s_column_span = 0; $s_column_span = 0;
if (empty($adv)) if (empty($adv)) {
{
$simple_auth = '<select name="simpleauth">'; $simple_auth = '<select name="simpleauth">';
for($j = 0; $j < count($simple_auth_types); $j++) for ($j = 0; $j < count($simple_auth_types); $j++) {
{ $selected = ($matched_type == $j) ? ' selected="selected"' : '';
$selected = ( $matched_type == $j ) ? ' selected="selected"' : '';
$simple_auth .= '<option value="' . $j . '"' . $selected . '>' . $simple_auth_types[$j] . '</option>'; $simple_auth .= '<option value="' . $j . '"' . $selected . '>' . $simple_auth_types[$j] . '</option>';
} }
@ -203,20 +169,13 @@ else
)); ));
$s_column_span++; $s_column_span++;
} } else {
else // Output values of individual fields
{ for ($j = 0; $j < count($forum_auth_fields); $j++) {
//
// Output values of individual
// fields
//
for ($j = 0; $j < count($forum_auth_fields); $j++)
{
$custom_auth[$j] = '&nbsp;<select name="' . $forum_auth_fields[$j] . '">'; $custom_auth[$j] = '&nbsp;<select name="' . $forum_auth_fields[$j] . '">';
for ($k = 0; $k < count($forum_auth_levels); $k++) for ($k = 0; $k < count($forum_auth_levels); $k++) {
{ $selected = ($forum_rows[0][$forum_auth_fields[$j]] == $forum_auth_const[$k]) ? ' selected="selected"' : '';
$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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . strtoupper($forum_auth_levels[$k])] . '</OPTION>';
} }
$custom_auth[$j] .= '</select>&nbsp;'; $custom_auth[$j] .= '</select>&nbsp;';
@ -232,9 +191,9 @@ else
} }
} }
$adv_mode = ( empty($adv) ) ? '1' : '0'; $adv_mode = (empty($adv)) ? '1' : '0';
$switch_mode = "admin_forumauth.php?f=$forum_id&amp;adv=$adv_mode"; $switch_mode = "admin_forumauth.php?f=$forum_id&amp;adv=$adv_mode";
$switch_mode_text = ( empty($adv) ) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE']; $switch_mode_text = (empty($adv)) ? $lang['ADVANCED_MODE'] : $lang['SIMPLE_MODE'];
$u_switch_mode = '<a href="' . $switch_mode . '">' . $switch_mode_text . '</a>'; $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 . '">';

View file

@ -1,34 +1,33 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['FORUMS']['PERMISSIONS_LIST'] = basename(__FILE__); $module['FORUMS']['PERMISSIONS_LIST'] = basename(__FILE__);
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
// View Read Post Reply Edit Delete Sticky Announce Vote Poll PostAttach Download // View Read Post Reply Edit Delete Sticky Announce Vote Poll PostAttach Download
$simple_auth_ary = array( $simple_auth_ary = [
/* 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 0 => [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 1 => [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] 2 => [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 3 => [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] 4 => [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 5 => [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] 6 => [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( $simple_auth_types = [
$lang['PUBLIC'], $lang['PUBLIC'],
$lang['REGISTERED'], $lang['REGISTERED'],
$lang['REGISTERED'] .' ['. $lang['HIDDEN'] .']', $lang['REGISTERED'] . ' [' . $lang['HIDDEN'] . ']',
$lang['PRIVATE'], $lang['PRIVATE'],
$lang['PRIVATE'] .' ['. $lang['HIDDEN'] .']', $lang['PRIVATE'] . ' [' . $lang['HIDDEN'] . ']',
$lang['MODERATORS'], $lang['MODERATORS'],
$lang['MODERATORS'] .' ['. $lang['HIDDEN'] .']', $lang['MODERATORS'] . ' [' . $lang['HIDDEN'] . ']',
); ];
$forum_auth_fields = array( $forum_auth_fields = [
'auth_view', 'auth_view',
'auth_read', 'auth_read',
'auth_reply', 'auth_reply',
@ -41,125 +40,96 @@ $forum_auth_fields = array(
'auth_post', 'auth_post',
'auth_sticky', 'auth_sticky',
'auth_announce', 'auth_announce',
); ];
$field_names = array(); $field_names = [];
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$field_names[$auth_type] = $lang[strtoupper($auth_type)]; $field_names[$auth_type] = $lang[strtoupper($auth_type)];
} }
$forum_auth_levels = array('ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'); $forum_auth_levels = ['ALL', 'REG', 'PRIVATE', 'MOD', 'ADMIN'];
$forum_auth_const = array(AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN); $forum_auth_const = [AUTH_ALL, AUTH_REG, AUTH_ACL, AUTH_MOD, AUTH_ADMIN];
if(isset($_GET[POST_FORUM_URL]) || isset($_POST[POST_FORUM_URL])) 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_id = (isset($_POST[POST_FORUM_URL])) ? intval($_POST[POST_FORUM_URL]) : intval($_GET[POST_FORUM_URL]);
$forum_sql = "AND forum_id = $forum_id"; $forum_sql = "AND forum_id = $forum_id";
} } else {
else
{
unset($forum_id); unset($forum_id);
$forum_sql = ''; $forum_sql = '';
} }
if(isset($_GET[POST_CAT_URL]) || isset($_POST[POST_CAT_URL])) 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_id = (isset($_POST[POST_CAT_URL])) ? intval($_POST[POST_CAT_URL]) : intval($_GET[POST_CAT_URL]);
$cat_sql = "AND c.cat_id = $cat_id"; $cat_sql = "AND c.cat_id = $cat_id";
} } else {
else
{
unset($cat_id); unset($cat_id);
$cat_sql = ''; $cat_sql = '';
} }
if( isset($_GET['adv']) ) if (isset($_GET['adv'])) {
{
$adv = intval($_GET['adv']); $adv = intval($_GET['adv']);
} } else {
else
{
unset($adv); unset($adv);
} }
// //
// Start program proper // Start program proper
// //
if( isset($_POST['submit']) ) if (isset($_POST['submit'])) {
{
$sql = ''; $sql = '';
if(!empty($forum_id)) if (!empty($forum_id)) {
{ if (isset($_POST['simpleauth'])) {
if(isset($_POST['simpleauth']))
{
$simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])]; $simple_ary = $simple_auth_ary[intval($_POST['simpleauth'])];
for($i = 0; $i < count($simple_ary); $i++) for ($i = 0; $i < count($simple_ary); $i++) {
{ $sql .= (($sql != '') ? ', ' : '') . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i];
$sql .= ( ( $sql != '' ) ? ', ' : '' ) . $forum_auth_fields[$i] . ' = ' . $simple_ary[$i];
} }
if (is_array($simple_ary)) if (is_array($simple_ary)) {
{
$sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id"; $sql = "UPDATE " . BB_FORUMS . " SET $sql WHERE forum_id = $forum_id";
} }
} } else {
else for ($i = 0; $i < count($forum_auth_fields); $i++) {
{
for($i = 0; $i < count($forum_auth_fields); $i++)
{
$value = intval($_POST[$forum_auth_fields[$i]]); $value = intval($_POST[$forum_auth_fields[$i]]);
if ( $forum_auth_fields[$i] == 'auth_vote' ) if ($forum_auth_fields[$i] == 'auth_vote') {
{ if ($_POST['auth_vote'] == AUTH_ALL) {
if ( $_POST['auth_vote'] == AUTH_ALL )
{
$value = AUTH_REG; $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 ($sql != '') {
{ if (!DB()->sql_query($sql)) {
if (!DB()->sql_query($sql))
{
bb_die('Could not update auth table #1'); bb_die('Could not update auth table #1');
} }
} }
$forum_sql = ''; $forum_sql = '';
$adv = 0; $adv = 0;
} } elseif (!empty($cat_id)) {
elseif (!empty($cat_id)) for ($i = 0; $i < count($forum_auth_fields); $i++) {
{
for ($i = 0; $i < count($forum_auth_fields); $i++)
{
$value = intval($_POST[$forum_auth_fields[$i]]); $value = intval($_POST[$forum_auth_fields[$i]]);
if ($forum_auth_fields[$i] == 'auth_vote') if ($forum_auth_fields[$i] == 'auth_vote') {
{ if ($_POST['auth_vote'] == AUTH_ALL) {
if ( $_POST['auth_vote'] == AUTH_ALL )
{
$value = AUTH_REG; $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 ($sql != '') {
{ if (!DB()->sql_query($sql)) {
if (!DB()->sql_query($sql))
{
bb_die('Could not update auth table #2'); bb_die('Could not update auth table #2');
} }
} }
@ -169,7 +139,6 @@ if( isset($_POST['submit']) )
$datastore->update('cat_forums'); $datastore->update('cat_forums');
bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="admin_forumauth_list.php">', "</a>")); bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="admin_forumauth_list.php">', "</a>"));
} // End of submit } // End of submit
// //
@ -182,27 +151,24 @@ $sql = "SELECT f.*
WHERE c.cat_id = f.cat_id WHERE c.cat_id = f.cat_id
$forum_sql $cat_sql $forum_sql $cat_sql
ORDER BY c.cat_order ASC, f.forum_order ASC"; ORDER BY c.cat_order ASC, f.forum_order ASC";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not obtain forum list'); bb_die('Could not obtain forum list');
} }
$forum_rows = DB()->sql_fetchrowset($result); $forum_rows = DB()->sql_fetchrowset($result);
DB()->sql_freeresult($result); DB()->sql_freeresult($result);
if( empty($forum_id) && empty($cat_id) ) if (empty($forum_id) && empty($cat_id)) {
{
// //
// Output the summary list if no forum id was // Output the summary list if no forum id was
// specified // specified
// //
$template->assign_vars(array( $template->assign_vars(array(
'TPL_AUTH_FORUM_LIST' => true, 'TPL_AUTH_FORUM_LIST' => true,
'S_COLUMN_SPAN' => count($forum_auth_fields)+1, 'S_COLUMN_SPAN' => count($forum_auth_fields) + 1,
)); ));
for ($i = 0; $i<count($forum_auth_fields); $i++) for ($i = 0; $i < count($forum_auth_fields); $i++) {
{
$template->assign_block_vars('forum_auth_titles', array( $template->assign_block_vars('forum_auth_titles', array(
'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]],
)); ));
@ -212,40 +178,33 @@ if( empty($forum_id) && empty($cat_id) )
$sql = "SELECT c.cat_id, c.cat_title, c.cat_order $sql = "SELECT c.cat_id, c.cat_title, c.cat_order
FROM " . BB_CATEGORIES . " c FROM " . BB_CATEGORIES . " c
ORDER BY c.cat_order"; ORDER BY c.cat_order";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not query categories list #1'); bb_die('Could not query categories list #1');
} }
$category_rows = DB()->sql_fetchrowset($result); $category_rows = DB()->sql_fetchrowset($result);
$cat_count = count($category_rows); $cat_count = count($category_rows);
for ($i=0; $i<$cat_count; $i++) for ($i = 0; $i < $cat_count; $i++) {
{
$cat_id = $category_rows[$i]['cat_id']; $cat_id = $category_rows[$i]['cat_id'];
$template->assign_block_vars('cat_row', array( $template->assign_block_vars('cat_row', array(
'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']), 'CAT_NAME' => htmlCHR($category_rows[$i]['cat_title']),
'CAT_URL' => 'admin_forumauth_list.php'.'?'.POST_CAT_URL.'='.$category_rows[$i]['cat_id']) 'CAT_URL' => 'admin_forumauth_list.php' . '?' . POST_CAT_URL . '=' . $category_rows[$i]['cat_id'])
); );
for ($j=0; $j<count($forum_rows); $j++) for ($j = 0; $j < count($forum_rows); $j++) {
{ if ($cat_id == $forum_rows[$j]['cat_id']) {
if ( $cat_id == $forum_rows[$j]['cat_id'] )
{
$template->assign_block_vars('cat_row.forum_row', array( $template->assign_block_vars('cat_row.forum_row', array(
'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', '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>', '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'], 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'],
)); ));
for ($k=0; $k<count($forum_auth_fields); $k++) for ($k = 0; $k < count($forum_auth_fields); $k++) {
{
$item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]];
for ($l=0; $l<count($forum_auth_const); $l++) for ($l = 0; $l < count($forum_auth_const); $l++) {
{ if ($item_auth_value == $forum_auth_const[$l]) {
if ($item_auth_value == $forum_auth_const[$l])
{
$item_auth_level = $forum_auth_levels[$l]; $item_auth_level = $forum_auth_levels[$l];
break; break;
} }
@ -258,9 +217,7 @@ if( empty($forum_id) && empty($cat_id) )
} }
} }
} }
} } else {
else
{
// //
// output the authorisation details if an category id was // output the authorisation details if an category id was
// specified // specified
@ -270,8 +227,7 @@ else
// first display the current details for all forums // first display the current details for all forums
// in the category // in the category
// //
for ($i = 0; $i<count($forum_auth_fields); $i++) for ($i = 0; $i < count($forum_auth_fields); $i++) {
{
$template->assign_block_vars('forum_auth_titles', array( $template->assign_block_vars('forum_auth_titles', array(
'CELL_TITLE' => $field_names[$forum_auth_fields[$i]], 'CELL_TITLE' => $field_names[$forum_auth_fields[$i]],
)); ));
@ -282,8 +238,7 @@ else
FROM " . BB_CATEGORIES . " c FROM " . BB_CATEGORIES . " c
WHERE c.cat_id = $cat_id WHERE c.cat_id = $cat_id
ORDER BY c.cat_order"; ORDER BY c.cat_order";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not query categories list #2'); bb_die('Could not query categories list #2');
} }
@ -294,26 +249,21 @@ else
$template->assign_block_vars('cat_row', array( $template->assign_block_vars('cat_row', array(
'CAT_NAME' => htmlCHR($cat_name), 'CAT_NAME' => htmlCHR($cat_name),
'CAT_URL' => 'admin_forumauth_list.php?'. POST_CAT_URL .'='. $cat_id) 'CAT_URL' => 'admin_forumauth_list.php?' . POST_CAT_URL . '=' . $cat_id)
); );
for ($j=0; $j<count($forum_rows); $j++) for ($j = 0; $j < count($forum_rows); $j++) {
{ if ($cat_id == $forum_rows[$j]['cat_id']) {
if ( $cat_id == $forum_rows[$j]['cat_id'] )
{
$template->assign_block_vars('cat_row.forum_row', array( $template->assign_block_vars('cat_row.forum_row', array(
'ROW_CLASS' => !($j % 2) ? 'row4' : 'row5', '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>', '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'], 'IS_SUBFORUM' => $forum_rows[$j]['forum_parent'],
)); ));
for ($k=0; $k<count($forum_auth_fields); $k++) for ($k = 0; $k < count($forum_auth_fields); $k++) {
{
$item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]]; $item_auth_value = $forum_rows[$j][$forum_auth_fields[$k]];
for ($l=0; $l<count($forum_auth_const); $l++) for ($l = 0; $l < count($forum_auth_const); $l++) {
{ if ($item_auth_value == $forum_auth_const[$l]) {
if ($item_auth_value == $forum_auth_const[$l])
{
$item_auth_level = $forum_auth_levels[$l]; $item_auth_level = $forum_auth_levels[$l];
break; break;
} }
@ -330,13 +280,11 @@ else
// next generate the information to allow the permissions to be changed // next generate the information to allow the permissions to be changed
// note: we always read from the first forum in the category // note: we always read from the first forum in the category
// //
for($j = 0; $j < count($forum_auth_fields); $j++) for ($j = 0; $j < count($forum_auth_fields); $j++) {
{
$custom_auth[$j] = '<select name="' . $forum_auth_fields[$j] . '">'; $custom_auth[$j] = '<select name="' . $forum_auth_fields[$j] . '">';
for($k = 0; $k < count($forum_auth_levels); $k++) 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"' : '';
$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] .= '<option value="' . $forum_auth_const[$k] . '"' . $selected . '>' . $lang['FORUM_' . $forum_auth_levels[$k]] . '</option>';
} }
$custom_auth[$j] .= '</select>'; $custom_auth[$j] .= '</select>';

File diff suppressed because it is too large Load diff

View file

@ -1,23 +1,19 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GROUPS']['MANAGE'] = basename(__FILE__); $module['GROUPS']['MANAGE'] = basename(__FILE__);
return; return;
} }
require('./pagestart.php'); 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; $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']) || !empty($_POST['new'])) {
{ if (!empty($_POST['edit'])) {
if (!empty($_POST['edit'])) if (!$row = get_group_data($group_id)) {
{
if (!$row = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
$group_info = array( $group_info = array(
@ -29,10 +25,8 @@ if (!empty($_POST['edit']) || !empty($_POST['new']))
'release_group' => $row['release_group'], 'release_group' => $row['release_group'],
); );
$mode = 'editgroup'; $mode = 'editgroup';
$template->assign_block_vars('group_edit', array()); $template->assign_block_vars('group_edit', []);
} } elseif (!empty($_POST['new'])) {
else if (!empty($_POST['new']))
{
$group_info = array( $group_info = array(
'group_name' => '', 'group_name' => '',
'group_description' => '', 'group_description' => '',
@ -46,8 +40,8 @@ if (!empty($_POST['edit']) || !empty($_POST['new']))
// Ok, now we know everything about them, let's show the page. // Ok, now we know everything about them, let's show the page.
$s_hidden_fields = ' $s_hidden_fields = '
<input type="hidden" name="mode" value="'. $mode .'" /> <input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="'. POST_GROUPS_URL .'" value="'. $group_id .'" /> <input type="hidden" name="' . POST_GROUPS_URL . '" value="' . $group_id . '" />
'; ';
$template->assign_vars(array( $template->assign_vars(array(
@ -57,83 +51,69 @@ if (!empty($_POST['edit']) || !empty($_POST['new']))
'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])), 'GROUP_DESCRIPTION' => stripslashes(htmlspecialchars($group_info['group_description'])),
'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']), 'GROUP_MODERATOR' => replace_quote($group_info['group_mod_name']),
'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'], 'T_GROUP_EDIT_DELETE' => ($mode == 'newgroup') ? $lang['CREATE_NEW_GROUP'] : $lang['EDIT_GROUP'],
'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", 'U_SEARCH_USER' => BB_ROOT . "search.php?mode=searchuser",
'S_GROUP_OPEN_TYPE' => GROUP_OPEN, 'S_GROUP_OPEN_TYPE' => GROUP_OPEN,
'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED, 'S_GROUP_CLOSED_TYPE' => GROUP_CLOSED,
'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN, 'S_GROUP_HIDDEN_TYPE' => GROUP_HIDDEN,
'S_GROUP_OPEN_CHECKED' => ($group_info['group_type'] == GROUP_OPEN) ? HTML_CHECKED : '', '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_CLOSED_CHECKED' => ($group_info['group_type'] == GROUP_CLOSED) ? HTML_CHECKED : '',
'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN ) ? HTML_CHECKED : '', 'S_GROUP_HIDDEN_CHECKED' => ($group_info['group_type'] == GROUP_HIDDEN) ? HTML_CHECKED : '',
'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false,
'S_GROUP_ACTION' => "admin_groups.php", 'S_GROUP_ACTION' => "admin_groups.php",
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } elseif (!empty($_POST['group_update'])) {
else if (!empty($_POST['group_update'])) if (!empty($_POST['group_delete'])) {
{ if (!$group_info = get_group_data($group_id)) {
if (!empty($_POST['group_delete']))
{
if (!$group_info = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
// Delete Group // Delete Group
delete_group($group_id); delete_group($group_id);
$message = $lang['DELETED_GROUP'] .'<br /><br />'; $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_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'); $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
} } else {
else
{
$group_type = isset($_POST['group_type']) ? intval($_POST['group_type']) : GROUP_OPEN; $group_type = isset($_POST['group_type']) ? intval($_POST['group_type']) : GROUP_OPEN;
$release_group = isset($_POST['release_group']) ? intval($_POST['release_group']) : 0; $release_group = isset($_POST['release_group']) ? intval($_POST['release_group']) : 0;
$group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : ''; $group_name = isset($_POST['group_name']) ? trim($_POST['group_name']) : '';
$group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : ''; $group_desc = isset($_POST['group_description']) ? trim($_POST['group_description']) : '';
$group_moderator = isset($_POST['username']) ? $_POST['username'] : ''; $group_moderator = isset($_POST['username']) ? $_POST['username'] : '';
if ($group_name === '') if ($group_name === '') {
{
bb_die($lang['NO_GROUP_NAME']); bb_die($lang['NO_GROUP_NAME']);
} } elseif ($group_moderator === '') {
else if ($group_moderator === '')
{
bb_die($lang['NO_GROUP_MODERATOR']); bb_die($lang['NO_GROUP_MODERATOR']);
} }
$this_userdata = get_userdata($group_moderator, true); $this_userdata = get_userdata($group_moderator, true);
if (!$group_moderator = $this_userdata['user_id']) if (!$group_moderator = $this_userdata['user_id']) {
{
bb_die($lang['NO_GROUP_MODERATOR']); bb_die($lang['NO_GROUP_MODERATOR']);
} }
$sql_ary = array( $sql_ary = array(
'group_type' => (int) $group_type, 'group_type' => (int)$group_type,
'release_group' => (int) $release_group, 'release_group' => (int)$release_group,
'group_name' => (string) $group_name, 'group_name' => (string)$group_name,
'group_description' => (string) $group_desc, 'group_description' => (string)$group_desc,
'group_moderator' => (int) $group_moderator, 'group_moderator' => (int)$group_moderator,
'group_single_user' => 0, 'group_single_user' => 0,
); );
if ($mode == "editgroup") if ($mode == "editgroup") {
{ if (!$group_info = get_group_data($group_id)) {
if (!$group_info = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
if ($group_info['group_moderator'] != $group_moderator) if ($group_info['group_moderator'] != $group_moderator) {
{
// Create user_group for new group's moderator // Create user_group for new group's moderator
add_user_into_group($group_id, $group_moderator); add_user_into_group($group_id, $group_moderator);
$sql_ary['mod_time'] = TIMENOW; $sql_ary['mod_time'] = TIMENOW;
// Delete old moderator's user_group // Delete old moderator's user_group
if (isset($_POST['delete_old_moderator'])) if (isset($_POST['delete_old_moderator'])) {
{
delete_user_group($group_id, $group_info['group_moderator']); delete_user_group($group_id, $group_info['group_moderator']);
} }
} }
@ -141,40 +121,34 @@ else if (!empty($_POST['group_update']))
$sql_args = DB()->build_array('UPDATE', $sql_ary); $sql_args = DB()->build_array('UPDATE', $sql_ary);
// Update group's data // Update group's data
DB()->query("UPDATE ". BB_GROUPS ." SET $sql_args WHERE group_id = $group_id"); DB()->query("UPDATE " . BB_GROUPS . " SET $sql_args WHERE group_id = $group_id");
$message = $lang['UPDATED_GROUP'] .'<br /><br />'; $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_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'); $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
} } elseif ($mode == 'newgroup') {
else if ($mode == 'newgroup')
{
$sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW; $sql_ary['group_time'] = $sql_ary['mod_time'] = TIMENOW;
$sql_args = DB()->build_array('INSERT', $sql_ary); $sql_args = DB()->build_array('INSERT', $sql_ary);
// Create new group // Create new group
DB()->query("INSERT INTO ". BB_GROUPS ." $sql_args"); DB()->query("INSERT INTO " . BB_GROUPS . " $sql_args");
$new_group_id = DB()->sql_nextid(); $new_group_id = DB()->sql_nextid();
// Create user_group for group's moderator // Create user_group for group's moderator
add_user_into_group($new_group_id, $group_moderator); add_user_into_group($new_group_id, $group_moderator);
$message = $lang['ADDED_NEW_GROUP'] .'<br /><br />'; $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_GROUPSADMIN'], '<a href="admin_groups.php">', '</a>') . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'); $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
} } else {
else
{
bb_die($lang['NO_GROUP_ACTION']); bb_die($lang['NO_GROUP_ACTION']);
} }
} }
} } else {
else
{
$template->assign_vars(array( $template->assign_vars(array(
'TPL_GROUP_SELECT' => true, 'TPL_GROUP_SELECT' => true,

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['USERS']['ACTIONS_LOG'] = basename(__FILE__); $module['USERS']['ACTIONS_LOG'] = basename(__FILE__);
return; return;
} }
@ -54,8 +53,7 @@ $def_forums = $all_forums;
$def_sort = $sort_desc; $def_sort = $sort_desc;
// Moderators data // Moderators data
if (!$mod = $datastore->get('moderators')) if (!$mod = $datastore->get('moderators')) {
{
$datastore->update('moderators'); $datastore->update('moderators');
$mod = $datastore->get('moderators'); $mod = $datastore->get('moderators');
} }
@ -67,8 +65,7 @@ $users = array($lang['ACTS_LOG_ALL_ACTIONS'] => $all_users) + array_flip($mod['m
unset($mod); unset($mod);
// Forums data // Forums data
if (!$forums = $datastore->get('cat_forums')) if (!$forums = $datastore->get('cat_forums')) {
{
$datastore->update('cat_forums'); $datastore->update('cat_forums');
$forums = $datastore->get('cat_forums'); $forums = $datastore->get('cat_forums');
} }
@ -83,12 +80,10 @@ $start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0;
$type_selected = array($def_types); $type_selected = array($def_types);
$type_csv = ''; $type_csv = '';
if ($var =& $_REQUEST[$type_key]) if ($var =& $_REQUEST[$type_key]) {
{
$type_selected = get_id_ary($var); $type_selected = get_id_ary($var);
if (in_array($all_types, $type_selected)) if (in_array($all_types, $type_selected)) {
{
$type_selected = array($all_types); $type_selected = array($all_types);
} }
$type_csv = join(',', $type_selected); $type_csv = join(',', $type_selected);
@ -99,12 +94,10 @@ if ($var =& $_REQUEST[$type_key])
$user_selected = array($def_users); $user_selected = array($def_users);
$user_csv = ''; $user_csv = '';
if ($var =& $_REQUEST[$user_key]) if ($var =& $_REQUEST[$user_key]) {
{
$user_selected = get_id_ary($var); $user_selected = get_id_ary($var);
if (in_array($all_users, $user_selected)) if (in_array($all_users, $user_selected)) {
{
$user_selected = array($all_users); $user_selected = array($all_users);
} }
$user_csv = join(',', $user_selected); $user_csv = join(',', $user_selected);
@ -115,12 +108,10 @@ if ($var =& $_REQUEST[$user_key])
$forum_selected = array($def_forums); $forum_selected = array($def_forums);
$forum_csv = ''; $forum_csv = '';
if ($var =& $_REQUEST[$forum_key]) if ($var =& $_REQUEST[$forum_key]) {
{
$forum_selected = get_id_ary($var); $forum_selected = get_id_ary($var);
if (in_array($all_forums, $forum_selected)) if (in_array($all_forums, $forum_selected)) {
{
$forum_selected = array($all_forums); $forum_selected = array($all_forums);
} }
$forum_csv = join(',', $forum_selected); $forum_csv = join(',', $forum_selected);
@ -131,8 +122,7 @@ if ($var =& $_REQUEST[$forum_key])
$topic_selected = null; $topic_selected = null;
$topic_csv = ''; $topic_csv = '';
if ($var =& $_REQUEST[$topic_key]) if ($var =& $_REQUEST[$topic_key]) {
{
$topic_selected = get_id_ary($var); $topic_selected = get_id_ary($var);
$topic_csv = join(',', $topic_selected); $topic_csv = join(',', $topic_selected);
$url = ($topic_csv) ? url_arg($url, $topic_key, $topic_csv) : $url; $url = ($topic_csv) ? url_arg($url, $topic_key, $topic_csv) : $url;
@ -141,8 +131,7 @@ if ($var =& $_REQUEST[$topic_key])
// Sort // Sort
$sort_val = $def_sort; $sort_val = $def_sort;
if (($var =& $_REQUEST[$sort_key]) && ($var != $def_sort)) if (($var =& $_REQUEST[$sort_key]) && ($var != $def_sort)) {
{
$sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc; $sort_val = ($var == $sort_asc) ? $sort_asc : $sort_desc;
$url = url_arg($url, $sort_key, $sort_val); $url = url_arg($url, $sort_key, $sort_val);
} }
@ -151,35 +140,30 @@ if (($var =& $_REQUEST[$sort_key]) && ($var != $def_sort))
$datetime_val = $def_datetime; $datetime_val = $def_datetime;
$daysback_val = $def_days; $daysback_val = $def_days;
if (($var =& $_REQUEST[$daysback_key]) && ($var != $def_days)) if (($var =& $_REQUEST[$daysback_key]) && ($var != $def_days)) {
{
$daysback_val = max(intval($var), 1); $daysback_val = max(intval($var), 1);
$url = url_arg($url, $daysback_key, $daysback_val); $url = url_arg($url, $daysback_key, $daysback_val);
} }
if (($var =& $_REQUEST[$datetime_key]) && ($var != $def_datetime)) if (($var =& $_REQUEST[$datetime_key]) && ($var != $def_datetime)) {
{
$tz = TIMENOW + (3600 * $di->config->get('board_timezone')); $tz = TIMENOW + (3600 * $di->config->get('board_timezone'));
if (($tmp_timestamp = strtotime($var, $tz)) > 0) if (($tmp_timestamp = strtotime($var, $tz)) > 0) {
{
$datetime_val = $tmp_timestamp; $datetime_val = $tmp_timestamp;
$url = url_arg($url, $datetime_key, date($dt_format, $datetime_val)); $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_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 // First log time
$row = DB()->fetch_row("SELECT MIN(log_time) AS first_log_time FROM ". BB_LOG); $row = DB()->fetch_row("SELECT MIN(log_time) AS first_log_time FROM " . BB_LOG);
$first_log_time = (int) $row['first_log_time']; $first_log_time = (int)$row['first_log_time'];
// Title match // Title match
$title_match_val = $title_match_sql = ''; $title_match_val = $title_match_sql = '';
if ($var =& $_REQUEST[$title_match_key]) if ($var =& $_REQUEST[$title_match_key]) {
{ if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len)) {
if ($tmp_title_match = substr(urldecode(trim($var)), 0, $title_match_max_len))
{
$title_match_sql = DB()->escape($tmp_title_match); $title_match_sql = DB()->escape($tmp_title_match);
$url = url_arg($url, $title_match_key, urlencode($tmp_title_match)); $url = url_arg($url, $title_match_key, urlencode($tmp_title_match));
} }
@ -194,25 +178,22 @@ $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)" : ''; $where .= ($title_match_sql) ? " AND MATCH (l.log_topic_title) AGAINST ('$title_match_sql' IN BOOLEAN MODE)" : '';
$sql = "SELECT l.*, u.* $sql = "SELECT l.*, u.*
FROM ". BB_LOG ." l FROM " . BB_LOG . " l
LEFT JOIN ". BB_USERS ." u ON(u.user_id = l.log_user_id) LEFT JOIN " . BB_USERS . " u ON(u.user_id = l.log_user_id)
$where $where
ORDER BY l.log_time ORDER BY l.log_time
$sort_val $sort_val
LIMIT $start, ". ($per_page + 1)." LIMIT $start, " . ($per_page + 1) . "
"; ";
$log_rowset = DB()->fetch_rowset($sql); $log_rowset = DB()->fetch_rowset($sql);
$log_count = count($log_rowset); $log_count = count($log_rowset);
if ($log_count == $per_page + 1) if ($log_count == $per_page + 1) {
{
$items_count = $start + ($per_page * 2); $items_count = $start + ($per_page * 2);
$pages = '?'; $pages = '?';
array_pop($log_rowset); array_pop($log_rowset);
} } else {
else
{
$items_count = $start + $log_count; $items_count = $start + $log_count;
$pages = (!$log_count) ? 1 : ceil($items_count / $per_page); $pages = (!$log_count) ? 1 : ceil($items_count / $per_page);
} }
@ -221,21 +202,18 @@ generate_pagination($url, $items_count, $per_page, $start);
$filter = array(); $filter = array();
if ($log_rowset) if ($log_rowset) {
{
$log_type = $log_action->log_type; $log_type = $log_action->log_type;
$log_type_flip = array_flip($log_type); $log_type_flip = array_flip($log_type);
foreach ($log_rowset as $row_num => $row) foreach ($log_rowset as $row_num => $row) {
{
$msg = ''; $msg = '';
$forum_name = $forum_name_new = ''; $forum_name = $forum_name_new = '';
$topic_title = $topic_title_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']) switch ($row['log_type_id']) {
{
case $log_type['mod_topic_delete']: case $log_type['mod_topic_delete']:
case $log_type['mod_topic_move']: case $log_type['mod_topic_move']:
case $log_type['mod_topic_lock']: case $log_type['mod_topic_lock']:
@ -243,24 +221,20 @@ if ($log_rowset)
case $log_type['mod_post_delete']: case $log_type['mod_post_delete']:
case $log_type['mod_topic_split']: case $log_type['mod_topic_split']:
// topic_title // topic_title
if (!empty($row['log_topic_title'])) if (!empty($row['log_topic_title'])) {
{
$topic_title = $row['log_topic_title']; $topic_title = $row['log_topic_title'];
} }
// topic_title_new // topic_title_new
if (!empty($row['log_topic_title_new'])) if (!empty($row['log_topic_title_new'])) {
{
$topic_title_new = $row['log_topic_title_new']; $topic_title_new = $row['log_topic_title_new'];
} }
// forum_name // forum_name
if ($fid =& $row['log_forum_id']) if ($fid =& $row['log_forum_id']) {
{ $forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id'];
$forum_name = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id'];
} }
// forum_name_new // forum_name_new
if ($fid =& $row['log_forum_id_new']) if ($fid =& $row['log_forum_id_new']) {
{ $forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:' . $row['log_forum_id'];
$forum_name_new = ($fname =& $f_data[$fid]['forum_name']) ? $fname : 'id:'. $row['log_forum_id'];
} }
break; break;
@ -311,24 +285,21 @@ if ($log_rowset)
)); ));
// Topics // Topics
if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) if ($topic_csv && empty($filter['topics'][$row['log_topic_title']])) {
{
$template->assign_block_vars('topics', array( $template->assign_block_vars('topics', array(
'TOPIC_TITLE' => $row['log_topic_title'], 'TOPIC_TITLE' => $row['log_topic_title'],
)); ));
$filter['topics'][$row['log_topic_title']] = true; $filter['topics'][$row['log_topic_title']] = true;
} }
// Forums // Forums
if ($forum_csv && empty($filter['forums'][$forum_name])) if ($forum_csv && empty($filter['forums'][$forum_name])) {
{
$template->assign_block_vars('forums', array( $template->assign_block_vars('forums', array(
'FORUM_NAME' => htmlCHR($forum_name), 'FORUM_NAME' => htmlCHR($forum_name),
)); ));
$filter['forums'][$forum_name] = true; $filter['forums'][$forum_name] = true;
} }
// Users // Users
if ($user_csv && empty($filter['users'])) if ($user_csv && empty($filter['users'])) {
{
$template->assign_block_vars('users', array( $template->assign_block_vars('users', array(
'USERNAME' => profile_url($row), 'USERNAME' => profile_url($row),
)); ));
@ -342,9 +313,7 @@ if ($log_rowset)
'FILTER_FORUMS' => !empty($filter['forums']), 'FILTER_FORUMS' => !empty($filter['forums']),
'FILTER_USERS' => !empty($filter['users']), 'FILTER_USERS' => !empty($filter['users']),
)); ));
} } else {
else
{
$template->assign_block_vars('log_not_found', array()); $template->assign_block_vars('log_not_found', array());
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['MODS']['MASS_EMAIL'] = basename(__FILE__); $module['MODS']['MASS_EMAIL'] = basename(__FILE__);
return; return;
} }
@ -12,58 +11,57 @@ $di = \TorrentPier\Di::getInstance();
set_time_limit(1200); set_time_limit(1200);
$subject = (string) trim(request_var('subject', '')); $subject = (string)trim(request_var('subject', ''));
$message = (string) request_var('message', ''); $message = (string)request_var('message', '');
$group_id = (int) request_var(POST_GROUPS_URL, 0); $group_id = (int)request_var(POST_GROUPS_URL, 0);
$errors = $user_id_sql = array(); $errors = $user_id_sql = [];
if (isset($_POST['submit'])) if (isset($_POST['submit'])) {
{ if (!$subject) {
if (!$subject) $errors[] = $lang['EMPTY_SUBJECT']; $errors[] = $lang['EMPTY_SUBJECT'];
if (!$message) $errors[] = $lang['EMPTY_MESSAGE']; }
if (!$group_id) $errors[] = $lang['GROUP_NOT_EXIST']; if (!$message) {
$errors[] = $lang['EMPTY_MESSAGE'];
}
if (!$group_id) {
$errors[] = $lang['GROUP_NOT_EXIST'];
}
if (!$errors) if (!$errors) {
{ $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) foreach ($sql as $row) {
{ $user_id_sql[] = ',' . $row['ban_userid'];
$user_id_sql[] = ','. $row['ban_userid'];
} }
$user_id_sql = join('', $user_id_sql); $user_id_sql = join('', $user_id_sql);
if ($group_id != -1) if ($group_id != -1) {
{
$user_list = DB()->fetch_rowset(" $user_list = DB()->fetch_rowset("
SELECT u.username, u.user_email, u.user_lang 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 WHERE ug.group_id = $group_id
AND ug.user_pending = 0 AND ug.user_pending = 0
AND u.user_id = ug.user_id AND u.user_id = ug.user_id
AND u.user_active = 1 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 {
else
{
$user_list = DB()->fetch_rowset(" $user_list = DB()->fetch_rowset("
SELECT username, user_email, user_lang SELECT username, user_email, user_lang
FROM ". BB_USERS ." FROM " . BB_USERS . "
WHERE user_active = 1 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) foreach ($user_list as $i => $row) {
{
$emailer = new emailer($di->config->get('smtp_delivery')); $emailer = new emailer($di->config->get('smtp_delivery'));
$emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>");
$emailer->email_address($row['username'] ." <{$row['user_email']}>"); $emailer->email_address($row['username'] . " <{$row['user_email']}>");
$emailer->use_template('admin_send_email'); $emailer->use_template('admin_send_email');
$emailer->assign_vars(array( $emailer->assign_vars(array(
@ -81,14 +79,13 @@ if (isset($_POST['submit']))
// Generate page // Generate page
// //
$sql = "SELECT group_id, group_name $sql = "SELECT group_id, group_name
FROM ". BB_GROUPS ." FROM " . BB_GROUPS . "
WHERE group_single_user = 0 WHERE group_single_user = 0
ORDER BY group_name ORDER BY group_name
"; ";
$groups = array('-- '. $lang['ALL_USERS'] .' --' => -1); $groups = array('-- ' . $lang['ALL_USERS'] . ' --' => -1);
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$groups[$row['group_name']] = $row['group_id']; $groups[$row['group_name']] = $row['group_id'];
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GENERAL']['PHP_INFO'] = basename(__FILE__); $module['GENERAL']['PHP_INFO'] = basename(__FILE__);
return; return;
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['USERS']['RANKS'] = basename(__FILE__); $module['USERS']['RANKS'] = basename(__FILE__);
return; return;
} }
@ -10,33 +9,23 @@ require('./pagestart.php');
$_POST['special_rank'] = 1; $_POST['special_rank'] = 1;
$_POST['min_posts'] = -1; $_POST['min_posts'] = -1;
if (isset($_GET['mode']) || isset($_POST['mode'])) if (isset($_GET['mode']) || isset($_POST['mode'])) {
{
$mode = isset($_GET['mode']) ? $_GET['mode'] : $_POST['mode']; $mode = isset($_GET['mode']) ? $_GET['mode'] : $_POST['mode'];
} } else {
else
{
// //
// These could be entered via a form button // These could be entered via a form button
// //
if (isset($_POST['add'])) if (isset($_POST['add'])) {
{
$mode = 'add'; $mode = 'add';
} } elseif (isset($_POST['save'])) {
elseif (isset($_POST['save']))
{
$mode = 'save'; $mode = 'save';
} } else {
else
{
$mode = ''; $mode = '';
} }
} }
if ($mode != '') if ($mode != '') {
{ if ($mode == 'edit' || $mode == 'add') {
if ($mode == 'edit' || $mode == 'add')
{
// //
// They want to add a new rank, show the form. // They want to add a new rank, show the form.
// //
@ -44,24 +33,19 @@ if ($mode != '')
$s_hidden_fields = ''; $s_hidden_fields = '';
if ($mode == 'edit') if ($mode == 'edit') {
{ if (empty($rank_id)) {
if (empty($rank_id))
{
bb_die($lang['MUST_SELECT_RANK']); bb_die($lang['MUST_SELECT_RANK']);
} }
$sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_id = $rank_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not obtain ranks data #1'); bb_die('Could not obtain ranks data #1');
} }
$rank_info = DB()->sql_fetchrow($result); $rank_info = DB()->sql_fetchrow($result);
$s_hidden_fields .= '<input type="hidden" name="id" value="'. $rank_id .'" />'; $s_hidden_fields .= '<input type="hidden" name="id" value="' . $rank_id . '" />';
} } else {
else
{
$rank_info['rank_special'] = 0; $rank_info['rank_special'] = 0;
} }
@ -79,14 +63,12 @@ if ($mode != '')
'MINIMUM' => ($rank_is_special) ? '' : $rank_info['rank_min'], 'MINIMUM' => ($rank_is_special) ? '' : $rank_info['rank_min'],
'IMAGE' => !empty($rank_info['rank_image']) ? $rank_info['rank_image'] : 'styles/images/ranks/rank_image.png', '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'] : '', 'STYLE' => !empty($rank_info['rank_style']) ? $rank_info['rank_style'] : '',
'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '<img src="../'. $rank_info['rank_image'] .'" />' : '', 'IMAGE_DISPLAY' => !empty($rank_info['rank_image']) ? '<img src="../' . $rank_info['rank_image'] . '" />' : '',
'S_RANK_ACTION' => "admin_ranks.php", 'S_RANK_ACTION' => "admin_ranks.php",
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } elseif ($mode == 'save') {
elseif ($mode == 'save')
{
// //
// Ok, they sent us our info, let's update it. // Ok, they sent us our info, let's update it.
// //
@ -94,17 +76,15 @@ if ($mode != '')
$rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : 0; $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : 0;
$rank_title = (isset($_POST['title'])) ? trim($_POST['title']) : ''; $rank_title = (isset($_POST['title'])) ? trim($_POST['title']) : '';
$rank_style = (isset($_POST['style'])) ? trim($_POST['style']) : ''; $rank_style = (isset($_POST['style'])) ? trim($_POST['style']) : '';
$special_rank = ($_POST['special_rank'] == 1) ? TRUE : 0; $special_rank = ($_POST['special_rank'] == 1) ? true : 0;
$min_posts = (isset($_POST['min_posts'])) ? intval($_POST['min_posts']) : -1; $min_posts = (isset($_POST['min_posts'])) ? intval($_POST['min_posts']) : -1;
$rank_image = ((isset($_POST['rank_image']))) ? trim($_POST['rank_image']) : ''; $rank_image = ((isset($_POST['rank_image']))) ? trim($_POST['rank_image']) : '';
if ($rank_title == '') if ($rank_title == '') {
{
bb_die($lang['MUST_SELECT_RANK']); bb_die($lang['MUST_SELECT_RANK']);
} }
if ($special_rank == 1) if ($special_rank == 1) {
{
$max_posts = -1; $max_posts = -1;
$min_posts = -1; $min_posts = -1;
} }
@ -112,44 +92,36 @@ if ($mode != '')
// //
// The rank image has to be a jpg, gif or png // The rank image has to be a jpg, gif or png
// //
if ($rank_image != '') if ($rank_image != '') {
{ if (!preg_match('/(\.gif|\.png|\.jpg)$/is', $rank_image)) {
if (!preg_match('/(\.gif|\.png|\.jpg)$/is', $rank_image))
{
$rank_image = ''; $rank_image = '';
} }
} }
if ($rank_id) if ($rank_id) {
{ if (!$special_rank) {
if (!$special_rank)
{
$sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die($lang['NO_UPDATE_RANKS']); bb_die($lang['NO_UPDATE_RANKS']);
} }
} }
$sql = "UPDATE " . BB_RANKS . " $sql = "UPDATE " . BB_RANKS . "
SET rank_title = '". DB()->escape($rank_title) ."', SET rank_title = '" . DB()->escape($rank_title) . "',
rank_special = $special_rank, rank_special = $special_rank,
rank_min = $min_posts, rank_min = $min_posts,
rank_image = '". DB()->escape($rank_image) . "', rank_image = '" . DB()->escape($rank_image) . "',
rank_style = '". DB()->escape($rank_style) ."' rank_style = '" . DB()->escape($rank_style) . "'
WHERE rank_id = $rank_id"; WHERE rank_id = $rank_id";
$message = $lang['RANK_UPDATED']; $message = $lang['RANK_UPDATED'];
} } else {
else
{
$sql = "INSERT INTO " . BB_RANKS . " (rank_title, rank_special, rank_min, rank_image, rank_style) $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) ."')"; 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)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not update / insert into ranks table'); bb_die('Could not update / insert into ranks table');
} }
@ -158,59 +130,44 @@ if ($mode != '')
$datastore->update('ranks'); $datastore->update('ranks');
bb_die($message); bb_die($message);
} } elseif ($mode == 'delete') {
elseif ($mode == 'delete')
{
// //
// Ok, they want to delete their rank // Ok, they want to delete their rank
// //
if (isset($_POST['id']) || isset($_GET['id'])) if (isset($_POST['id']) || isset($_GET['id'])) {
{
$rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : intval($_GET['id']); $rank_id = (isset($_POST['id'])) ? intval($_POST['id']) : intval($_GET['id']);
} } else {
else
{
$rank_id = 0; $rank_id = 0;
} }
if ($rank_id) if ($rank_id) {
{
$sql = "DELETE FROM " . BB_RANKS . " WHERE rank_id = $rank_id"; $sql = "DELETE FROM " . BB_RANKS . " WHERE rank_id = $rank_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not delete rank data'); bb_die('Could not delete rank data');
} }
$sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id"; $sql = "UPDATE " . BB_USERS . " SET user_rank = 0 WHERE user_rank = $rank_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die($lang['NO_UPDATE_RANKS']); 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>')); 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 {
else
{
bb_die($lang['MUST_SELECT_RANK']); bb_die($lang['MUST_SELECT_RANK']);
} }
} } else {
else
{
bb_die('Invalid mode'); bb_die('Invalid mode');
} }
} } else {
else
{
// //
// Show the default page // Show the default page
// //
$sql = "SELECT * FROM " . BB_RANKS . " ORDER BY rank_min, rank_title"; $sql = "SELECT * FROM " . BB_RANKS . " ORDER BY rank_min, rank_title";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not obtain ranks data #2'); bb_die('Could not obtain ranks data #2');
} }
$rank_count = DB()->num_rows($result); $rank_count = DB()->num_rows($result);
@ -221,15 +178,13 @@ else
'S_RANKS_ACTION' => "admin_ranks.php", 'S_RANKS_ACTION' => "admin_ranks.php",
)); ));
for ($i = 0; $i < $rank_count; $i++) for ($i = 0; $i < $rank_count; $i++) {
{
$rank = $rank_rows[$i]['rank_title']; $rank = $rank_rows[$i]['rank_title'];
$special_rank = $rank_rows[$i]['rank_special']; $special_rank = $rank_rows[$i]['rank_special'];
$rank_id = $rank_rows[$i]['rank_id']; $rank_id = $rank_rows[$i]['rank_id'];
$rank_min = $rank_rows[$i]['rank_min']; $rank_min = $rank_rows[$i]['rank_min'];
if ($special_rank == 1) if ($special_rank == 1) {
{
$rank_min = $rank_max = '-'; $rank_min = $rank_max = '-';
} }
@ -241,7 +196,7 @@ else
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'RANK' => $rank, 'RANK' => $rank,
'STYLE' => $rank_rows[$i]['rank_style'], 'STYLE' => $rank_rows[$i]['rank_style'],
'IMAGE_DISPLAY' => ($rank_rows[$i]['rank_image']) ? '<img src="../'. $rank_rows[$i]['rank_image'] .'" />' : '', 'IMAGE_DISPLAY' => ($rank_rows[$i]['rank_image']) ? '<img src="../' . $rank_rows[$i]['rank_image'] . '" />' : '',
'SPECIAL_RANK' => $rank_is_special, 'SPECIAL_RANK' => $rank_is_special,
'RANK_MIN' => $rank_min, 'RANK_MIN' => $rank_min,

View file

@ -1,15 +1,18 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{ if (IS_SUPER_ADMIN) {
if (IS_SUPER_ADMIN) $module['GENERAL']['REBUILD_SEARCH_INDEX'] = basename(__FILE__); $module['GENERAL']['REBUILD_SEARCH_INDEX'] = basename(__FILE__);
}
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
if (!IS_SUPER_ADMIN) bb_die($lang['NOT_ADMIN']); 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_PROCESSED', 1); // when a batch of posts has been processed
@ -23,26 +26,24 @@ $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_data = get_rebuild_session_details('last', 'all');
$last_session_id = (int) $last_session_data['rebuild_session_id']; $last_session_id = (int)$last_session_data['rebuild_session_id'];
$max_post_id = get_latest_post_id(); $max_post_id = get_latest_post_id();
$start_time = TIMENOW; $start_time = TIMENOW;
$mode = (string) $_REQUEST['mode']; $mode = (string)$_REQUEST['mode'];
// check if the user has choosen to stop processing // check if the user has choosen to stop processing
if (isset($_REQUEST['cancel_button'])) if (isset($_REQUEST['cancel_button'])) {
{
// update the rebuild_status // update the rebuild_status
if ($last_session_id) if ($last_session_id) {
{
DB()->query(" DB()->query("
UPDATE ". BB_SEARCH_REBUILD ." SET UPDATE " . BB_SEARCH_REBUILD . " SET
rebuild_session_status = ". REBUILD_SEARCH_ABORTED ." rebuild_session_status = " . REBUILD_SEARCH_ABORTED . "
WHERE rebuild_session_id = $last_session_id 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 // from which post to start processing
@ -52,90 +53,75 @@ $start = abs(intval($_REQUEST['start']));
$total_posts = get_total_posts(); $total_posts = get_total_posts();
// clear the search tables and clear mode (delete or truncate) // 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 // 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; $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; $session_posts_processed = ($mode == 'refresh') ? get_processed_posts('session') : 0;
// find how many posts aren't processed // find how many posts aren't processed
$total_posts_processing = $total_posts - $total_posts_processed; $total_posts_processing = $total_posts - $total_posts_processed;
// how many posts to process in this session // how many posts to process in this session
if ($session_posts_processing = intval($_REQUEST['session_posts_processing'])) if ($session_posts_processing = intval($_REQUEST['session_posts_processing'])) {
{ if ($mode == 'submit') {
if ($mode == 'submit')
{
// check if we passed over total_posts just after submitting // check if we passed over total_posts just after submitting
if ($session_posts_processing + $total_posts_processed > $total_posts) if ($session_posts_processing + $total_posts_processed > $total_posts) {
{
$session_posts_processing = $total_posts - $total_posts_processed; $session_posts_processing = $total_posts - $total_posts_processed;
} }
} }
// correct it when posts are deleted during processing // correct it when posts are deleted during processing
$session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing; $session_posts_processing = ($session_posts_processing > $total_posts) ? $total_posts : $session_posts_processing;
} } else {
else
{
// if we have finished, get all the posts, else only the remaining // if we have finished, get all the posts, else only the remaining
$session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing; $session_posts_processing = (!$total_posts_processing) ? $total_posts : $total_posts_processing;
} }
// how many posts to process per cycle // 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 // correct the post_limit when we pass over it
if ( $session_posts_processed + $post_limit > $session_posts_processing ) if ($session_posts_processed + $post_limit > $session_posts_processing) {
{
$post_limit = $session_posts_processing - $session_posts_processed; $post_limit = $session_posts_processing - $session_posts_processed;
} }
// how much time to wait per cycle // how much time to wait per cycle
if (isset($_REQUEST['time_limit'])) if (isset($_REQUEST['time_limit'])) {
{ $time_limit = (int)$_REQUEST['time_limit'];
$time_limit = (int) $_REQUEST['time_limit']; } else {
}
else
{
$time_limit = $def_time_limit; $time_limit = $def_time_limit;
$time_limit_explain = $lang['TIME_LIMIT_EXPLAIN']; $time_limit_explain = $lang['TIME_LIMIT_EXPLAIN'];
// check for safe mode timeout // check for safe mode timeout
if ( ini_get('safe_mode') ) if (ini_get('safe_mode')) {
{
// get execution time // get execution time
$max_execution_time = ini_get('max_execution_time'); $max_execution_time = ini_get('max_execution_time');
$time_limit_explain .= '<br />' . sprintf($lang['TIME_LIMIT_EXPLAIN_SAFE'], $max_execution_time); $time_limit_explain .= '<br />' . sprintf($lang['TIME_LIMIT_EXPLAIN_SAFE'], $max_execution_time);
if ( $time_limit > $max_execution_time ) if ($time_limit > $max_execution_time) {
{
$time_limit = $max_execution_time; $time_limit = $max_execution_time;
} }
} }
// check for webserver timeout (IE returns null) // check for webserver timeout (IE returns null)
if ( isset($_SERVER["HTTP_KEEP_ALIVE"]) ) if (isset($_SERVER["HTTP_KEEP_ALIVE"])) {
{
// get webserver timeout // get webserver timeout
$webserver_timeout = intval($_SERVER["HTTP_KEEP_ALIVE"]); $webserver_timeout = intval($_SERVER["HTTP_KEEP_ALIVE"]);
$time_limit_explain .= '<br />' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout); $time_limit_explain .= '<br />' . sprintf($lang['TIME_LIMIT_EXPLAIN_WEBSERVER'], $webserver_timeout);
if ( $time_limit > $webserver_timeout ) if ($time_limit > $webserver_timeout) {
{
$time_limit = $webserver_timeout; $time_limit = $webserver_timeout;
} }
} }
} }
// how much time to wait between page refreshes // 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 // check if the user gave wrong input
if ($mode == 'submit') if ($mode == 'submit') {
{ if (($session_posts_processing || $post_limit || $refresh_rate || $time_limit) <= 0) {
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>'));
{
bb_die($lang['WRONG_INPUT'] .'<br /><br />'. sprintf($lang['CLICK_RETURN_REBUILD_SEARCH'], '<a href="admin_rebuild_search.php">', '</a>'));
} }
} }
@ -143,11 +129,9 @@ if ($mode == 'submit')
set_time_limit($time_limit + 20); set_time_limit($time_limit + 20);
// check if we are should start processing // check if we are should start processing
if ($mode == 'submit' || $mode == 'refresh') if ($mode == 'submit' || $mode == 'refresh') {
{
// check if we are in the beginning of processing // check if we are in the beginning of processing
if ($start == 0) if ($start == 0) {
{
$last_session_data = get_empty_last_session_data(); $last_session_data = get_empty_last_session_data();
clear_search_tables($clear_search); clear_search_tables($clear_search);
} }
@ -161,12 +145,12 @@ if ($mode == 'submit' || $mode == 'refresh')
pt.post_id, pt.post_text, pt.post_id, pt.post_text,
IF(p.post_id = t.topic_first_post_id, t.topic_title, '') AS post_subject IF(p.post_id = t.topic_first_post_id, t.topic_title, '') AS post_subject
FROM FROM
". BB_POSTS_TEXT ." pt, " . BB_POSTS_TEXT . " pt,
". BB_POSTS ." p, " . BB_POSTS . " p,
". BB_TOPICS ." t " . BB_TOPICS . " t
WHERE p.post_id = pt.post_id WHERE p.post_id = pt.post_id
AND t.topic_id = p.topic_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 AND pt.post_id >= $start
ORDER BY pt.post_id ASC ORDER BY pt.post_id ASC
LIMIT $post_limit LIMIT $post_limit
@ -177,8 +161,7 @@ if ($mode == 'submit' || $mode == 'refresh')
$timer_expired = false; $timer_expired = false;
$words_sql = array(); $words_sql = array();
while (($row = DB()->fetch_next($result)) && !$timer_expired) while (($row = DB()->fetch_next($result)) && !$timer_expired) {
{
set_time_limit(600); set_time_limit(600);
$start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id; $start_post_id = ($num_rows == 0) ? $row['post_id'] : $start_post_id;
$end_post_id = $row['post_id']; $end_post_id = $row['post_id'];
@ -187,7 +170,7 @@ if ($mode == 'submit' || $mode == 'refresh')
$s_post_text = str_replace('\n', "\n", $row['post_text']); $s_post_text = str_replace('\n', "\n", $row['post_text']);
$s_post_subject = str_replace('\n', "\n", $row['post_subject']); $s_post_subject = str_replace('\n', "\n", $row['post_subject']);
$words_sql[] = array( $words_sql[] = array(
'post_id' => (int) $row['post_id'], 'post_id' => (int)$row['post_id'],
'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true), 'search_words' => add_search_words($row['post_id'], stripslashes($s_post_text), stripslashes($s_post_subject), true),
); );
@ -196,46 +179,43 @@ if ($mode == 'submit' || $mode == 'refresh')
} }
// Store search words // Store search words
if ($words_sql) if ($words_sql) {
{ DB()->query("REPLACE INTO " . BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql));
DB()->query("REPLACE INTO ". BB_POSTS_SEARCH . DB()->build_array('MULTI_INSERT', $words_sql));
} }
// find how much time the last cycle took // find how much time the last cycle took
$last_cycle_time = intval(TIMENOW - $start_time); $last_cycle_time = intval(TIMENOW - $start_time);
// check if we had any data // check if we had any data
if ($num_rows != 0) if ($num_rows != 0) {
{ if ($mode == 'submit') {
if ($mode == 'submit')
{
// insert a new session entry // insert a new session entry
$args = DB()->build_array('INSERT', array( $args = DB()->build_array('INSERT', array(
'end_post_id' => (int) $end_post_id, 'end_post_id' => (int)$end_post_id,
'end_time' => (int) TIMENOW, 'end_time' => (int)TIMENOW,
'last_cycle_time' => (int) $last_cycle_time, 'last_cycle_time' => (int)$last_cycle_time,
'session_time' => (int) $last_cycle_time, 'session_time' => (int)$last_cycle_time,
'session_posts' => (int) $num_rows, 'session_posts' => (int)$num_rows,
'session_cycles' => (int) 1, 'session_cycles' => (int)1,
'start_post_id' => (int) $start_post_id, 'start_post_id' => (int)$start_post_id,
'start_time' => (int) $start_time, 'start_time' => (int)$start_time,
'search_size' => (int) $search_tables_size, 'search_size' => (int)$search_tables_size,
'rebuild_session_status' => REBUILD_SEARCH_PROCESSED, 'rebuild_session_status' => REBUILD_SEARCH_PROCESSED,
)); ));
DB()->query("REPLACE INTO ". BB_SEARCH_REBUILD . $args); DB()->query("REPLACE INTO " . BB_SEARCH_REBUILD . $args);
} } else {
else // refresh // refresh
{
// update the last session entry // update the last session entry
DB()->query(" DB()->query("
UPDATE ". BB_SEARCH_REBUILD ." SET UPDATE " . BB_SEARCH_REBUILD . " SET
end_post_id = $end_post_id, end_post_id = $end_post_id,
end_time = ". TIMENOW .", end_time = " . TIMENOW . ",
last_cycle_time = $last_cycle_time, last_cycle_time = $last_cycle_time,
session_time = session_time + $last_cycle_time, session_time = session_time + $last_cycle_time,
session_posts = session_posts + $num_rows, session_posts = session_posts + $num_rows,
session_cycles = session_cycles + 1, session_cycles = session_cycles + 1,
rebuild_session_status = ". REBUILD_SEARCH_PROCESSED ." rebuild_session_status = " . REBUILD_SEARCH_PROCESSED . "
WHERE rebuild_session_id = $last_session_id WHERE rebuild_session_id = $last_session_id
"); ");
} }
@ -253,15 +233,14 @@ if ($mode == 'submit' || $mode == 'refresh')
$total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']); $total_posts_processed = get_total_posts('before', $last_session_data['end_post_id']);
$total_posts = get_total_posts(); $total_posts = get_total_posts();
if ( $session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts ) if ($session_posts_processed < $session_posts_processing && $total_posts_processed < $total_posts) {
{ $form_parameters = '&start=' . ($end_post_id + 1);
$form_parameters = '&start='.($end_post_id+1); $form_parameters .= '&session_posts_processing=' . $session_posts_processing;
$form_parameters .= '&session_posts_processing='.$session_posts_processing; $form_parameters .= '&post_limit=' . $post_limit;
$form_parameters .= '&post_limit='.$post_limit; $form_parameters .= '&time_limit=' . $time_limit;
$form_parameters .= '&time_limit='.$time_limit; $form_parameters .= '&refresh_rate=' . $refresh_rate;
$form_parameters .= '&refresh_rate='.$refresh_rate;
$form_action = 'admin_rebuild_search.php'.'?mode=refresh'.$form_parameters; $form_action = 'admin_rebuild_search.php' . '?mode=refresh' . $form_parameters;
$next_button = $lang['NEXT']; $next_button = $lang['NEXT'];
$progress_bar_img = $images['progress_bar']; $progress_bar_img = $images['progress_bar'];
@ -273,19 +252,19 @@ if ($mode == 'submit' || $mode == 'refresh')
$template->assign_vars(array( $template->assign_vars(array(
'CANCEL_BUTTON' => true, 'CANCEL_BUTTON' => true,
)); ));
} } else {
else // end of processing // end of processing
{
$form_action = "admin_rebuild_search.php"; $form_action = "admin_rebuild_search.php";
$next_button = $lang['FINISHED']; $next_button = $lang['FINISHED'];
$progress_bar_img = $images['progress_bar_full']; $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 .= ($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 .= ($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 // if we have processed all the db posts we need to update the rebuild_status
DB()->query("UPDATE ". BB_SEARCH_REBUILD ." SET DB()->query("UPDATE " . BB_SEARCH_REBUILD . " SET
rebuild_session_status = ". REBUILD_SEARCH_COMPLETED ." rebuild_session_status = " . REBUILD_SEARCH_COMPLETED . "
WHERE rebuild_session_id = $last_session_id WHERE rebuild_session_id = $last_session_id
AND end_post_id = $max_post_id AND end_post_id = $max_post_id
"); ");
@ -293,8 +272,7 @@ if ($mode == 'submit' || $mode == 'refresh')
// optimize all search tables when finished // optimize all search tables when finished
$table_ary = array(BB_POSTS_SEARCH); $table_ary = array(BB_POSTS_SEARCH);
foreach ($table_ary as $table) foreach ($table_ary as $table) {
{
DB()->query("ANALYZE TABLE $table"); DB()->query("ANALYZE TABLE $table");
DB()->query("OPTIMIZE TABLE $table"); DB()->query("OPTIMIZE TABLE $table");
} }
@ -312,8 +290,7 @@ if ($mode == 'submit' || $mode == 'refresh')
// calculate the final (estimated) values // calculate the final (estimated) values
$final_search_tables_size = ''; $final_search_tables_size = '';
if ($search_tables_size) if ($search_tables_size) {
{
$start_search_tables_size = $last_session_data['search_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)); $final_search_tables_size = $start_search_tables_size + round(($search_tables_size - $start_search_tables_size) * (100 / $session_percent));
} }
@ -343,7 +320,7 @@ if ($mode == 'submit' || $mode == 'refresh')
'LAST_CYCLE_TIME' => delta_time(TIMENOW), 'LAST_CYCLE_TIME' => delta_time(TIMENOW),
'SESSION_TIME' => delta_time($last_session_data['start_time']), 'SESSION_TIME' => delta_time($last_session_data['start_time']),
'SESSION_AVERAGE_CYCLE_TIME'=> delta_time($session_average_cycle_time, 0), 'SESSION_AVERAGE_CYCLE_TIME' => delta_time($session_average_cycle_time, 0),
'SESSION_ESTIMATED_TIME' => delta_time($session_estimated_time, 0), 'SESSION_ESTIMATED_TIME' => delta_time($session_estimated_time, 0),
'SEARCH_TABLES_SIZE' => humn_size($search_tables_size), 'SEARCH_TABLES_SIZE' => humn_size($search_tables_size),
@ -358,57 +335,48 @@ if ($mode == 'submit' || $mode == 'refresh')
'S_REBUILD_SEARCH_ACTION' => $form_action, 'S_REBUILD_SEARCH_ACTION' => $form_action,
)); ));
} } else {
else // show the input page // show the input page
{
// create the page // create the page
// used only with the select input // used only with the select input
$post_limit_hidden = ( $def_post_limit > $total_posts ) ? $total_posts : $def_post_limit; $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="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="total_posts_stored" value="' . $total_posts . '" />';
$next_start_post_id = 0; $next_start_post_id = 0;
$last_saved_processing = ''; $last_saved_processing = '';
$clear_search_disabled = ''; $clear_search_disabled = '';
if ($last_session_data['rebuild_session_id']) if ($last_session_data['rebuild_session_id']) {
{
$last_saved_post_id = $last_session_data['end_post_id']; $last_saved_post_id = $last_session_data['end_post_id'];
$next_start_post_id = $last_saved_post_id + 1; $next_start_post_id = $last_saved_post_id + 1;
$last_saved_date = bb_date($last_session_data['end_time']); $last_saved_date = bb_date($last_session_data['end_time']);
// check our last status // check our last status
if ( $last_session_data['rebuild_session_status'] == REBUILD_SEARCH_PROCESSED ) 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); $last_saved_processing = sprintf($lang['INFO_PROCESSING_STOPPED'], $last_saved_post_id, $total_posts_processed, $last_saved_date);
$clear_search_disabled = 'disabled="disabled"'; $clear_search_disabled = 'disabled="disabled"';
$template->assign_block_vars("start_select_input", array()); $template->assign_block_vars("start_select_input", array());
} } elseif ($last_session_data['rebuild_session_status'] == REBUILD_SEARCH_ABORTED) {
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); $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 // check if the interrupted cycle has finished
if ( TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time'] ) if (TIMENOW - $last_session_data['end_time'] < $last_session_data['last_cycle_time']) {
{ $last_saved_processing .= '<br />' . $lang['INFO_PROCESSING_ABORTED_SOON'];
$last_saved_processing .= '<br />'.$lang['INFO_PROCESSING_ABORTED_SOON'];
} }
$clear_search_disabled = 'disabled="disabled"'; $clear_search_disabled = 'disabled="disabled"';
$template->assign_block_vars("start_select_input", array()); $template->assign_block_vars("start_select_input", array());
} } else {
else // when finished // when finished
{
if ( $last_session_data['end_post_id'] < $max_post_id ) 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)); $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"'; $clear_search_disabled = 'disabled="disabled"';
$template->assign_block_vars("start_select_input", array()); $template->assign_block_vars("start_select_input", array());
} } else {
else
{
$last_saved_processing = sprintf($lang['INFO_PROCESSING_FINISHED'], $total_posts, $last_saved_date); $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());
@ -416,9 +384,7 @@ else // show the input page
} }
$template->assign_block_vars("last_saved_info", array()); $template->assign_block_vars("last_saved_info", array());
} } else {
else
{
$template->assign_block_vars("start_text_input", array()); $template->assign_block_vars("start_text_input", array());
} }
@ -449,31 +415,30 @@ print_page('admin_rebuild_search.tpl', 'admin');
// //
// Functions // Functions
// //
function get_db_sizes () function get_db_sizes()
{ {
$search_data_size = $search_index_size = 0; $search_data_size = $search_index_size = 0;
$search_table_like = DB()->escape(BB_POSTS_SEARCH); $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) foreach (DB()->fetch_rowset($sql) as $row) {
{
$search_data_size += $row['Data_length']; $search_data_size += $row['Data_length'];
$search_index_size += $row['Index_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 // 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( return array(
'rebuild_session_id' => 0, 'rebuild_session_id' => 0,
@ -493,21 +458,17 @@ function get_empty_last_session_data ()
// get some or all of the rebuild details of a specific session or of the last session // 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 // $id is the id or the 'last' id
// $details is one of the fields or 'all' of them // $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') if ($id != 'last') {
{ $sql = "SELECT * FROM " . BB_SEARCH_REBUILD . " WHERE rebuild_session_id = $id";
$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";
else
{
$sql = "SELECT * FROM ". BB_SEARCH_REBUILD ." ORDER BY rebuild_session_id DESC LIMIT 1";
} }
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{
$session_details = ($details == 'all') ? $row : $row[$details]; $session_details = ($details == 'all') ? $row : $row[$details];
} }
@ -517,52 +478,44 @@ function get_rebuild_session_details ($id, $details = 'all')
// get the number of processed posts in the last session or in all sessions // get the number of processed posts in the last session or in all sessions
// 'total' to get the sum of posts of all sessions // 'total' to get the sum of posts of all sessions
// 'session' to get the posts of the last session // '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') if ($mode == 'total') {
{ $sql = "SELECT SUM(session_posts) as posts FROM " . BB_SEARCH_REBUILD;
$sql = "SELECT SUM(session_posts) as posts FROM ". BB_SEARCH_REBUILD;
$row = DB()->fetch_row($sql); $row = DB()->fetch_row($sql);
} } else {
else
{
$row['posts'] = $last_session_data['session_posts']; $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 // how many posts are in the db before or after a specific post_id
// after/before require and the 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) if ($post_id) {
{
$sql = "SELECT COUNT(post_id) as total_posts FROM " . BB_POSTS_TEXT . " $sql = "SELECT COUNT(post_id) as total_posts FROM " . BB_POSTS_TEXT . "
WHERE post_id " . (($mode == 'after') ? '>= ' : '<= ' ) . (int) $post_id; WHERE post_id " . (($mode == 'after') ? '>= ' : '<= ') . (int)$post_id;
} } else {
else
{
$sql = "SELECT COUNT(*) as total_posts FROM " . BB_POSTS_TEXT; $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) if ($mode) {
{
$table_ary = array(BB_POSTS_SEARCH); $table_ary = array(BB_POSTS_SEARCH);
foreach ($table_ary as $table) foreach ($table_ary as $table) {
{
$sql = (($mode == 1) ? "DELETE FROM " : "TRUNCATE TABLE ") . $table; $sql = (($mode == 1) ? "DELETE FROM " : "TRUNCATE TABLE ") . $table;
DB()->query($sql); DB()->query($sql);
} }
@ -582,11 +535,9 @@ function create_percent_color($percent)
'b' => array(51, 85), 'b' => array(51, 85),
); );
foreach ($percent_ary as $key => $value) foreach ($percent_ary as $key => $value) {
{ if ($percent <= $value[1]) {
if ( $percent <= $value[1] ) $percent_color = create_color($key, round(200 - ($percent - $value[0]) * (200 / ($value[1] - $value[0]))));
{
$percent_color = create_color($key, round(200-($percent-$value[0])*(200/($value[1]-$value[0]))));
break; break;
} }
} }
@ -597,7 +548,7 @@ function create_percent_color($percent)
// create the hex representation of color // create the hex representation of color
function create_color($mode, $code) 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 // create the percent bar & box
@ -605,16 +556,13 @@ function create_percent_box($box, $percent_color, $percent_width)
{ {
global $template; global $template;
if ($box == 'session') if ($box == 'session') {
{
$template->assign_vars(array( $template->assign_vars(array(
'SESSION_PERCENT_BOX' => true, 'SESSION_PERCENT_BOX' => true,
'SESSION_PERCENT_COLOR' => $percent_color, 'SESSION_PERCENT_COLOR' => $percent_color,
'SESSION_PERCENT_WIDTH' => round($percent_width), 'SESSION_PERCENT_WIDTH' => round($percent_width),
)); ));
} } else {
else
{
$template->assign_vars(array( $template->assign_vars(array(
'TOTAL_PERCENT_BOX' => true, 'TOTAL_PERCENT_BOX' => true,
'TOTAL_PERCENT_COLOR' => $percent_color, 'TOTAL_PERCENT_COLOR' => $percent_color,

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['MODS']['SITEMAP'] = basename(__FILE__); $module['MODS']['SITEMAP'] = basename(__FILE__);
return; return;
} }
@ -21,11 +20,11 @@ if (request_var('submit', '')) {
bb_die('<a href="admin_sitemap.php">' . $lang['GO_BACK'] . '</a>'); 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( $template->assign_vars(array(
'STATIC_SITEMAP' => $di->config->get('static_sitemap'), 'STATIC_SITEMAP' => $di->config->get('static_sitemap'),
'MESSAGE' => (file_exists(INT_DATA_DIR ."sitemap/sitemap.xml")) ? $s_mess : $lang['SITEMAP_NOT_CREATED'], '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,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GENERAL']['SMILIES'] = basename(__FILE__); $module['GENERAL']['SMILIES'] = basename(__FILE__);
return; return;
} }
@ -11,13 +10,10 @@ require('./pagestart.php');
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
// Check to see what mode we should operate in // Check to see what mode we should operate in
if (isset($_POST['mode']) || isset($_GET['mode'])) if (isset($_POST['mode']) || isset($_GET['mode'])) {
{ $mode = (isset($_POST['mode'])) ? $_POST['mode'] : $_GET['mode'];
$mode = ( isset($_POST['mode']) ) ? $_POST['mode'] : $_GET['mode'];
$mode = htmlspecialchars($mode); $mode = htmlspecialchars($mode);
} } else {
else
{
$mode = ''; $mode = '';
} }
@ -26,18 +22,13 @@ $delimeter = '=+:';
// Read a listing of uploaded smilies for use in the add or edit smliey code // Read a listing of uploaded smilies for use in the add or edit smliey code
$dir = opendir(BB_ROOT . $di->config->get('smilies_path')); $dir = opendir(BB_ROOT . $di->config->get('smilies_path'));
while ($file = readdir($dir)) while ($file = readdir($dir)) {
{ if (!is_dir(bb_realpath(BB_ROOT . $di->config->get('smilies_path') . '/' . $file))) {
if (!is_dir(bb_realpath(BB_ROOT . $di->config->get('smilies_path') . '/' . $file)))
{
$img_size = getimagesize(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]) if ($img_size[0] && $img_size[1]) {
{
$smiley_images[] = $file; $smiley_images[] = $file;
} } elseif (preg_match('/.pak$/i', $file)) {
else if (preg_match('/.pak$/i', $file))
{
$smiley_paks[] = $file; $smiley_paks[] = $file;
} }
} }
@ -46,83 +37,64 @@ while ($file = readdir($dir))
closedir($dir); closedir($dir);
// Select main mode // Select main mode
if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) {
{ $smile_pak = (string)request_var('smile_pak', '');
$smile_pak = (string) request_var('smile_pak', ''); $clear_current = (int)request_var('clear_current', '');
$clear_current = (int) request_var('clear_current', ''); $replace_existing = (int)request_var('replace', '');
$replace_existing = (int) request_var('replace', '');
if (!empty($smile_pak)) if (!empty($smile_pak)) {
{
// The user has already selected a smile_pak file.. Import it // The user has already selected a smile_pak file.. Import it
if (!empty($clear_current)) if (!empty($clear_current)) {
{
$sql = "DELETE FROM " . BB_SMILIES; $sql = "DELETE FROM " . BB_SMILIES;
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not delete current smilies'); bb_die('Could not delete current smilies');
} }
$datastore->update('smile_replacements'); $datastore->update('smile_replacements');
} } else {
else $sql = "SELECT code FROM " . BB_SMILIES;
{ if (!$result = DB()->sql_query($sql)) {
$sql = "SELECT code FROM ". BB_SMILIES;
if (!$result = DB()->sql_query($sql))
{
bb_die('Could not get current smilies'); 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++) for ($i = 0; $i < count($cur_smilies); $i++) {
{
$k = $cur_smilies[$i]['code']; $k = $cur_smilies[$i]['code'];
$smiles[$k] = 1; $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)) if (empty($fcontents)) {
{
bb_die('Could not read smiley pak file'); bb_die('Could not read smiley pak file');
} }
for ($i = 0; $i < count($fcontents); $i++) for ($i = 0; $i < count($fcontents); $i++) {
{
$smile_data = explode($delimeter, trim(addslashes($fcontents[$i]))); $smile_data = explode($delimeter, trim(addslashes($fcontents[$i])));
for ($j = 2; $j < count($smile_data); $j++) for ($j = 2; $j < count($smile_data); $j++) {
{
// Replace > and < with the proper html_entities for matching // Replace > and < with the proper html_entities for matching
$smile_data[$j] = str_replace('<', '&lt;', $smile_data[$j]); $smile_data[$j] = str_replace('<', '&lt;', $smile_data[$j]);
$smile_data[$j] = str_replace('>', '&gt;', $smile_data[$j]); $smile_data[$j] = str_replace('>', '&gt;', $smile_data[$j]);
$k = $smile_data[$j]; $k = $smile_data[$j];
if (isset($smiles[$k])) if (isset($smiles[$k])) {
{ if (!empty($replace_existing)) {
if( !empty($replace_existing) )
{
$sql = "UPDATE " . BB_SMILIES . " $sql = "UPDATE " . BB_SMILIES . "
SET smile_url = '" . DB()->escape($smile_data[0]) . "', emoticon = '" . DB()->escape($smile_data[1]) . "' SET smile_url = '" . DB()->escape($smile_data[0]) . "', emoticon = '" . DB()->escape($smile_data[1]) . "'
WHERE code = '" . DB()->escape($smile_data[$j]) . "'"; WHERE code = '" . DB()->escape($smile_data[$j]) . "'";
} } else {
else
{
$sql = ''; $sql = '';
} }
} } else {
else
{
$sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) $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]) . "')"; VALUES('" . DB()->escape($smile_data[$j]) . "', '" . DB()->escape($smile_data[0]) . "', '" . DB()->escape($smile_data[1]) . "')";
} }
if ($sql != '') if ($sql != '') {
{
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not update smilies #1'); bb_die('Could not update smilies #1');
} }
$datastore->update('smile_replacements'); $datastore->update('smile_replacements');
@ -131,15 +103,11 @@ if (isset($_GET['import_pack']) || isset($_POST['import_pack']))
} }
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>')); 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 {
else
{
// Display the script to get the smile_pak cfg file // Display the script to get the smile_pak cfg file
$smile_paks_select = '<select name="smile_pak"><option value="">' . $lang['SELECT_PAK'] . '</option>'; $smile_paks_select = '<select name="smile_pak"><option value="">' . $lang['SELECT_PAK'] . '</option>';
while (list($key, $value) = each($smiley_paks)) while (list($key, $value) = each($smiley_paks)) {
{ if (!empty($value)) {
if (!empty($value))
{
$smile_paks_select .= '<option>' . $value . '</option>'; $smile_paks_select .= '<option>' . $value . '</option>';
} }
} }
@ -155,24 +123,19 @@ if (isset($_GET['import_pack']) || isset($_POST['import_pack']))
'S_HIDDEN_FIELDS' => $hidden_vars, 'S_HIDDEN_FIELDS' => $hidden_vars,
)); ));
} }
} } elseif (isset($_POST['export_pack']) || isset($_GET['export_pack'])) {
else if (isset($_POST['export_pack']) || isset($_GET['export_pack'])) $export_pack = (string)request_var('export_pack', '');
{
$export_pack = (string) request_var('export_pack', '');
if ($export_pack == 'send') if ($export_pack == 'send') {
{
$sql = "SELECT * FROM " . BB_SMILIES; $sql = "SELECT * FROM " . BB_SMILIES;
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get smiley list'); bb_die('Could not get smiley list');
} }
$resultset = DB()->sql_fetchrowset($result); $resultset = DB()->sql_fetchrowset($result);
$smile_pak = ''; $smile_pak = '';
for ($i = 0; $i < count($resultset); $i++) for ($i = 0; $i < count($resultset); $i++) {
{
$smile_pak .= $resultset[$i]['smile_url'] . $delimeter; $smile_pak .= $resultset[$i]['smile_url'] . $delimeter;
$smile_pak .= $resultset[$i]['emoticon'] . $delimeter; $smile_pak .= $resultset[$i]['emoticon'] . $delimeter;
$smile_pak .= $resultset[$i]['code'] . "\n"; $smile_pak .= $resultset[$i]['code'] . "\n";
@ -187,13 +150,10 @@ else if (isset($_POST['export_pack']) || isset($_GET['export_pack']))
} }
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>')); 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>'));
} } elseif (isset($_POST['add']) || isset($_GET['add'])) {
else if (isset($_POST['add']) || isset($_GET['add']))
{
$filename_list = ''; $filename_list = '';
for ($i = 0; $i < count($smiley_images); $i++) for ($i = 0; $i < count($smiley_images); $i++) {
{ $filename_list .= '<option value="' . $smiley_images[$i] . '">' . $smiley_images[$i] . '</option>';
$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" />';
@ -206,19 +166,15 @@ else if (isset($_POST['add']) || isset($_GET['add']))
'S_FILENAME_OPTIONS' => $filename_list, 'S_FILENAME_OPTIONS' => $filename_list,
'S_SMILEY_BASEDIR' => BB_ROOT . $di->config->get('smilies_path') 'S_SMILEY_BASEDIR' => BB_ROOT . $di->config->get('smilies_path')
)); ));
} } elseif ($mode != '') {
else if ( $mode != '' ) switch ($mode) {
{
switch( $mode )
{
case 'delete': case 'delete':
$smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id'];
$smiley_id = intval($smiley_id); $smiley_id = intval($smiley_id);
$sql = "DELETE FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; $sql = "DELETE FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id;
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not delete smiley'); bb_die('Could not delete smiley');
} }
$datastore->update('smile_replacements'); $datastore->update('smile_replacements');
@ -227,33 +183,28 @@ else if ( $mode != '' )
break; break;
case 'edit': case 'edit':
$smiley_id = ( !empty($_POST['id']) ) ? $_POST['id'] : $_GET['id']; $smiley_id = (!empty($_POST['id'])) ? $_POST['id'] : $_GET['id'];
$smiley_id = intval($smiley_id); $smiley_id = intval($smiley_id);
$sql = "SELECT * FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id; $sql = "SELECT * FROM " . BB_SMILIES . " WHERE smilies_id = " . $smiley_id;
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not obtain emoticon information'); bb_die('Could not obtain emoticon information');
} }
$smile_data = DB()->sql_fetchrow($result); $smile_data = DB()->sql_fetchrow($result);
$filename_list = ''; $filename_list = '';
for ($i = 0; $i < count($smiley_images); $i++) for ($i = 0; $i < count($smiley_images); $i++) {
{ if ($smiley_images[$i] == $smile_data['smile_url']) {
if ($smiley_images[$i] == $smile_data['smile_url'])
{
$smiley_selected = 'selected="selected"'; $smiley_selected = 'selected="selected"';
$smiley_edit_img = $smiley_images[$i]; $smiley_edit_img = $smiley_images[$i];
} } else {
else
{
$smiley_selected = ''; $smiley_selected = '';
} }
$filename_list .= '<option value="' . $smiley_images[$i] . '"' . $smiley_selected . '>' . $smiley_images[$i] . '</option>'; $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( $template->assign_vars(array(
'TPL_SMILE_EDIT' => true, 'TPL_SMILE_EDIT' => true,
@ -269,15 +220,14 @@ else if ( $mode != '' )
break; break;
case 'save': case 'save':
$smile_code = ( isset($_POST['smile_code']) ) ? trim($_POST['smile_code']) : trim($_GET['smile_code']); $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 = (isset($_POST['smile_url'])) ? trim($_POST['smile_url']) : trim($_GET['smile_url']);
$smile_url = bb_ltrim(basename($smile_url), "'"); $smile_url = bb_ltrim(basename($smile_url), "'");
$smile_emotion = ( isset($_POST['smile_emotion']) ) ? trim($_POST['smile_emotion']) : trim($_GET['smile_emotion']); $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']); $smile_id = (isset($_POST['smile_id'])) ? intval($_POST['smile_id']) : intval($_GET['smile_id']);
// If no code was entered complain // If no code was entered complain
if ($smile_code == '' || $smile_url == '') if ($smile_code == '' || $smile_url == '') {
{
bb_die($lang['FIELDS_EMPTY']); bb_die($lang['FIELDS_EMPTY']);
} }
@ -289,8 +239,7 @@ else if ( $mode != '' )
$sql = "UPDATE " . BB_SMILIES . " $sql = "UPDATE " . BB_SMILIES . "
SET code = '" . DB()->escape($smile_code) . "', smile_url = '" . DB()->escape($smile_url) . "', emoticon = '" . DB()->escape($smile_emotion) . "' SET code = '" . DB()->escape($smile_code) . "', smile_url = '" . DB()->escape($smile_url) . "', emoticon = '" . DB()->escape($smile_emotion) . "'
WHERE smilies_id = $smile_id"; WHERE smilies_id = $smile_id";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not update smilies #2'); bb_die('Could not update smilies #2');
} }
$datastore->update('smile_replacements'); $datastore->update('smile_replacements');
@ -299,17 +248,16 @@ else if ( $mode != '' )
break; break;
case 'savenew': case 'savenew':
$smile_code = ( isset($_POST['smile_code']) ) ? $_POST['smile_code'] : $_GET['smile_code']; $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 = (isset($_POST['smile_url'])) ? $_POST['smile_url'] : $_GET['smile_url'];
$smile_url = bb_ltrim(basename($smile_url), "'"); $smile_url = bb_ltrim(basename($smile_url), "'");
$smile_emotion = ( isset($_POST['smile_emotion']) ) ? $_POST['smile_emotion'] : $_GET['smile_emotion']; $smile_emotion = (isset($_POST['smile_emotion'])) ? $_POST['smile_emotion'] : $_GET['smile_emotion'];
$smile_code = trim($smile_code); $smile_code = trim($smile_code);
$smile_url = trim($smile_url); $smile_url = trim($smile_url);
$smile_emotion = trim($smile_emotion); $smile_emotion = trim($smile_emotion);
// If no code was entered complain // If no code was entered complain
if ($smile_code == '' || $smile_url == '') if ($smile_code == '' || $smile_url == '') {
{
bb_die($lang['FIELDS_EMPTY']); bb_die($lang['FIELDS_EMPTY']);
} }
@ -321,8 +269,7 @@ else if ( $mode != '' )
$sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon) $sql = "INSERT INTO " . BB_SMILIES . " (code, smile_url, emoticon)
VALUES ('" . DB()->escape($smile_code) . "', '" . DB()->escape($smile_url) . "', '" . DB()->escape($smile_emotion) . "')"; VALUES ('" . DB()->escape($smile_code) . "', '" . DB()->escape($smile_url) . "', '" . DB()->escape($smile_emotion) . "')";
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not insert new smiley'); bb_die('Could not insert new smiley');
} }
$datastore->update('smile_replacements'); $datastore->update('smile_replacements');
@ -330,13 +277,10 @@ else if ( $mode != '' )
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>')); 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; break;
} }
} } else {
else
{
$sql = "SELECT * FROM " . BB_SMILIES; $sql = "SELECT * FROM " . BB_SMILIES;
$result = DB()->sql_query($sql); $result = DB()->sql_query($sql);
if (!$result) if (!$result) {
{
bb_die('Could not obtain smileys from database'); bb_die('Could not obtain smileys from database');
} }
@ -349,8 +293,7 @@ else
)); ));
// Loop throuh the rows of smilies setting block vars for the template // Loop throuh the rows of smilies setting block vars for the template
for ($i = 0; $i < count($smilies); $i++) for ($i = 0; $i < count($smilies); $i++) {
{
// Replace htmlentites for < and > with actual character // Replace htmlentites for < and > with actual character
$smilies[$i]['code'] = str_replace('&lt;', '<', $smilies[$i]['code']); $smilies[$i]['code'] = str_replace('&lt;', '<', $smilies[$i]['code']);
$smilies[$i]['code'] = str_replace('&gt;', '>', $smilies[$i]['code']); $smilies[$i]['code'] = str_replace('&gt;', '>', $smilies[$i]['code']);
@ -360,12 +303,12 @@ else
$template->assign_block_vars('smiles', array( $template->assign_block_vars('smiles', array(
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'SMILEY_IMG' => BB_ROOT . $di->config->get('smilies_path') .'/'. $smilies[$i]['smile_url'], 'SMILEY_IMG' => BB_ROOT . $di->config->get('smilies_path') . '/' . $smilies[$i]['smile_url'],
'CODE' => $smilies[$i]['code'], 'CODE' => $smilies[$i]['code'],
'EMOT' => $smilies[$i]['emoticon'], 'EMOT' => $smilies[$i]['emoticon'],
'U_SMILEY_EDIT' => "admin_smilies.php?mode=edit&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'], 'U_SMILEY_DELETE' => "admin_smilies.php?mode=delete&amp;id=" . $smilies[$i]['smilies_id'],
)); ));
} }
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GENERAL']['TERMS'] = basename(__FILE__); $module['GENERAL']['TERMS'] = basename(__FILE__);
return; return;
} }
@ -10,10 +9,9 @@ require('./pagestart.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
require(INC_DIR .'bbcode.php'); require(INC_DIR . 'bbcode.php');
if (isset($_POST['post']) && $di->config->get('terms') != $_POST['message']) if (isset($_POST['post']) && $di->config->get('terms') != $_POST['message']) {
{
bb_update_config(array('terms' => $_POST['message'])); bb_update_config(array('terms' => $_POST['message']));
bb_die($lang['CONFIG_UPDATED']); bb_die($lang['CONFIG_UPDATED']);
} }

View file

@ -1,24 +1,23 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{ $module['USERS']['PERMISSIONS'] = basename(__FILE__) . '?mode=user';
$module['USERS']['PERMISSIONS'] = basename(__FILE__) .'?mode=user'; $module['GROUPS']['PERMISSIONS'] = basename(__FILE__) . '?mode=group';
$module['GROUPS']['PERMISSIONS'] = basename(__FILE__) .'?mode=group';
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
$max_forum_name_length = 50; $max_forum_name_length = 50;
require(INC_DIR .'functions_group.php'); require(INC_DIR . 'functions_group.php');
$yes_sign = '&radic;'; $yes_sign = '&radic;';
$no_sign = 'x'; $no_sign = 'x';
$group_id = (int) $_REQUEST['g']; $group_id = (int)$_REQUEST['g'];
$user_id = (int) $_REQUEST['u']; $user_id = (int)$_REQUEST['u'];
$cat_id = (int) $_REQUEST['c']; $cat_id = (int)$_REQUEST['c'];
$mode = (string) $_REQUEST['mode']; $mode = (string)$_REQUEST['mode'];
$submit = isset($_POST['submit']); $submit = isset($_POST['submit']);
$group_data = array(); $group_data = array();
@ -38,72 +37,61 @@ $forum_auth_fields = array(
'auth_announce', 'auth_announce',
); );
if ($submit && $mode == 'user') if ($submit && $mode == 'user') {
{
$this_user_level = null; $this_user_level = null;
// Obtain relevant data for this user // Obtain relevant data for this user
if (!$row = get_userdata($user_id)) if (!$row = get_userdata($user_id)) {
{
bb_die($lang['NO_SUCH_USER']); bb_die($lang['NO_SUCH_USER']);
} }
$this_user_level = $row['user_level']; $this_user_level = $row['user_level'];
// Get "single_user" group_id for this user // Get "single_user" group_id for this user
$sql = "SELECT g.group_id $sql = "SELECT g.group_id
FROM ". BB_USER_GROUP ." ug, ". BB_GROUPS ." g FROM " . BB_USER_GROUP . " ug, " . BB_GROUPS . " g
WHERE ug.user_id = $user_id WHERE ug.user_id = $user_id
AND g.group_id = ug.group_id AND g.group_id = ug.group_id
AND g.group_single_user = 1"; AND g.group_single_user = 1";
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{
$group_id = $row['group_id']; $group_id = $row['group_id'];
} } else {
else
{
$group_id = create_user_group($user_id); $group_id = create_user_group($user_id);
} }
if (!$group_id || !$user_id || is_null($this_user_level)) if (!$group_id || !$user_id || is_null($this_user_level)) {
{
trigger_error('data missing', E_USER_ERROR); trigger_error('data missing', E_USER_ERROR);
} }
// Make user an admin (if already user) // Make user an admin (if already user)
if ($_POST['userlevel'] === 'admin') if ($_POST['userlevel'] === 'admin') {
{ if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID) {
if ($userdata['user_id'] == $user_id || $user_id == GUEST_UID || $user_id == BOT_UID)
{
bb_die("Could not update admin status"); 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 any entries in auth_access, they are not required if user is becoming an admin
delete_permissions($group_id, $user_id); delete_permissions($group_id, $user_id);
$message = $lang['AUTH_UPDATED'] .'<br /><br />'; $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_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 .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
} } // Make admin a user (if already admin)
// Make admin a user (if already admin) elseif ($_POST['userlevel'] === 'user') {
else if ($_POST['userlevel'] === 'user')
{
// ignore if you're trying to change yourself from an admin to user! // ignore if you're trying to change yourself from an admin to user!
if ($userdata['user_id'] == $user_id) if ($userdata['user_id'] == $user_id) {
{
bb_die("Could not update admin status<br /><br />Could not change yourself from an admin to user"); bb_die("Could not update admin status<br /><br />Could not change yourself from an admin to user");
} }
// Update users level, reset to USER // Update users level, reset to USER
DB()->query("UPDATE ". BB_USERS ." SET user_level = ". USER ." WHERE user_id = $user_id LIMIT 1"); 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 = $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_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 .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
@ -114,14 +102,11 @@ if ($submit && $mode == 'user')
// //
$auth = array(); $auth = array();
if (is_array($_POST['auth'])) if (is_array($_POST['auth'])) {
{
array_deep($_POST['auth'], 'intval'); array_deep($_POST['auth'], 'intval');
foreach ($_POST['auth'] as $f_id => $bf_ary) foreach ($_POST['auth'] as $f_id => $bf_ary) {
{ if (array_sum($bf_ary)) {
if (array_sum($bf_ary))
{
$auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); $auth[$f_id] = bit2dec(array_keys($bf_ary, 1));
} }
} }
@ -133,8 +118,8 @@ if ($submit && $mode == 'user')
update_user_level($user_id); update_user_level($user_id);
$l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH']; $l_auth_return = ($mode == 'user') ? $lang['CLICK_RETURN_USERAUTH'] : $lang['CLICK_RETURN_GROUPAUTH'];
$message = $lang['AUTH_UPDATED'] .'<br /><br />'; $message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<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>'); $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
@ -142,20 +127,16 @@ if ($submit && $mode == 'user')
// //
// Submit new GROUP permissions // Submit new GROUP permissions
// //
else if ($submit && $mode == 'group' && is_array($_POST['auth'])) elseif ($submit && $mode == 'group' && is_array($_POST['auth'])) {
{ if (!$group_data = get_group_data($group_id)) {
if (!$group_data = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
$auth = array(); $auth = array();
array_deep($_POST['auth'], 'intval'); array_deep($_POST['auth'], 'intval');
foreach ($_POST['auth'] as $f_id => $bf_ary) foreach ($_POST['auth'] as $f_id => $bf_ary) {
{ if (array_sum($bf_ary)) {
if (array_sum($bf_ary))
{
$auth[$f_id] = bit2dec(array_keys($bf_ary, 1)); $auth[$f_id] = bit2dec(array_keys($bf_ary, 1));
} }
} }
@ -166,8 +147,8 @@ else if ($submit && $mode == 'group' && is_array($_POST['auth']))
update_user_level('all'); update_user_level('all');
$l_auth_return = $lang['CLICK_RETURN_GROUPAUTH']; $l_auth_return = $lang['CLICK_RETURN_GROUPAUTH'];
$message = $lang['AUTH_UPDATED'] .'<br /><br />'; $message = $lang['AUTH_UPDATED'] . '<br /><br />';
$message .= sprintf($l_auth_return, '<a href="admin_ug_auth.php?mode='. $mode .'">', '</a>') .'<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>'); $message .= sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message); bb_die($message);
@ -176,30 +157,24 @@ else if ($submit && $mode == 'group' && is_array($_POST['auth']))
// //
// Front end (changing permissions) // Front end (changing permissions)
// //
if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) if ($mode == 'user' && (!empty($_POST['username']) || $user_id)) {
{
$page_cfg['quirks_mode'] = true; $page_cfg['quirks_mode'] = true;
if (!empty($_POST['username'])) if (!empty($_POST['username'])) {
{
$this_userdata = get_userdata($_POST['username'], true); $this_userdata = get_userdata($_POST['username'], true);
$user_id = $this_userdata['user_id']; $user_id = $this_userdata['user_id'];
} } else {
else
{
$this_userdata = get_userdata($user_id); $this_userdata = get_userdata($user_id);
} }
if (!$this_userdata) if (!$this_userdata) {
{
bb_die($lang['NO_SUCH_USER']); bb_die($lang['NO_SUCH_USER']);
} }
if (!$forums = $datastore->get('cat_forums')) if (!$forums = $datastore->get('cat_forums')) {
{
$datastore->update('cat_forums'); $datastore->update('cat_forums');
$forums = $datastore->get('cat_forums'); $forums = $datastore->get('cat_forums');
} }
$base_url = basename(__FILE__) ."?mode=user&amp;u=$user_id"; $base_url = basename(__FILE__) . "?mode=user&amp;u=$user_id";
$ug_data = $this_userdata; $ug_data = $this_userdata;
$ug_data['session_logged_in'] = 1; $ug_data['session_logged_in'] = 1;
@ -207,21 +182,18 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
$u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_USER_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); $g_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data, array(), UG_PERM_GROUP_ONLY);
foreach ($forums['c'] as $c_id => $c_data) foreach ($forums['c'] as $c_id => $c_data) {
{
$template->assign_block_vars('c', array( $template->assign_block_vars('c', array(
'CAT_ID' => $c_id, 'CAT_ID' => $c_id,
'CAT_TITLE' => $forums['cat_title_html'][$c_id], 'CAT_TITLE' => $forums['cat_title_html'][$c_id],
'CAT_HREF' => "$base_url&amp;c=$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'])) if (!($c =& $_REQUEST['c']) || !in_array($c, array('all', $c_id)) || empty($c_data['forums'])) {
{
continue; continue;
} }
foreach ($c_data['forums'] as $f_id) foreach ($c_data['forums'] as $f_id) {
{
$f_data = $forums['f'][$f_id]; $f_data = $forums['f'][$f_id];
$auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']); $auth_mod = ($u_access[$f_id]['auth_mod'] || $g_access[$f_id]['auth_mod']);
$disabled = $g_access[$f_id]['auth_mod']; $disabled = $g_access[$f_id]['auth_mod'];
@ -231,26 +203,22 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
'FORUM_ID' => $f_id, 'FORUM_ID' => $f_id,
'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length),
'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '',
'IS_MODERATOR' => (bool) $auth_mod, 'IS_MODERATOR' => (bool)$auth_mod,
'MOD_STATUS' => ($auth_mod) ? $lang['RANK_MODERATOR'] : $lang['NONE'], 'MOD_STATUS' => ($auth_mod) ? $lang['RANK_MODERATOR'] : $lang['NONE'],
'MOD_CLASS' => ($auth_mod) ? (($disabled) ? 'yesDisabled' : 'yesMOD') : 'noMOD', 'MOD_CLASS' => ($auth_mod) ? (($disabled) ? 'yesDisabled' : 'yesMOD') : 'noMOD',
'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0,
)); ));
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$bf_num = $bf['forum_perm'][$auth_type]; $bf_num = $bf['forum_perm'][$auth_type];
$f_perm = $f_data[$auth_type]; $f_perm = $f_data[$auth_type];
$auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]); $auth_via_acl = ($u_access[$f_id][$auth_type] || $g_access[$f_id][$auth_type]);
if ($f_perm == AUTH_ACL) if ($f_perm == AUTH_ACL) {
{
$disabled = ($auth_mod || $g_access[$f_id][$auth_type]); $disabled = ($auth_mod || $g_access[$f_id][$auth_type]);
$perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign;
$acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no';
} } else {
else
{
$disabled = true; $disabled = true;
$perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign;
$acl_class = ($auth_via_acl) ? 'yes' : 'no'; $acl_class = ($auth_via_acl) ? 'yes' : 'no';
@ -274,8 +242,7 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
$s_column_span = 2; $s_column_span = 2;
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$template->assign_block_vars('acltype', array( $template->assign_block_vars('acltype', array(
'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1<br />", $lang[strtoupper($auth_type)]), 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1<br />", $lang[strtoupper($auth_type)]),
'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type],
@ -287,19 +254,19 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
$datastore->rm('cat_forums'); $datastore->rm('cat_forums');
$s_hidden_fields = ' $s_hidden_fields = '
<input type="hidden" name="mode" value="'. $mode .'" /> <input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="'. POST_USERS_URL .'" value="'. $user_id .'" /> <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"> <select name="userlevel">
<option value="admin" selected="selected">'. $lang['RANK_ADMIN'] .'</option> <option value="admin" selected="selected">' . $lang['RANK_ADMIN'] . '</option>
<option value="user">'. $lang['USER'] .'</option> <option value="user">' . $lang['USER'] . '</option>
</select> </select>
' : ' ' : '
<select name="userlevel"> <select name="userlevel">
<option value="admin">'. $lang['RANK_ADMIN'] .'</option> <option value="admin">' . $lang['RANK_ADMIN'] . '</option>
<option value="user" selected="selected">'. $lang['USER'] .'</option> <option value="user" selected="selected">' . $lang['USER'] . '</option>
</select> </select>
'; ';
@ -308,48 +275,41 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
$template->assign_vars(array( $template->assign_vars(array(
'TPL_AUTH_UG_MAIN' => true, 'TPL_AUTH_UG_MAIN' => true,
'USER_OR_GROUPNAME' => $this_userdata['username'], 'USER_OR_GROUPNAME' => $this_userdata['username'],
'USER_LEVEL' => $lang['USER_LEVEL'] .' : '. $s_user_type, 'USER_LEVEL' => $lang['USER_LEVEL'] . ' : ' . $s_user_type,
'T_USER_OR_GROUPNAME' => $lang['USERNAME'], 'T_USER_OR_GROUPNAME' => $lang['USERNAME'],
'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'], 'T_AUTH_TITLE' => $lang['AUTH_CONTROL_USER'],
'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'], 'T_AUTH_EXPLAIN' => $lang['USER_AUTH_EXPLAIN'],
'S_COLUMN_SPAN' => $s_column_span, 'S_COLUMN_SPAN' => $s_column_span,
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } elseif ($mode == 'group' && $group_id) {
else if ($mode == 'group' && $group_id)
{
$page_cfg['quirks_mode'] = true; $page_cfg['quirks_mode'] = true;
if (!$group_data = get_group_data($group_id)) if (!$group_data = get_group_data($group_id)) {
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
if (!$forums = $datastore->get('cat_forums')) if (!$forums = $datastore->get('cat_forums')) {
{
$datastore->update('cat_forums'); $datastore->update('cat_forums');
$forums = $datastore->get('cat_forums'); $forums = $datastore->get('cat_forums');
} }
$base_url = basename(__FILE__) ."?mode=group&amp;g=$group_id"; $base_url = basename(__FILE__) . "?mode=group&amp;g=$group_id";
$ug_data = array('group_id' => $group_id); $ug_data = array('group_id' => $group_id);
$u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data); $u_access = auth(AUTH_ALL, AUTH_LIST_ALL, $ug_data);
foreach ($forums['c'] as $c_id => $c_data) foreach ($forums['c'] as $c_id => $c_data) {
{
$template->assign_block_vars('c', array( $template->assign_block_vars('c', array(
'CAT_ID' => $c_id, 'CAT_ID' => $c_id,
'CAT_TITLE' => $forums['cat_title_html'][$c_id], 'CAT_TITLE' => $forums['cat_title_html'][$c_id],
'CAT_HREF' => "$base_url&amp;c=$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'])) if (!($c =& $_REQUEST['c']) || !in_array($c, array('all', $c_id)) || empty($c_data['forums'])) {
{
continue; continue;
} }
foreach ($c_data['forums'] as $f_id) foreach ($c_data['forums'] as $f_id) {
{
$f_data = $forums['f'][$f_id]; $f_data = $forums['f'][$f_id];
$auth_mod = $u_access[$f_id]['auth_mod']; $auth_mod = $u_access[$f_id]['auth_mod'];
@ -358,26 +318,22 @@ else if ($mode == 'group' && $group_id)
'FORUM_ID' => $f_id, 'FORUM_ID' => $f_id,
'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length), 'FORUM_NAME' => str_short($forums['forum_name_html'][$f_id], $max_forum_name_length),
'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '', 'SF_SPACER' => ($f_data['forum_parent']) ? HTML_SF_SPACER : '',
'IS_MODERATOR' => (bool) $auth_mod, 'IS_MODERATOR' => (bool)$auth_mod,
'MOD_STATUS' => ($auth_mod) ? $lang['RANK_MODERATOR'] : $lang['NO'], 'MOD_STATUS' => ($auth_mod) ? $lang['RANK_MODERATOR'] : $lang['NO'],
'MOD_CLASS' => ($auth_mod) ? 'yesMOD' : 'noMOD', 'MOD_CLASS' => ($auth_mod) ? 'yesMOD' : 'noMOD',
'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0, 'AUTH_MOD_VAL' => ($auth_mod) ? 1 : 0,
)); ));
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$bf_num = $bf['forum_perm'][$auth_type]; $bf_num = $bf['forum_perm'][$auth_type];
$f_perm = $f_data[$auth_type]; $f_perm = $f_data[$auth_type];
$auth_via_acl = $u_access[$f_id][$auth_type]; $auth_via_acl = $u_access[$f_id][$auth_type];
if ($f_perm == AUTH_ACL) if ($f_perm == AUTH_ACL) {
{
$disabled = $auth_mod; $disabled = $auth_mod;
$perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign; $perm_sign = ($auth_via_acl || $auth_mod) ? $yes_sign : $no_sign;
$acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no'; $acl_class = ($auth_via_acl || $auth_mod) ? 'yes' : 'no';
} } else {
else
{
$disabled = true; $disabled = true;
$perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign; $perm_sign = ($auth_via_acl) ? $yes_sign : $no_sign;
$acl_class = ($auth_via_acl) ? 'yes' : 'no'; $acl_class = ($auth_via_acl) ? 'yes' : 'no';
@ -401,8 +357,7 @@ else if ($mode == 'group' && $group_id)
$s_column_span = 2; $s_column_span = 2;
foreach ($forum_auth_fields as $auth_type) foreach ($forum_auth_fields as $auth_type) {
{
$template->assign_block_vars('acltype', array( $template->assign_block_vars('acltype', array(
'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1<br />", $lang[strtoupper($auth_type)]), 'ACL_TYPE_NAME' => preg_replace("#(.{5})#u", "\\1<br />", $lang[strtoupper($auth_type)]),
'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type], 'ACL_TYPE_BF' => $bf['forum_perm'][$auth_type],
@ -414,8 +369,8 @@ else if ($mode == 'group' && $group_id)
$datastore->rm('cat_forums'); $datastore->rm('cat_forums');
$s_hidden_fields = ' $s_hidden_fields = '
<input type="hidden" name="mode" value="'. $mode .'" /> <input type="hidden" name="mode" value="' . $mode . '" />
<input type="hidden" name="g" value="'. $group_id .'" /> <input type="hidden" name="g" value="' . $group_id . '" />
'; ';
$template->assign_vars(array( $template->assign_vars(array(
@ -428,26 +383,21 @@ else if ($mode == 'group' && $group_id)
'S_COLUMN_SPAN' => $s_column_span, 'S_COLUMN_SPAN' => $s_column_span,
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } else {
else
{
// Select a user/group // Select a user/group
if ($mode == 'user') if ($mode == 'user') {
{
$template->assign_vars(array( $template->assign_vars(array(
'TPL_SELECT_USER' => true, 'TPL_SELECT_USER' => true,
'U_SEARCH_USER' => BB_ROOT ."search.php?mode=searchuser", 'U_SEARCH_USER' => BB_ROOT . "search.php?mode=searchuser",
)); ));
} } else {
else
{
$template->assign_vars(array( $template->assign_vars(array(
'TPL_SELECT_GROUP' => true, 'TPL_SELECT_GROUP' => true,
'S_GROUP_SELECT' => get_select('groups'), '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( $template->assign_vars(array(
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,

View file

@ -1,24 +1,20 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['USERS']['BAN_MANAGEMENT'] = basename(__FILE__); $module['USERS']['BAN_MANAGEMENT'] = basename(__FILE__);
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
if (isset($_POST['submit'])) if (isset($_POST['submit'])) {
{
$user_bansql = ''; $user_bansql = '';
$email_bansql = ''; $email_bansql = '';
$ip_bansql = ''; $ip_bansql = '';
$user_list = array(); $user_list = array();
if (!empty($_POST['username'])) if (!empty($_POST['username'])) {
{
$this_userdata = get_userdata($_POST['username'], true); $this_userdata = get_userdata($_POST['username'], true);
if (!$this_userdata) if (!$this_userdata) {
{
bb_die($lang['NO_USER_ID_SPECIFIED']); bb_die($lang['NO_USER_ID_SPECIFIED']);
} }
@ -26,58 +22,48 @@ if (isset($_POST['submit']))
} }
$ip_list = array(); $ip_list = array();
if (isset($_POST['ban_ip'])) if (isset($_POST['ban_ip'])) {
{
$ip_list_temp = explode(',', $_POST['ban_ip']); $ip_list_temp = explode(',', $_POST['ban_ip']);
for ($i = 0; $i < count($ip_list_temp); $i++) 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)) {
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_counter = $ip_range_explode[1];
$ip_1_end = $ip_range_explode[5]; $ip_1_end = $ip_range_explode[5];
while ( $ip_1_counter <= $ip_1_end ) while ($ip_1_counter <= $ip_1_end) {
{ $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
$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];
$ip_2_end = ( $ip_1_counter < $ip_1_end ) ? 254 : $ip_range_explode[6];
if ( $ip_2_counter == 0 && $ip_2_end == 254 ) if ($ip_2_counter == 0 && $ip_2_end == 254) {
{
$ip_2_counter = 255; $ip_2_counter = 255;
$ip_2_fragment = 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 ) 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_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];
$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 ) if ($ip_3_counter == 0 && $ip_3_end == 254) {
{
$ip_3_counter = 255; $ip_3_counter = 255;
$ip_3_fragment = 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 ) 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_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];
$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 ) if ($ip_4_counter == 0 && $ip_4_end == 254) {
{
$ip_4_counter = 255; $ip_4_counter = 255;
$ip_4_fragment = 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 ) while ($ip_4_counter <= $ip_4_end) {
{
$ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter"); $ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter");
$ip_4_counter++; $ip_4_counter++;
} }
@ -87,43 +73,33 @@ if (isset($_POST['submit']))
} }
$ip_1_counter++; $ip_1_counter++;
} }
} } elseif (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i]))) {
else if (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i])))
{
$ip = gethostbynamel(trim($ip_list_temp[$i])); $ip = gethostbynamel(trim($ip_list_temp[$i]));
for ($j = 0; $j < count($ip); $j++) for ($j = 0; $j < count($ip); $j++) {
{ if (!empty($ip[$j])) {
if (!empty($ip[$j]))
{
$ip_list[] = encode_ip($ip[$j]); $ip_list[] = encode_ip($ip[$j]);
} }
} }
} } elseif (preg_match('/^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$/', trim($ip_list_temp[$i]))) {
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]))); $ip_list[] = encode_ip(str_replace('*', '255', trim($ip_list_temp[$i])));
} }
} }
} }
$email_list = array(); $email_list = array();
if (isset($_POST['ban_email'])) if (isset($_POST['ban_email'])) {
{
$email_list_temp = explode(',', $_POST['ban_email']); $email_list_temp = explode(',', $_POST['ban_email']);
for ($i = 0; $i < count($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]))) {
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]); $email_list[] = trim($email_list_temp[$i]);
} }
} }
} }
$sql = "SELECT * FROM " . BB_BANLIST; $sql = "SELECT * FROM " . BB_BANLIST;
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not obtain banlist information'); bb_die('Could not obtain banlist information');
} }
@ -131,87 +107,67 @@ if (isset($_POST['submit']))
DB()->sql_freeresult($result); DB()->sql_freeresult($result);
$kill_session_sql = ''; $kill_session_sql = '';
for ($i = 0; $i < count($user_list); $i++) for ($i = 0; $i < count($user_list); $i++) {
{
$in_banlist = false; $in_banlist = false;
for ($j = 0; $j < count($current_banlist); $j++) for ($j = 0; $j < count($current_banlist); $j++) {
{ if ($user_list[$i] == $current_banlist[$j]['ban_userid']) {
if ($user_list[$i] == $current_banlist[$j]['ban_userid'])
{
$in_banlist = true; $in_banlist = true;
} }
} }
if (!$in_banlist) if (!$in_banlist) {
{ $kill_session_sql .= (($kill_session_sql != '') ? ' OR ' : '') . "session_user_id = " . $user_list[$i];
$kill_session_sql .= ( ( $kill_session_sql != '' ) ? ' OR ' : '' ) . "session_user_id = " . $user_list[$i];
$sql = "INSERT INTO " . BB_BANLIST . " (ban_userid) VALUES (" . $user_list[$i] . ")"; $sql = "INSERT INTO " . BB_BANLIST . " (ban_userid) VALUES (" . $user_list[$i] . ")";
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not insert ban_userid info into database'); bb_die('Could not insert ban_userid info into database');
} }
} }
} }
for ($i = 0; $i < count($ip_list); $i++) for ($i = 0; $i < count($ip_list); $i++) {
{
$in_banlist = false; $in_banlist = false;
for ($j = 0; $j < count($current_banlist); $j++) for ($j = 0; $j < count($current_banlist); $j++) {
{ if ($ip_list[$i] == $current_banlist[$j]['ban_ip']) {
if ($ip_list[$i] == $current_banlist[$j]['ban_ip'])
{
$in_banlist = true; $in_banlist = true;
} }
} }
if (!$in_banlist) if (!$in_banlist) {
{ if (preg_match('/(ff\.)|(\.ff)/is', chunk_split($ip_list[$i], 2, '.'))) {
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, "."))) . "'"; $kill_ip_sql = "session_ip LIKE '" . str_replace('.', '', preg_replace('/(ff\.)|(\.ff)/is', '%', chunk_split($ip_list[$i], 2, "."))) . "'";
} } else {
else
{
$kill_ip_sql = "session_ip = '" . $ip_list[$i] . "'"; $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] . "')"; $sql = "INSERT INTO " . BB_BANLIST . " (ban_ip) VALUES ('" . $ip_list[$i] . "')";
if ( !DB()->sql_query($sql) ) if (!DB()->sql_query($sql)) {
{
bb_die('Could not insert ban_ip info into database'); bb_die('Could not insert ban_ip info into database');
} }
} }
} }
// Now we'll delete all entries from the session table // Now we'll delete all entries from the session table
if ($kill_session_sql != '') if ($kill_session_sql != '') {
{
$sql = "DELETE FROM " . BB_SESSIONS . " WHERE $kill_session_sql"; $sql = "DELETE FROM " . BB_SESSIONS . " WHERE $kill_session_sql";
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not delete banned sessions from database'); bb_die('Could not delete banned sessions from database');
} }
} }
for ($i = 0; $i < count($email_list); $i++) for ($i = 0; $i < count($email_list); $i++) {
{
$in_banlist = false; $in_banlist = false;
for ($j = 0; $j < count($current_banlist); $j++) for ($j = 0; $j < count($current_banlist); $j++) {
{ if ($email_list[$i] == $current_banlist[$j]['ban_email']) {
if ($email_list[$i] == $current_banlist[$j]['ban_email'])
{
$in_banlist = true; $in_banlist = true;
} }
} }
if (!$in_banlist) if (!$in_banlist) {
{
$sql = "INSERT INTO " . BB_BANLIST . " (ban_email) VALUES ('" . DB()->escape($email_list[$i]) . "')"; $sql = "INSERT INTO " . BB_BANLIST . " (ban_email) VALUES ('" . DB()->escape($email_list[$i]) . "')";
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not insert ban_email info into database'); bb_die('Could not insert ban_email info into database');
} }
} }
@ -219,58 +175,45 @@ if (isset($_POST['submit']))
$where_sql = ''; $where_sql = '';
if (isset($_POST['unban_user'])) if (isset($_POST['unban_user'])) {
{
$user_list = $_POST['unban_user']; $user_list = $_POST['unban_user'];
for ($i = 0; $i < count($user_list); $i++) for ($i = 0; $i < count($user_list); $i++) {
{ if ($user_list[$i] != -1) {
if ($user_list[$i] != -1) $where_sql .= (($where_sql != '') ? ', ' : '') . intval($user_list[$i]);
{
$where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . intval($user_list[$i]);
} }
} }
} }
if (isset($_POST['unban_ip'])) if (isset($_POST['unban_ip'])) {
{
$ip_list = $_POST['unban_ip']; $ip_list = $_POST['unban_ip'];
for ($i = 0; $i < count($ip_list); $i++) for ($i = 0; $i < count($ip_list); $i++) {
{ if ($ip_list[$i] != -1) {
if ($ip_list[$i] != -1) $where_sql .= (($where_sql != '') ? ', ' : '') . DB()->escape($ip_list[$i]);
{
$where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($ip_list[$i]);
} }
} }
} }
if (isset($_POST['unban_email'])) if (isset($_POST['unban_email'])) {
{
$email_list = $_POST['unban_email']; $email_list = $_POST['unban_email'];
for ($i = 0; $i < count($email_list); $i++) for ($i = 0; $i < count($email_list); $i++) {
{ if ($email_list[$i] != -1) {
if ($email_list[$i] != -1) $where_sql .= (($where_sql != '') ? ', ' : '') . DB()->escape($email_list[$i]);
{
$where_sql .= ( ( $where_sql != '' ) ? ', ' : '' ) . DB()->escape($email_list[$i]);
} }
} }
} }
if ($where_sql != '') if ($where_sql != '') {
{
$sql = "DELETE FROM " . BB_BANLIST . " WHERE ban_id IN ($where_sql)"; $sql = "DELETE FROM " . BB_BANLIST . " WHERE ban_id IN ($where_sql)";
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not delete ban info from database'); 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>')); 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 {
else
{
$template->assign_vars(array( $template->assign_vars(array(
'S_BANLIST_ACTION' => 'admin_user_ban.php', 'S_BANLIST_ACTION' => 'admin_user_ban.php',
)); ));
@ -285,8 +228,7 @@ else
AND b.ban_userid <> 0 AND b.ban_userid <> 0
AND u.user_id <> " . GUEST_UID . " AND u.user_id <> " . GUEST_UID . "
ORDER BY u.username ASC"; ORDER BY u.username ASC";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not select current user_id ban list'); bb_die('Could not select current user_id ban list');
} }
@ -294,22 +236,19 @@ else
DB()->sql_freeresult($result); DB()->sql_freeresult($result);
$select_userlist = ''; $select_userlist = '';
for ($i = 0; $i < count($user_list); $i++) for ($i = 0; $i < count($user_list); $i++) {
{
$select_userlist .= '<option value="' . $user_list[$i]['ban_id'] . '">' . $user_list[$i]['username'] . '</option>'; $select_userlist .= '<option value="' . $user_list[$i]['ban_id'] . '">' . $user_list[$i]['username'] . '</option>';
$userban_count++; $userban_count++;
} }
if ($select_userlist == '') if ($select_userlist == '') {
{
$select_userlist = '<option value="-1">' . $lang['NO_BANNED_USERS'] . '</option>'; $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"; $sql = "SELECT ban_id, ban_ip, ban_email FROM " . BB_BANLIST . " ORDER BY ban_ip";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not select current ip ban list'); bb_die('Could not select current ip ban list');
} }
@ -319,31 +258,25 @@ else
$select_iplist = ''; $select_iplist = '';
$select_emaillist = ''; $select_emaillist = '';
for ($i = 0; $i < count($banlist); $i++) for ($i = 0; $i < count($banlist); $i++) {
{
$ban_id = $banlist[$i]['ban_id']; $ban_id = $banlist[$i]['ban_id'];
if (!empty($banlist[$i]['ban_ip'])) if (!empty($banlist[$i]['ban_ip'])) {
{
$ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip'])); $ban_ip = str_replace('255', '*', decode_ip($banlist[$i]['ban_ip']));
$select_iplist .= '<option value="' . $ban_id . '">' . $ban_ip . '</option>'; $select_iplist .= '<option value="' . $ban_id . '">' . $ban_ip . '</option>';
$ipban_count++; $ipban_count++;
} } elseif (!empty($banlist[$i]['ban_email'])) {
else if (!empty($banlist[$i]['ban_email']))
{
$ban_email = $banlist[$i]['ban_email']; $ban_email = $banlist[$i]['ban_email'];
$select_emaillist .= '<option value="' . $ban_id . '">' . $ban_email . '</option>'; $select_emaillist .= '<option value="' . $ban_id . '">' . $ban_email . '</option>';
$emailban_count++; $emailban_count++;
} }
} }
if ($select_iplist == '') if ($select_iplist == '') {
{
$select_iplist = '<option value="-1">' . $lang['NO_BANNED_IP'] . '</option>'; $select_iplist = '<option value="-1">' . $lang['NO_BANNED_IP'] . '</option>';
} }
if ($select_emaillist == '') if ($select_emaillist == '') {
{
$select_emaillist = '<option value="-1">' . $lang['NO_BANNED_EMAIL'] . '</option>'; $select_emaillist = '<option value="-1">' . $lang['NO_BANNED_EMAIL'] . '</option>';
} }

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GENERAL']['WORD_CENSOR'] = basename(__FILE__); $module['GENERAL']['WORD_CENSOR'] = basename(__FILE__);
return; return;
} }
@ -13,38 +12,29 @@ $di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */ /** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache; $cache = $di->cache;
if (!$di->config->get('use_word_censor')) if (!$di->config->get('use_word_censor')) {
{
bb_die('Word censor disabled'); bb_die('Word censor disabled');
} }
$mode = request_var('mode', ''); $mode = request_var('mode', '');
$mode = htmlspecialchars($mode); $mode = htmlspecialchars($mode);
if (isset($_POST['add'])) if (isset($_POST['add'])) {
{
$mode = 'add'; $mode = 'add';
} } elseif (isset($_POST['save'])) {
else if (isset($_POST['save']))
{
$mode = 'save'; $mode = 'save';
} }
if ($mode != '') if ($mode != '') {
{ if ($mode == 'edit' || $mode == 'add') {
if ($mode == 'edit' || $mode == 'add')
{
$word_id = intval(request_var('id', 0)); $word_id = intval(request_var('id', 0));
$s_hidden_fields = $word = $replacement = ''; $s_hidden_fields = $word = $replacement = '';
if ($mode == 'edit') if ($mode == 'edit') {
{ if ($word_id) {
if ($word_id)
{
$sql = "SELECT * FROM " . BB_WORDS . " WHERE word_id = $word_id"; $sql = "SELECT * FROM " . BB_WORDS . " WHERE word_id = $word_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not query words table #1'); bb_die('Could not query words table #1');
} }
@ -52,9 +42,7 @@ if ($mode != '')
$s_hidden_fields .= '<input type="hidden" name="id" value="' . $word_id . '" />'; $s_hidden_fields .= '<input type="hidden" name="id" value="' . $word_id . '" />';
$word = $word_info['word']; $word = $word_info['word'];
$replacement = $word_info['replacement']; $replacement = $word_info['replacement'];
} } else {
else
{
bb_die($lang['NO_WORD_SELECTED']); bb_die($lang['NO_WORD_SELECTED']);
} }
} }
@ -66,34 +54,27 @@ if ($mode != '')
'S_WORDS_ACTION' => 'admin_words.php', 'S_WORDS_ACTION' => 'admin_words.php',
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } elseif ($mode == 'save') {
else if ($mode == 'save')
{
$word_id = intval(request_var('id', 0)); $word_id = intval(request_var('id', 0));
$word = trim(request_var('word', '')); $word = trim(request_var('word', ''));
$replacement = trim(request_var('replacement', '')); $replacement = trim(request_var('replacement', ''));
if ($word == '' || $replacement == '') if ($word == '' || $replacement == '') {
{
bb_die($lang['MUST_ENTER_WORD']); bb_die($lang['MUST_ENTER_WORD']);
} }
if ($word_id) if ($word_id) {
{
$sql = "UPDATE " . BB_WORDS . " $sql = "UPDATE " . BB_WORDS . "
SET word = '" . DB()->escape($word) . "', replacement = '" . DB()->escape($replacement) . "' SET word = '" . DB()->escape($word) . "', replacement = '" . DB()->escape($replacement) . "'
WHERE word_id = $word_id"; WHERE word_id = $word_id";
$message = $lang['WORD_UPDATED']; $message = $lang['WORD_UPDATED'];
} } else {
else
{
$sql = "INSERT INTO " . BB_WORDS . " (word, replacement) $sql = "INSERT INTO " . BB_WORDS . " (word, replacement)
VALUES ('" . DB()->escape($word) . "', '" . DB()->escape($replacement) . "')"; VALUES ('" . DB()->escape($word) . "', '" . DB()->escape($replacement) . "')";
$message = $lang['WORD_ADDED']; $message = $lang['WORD_ADDED'];
} }
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not insert data into words table'); bb_die('Could not insert data into words table');
} }
@ -101,35 +82,26 @@ if ($mode != '')
$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>'); $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); bb_die($message);
} } elseif ($mode == 'delete') {
else if ($mode == 'delete')
{
$word_id = intval(request_var('id', 0)); $word_id = intval(request_var('id', 0));
if ($word_id) if ($word_id) {
{
$sql = "DELETE FROM " . BB_WORDS . " WHERE word_id = $word_id"; $sql = "DELETE FROM " . BB_WORDS . " WHERE word_id = $word_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not remove data from words table'); 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>')); 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 {
else
{
bb_die($lang['NO_WORD_SELECTED']); bb_die($lang['NO_WORD_SELECTED']);
} }
} }
} } else {
else
{
$sql = "SELECT * FROM " . BB_WORDS . " ORDER BY word"; $sql = "SELECT * FROM " . BB_WORDS . " ORDER BY word";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not query words table #2'); bb_die('Could not query words table #2');
} }
@ -142,8 +114,7 @@ else
'S_HIDDEN_FIELDS' => '', 'S_HIDDEN_FIELDS' => '',
)); ));
for ($i = 0; $i < $word_count; $i++) for ($i = 0; $i < $word_count; $i++) {
{
$word = $word_rows[$i]['word']; $word = $word_rows[$i]['word'];
$replacement = $word_rows[$i]['replacement']; $replacement = $word_rows[$i]['replacement'];
$word_id = $word_rows[$i]['word_id']; $word_id = $word_rows[$i]['word_id'];

View file

@ -9,8 +9,7 @@ $di = \TorrentPier\Di::getInstance();
$cache = $di->cache; $cache = $di->cache;
// Generate relevant output // Generate relevant output
if (isset($_GET['pane']) && $_GET['pane'] == 'left') if (isset($_GET['pane']) && $_GET['pane'] == 'left') {
{
$module = []; $module = [];
if (!$cache->has('admin_module_' . $user->id)) { if (!$cache->has('admin_module_' . $user->id)) {
$dir = opendir('.'); $dir = opendir('.');
@ -35,8 +34,7 @@ if (isset($_GET['pane']) && $_GET['pane'] == 'left')
ksort($module); ksort($module);
while (list($cat, $action_array) = each($module)) while (list($cat, $action_array) = each($module)) {
{
$cat = (!empty($lang[$cat])) ? $lang[$cat] : preg_replace('/_/', ' ', $cat); $cat = (!empty($lang[$cat])) ? $lang[$cat] : preg_replace('/_/', ' ', $cat);
$template->assign_block_vars('catrow', array( $template->assign_block_vars('catrow', array(
@ -46,8 +44,7 @@ if (isset($_GET['pane']) && $_GET['pane'] == 'left')
ksort($action_array); ksort($action_array);
$row_count = 0; $row_count = 0;
while (list($action, $file) = each($action_array)) while (list($action, $file) = each($action_array)) {
{
$row_class = !($row_count % 2) ? 'row1' : 'row2'; $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);
@ -60,13 +57,11 @@ if (isset($_GET['pane']) && $_GET['pane'] == 'left')
$row_count++; $row_count++;
} }
} }
} } elseif (isset($_GET['pane']) && $_GET['pane'] == 'right') {
elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
{
$template->assign_vars(array( $template->assign_vars(array(
'TPL_ADMIN_MAIN' => true, 'TPL_ADMIN_MAIN' => true,
'ADMIN_LOCK' => ($di->config->get('board_disable')) ? true : false, 'ADMIN_LOCK' => ($di->config->get('board_disable')) ? true : false,
'ADMIN_LOCK_CRON' => (file_exists(BB_DISABLED)) ? true :false, 'ADMIN_LOCK_CRON' => (file_exists(BB_DISABLED)) ? true : false,
)); ));
// Get forum statistics // Get forum statistics
@ -82,76 +77,58 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
$avatar_dir_size = 0; $avatar_dir_size = 0;
if ($avatar_dir = opendir(BB_ROOT . $di->config->get('avatar_path'))) if ($avatar_dir = opendir(BB_ROOT . $di->config->get('avatar_path'))) {
{ while ($file = readdir($avatar_dir)) {
while( $file = readdir($avatar_dir) ) if ($file != '.' && $file != '..') {
{
if( $file != '.' && $file != '..' )
{
$avatar_dir_size += filesize(BB_ROOT . $di->config->get('avatar_path') . '/' . $file); $avatar_dir_size += filesize(BB_ROOT . $di->config->get('avatar_path') . '/' . $file);
} }
} }
closedir($avatar_dir); closedir($avatar_dir);
$avatar_dir_size = humn_size($avatar_dir_size); $avatar_dir_size = humn_size($avatar_dir_size);
} } else {
else
{
$avatar_dir_size = $lang['NOT_AVAILABLE']; $avatar_dir_size = $lang['NOT_AVAILABLE'];
} }
if (intval($posts_per_day) > $total_posts) if (intval($posts_per_day) > $total_posts) {
{
$posts_per_day = $total_posts; $posts_per_day = $total_posts;
} }
if (intval($topics_per_day) > $total_topics) if (intval($topics_per_day) > $total_topics) {
{
$topics_per_day = $total_topics; $topics_per_day = $total_topics;
} }
if ($users_per_day > $total_users) if ($users_per_day > $total_users) {
{
$users_per_day = $total_users; $users_per_day = $total_users;
} }
// DB size ... MySQL only // DB size ... MySQL only
$sql = "SELECT VERSION() AS mysql_version"; $sql = "SELECT VERSION() AS mysql_version";
if ($result = DB()->sql_query($sql)) if ($result = DB()->sql_query($sql)) {
{
$row = DB()->sql_fetchrow($result); $row = DB()->sql_fetchrow($result);
$version = $row['mysql_version']; $version = $row['mysql_version'];
if (preg_match('/^(3\.23|4\.|5\.|10\.)/', $version)) if (preg_match('/^(3\.23|4\.|5\.|10\.)/', $version)) {
{
$dblist = array(); $dblist = array();
foreach ($di->config->get('db') as $name => $row) foreach ($di->config->get('db') as $name => $row) {
{
$sql = "SHOW TABLE STATUS FROM {$row[1]}"; $sql = "SHOW TABLE STATUS FROM {$row[1]}";
if ($result = DB()->sql_query($sql)) if ($result = DB()->sql_query($sql)) {
{
$tabledata_ary = DB()->sql_fetchrowset($result); $tabledata_ary = DB()->sql_fetchrowset($result);
$dbsize = 0; $dbsize = 0;
for ($i = 0; $i < count($tabledata_ary); $i++) for ($i = 0; $i < count($tabledata_ary); $i++) {
{ if ($tabledata_ary[$i]['Type'] != 'MRG_MYISAM') {
if( $tabledata_ary[$i]['Type'] != 'MRG_MYISAM' )
{
$dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length']; $dbsize += $tabledata_ary[$i]['Data_length'] + $tabledata_ary[$i]['Index_length'];
} }
} }
$dblist[] = '<span title="'. $name .'">'. humn_size($dbsize) .'</span>'; $dblist[] = '<span title="' . $name . '">' . humn_size($dbsize) . '</span>';
} }
} }
$dbsize = implode('&nbsp;|&nbsp;', $dblist); $dbsize = implode('&nbsp;|&nbsp;', $dblist);
} } else {
else
{
$dbsize = $lang['NOT_AVAILABLE']; $dbsize = $lang['NOT_AVAILABLE'];
} }
} } else {
else
{
$dbsize = $lang['NOT_AVAILABLE']; $dbsize = $lang['NOT_AVAILABLE'];
} }
@ -171,8 +148,7 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
'ZF_VERSION' => Zend\Version\Version::VERSION, 'ZF_VERSION' => Zend\Version\Version::VERSION,
)); ));
if ($_GET['users_online']) if ($_GET['users_online']) {
{
$template->assign_vars(array( $template->assign_vars(array(
'SHOW_USERS_ONLINE' => true, 'SHOW_USERS_ONLINE' => true,
)); ));
@ -183,10 +159,9 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
WHERE s.session_logged_in = 1 WHERE s.session_logged_in = 1
AND u.user_id = s.session_user_id AND u.user_id = s.session_user_id
AND u.user_id <> " . GUEST_UID . " 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"; ORDER BY s.session_ip ASC, s.session_time DESC";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not obtain reged user / online information'); bb_die('Could not obtain reged user / online information');
} }
$onlinerow_reg = DB()->sql_fetchrowset($result); $onlinerow_reg = DB()->sql_fetchrowset($result);
@ -194,37 +169,30 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
$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 . " FROM " . BB_SESSIONS . "
WHERE session_logged_in = 0 WHERE session_logged_in = 0
AND session_time >= " . ( TIMENOW - 300 ) . " AND session_time >= " . (TIMENOW - 300) . "
ORDER BY session_ip ASC, session_time DESC"; ORDER BY session_ip ASC, session_time DESC";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not obtain guest user / online information'); bb_die('Could not obtain guest user / online information');
} }
$onlinerow_guest = DB()->sql_fetchrowset($result); $onlinerow_guest = DB()->sql_fetchrowset($result);
$reg_userid_ary = array(); $reg_userid_ary = array();
if (count($onlinerow_reg)) if (count($onlinerow_reg)) {
{
$registered_users = $hidden_users = 0; $registered_users = $hidden_users = 0;
for ($i = 0, $cnt = count($onlinerow_reg); $i < $cnt; $i++) for ($i = 0, $cnt = count($onlinerow_reg); $i < $cnt; $i++) {
{ if (!in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary)) {
if (!in_array($onlinerow_reg[$i]['user_id'], $reg_userid_ary))
{
$reg_userid_ary[] = $onlinerow_reg[$i]['user_id']; $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')) if (bf($onlinerow_reg[$i]['user_opt'], 'user_opt', 'user_viewonline')) {
{
$hidden_users++; $hidden_users++;
$hidden = TRUE; $hidden = true;
} } else {
else
{
$registered_users++; $registered_users++;
$hidden = FALSE; $hidden = false;
} }
$row_class = 'row1'; $row_class = 'row1';
@ -244,12 +212,10 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
} }
// Guest users // Guest users
if (count($onlinerow_guest)) if (count($onlinerow_guest)) {
{
$guest_users = 0; $guest_users = 0;
for ($i = 0; $i < count($onlinerow_guest); $i++) for ($i = 0; $i < count($onlinerow_guest); $i++) {
{
$guest_userip_ary[] = $onlinerow_guest[$i]['session_ip']; $guest_userip_ary[] = $onlinerow_guest[$i]['session_ip'];
$guest_users++; $guest_users++;
@ -260,22 +226,18 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
$template->assign_block_vars('guest_user_row', array( $template->assign_block_vars('guest_user_row', array(
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'H:i', false), 'STARTED' => bb_date($onlinerow_guest[$i]['session_start'], 'H:i', false),
'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'H:i' , false), 'LASTUPDATE' => bb_date($onlinerow_guest[$i]['session_time'], 'H:i', false),
'IP_ADDRESS' => $guest_ip, 'IP_ADDRESS' => $guest_ip,
'U_WHOIS_IP' => $di->config->get('whois_info') . $guest_ip, 'U_WHOIS_IP' => $di->config->get('whois_info') . $guest_ip,
)); ));
} }
} }
} } else {
else
{
$template->assign_vars(array( $template->assign_vars(array(
'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1', 'USERS_ONLINE_HREF' => 'index.php?pane=right&users_online=1',
)); ));
} }
} } else {
else
{
// Generate frameset // Generate frameset
$template->assign_vars(array( $template->assign_vars(array(
'CONTENT_ENCODING' => $di->config->get('lang.' . $userdata['user_lang'] . '.encoding'), 'CONTENT_ENCODING' => $di->config->get('lang.' . $userdata['user_lang'] . '.encoding'),

View file

@ -3,23 +3,20 @@
define('BB_ROOT', './../'); define('BB_ROOT', './../');
define('IN_ADMIN', true); define('IN_ADMIN', true);
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
require_once(INC_DIR .'functions_admin.php'); require_once(INC_DIR . 'functions_admin.php');
$user->session_start(); $user->session_start();
if (IS_GUEST) if (IS_GUEST) {
{
redirect(LOGIN_URL . "?redirect=admin/index.php"); redirect(LOGIN_URL . "?redirect=admin/index.php");
} }
if (!IS_ADMIN) if (!IS_ADMIN) {
{
bb_die($lang['NOT_ADMIN']); bb_die($lang['NOT_ADMIN']);
} }
if (!$userdata['session_admin']) if (!$userdata['session_admin']) {
{
$redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1); $redirect = url_arg($_SERVER['REQUEST_URI'], 'admin', 1);
redirect("login.php?redirect=$redirect"); redirect("login.php?redirect=$redirect");
} }

View file

@ -2,47 +2,43 @@
define('IN_ADMIN', true); define('IN_ADMIN', true);
define('BB_ROOT', './../../'); define('BB_ROOT', './../../');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
$user->session_start(); $user->session_start();
if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); if (!IS_ADMIN) {
bb_die($lang['NOT_AUTHORISED']);
}
$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000'; $sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-2592000';
$sql[] = 'SELECT count(*) FROM `'.BB_USERS.'` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000'; $sql[] = 'SELECT count(*) FROM `' . BB_USERS . '` WHERE `user_lastvisit` < UNIX_TIMESTAMP()-7776000';
$sql[] = 'SELECT round(avg(size)/1048576) FROM `'.BB_BT_TORRENTS.'`'; $sql[] = 'SELECT round(avg(size)/1048576) FROM `' . BB_BT_TORRENTS . '`';
$sql[] = 'SELECT count(*) 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 > 0';
$sql[] = 'SELECT count(distinct(topic_id)) FROM `'.BB_BT_TRACKER_SNAP.'` WHERE seeders > 5'; $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 . '`';
$sql[] = 'SELECT count(distinct(poster_id)) FROM `'.BB_BT_TORRENTS.'` WHERE reg_time >= UNIX_TIMESTAMP()-2592000'; $sql[] = 'SELECT count(distinct(poster_id)) FROM `' . BB_BT_TORRENTS . '` WHERE reg_time >= UNIX_TIMESTAMP()-2592000';
echo '<html><body><head></head>'; echo '<html><body><head></head>';
echo ' echo '<br /><br /><table border="1" cellspacing="0" cellpadding="6" align="center">';
<br /><br />
<table border="1" cellspacing="0" cellpadding="6" align="center">';
foreach ($sql as $i => $query) foreach ($sql as $i => $query) {
{
$row = mysql_fetch_row(DB()->query($query)); // TODO: deprecated $row = mysql_fetch_row(DB()->query($query)); // TODO: deprecated
echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>"; echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>";
} }
echo '</table>'; echo '</table>';
echo '<div align="center"><pre>'; echo '<div align="center"><pre>';
if ($l = sys('la')) if ($l = sys('la')) {
{
$l = explode(' ', $l); $l = explode(' ', $l);
for ($i=0; $i < 3; $i++) for ($i = 0; $i < 3; $i++) {
{
$l[$i] = round($l[$i], 1); $l[$i] = round($l[$i], 1);
} }
echo "\n\n<b>loadavg: </b>$l[0] $l[1] $l[2]\n\n"; 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 '</pre></div>';
echo '</body></html>'; echo '</body></html>';

View file

@ -2,16 +2,18 @@
define('IN_ADMIN', true); define('IN_ADMIN', true);
define('BB_ROOT', './../../'); define('BB_ROOT', './../../');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$user->session_start(); $user->session_start();
if (!IS_ADMIN) bb_die($lang['NOT_AUTHORISED']); if (!IS_ADMIN) {
bb_die($lang['NOT_AUTHORISED']);
}
$peers_in_last_minutes = array(30, 15, 5, 1); $peers_in_last_minutes = [30, 15, 5, 1];
$peers_in_last_sec_limit = 300; $peers_in_last_sec_limit = 300;
$announce_interval = intval($di->config->get('announce_interval')); $announce_interval = intval($di->config->get('announce_interval'));
@ -20,7 +22,7 @@ $stat = array();
define('TMP_TRACKER_TABLE', 'tmp_tracker'); define('TMP_TRACKER_TABLE', 'tmp_tracker');
DB()->query(" DB()->query("
CREATE TEMPORARY TABLE ". TMP_TRACKER_TABLE ." ( CREATE TEMPORARY TABLE " . TMP_TRACKER_TABLE . " (
`topic_id` mediumint(8) unsigned NOT NULL default '0', `topic_id` mediumint(8) unsigned NOT NULL default '0',
`user_id` mediumint(9) NOT NULL default '0', `user_id` mediumint(9) NOT NULL default '0',
`ip` char(8) binary NOT NULL default '0', `ip` char(8) binary NOT NULL default '0',
@ -31,63 +33,55 @@ DB()->query("
) )
SELECT SELECT
topic_id, user_id, ip, seeder, speed_up, speed_down, update_time topic_id, user_id, ip, seeder, speed_up, speed_down, update_time
FROM ". BB_BT_TRACKER ." FROM " . BB_BT_TRACKER . "
"); ");
// Peers within announce interval // 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" // 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 // 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 // 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 // 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 // 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 // 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 // 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 // Last xx minutes
$peers_in_last_min = array(); $peers_in_last_min = array();
foreach ($peers_in_last_minutes as $t) foreach ($peers_in_last_minutes as $t) {
{
$row = DB()->fetch_row(" $row = DB()->fetch_row("
SELECT COUNT(*) AS peers FROM ". TMP_TRACKER_TABLE ." WHERE update_time >= ". (TIMENOW - 60*$t) ." 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 // Last xx seconds
$peers_in_last_sec = array(); $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"); $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) foreach ($rowset as $cnt => $row) {
{ $peers_in_last_sec[] = sprintf('%3s', $row['peers']) . (($cnt && !(++$cnt % 15)) ? " \n" : '');
$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'); ob_start('commify_ob');
echo '<html><body><head></head>'; echo '<html><body><head></head>';
echo ' echo '<br /><br /><table border="1" cellspacing="0" cellpadding="6" align="center"><col width="40%"><col width="60%">';
<br /><br />
<table border="1" cellspacing="0" cellpadding="6" align="center">
<col width="40%">
<col width="60%">
';
echo "\n<tr><td align=center> users: bb-all / bt-all / bt-active </td><td align=center> $stat[u_bb_all] / $stat[u_bt_all] / <b>$stat[u_bt_active]</b> </td></tr>\n"; echo "\n<tr><td align=center> users: bb-all / bt-all / bt-active </td><td align=center> $stat[u_bb_all] / $stat[u_bt_all] / <b>$stat[u_bt_active]</b> </td></tr>\n";
echo "\n echo "\n
@ -95,7 +89,7 @@ echo "\n
<td align=center> <td align=center>
$stat[tor_all] / <b>$stat[tor_active]</b> / $stat[tor_with_seeder] $stat[tor_all] / <b>$stat[tor_active]</b> / $stat[tor_with_seeder]
&nbsp; &nbsp;
[ ". humn_size($stat['torrents_size']) ." ] [ " . humn_size($stat['torrents_size']) . " ]
</td></tr> </td></tr>
\n"; \n";
@ -104,36 +98,30 @@ echo "\n
<td align=center> <td align=center>
$stat[p_all] / <b>$stat[p_within_ann]</b> $stat[p_all] / <b>$stat[p_within_ann]</b>
&nbsp; &nbsp;
[ up: ". humn_size($stat['speed_up']) ."/s, [ up: " . humn_size($stat['speed_up']) . "/s,
down: ". humn_size($stat['speed_down']) ."/s ] down: " . humn_size($stat['speed_down']) . "/s ]
</td></tr> </td></tr>
\n"; \n";
echo "\n<tr><td align=center> peers: in last ". join(' / ', $peers_in_last_minutes) ." min</td>\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<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 "\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 '<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 '</table>';
echo '<div align="center"><pre>'; echo '<div align="center"><pre>';
if ($l = sys('la')) if ($l = sys('la')) {
{
$l = explode(' ', $l); $l = explode(' ', $l);
for ($i=0; $i < 3; $i++) for ($i = 0; $i < 3; $i++) {
{
$l[$i] = round($l[$i], 1); $l[$i] = round($l[$i], 1);
} }
echo "\n\n<b>loadavg: </b>$l[0] $l[1] $l[2]\n\n"; 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 '</pre></div>';
echo '</body></html>'; echo '</body></html>';
DB()->query("DROP TEMPORARY TABLE ". TMP_TRACKER_TABLE); DB()->query("DROP TEMPORARY TABLE " . TMP_TRACKER_TABLE);
bb_exit(); bb_exit();

145
ajax.php
View file

@ -15,21 +15,16 @@ $user->session_start();
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
// Exit if board is disabled via ON/OFF trigger or by admin // Exit if board is disabled via ON/OFF trigger or by admin
if ($ajax->action != 'manage_admin') if ($ajax->action != 'manage_admin') {
{ if ($di->config->get('board_disable')) {
if ($di->config->get('board_disable'))
{
$ajax->ajax_die($lang['BOARD_DISABLE']); $ajax->ajax_die($lang['BOARD_DISABLE']);
} } elseif (file_exists(BB_DISABLED)) {
else if (file_exists(BB_DISABLED))
{
$ajax->ajax_die($lang['BOARD_DISABLE_CRON']); $ajax->ajax_die($lang['BOARD_DISABLE_CRON']);
} }
} }
// Load actions required modules // Load actions required modules
switch ($ajax->action) switch ($ajax->action) {
{
case 'view_post': case 'view_post':
require(INC_DIR . 'bbcode.php'); require(INC_DIR . 'bbcode.php');
break; break;
@ -64,7 +59,7 @@ switch ($ajax->action)
break; break;
case 'sitemap'; case 'sitemap';
require(CLASS_DIR .'sitemap.php'); require(CLASS_DIR . 'sitemap.php');
break; break;
} }
@ -78,10 +73,10 @@ $ajax->exec();
// //
class ajax_common class ajax_common
{ {
var $request = []; public $request = [];
var $response = []; public $response = [];
var $valid_actions = [ public $valid_actions = [
// ACTION NAME AJAX_AUTH // ACTION NAME AJAX_AUTH
'edit_user_profile' => ['admin'], 'edit_user_profile' => ['admin'],
'change_user_rank' => ['admin'], 'change_user_rank' => ['admin'],
@ -108,12 +103,12 @@ class ajax_common
'index_data' => ['guest'], 'index_data' => ['guest'],
]; ];
var $action = null; public $action = null;
/** /**
* Constructor * Constructor
*/ */
function ajax_common() public function ajax_common()
{ {
ob_start([&$this, 'ob_handler']); ob_start([&$this, 'ob_handler']);
header('Content-Type: text/plain'); header('Content-Type: text/plain');
@ -122,47 +117,40 @@ class ajax_common
/** /**
* Perform action * Perform action
*/ */
function exec() public function exec()
{ {
global $lang; global $lang;
// Exit if we already have errors // Exit if we already have errors
if (!empty($this->response['error_code'])) if (!empty($this->response['error_code'])) {
{
$this->send(); $this->send();
} }
// Check that requested action is valid // Check that requested action is valid
$action = $this->action; $action = $this->action;
if (!$action || !is_string($action)) if (!$action || !is_string($action)) {
{
$this->ajax_die('no action specified'); $this->ajax_die('no action specified');
} } elseif (!$action_params =& $this->valid_actions[$action]) {
elseif (!$action_params =& $this->valid_actions[$action])
{
$this->ajax_die('invalid action: ' . $action); $this->ajax_die('invalid action: ' . $action);
} }
// Auth check // Auth check
switch ($action_params[AJAX_AUTH]) switch ($action_params[AJAX_AUTH]) {
{
// GUEST // GUEST
case 'guest': case 'guest':
break; break;
// USER // USER
case 'user': case 'user':
if (IS_GUEST) if (IS_GUEST) {
{
$this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']);
} }
break; break;
// MOD // MOD
case 'mod': case 'mod':
if (!IS_AM) if (!IS_AM) {
{
$this->ajax_die($lang['ONLY_FOR_MOD']); $this->ajax_die($lang['ONLY_FOR_MOD']);
} }
$this->check_admin_session(); $this->check_admin_session();
@ -170,8 +158,7 @@ class ajax_common
// ADMIN // ADMIN
case 'admin': case 'admin':
if (!IS_ADMIN) if (!IS_ADMIN) {
{
$this->ajax_die($lang['ONLY_FOR_ADMIN']); $this->ajax_die($lang['ONLY_FOR_ADMIN']);
} }
$this->check_admin_session(); $this->check_admin_session();
@ -179,8 +166,7 @@ class ajax_common
// SUPER_ADMIN // SUPER_ADMIN
case 'super_admin': case 'super_admin':
if (!IS_SUPER_ADMIN) if (!IS_SUPER_ADMIN) {
{
$this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']); $this->ajax_die($lang['ONLY_FOR_SUPER_ADMIN']);
} }
$this->check_admin_session(); $this->check_admin_session();
@ -203,7 +189,7 @@ class ajax_common
* @param $error_msg * @param $error_msg
* @param int $error_code * @param int $error_code
*/ */
function ajax_die($error_msg, $error_code = E_AJAX_GENERAL_ERROR) public function ajax_die($error_msg, $error_code = E_AJAX_GENERAL_ERROR)
{ {
$this->response['error_code'] = $error_code; $this->response['error_code'] = $error_code;
$this->response['error_msg'] = $error_msg; $this->response['error_msg'] = $error_msg;
@ -214,7 +200,7 @@ class ajax_common
/** /**
* Initialization * Initialization
*/ */
function init() public function init()
{ {
$this->request = $_POST; $this->request = $_POST;
$this->action =& $this->request['action']; $this->action =& $this->request['action'];
@ -223,12 +209,11 @@ class ajax_common
/** /**
* Send data * Send data
*/ */
function send() public function send()
{ {
$this->response['action'] = $this->action; $this->response['action'] = $this->action;
if (DBG_USER && SQL_DEBUG && !empty($_COOKIE['sql_log'])) if (DBG_USER && SQL_DEBUG && !empty($_COOKIE['sql_log'])) {
{
$this->response['sql_log'] = get_sql_log(); $this->response['sql_log'] = get_sql_log();
} }
@ -243,22 +228,18 @@ class ajax_common
* *
* @return string * @return string
*/ */
function ob_handler($contents) public function ob_handler($contents)
{
if (DBG_USER)
{
if ($contents)
{ {
if (DBG_USER) {
if ($contents) {
$this->response['raw_output'] = $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 (GZIP_OUTPUT_ALLOWED && !defined('NO_GZIP')) {
{ if (UA_GZIP_SUPPORTED && strlen($response_js) > 2000) {
if (UA_GZIP_SUPPORTED && strlen($response_js) > 2000)
{
header('Content-Encoding: gzip'); header('Content-Encoding: gzip');
$response_js = gzencode($response_js, 1); $response_js = gzencode($response_js, 1);
} }
@ -270,24 +251,19 @@ class ajax_common
/** /**
* Admin session * Admin session
*/ */
function check_admin_session() public function check_admin_session()
{ {
global $user; global $user;
if (!$user->data['session_admin']) if (!$user->data['session_admin']) {
{ if (empty($this->request['user_password'])) {
if (empty($this->request['user_password']))
{
$this->prompt_for_password(); $this->prompt_for_password();
} } else {
else
{
$login_args = [ $login_args = [
'login_username' => $user->data['username'], 'login_username' => $user->data['username'],
'login_password' => $_POST['user_password'], 'login_password' => $_POST['user_password'],
]; ];
if (!$user->login($login_args, true)) if (!$user->login($login_args, true)) {
{
$this->ajax_die('Wrong password'); $this->ajax_die('Wrong password');
} }
} }
@ -297,7 +273,7 @@ class ajax_common
/** /**
* Prompt for password * Prompt for password
*/ */
function prompt_for_password() public function prompt_for_password()
{ {
$this->response['prompt_password'] = 1; $this->response['prompt_password'] = 1;
$this->send(); $this->send();
@ -308,9 +284,11 @@ class ajax_common
* *
* @param $confirm_msg * @param $confirm_msg
*/ */
function prompt_for_confirm($confirm_msg) public function prompt_for_confirm($confirm_msg)
{ {
if (empty($confirm_msg)) $this->ajax_die('false'); if (empty($confirm_msg)) {
$this->ajax_die('false');
}
$this->response['prompt_confirm'] = 1; $this->response['prompt_confirm'] = 1;
$this->response['confirm_msg'] = $confirm_msg; $this->response['confirm_msg'] = $confirm_msg;
@ -322,115 +300,114 @@ class ajax_common
* *
* @param $forum_id * @param $forum_id
*/ */
function verify_mod_rights($forum_id) public function verify_mod_rights($forum_id)
{ {
global $userdata, $lang; global $userdata, $lang;
$is_auth = auth(AUTH_MOD, $forum_id, $userdata); $is_auth = auth(AUTH_MOD, $forum_id, $userdata);
if (!$is_auth['auth_mod']) if (!$is_auth['auth_mod']) {
{
$this->ajax_die($lang['ONLY_FOR_MOD']); $this->ajax_die($lang['ONLY_FOR_MOD']);
} }
} }
function edit_user_profile() public function edit_user_profile()
{ {
require(AJAX_DIR . 'edit_user_profile.php'); require(AJAX_DIR . 'edit_user_profile.php');
} }
function change_user_rank() public function change_user_rank()
{ {
require(AJAX_DIR . 'change_user_rank.php'); require(AJAX_DIR . 'change_user_rank.php');
} }
function change_user_opt() public function change_user_opt()
{ {
require(AJAX_DIR . 'change_user_opt.php'); require(AJAX_DIR . 'change_user_opt.php');
} }
function gen_passkey() public function gen_passkey()
{ {
require(AJAX_DIR . 'gen_passkey.php'); require(AJAX_DIR . 'gen_passkey.php');
} }
function group_membership() public function group_membership()
{ {
require(AJAX_DIR . 'group_membership.php'); require(AJAX_DIR . 'group_membership.php');
} }
function manage_group() public function manage_group()
{ {
require(AJAX_DIR . 'edit_group_profile.php'); require(AJAX_DIR . 'edit_group_profile.php');
} }
function post_mod_comment() public function post_mod_comment()
{ {
require(AJAX_DIR . 'post_mod_comment.php'); require(AJAX_DIR . 'post_mod_comment.php');
} }
function view_post() public function view_post()
{ {
require(AJAX_DIR . 'view_post.php'); require(AJAX_DIR . 'view_post.php');
} }
function change_tor_status() public function change_tor_status()
{ {
require(AJAX_DIR . 'change_tor_status.php'); require(AJAX_DIR . 'change_tor_status.php');
} }
function change_torrent() public function change_torrent()
{ {
require(AJAX_DIR . 'change_torrent.php'); require(AJAX_DIR . 'change_torrent.php');
} }
function view_torrent() public function view_torrent()
{ {
require(AJAX_DIR . 'view_torrent.php'); require(AJAX_DIR . 'view_torrent.php');
} }
function user_register() public function user_register()
{ {
require(AJAX_DIR . 'user_register.php'); require(AJAX_DIR . 'user_register.php');
} }
function mod_action() public function mod_action()
{ {
require(AJAX_DIR . 'mod_action.php'); require(AJAX_DIR . 'mod_action.php');
} }
function posts() public function posts()
{ {
require(AJAX_DIR . 'posts.php'); require(AJAX_DIR . 'posts.php');
} }
function manage_user() public function manage_user()
{ {
require(AJAX_DIR . 'manage_user.php'); require(AJAX_DIR . 'manage_user.php');
} }
function manage_admin() public function manage_admin()
{ {
require(AJAX_DIR . 'manage_admin.php'); require(AJAX_DIR . 'manage_admin.php');
} }
function topic_tpl() public function topic_tpl()
{ {
require(AJAX_DIR . 'topic_tpl.php'); require(AJAX_DIR . 'topic_tpl.php');
} }
function index_data() public function index_data()
{ {
require(AJAX_DIR . 'index_data.php'); require(AJAX_DIR . 'index_data.php');
} }
function avatar() public function avatar()
{ {
require(AJAX_DIR . 'avatar.php'); require(AJAX_DIR . 'avatar.php');
} }
function sitemap() public function sitemap()
{ {
require(AJAX_DIR .'sitemap.php'); require(AJAX_DIR . 'sitemap.php');
} }
} }

View file

@ -2,7 +2,7 @@
define('IN_TRACKER', true); define('IN_TRACKER', true);
define('BB_ROOT', './../'); define('BB_ROOT', './../');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -10,16 +10,16 @@ $di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */ /** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache; $cache = $di->cache;
if (empty($_SERVER['HTTP_USER_AGENT'])) if (empty($_SERVER['HTTP_USER_AGENT'])) {
{
header('Location: http://127.0.0.1', true, 301); header('Location: http://127.0.0.1', true, 301);
die; die;
} }
// Ignore 'completed' event // Ignore 'completed' event
if (isset($_GET['event']) && $_GET['event'] === 'completed') if (isset($_GET['event']) && $_GET['event'] === 'completed') {
{ if (DBG_LOG) {
if (DBG_LOG) dbg_log(' ', '!die-event-completed'); dbg_log(' ', '!die-event-completed');
}
dummy_exit(mt_rand(600, 1200)); dummy_exit(mt_rand(600, 1200));
} }
@ -31,18 +31,15 @@ $max_up_add_val = 85899345920; // 80 GB
$max_down_add_val = 85899345920; // 80 GB $max_down_add_val = 85899345920; // 80 GB
// Recover info_hash // Recover info_hash
if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) {
{
$_GET['info_hash'] = $_GET['?info_hash']; $_GET['info_hash'] = $_GET['?info_hash'];
} }
// Initial request verification // Initial request verification
if (strpos($_SERVER['REQUEST_URI'], 'scrape') !== false) if (strpos($_SERVER['REQUEST_URI'], 'scrape') !== false) {
{
msg_die('Please disable SCRAPE!'); msg_die('Please disable SCRAPE!');
} }
if (!isset($_GET[$passkey_key]) || !is_string($_GET[$passkey_key]) || strlen($_GET[$passkey_key]) != BT_AUTH_KEY_LENGTH) 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)'); msg_die('Please LOG IN and REDOWNLOAD this torrent (passkey not found)');
} }
@ -66,66 +63,50 @@ $input_vars_num = array(
// Init received data // Init received data
// String // String
foreach ($input_vars_str as $var_name) foreach ($input_vars_str as $var_name) {
{ $$var_name = isset($_GET[$var_name]) ? (string)$_GET[$var_name] : null;
$$var_name = isset($_GET[$var_name]) ? (string) $_GET[$var_name] : null;
} }
// Numeric // Numeric
foreach ($input_vars_num as $var_name) foreach ($input_vars_num as $var_name) {
{ $$var_name = isset($_GET[$var_name]) ? (float)$_GET[$var_name] : null;
$$var_name = isset($_GET[$var_name]) ? (float) $_GET[$var_name] : null;
} }
// Passkey // Passkey
$passkey = isset($$passkey_key) ? $$passkey_key : null; $passkey = isset($$passkey_key) ? $$passkey_key : null;
// Verify request // Verify request
// Required params (info_hash, peer_id, port, uploaded, downloaded, left, passkey) // Required params (info_hash, peer_id, port, uploaded, downloaded, left, passkey)
if (!isset($info_hash) || strlen($info_hash) != 20) if (!isset($info_hash) || strlen($info_hash) != 20) {
{
msg_die('Invalid info_hash'); msg_die('Invalid info_hash');
} }
if (!isset($peer_id) || strlen($peer_id) != 20) if (!isset($peer_id) || strlen($peer_id) != 20) {
{
msg_die('Invalid peer_id'); msg_die('Invalid peer_id');
} }
if (!isset($port) || $port < 0 || $port > 0xFFFF) if (!isset($port) || $port < 0 || $port > 0xFFFF) {
{
msg_die('Invalid port'); msg_die('Invalid port');
} }
if (!isset($uploaded) || $uploaded < 0 || $uploaded > $max_up_down_val || $uploaded == 1844674407370) if (!isset($uploaded) || $uploaded < 0 || $uploaded > $max_up_down_val || $uploaded == 1844674407370) {
{
msg_die('Invalid uploaded value'); msg_die('Invalid uploaded value');
} }
if (!isset($downloaded) || $downloaded < 0 || $downloaded > $max_up_down_val || $downloaded == 1844674407370) if (!isset($downloaded) || $downloaded < 0 || $downloaded > $max_up_down_val || $downloaded == 1844674407370) {
{
msg_die('Invalid downloaded value'); msg_die('Invalid downloaded value');
} }
if (!isset($left) || $left < 0 || $left > $max_left_val) if (!isset($left) || $left < 0 || $left > $max_left_val) {
{
msg_die('Invalid left value'); msg_die('Invalid left value');
} }
if (!verify_id($passkey, BT_AUTH_KEY_LENGTH)) if (!verify_id($passkey, BT_AUTH_KEY_LENGTH)) {
{
msg_die('Invalid passkey'); msg_die('Invalid passkey');
} }
// IP // IP
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
if (!$di->config->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_GET['ip']) if (!$di->config->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_GET['ip']) {
{ if (!$di->config->get('verify_reported_ip')) {
if (!$di->config->get('verify_reported_ip'))
{
$ip = $_GET['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)) {
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']) {
foreach ($matches[0] as $x_ip) if (!$di->config->get('allow_internal_ip') && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip)) {
{
if ($x_ip === $_GET['ip'])
{
if (!$di->config->get('allow_internal_ip') && preg_match("#^(10|172\.16|192\.168)\.#", $x_ip))
{
break; break;
} }
$ip = $x_ip; $ip = $x_ip;
@ -135,8 +116,7 @@ if (!$di->config->get('ignore_reported_ip') && isset($_GET['ip']) && $ip !== $_G
} }
} }
// Check that IP format is valid // Check that IP format is valid
if (!verify_ip($ip)) if (!verify_ip($ip)) {
{
msg_die("Invalid IP: $ip"); msg_die("Invalid IP: $ip");
} }
// Convert IP to HEX format // Convert IP to HEX format
@ -150,21 +130,21 @@ $peer_hash = md5(
// Get cached peer info from previous announce (last peer info) // Get cached peer info from previous announce (last peer info)
$lp_info = $cache->get(PEER_HASH_PREFIX . $peer_hash); $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 // Drop fast announce
if ($lp_info && (!isset($event) || $event !== 'stopped')) if ($lp_info && (!isset($event) || $event !== 'stopped')) {
{
drop_fast_announce($lp_info); drop_fast_announce($lp_info);
} }
// Functions // 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)) if ($lp_info['update_time'] < (TIMENOW - $announce_interval + 60)) {
{
return; // if announce interval correct return; // if announce interval correct
} }
@ -173,24 +153,23 @@ function drop_fast_announce ($lp_info)
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, # 'interval' => (int) 1800,
'min interval' => (int) 1800, 'min interval' => (int)1800,
# 'peers' => (string) DUMMY_PEER, # 'peers' => (string) DUMMY_PEER,
'failure reason' => (string) $msg, 'failure reason' => (string)$msg,
'warning message' => (string) $msg, 'warning message' => (string)$msg,
]); ]);
die($output); die($output);
} }
# $agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-';
# bb_log("$agent | ". str_compact($peer_id) ."\n", 'agent');
// Start announcer // Start announcer
define('TR_ROOT', './'); define('TR_ROOT', './');
require(TR_ROOT . 'includes/init_tr.php'); require(TR_ROOT . 'includes/init_tr.php');
@ -199,26 +178,26 @@ $seeder = ($left == 0) ? 1 : 0;
$stopped = ($event === 'stopped'); $stopped = ($event === 'stopped');
// Stopped event // Stopped event
if ($stopped) if ($stopped) {
{
$cache->delete(PEER_HASH_PREFIX . $peer_hash); $cache->delete(PEER_HASH_PREFIX . $peer_hash);
if (DBG_LOG) dbg_log(' ', 'stopped'); if (DBG_LOG) {
dbg_log(' ', 'stopped');
}
} }
// Get last peer info from DB // Get last peer info from DB
if (!$lp_info) if (!$lp_info) {
{
$lp_info = DB()->fetch_row(" $lp_info = DB()->fetch_row("
SELECT * FROM ". BB_BT_TRACKER ." WHERE peer_hash = '$peer_hash' LIMIT 1 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 ($lp_info) {
{ if (!$stopped) {
if (!$stopped)
{
drop_fast_announce($lp_info); drop_fast_announce($lp_info);
} }
@ -226,49 +205,41 @@ if ($lp_info)
$topic_id = $lp_info['topic_id']; $topic_id = $lp_info['topic_id'];
$releaser = $lp_info['releaser']; $releaser = $lp_info['releaser'];
$tor_type = $lp_info['tor_type']; $tor_type = $lp_info['tor_type'];
} } else {
else
{
// Verify if torrent registered on tracker and user authorized // Verify if torrent registered on tracker and user authorized
$info_hash_sql = rtrim(DB()->escape($info_hash), ' '); $info_hash_sql = rtrim(DB()->escape($info_hash), ' ');
$passkey_sql = DB()->escape($passkey); $passkey_sql = DB()->escape($passkey);
$sql = " $sql = "
SELECT tor.topic_id, tor.poster_id, tor.tor_type, u.* SELECT tor.topic_id, tor.poster_id, tor.tor_type, u.*
FROM ". BB_BT_TORRENTS ." tor FROM " . BB_BT_TORRENTS . " tor
LEFT JOIN ". BB_BT_USERS ." u ON u.auth_key = '$passkey_sql' LEFT JOIN " . BB_BT_USERS . " u ON u.auth_key = '$passkey_sql'
WHERE tor.info_hash = '$info_hash_sql' WHERE tor.info_hash = '$info_hash_sql'
LIMIT 1 LIMIT 1
"; ";
$row = DB()->fetch_row($sql); $row = DB()->fetch_row($sql);
if (empty($row['topic_id'])) if (empty($row['topic_id'])) {
{
msg_die('Torrent not registered, info_hash = ' . bin2hex($info_hash_sql)); msg_die('Torrent not registered, info_hash = ' . bin2hex($info_hash_sql));
} }
if (empty($row['user_id'])) if (empty($row['user_id'])) {
{
msg_die('Please LOG IN and REDOWNLOAD this torrent (user not found)'); msg_die('Please LOG IN and REDOWNLOAD this torrent (user not found)');
} }
$user_id = $row['user_id']; $user_id = $row['user_id'];
$topic_id = $row['topic_id']; $topic_id = $row['topic_id'];
$releaser = (int) ($user_id == $row['poster_id']); $releaser = (int)($user_id == $row['poster_id']);
$tor_type = $row['tor_type']; $tor_type = $row['tor_type'];
// Ratio limits // Ratio limits
if ((TR_RATING_LIMITS || $tr_cfg['limit_concurrent_ips']) && !$stopped) 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; $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 = ''; $rating_msg = '';
if (!$seeder) if (!$seeder) {
{ foreach ($rating_limits as $ratio => $limit) {
foreach ($rating_limits as $ratio => $limit) if ($user_ratio < $ratio) {
{
if ($user_ratio < $ratio)
{
$tr_cfg['limit_active_tor'] = 1; $tr_cfg['limit_active_tor'] = 1;
$tr_cfg['limit_leech_count'] = $limit; $tr_cfg['limit_leech_count'] = $limit;
$rating_msg = " (ratio < $ratio)"; $rating_msg = " (ratio < $ratio)";
@ -278,58 +249,46 @@ else
} }
// Limit active torrents // 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))) 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 $sql = "SELECT COUNT(DISTINCT topic_id) AS active_torrents
FROM ". BB_BT_TRACKER ." FROM " . BB_BT_TRACKER . "
WHERE user_id = $user_id WHERE user_id = $user_id
AND seeder = $seeder AND seeder = $seeder
AND topic_id != $topic_id"; AND topic_id != $topic_id";
if (!$seeder && $tr_cfg['leech_expire_factor'] && $user_ratio < 0.5) if (!$seeder && $tr_cfg['leech_expire_factor'] && $user_ratio < 0.5) {
{ $sql .= " AND update_time > " . (TIMENOW - 60 * $tr_cfg['leech_expire_factor']);
$sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']);
} }
$sql .= " GROUP BY user_id"; $sql .= " GROUP BY user_id";
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{ if ($seeder && $tr_cfg['limit_seed_count'] && $row['active_torrents'] >= $tr_cfg['limit_seed_count']) {
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_seed_count'] .' torrent(s) allowed for seeding'); msg_die('Only ' . $tr_cfg['limit_leech_count'] . ' torrent(s) allowed for leeching' . $rating_msg);
}
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 // Limit concurrent IPs
if ($tr_cfg['limit_concurrent_ips'] && (($tr_cfg['limit_seed_ips'] && $seeder) || ($tr_cfg['limit_leech_ips'] && !$seeder))) 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 $sql = "SELECT COUNT(DISTINCT ip) AS ips
FROM ". BB_BT_TRACKER ." FROM " . BB_BT_TRACKER . "
WHERE topic_id = $topic_id WHERE topic_id = $topic_id
AND user_id = $user_id AND user_id = $user_id
AND seeder = $seeder AND seeder = $seeder
AND ip != '$ip_sql'"; AND ip != '$ip_sql'";
if (!$seeder && $tr_cfg['leech_expire_factor']) if (!$seeder && $tr_cfg['leech_expire_factor']) {
{ $sql .= " AND update_time > " . (TIMENOW - 60 * $tr_cfg['leech_expire_factor']);
$sql .= " AND update_time > ". (TIMENOW - 60*$tr_cfg['leech_expire_factor']);
} }
$sql .= " GROUP BY topic_id"; $sql .= " GROUP BY topic_id";
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{ if ($seeder && $tr_cfg['limit_seed_ips'] && $row['ips'] >= $tr_cfg['limit_seed_ips']) {
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 seed only from '. $tr_cfg['limit_seed_ips'] ." IP's"); msg_die('You can leech only from ' . $tr_cfg['limit_leech_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");
} }
} }
} }
@ -339,14 +298,11 @@ else
// Up/Down speed // Up/Down speed
$speed_up = $speed_down = 0; $speed_up = $speed_down = 0;
if ($lp_info && $lp_info['update_time'] < TIMENOW) if ($lp_info && $lp_info['update_time'] < TIMENOW) {
{ if ($uploaded > $lp_info['uploaded']) {
if ($uploaded > $lp_info['uploaded'])
{
$speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time'])); $speed_up = ceil(($uploaded - $lp_info['uploaded']) / (TIMENOW - $lp_info['update_time']));
} }
if ($downloaded > $lp_info['downloaded']) if ($downloaded > $lp_info['downloaded']) {
{
$speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time'])); $speed_down = ceil(($downloaded - $lp_info['downloaded']) / (TIMENOW - $lp_info['update_time']));
} }
} }
@ -356,29 +312,26 @@ $up_add = ($lp_info && $uploaded > $lp_info['uploaded']) ? $uploaded - $lp_info[
$down_add = ($lp_info && $downloaded > $lp_info['downloaded']) ? $downloaded - $lp_info['downloaded'] : 0; $down_add = ($lp_info && $downloaded > $lp_info['downloaded']) ? $downloaded - $lp_info['downloaded'] : 0;
// Gold / silver releases // Gold / silver releases
if ($tr_cfg['gold_silver_enabled'] && $down_add) if ($tr_cfg['gold_silver_enabled'] && $down_add) {
{ if ($tor_type == TOR_TYPE_GOLD) {
if ($tor_type == TOR_TYPE_GOLD)
{
$down_add = 0; $down_add = 0;
} } // Silver releases
// Silver releases elseif ($tor_type == TOR_TYPE_SILVER) {
elseif ($tor_type == TOR_TYPE_SILVER) $down_add = ceil($down_add / 2);
{
$down_add = ceil($down_add/2);
} }
} }
// Freeleech // Freeleech
if ($tr_cfg['freeleech'] && $down_add) $down_add = 0; if ($tr_cfg['freeleech'] && $down_add) {
$down_add = 0;
}
// Insert / update peer info // Insert / update peer info
$peer_info_updated = false; $peer_info_updated = false;
$update_time = ($stopped) ? 0 : TIMENOW; $update_time = ($stopped) ? 0 : TIMENOW;
if ($lp_info) if ($lp_info) {
{ $sql = "UPDATE " . BB_BT_TRACKER . " SET update_time = $update_time";
$sql = "UPDATE ". BB_BT_TRACKER ." SET update_time = $update_time";
$sql .= ", seeder = $seeder"; $sql .= ", seeder = $seeder";
$sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : ''; $sql .= ($releaser != $lp_info['releaser']) ? ", releaser = $releaser" : '';
@ -402,75 +355,75 @@ if ($lp_info)
$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) 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'; $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"; $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 // Exit if stopped
if ($stopped) if ($stopped) {
{
silent_exit(); silent_exit();
} }
// Store peer info in cache // Store peer info in cache
$lp_info = array( $lp_info = array(
'downloaded' => (float) $downloaded, 'downloaded' => (float)$downloaded,
'releaser' => (int) $releaser, 'releaser' => (int)$releaser,
'seeder' => (int) $seeder, 'seeder' => (int)$seeder,
'topic_id' => (int) $topic_id, 'topic_id' => (int)$topic_id,
'update_time' => (int) TIMENOW, 'update_time' => (int)TIMENOW,
'uploaded' => (float) $uploaded, 'uploaded' => (float)$uploaded,
'user_id' => (int) $user_id, 'user_id' => (int)$user_id,
'tor_type' => (int) $tor_type, 'tor_type' => (int)$tor_type,
); );
$lp_info_cached = $cache->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, PEER_HASH_EXPIRE); $lp_info_cached = $cache->set(PEER_HASH_PREFIX . $peer_hash, $lp_info, PEER_HASH_EXPIRE);
if (DBG_LOG && !$lp_info_cached) dbg_log(' ', '$lp_info-caching-FAIL'); if (DBG_LOG && !$lp_info_cached) {
dbg_log(' ', '$lp_info-caching-FAIL');
}
// Get cached output // Get cached output
$output = $cache->get(PEERS_LIST_PREFIX . $topic_id); $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) if (!$output) {
{
// Retrieve peers // Retrieve peers
$numwant = (int) $tr_cfg['numwant']; $numwant = (int)$tr_cfg['numwant'];
$compact_mode = ($tr_cfg['compact_mode'] || !empty($compact)); $compact_mode = ($tr_cfg['compact_mode'] || !empty($compact));
$rowset = DB()->fetch_rowset(" $rowset = DB()->fetch_rowset("
SELECT ip, port SELECT ip, port
FROM ". BB_BT_TRACKER ." FROM " . BB_BT_TRACKER . "
WHERE topic_id = $topic_id WHERE topic_id = $topic_id
ORDER BY RAND() ORDER BY RAND()
LIMIT $numwant LIMIT $numwant
"); ");
if ($compact_mode) if ($compact_mode) {
{
$peers = ''; $peers = '';
foreach ($rowset as $peer) foreach ($rowset as $peer) {
{
$peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']); $peers .= pack('Nn', ip2long(decode_ip($peer['ip'])), $peer['port']);
} }
} } else {
else
{
$peers = array(); $peers = array();
foreach ($rowset as $peer) foreach ($rowset as $peer) {
{
$peers[] = array( $peers[] = array(
'ip' => decode_ip($peer['ip']), 'ip' => decode_ip($peer['ip']),
'port' => intval($peer['port']), 'port' => intval($peer['port']),
@ -481,11 +434,10 @@ if (!$output)
$seeders = 0; $seeders = 0;
$leechers = 0; $leechers = 0;
if ($tr_cfg['scrape']) if ($tr_cfg['scrape']) {
{
$row = DB()->fetch_row(" $row = DB()->fetch_row("
SELECT seeders, leechers SELECT seeders, leechers
FROM ". BB_BT_TRACKER_SNAP ." FROM " . BB_BT_TRACKER_SNAP . "
WHERE topic_id = $topic_id WHERE topic_id = $topic_id
LIMIT 1 LIMIT 1
"); ");
@ -495,16 +447,18 @@ if (!$output)
} }
$output = array( $output = array(
'interval' => (int) $announce_interval, 'interval' => (int)$announce_interval,
'min interval' => (int) $announce_interval, 'min interval' => (int)$announce_interval,
'peers' => $peers, 'peers' => $peers,
'complete' => (int) $seeders, 'complete' => (int)$seeders,
'incomplete' => (int) $leechers, '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 // Return data to client

View file

@ -1,29 +1,31 @@
<?php <?php
if (!defined('IN_TRACKER')) die(basename(__FILE__)); if (!defined('IN_TRACKER')) {
die(basename(__FILE__));
}
// Exit if tracker is disabled // Exit if tracker is disabled
if ($tr_cfg['off']) tr_die($tr_cfg['off_reason']); if ($tr_cfg['off']) {
tr_die($tr_cfg['off_reason']);
}
// //
// Functions // Functions
// //
function tracker_exit () function tracker_exit()
{ {
global $DBS; global $DBS;
if (DBG_LOG && DBG_TRACKER) if (DBG_LOG && DBG_TRACKER) {
{ if ($gen_time = utime() - TIMESTART) {
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);
$sql_init_perc = round($DBS->sql_inittime*100/$gen_time);
$sql_total_perc = round($DBS->sql_timetotal*100/$gen_time);
$str = array(); $str = array();
$str[] = substr(TIMENOW, -4, 4); $str[] = substr(TIMENOW, -4, 4);
$str[] = sprintf('%.4f', $gen_time); $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_inittime, $sql_init_perc);
$str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_timetotal, $sql_total_perc); $str[] = sprintf('%.4f' . LOG_SEPR . '%02d%%', $DBS->sql_timetotal, $sql_total_perc);
$str[] = $DBS->num_queries; $str[] = $DBS->num_queries;
$str[] = sprintf('%.1f', sys('la')); $str[] = sprintf('%.1f', sys('la'));
$str = join(LOG_SEPR, $str) . LOG_LF; $str = join(LOG_SEPR, $str) . LOG_LF;
@ -33,16 +35,18 @@ function tracker_exit ()
exit; 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();
@ -54,33 +58,35 @@ function error_exit ($msg = '')
// Database // Database
class sql_db class sql_db
{ {
var $cfg = array(); public $cfg = array();
var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); public $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist');
var $link = null; public $link = null;
var $result = null; public $result = null;
var $db_server = ''; public $db_server = '';
var $selected_db = null; public $selected_db = null;
var $locked = false; public $locked = false;
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $sql_last_time = 0; public $sql_last_time = 0;
var $slow_time = 0; public $slow_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
var $DBS = array(); public $DBS = array();
/** /**
* Constructor * Constructor
* @param $cfg_values
* @return sql_db
*/ */
function sql_db ($cfg_values) public function sql_db($cfg_values)
{ {
global $DBS; global $DBS;
@ -96,7 +102,7 @@ class sql_db
/** /**
* Initialize connection * Initialize connection
*/ */
function init () public function init()
{ {
// Connect to server // Connect to server
$this->link = $this->connect(); $this->link = $this->connect();
@ -105,10 +111,8 @@ class sql_db
$this->selected_db = $this->select_db(); $this->selected_db = $this->select_db();
// Set charset // Set charset
if ($this->cfg['charset'] && !mysql_set_charset($this->cfg['charset'], $this->link)) if ($this->cfg['charset'] && !mysql_set_charset($this->cfg['charset'], $this->link)) {
{ if (!$this->sql_query("SET NAMES {$this->cfg['charset']}")) {
if (!$this->sql_query("SET NAMES {$this->cfg['charset']}"))
{
error_exit("Could not set charset {$this->cfg['charset']}"); error_exit("Could not set charset {$this->cfg['charset']}");
} }
} }
@ -121,15 +125,14 @@ class sql_db
/** /**
* Open connection * Open connection
*/ */
function connect () public function connect()
{ {
$this->cur_query = 'connect'; $this->cur_query = 'connect';
$this->debug('start'); $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'])) if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) {
{
$this->log_error(); $this->log_error();
} }
@ -140,14 +143,10 @@ class sql_db
# if (DBG_LOG) dbg_log(' ', 'DB-connect'. ($link ? '' : '-FAIL')); # if (DBG_LOG) dbg_log(' ', 'DB-connect'. ($link ? '' : '-FAIL'));
if (!$link) if (!$link) {
{ if (function_exists('dummy_exit')) {
if (function_exists('dummy_exit'))
{
dummy_exit(mt_rand(1200, 2400)); dummy_exit(mt_rand(1200, 2400));
} } else {
else
{
die; die;
} }
} }
@ -158,13 +157,12 @@ class sql_db
/** /**
* Select database * Select database
*/ */
function select_db () public function select_db()
{ {
$this->cur_query = 'select db'; $this->cur_query = 'select db';
$this->debug('start'); $this->debug('start');
if (!mysql_select_db($this->cfg['dbname'], $this->link)) if (!mysql_select_db($this->cfg['dbname'], $this->link)) {
{
$this->log_error(); $this->log_error();
error_exit("Could not select database '{$this->cfg['dbname']}'"); error_exit("Could not select database '{$this->cfg['dbname']}'");
} }
@ -177,18 +175,18 @@ class sql_db
/** /**
* Base query method * Base query method
* @param $query
* @return null|resource
*/ */
function sql_query ($query) public function sql_query($query)
{
if (!is_resource($this->link))
{ {
if (!is_resource($this->link)) {
$this->init(); $this->init();
} }
$this->cur_query = $query; $this->cur_query = $query;
$this->debug('start'); $this->debug('start');
if (!$this->result = mysql_query($query, $this->link)) if (!$this->result = mysql_query($query, $this->link)) {
{
$this->log_error(); $this->log_error();
} }
@ -203,11 +201,12 @@ class sql_db
/** /**
* Execute query WRAPPER (with error handling) * Execute query WRAPPER (with error handling)
* @param $query
* @return null|resource
*/ */
function query ($query) public function query($query)
{
if (!$result = $this->sql_query($query))
{ {
if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
} }
@ -216,13 +215,14 @@ class sql_db
/** /**
* Return number of rows * Return number of rows
* @param bool $result
* @return bool|int
*/ */
function num_rows ($result = false) public function num_rows($result = false)
{ {
$num_rows = false; $num_rows = false;
if ($result || ($result = $this->result)) if ($result || ($result = $this->result)) {
{
$num_rows = is_resource($result) ? mysql_num_rows($result) : false; $num_rows = is_resource($result) ? mysql_num_rows($result) : false;
} }
@ -232,34 +232,39 @@ class sql_db
/** /**
* Return number of affected rows * Return number of affected rows
*/ */
function affected_rows () public function affected_rows()
{ {
return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; return is_resource($this->link) ? mysql_affected_rows($this->link) : -1;
} }
/** /**
* Fetch current row * Fetch current row
* @param $result
* @return array|bool
*/ */
function sql_fetchrow ($result) public function sql_fetchrow($result)
{ {
return is_resource($result) ? mysql_fetch_assoc($result) : false; return is_resource($result) ? mysql_fetch_assoc($result) : false;
} }
/** /**
* Alias of sql_fetchrow() * Alias of sql_fetchrow()
* @param $result
* @return array|bool
*/ */
function fetch_next ($result) public function fetch_next($result)
{ {
return $this->sql_fetchrow($result); return $this->sql_fetchrow($result);
} }
/** /**
* Fetch row WRAPPER (with error handling) * Fetch row WRAPPER (with error handling)
* @param $query
* @return array|bool
*/ */
function fetch_row ($query) public function fetch_row($query)
{
if (!$result = $this->sql_query($query))
{ {
if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
} }
@ -268,13 +273,14 @@ class sql_db
/** /**
* Fetch all rows * Fetch all rows
* @param $result
* @return array
*/ */
function sql_fetchrowset ($result) public function sql_fetchrowset($result)
{ {
$rowset = array(); $rowset = array();
while ($row = mysql_fetch_assoc($result)) while ($row = mysql_fetch_assoc($result)) {
{
$rowset[] = $row; $rowset[] = $row;
} }
@ -283,11 +289,12 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
* @param $query
* @return array
*/ */
function fetch_rowset ($query) public function fetch_rowset($query)
{
if (!$result = $this->sql_query($query))
{ {
if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
} }
@ -296,42 +303,46 @@ class sql_db
/** /**
* Escape string used in sql query * Escape string used in sql query
* @param $v
* @param bool $check_type
* @return string
*/ */
function escape ($v, $check_type = false) public function escape($v, $check_type = false)
{
if (!is_resource($this->link))
{ {
if (!is_resource($this->link)) {
$this->init(); $this->init();
} }
if (!$check_type) if (!$check_type) {
{
return mysql_real_escape_string($v); return mysql_real_escape_string($v);
} }
switch (true) switch (true) {
{ case is_string($v):
case is_string ($v): return "'". mysql_real_escape_string($v) ."'"; return "'" . mysql_real_escape_string($v) . "'";
case is_int ($v): return "$v"; case is_int($v):
case is_bool ($v): return ($v) ? '1' : '0'; return "$v";
case is_float ($v): return "'$v'"; case is_bool($v):
case is_null ($v): return 'NULL'; return ($v) ? '1' : '0';
case is_float($v):
return "'$v'";
case is_null($v):
return 'NULL';
} }
// if $v has unsuitable type // if $v has unsuitable type
$this->trigger_error(__FUNCTION__ .' - wrong params'); $this->trigger_error(__FUNCTION__ . ' - wrong params');
} }
/** /**
* Return sql error array * Return sql error array
*/ */
function sql_error () public function sql_error()
{ {
$return_ary = array( $return_ary = array(
'code' => '', 'code' => '',
'message' => 'not connected', 'message' => 'not connected',
); );
if (is_resource($this->link)) if (is_resource($this->link)) {
{
$return_ary = array( $return_ary = array(
'code' => mysql_errno($this->link), 'code' => mysql_errno($this->link),
'message' => mysql_error($this->link), 'message' => mysql_error($this->link),
@ -344,38 +355,34 @@ class sql_db
/** /**
* Close sql connection * Close sql connection
*/ */
function close () public function close()
{
if (is_resource($this->link))
{ {
if (is_resource($this->link)) {
mysql_close($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 * Get info about last query
*/ */
function query_info () public function query_info()
{ {
$info = array(); $info = array();
if ($num = $this->num_rows($this->result)) if ($num = $this->num_rows($this->result)) {
{
$info[] = "$num rows"; $info[] = "$num rows";
} }
if (is_resource($this->link) && ($ext = mysql_info($this->link))) if (is_resource($this->link) && ($ext = mysql_info($this->link))) {
{
$info[] = "$ext"; $info[] = "$ext";
} } elseif (!$num && ($aff = $this->affected_rows($this->result))) {
elseif (!$num && ($aff = $this->affected_rows($this->result))) if ($aff != -1) {
{
if ($aff != -1)
{
$info[] = "$aff rows"; $info[] = "$aff rows";
} }
} }
@ -385,34 +392,31 @@ class sql_db
/** /**
* Store debug info * Store debug info
* @param $mode
*/ */
function debug ($mode) public function debug($mode)
{ {
if (!SQL_DEBUG) return; if (!SQL_DEBUG) {
return;
}
if ($mode == 'start') if ($mode == 'start') {
{ if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) {
if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES)
{
$this->sql_starttime = utime(); $this->sql_starttime = utime();
$this->sql_last_time = 0; $this->sql_last_time = 0;
} }
} } elseif ($mode == 'end') {
elseif ($mode == 'end') if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) {
{
if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES)
{
$this->sql_last_time = utime() - $this->sql_starttime; $this->sql_last_time = utime() - $this->sql_starttime;
$this->sql_timetotal += $this->sql_last_time; $this->sql_timetotal += $this->sql_last_time;
$this->DBS['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) if (SQL_LOG_SLOW_QUERIES && $this->sql_last_time > $this->slow_time) {
{
$msg = date('m-d H:i:s') . LOG_SEPR; $msg = date('m-d H:i:s') . LOG_SEPR;
$msg .= sprintf('%03d', round($this->sql_last_time)); $msg .= sprintf('%03d', round($this->sql_last_time));
$msg .= LOG_SEPR . sprintf('%.1f', sys('la')); $msg .= LOG_SEPR . sprintf('%.1f', sys('la'));
$msg .= LOG_SEPR . str_compact($this->cur_query); $msg .= LOG_SEPR . str_compact($this->cur_query);
$msg .= LOG_SEPR .' # '. $this->query_info(); $msg .= LOG_SEPR . ' # ' . $this->query_info();
$msg .= LOG_SEPR . $this->debug_find_source(); $msg .= LOG_SEPR . $this->debug_find_source();
bb_log($msg . LOG_LF, 'sql_slow_tr'); bb_log($msg . LOG_LF, 'sql_slow_tr');
} }
@ -423,21 +427,20 @@ class sql_db
/** /**
* Trigger error * Trigger error
* @param string $msg
*/ */
function trigger_error ($msg = '') public function trigger_error($msg = '')
{ {
if (error_reporting()) if (error_reporting()) {
{ if (!$msg) {
if (!$msg) $msg = 'DB Error'; $msg = 'DB Error';
}
if (DBG_TRACKER === true) if (DBG_TRACKER === true) {
{
$err = $this->sql_error(); $err = $this->sql_error();
$msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message'])); $msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message']));
} } else {
else $msg .= " [" . $this->debug_find_source() . "]";
{
$msg .= " [". $this->debug_find_source() ."]";
} }
error_exit($msg); error_exit($msg);
@ -447,16 +450,14 @@ class sql_db
/** /**
* Find caller source * Find caller source
*/ */
function debug_find_source () public function debug_find_source()
{ {
$source = ''; $source = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
foreach ($backtrace as $trace) foreach ($backtrace as $trace) {
{ if ($trace['file'] !== __FILE__) {
if ($trace['file'] !== __FILE__) $source = str_replace(BB_PATH, '', $trace['file']) . '(' . $trace['line'] . ')';
{
$source = str_replace(BB_PATH, '', $trace['file']) .'('. $trace['line'] .')';
break; break;
} }
} }
@ -467,10 +468,14 @@ class sql_db
/** /**
* Log error * Log error
*/ */
function log_error () public function log_error()
{ {
if (!SQL_LOG_ERRORS) return; if (!SQL_LOG_ERRORS) {
if (!error_reporting()) return; return;
}
if (!error_reporting()) {
return;
}
$msg = array(); $msg = array();
$err = $this->sql_error(); $err = $this->sql_error();
@ -478,14 +483,14 @@ class sql_db
$msg[] = ''; $msg[] = '';
$msg[] = str_compact($this->cur_query); $msg[] = str_compact($this->cur_query);
$msg[] = ''; $msg[] = '';
$msg[] = 'Source : '. $this->debug_find_source(); $msg[] = 'Source : ' . $this->debug_find_source();
$msg[] = 'IP : '. $_SERVER['REMOTE_ADDR']; $msg[] = 'IP : ' . $_SERVER['REMOTE_ADDR'];
$msg[] = 'Date : '. date('Y-m-d H:i:s'); $msg[] = 'Date : ' . date('Y-m-d H:i:s');
$msg[] = 'Agent : '. $_SERVER['HTTP_USER_AGENT']; $msg[] = 'Agent : ' . $_SERVER['HTTP_USER_AGENT'];
$msg[] = 'Req_URI : '. $_SERVER['REQUEST_URI']; $msg[] = 'Req_URI : ' . $_SERVER['REQUEST_URI'];
$msg[] = 'Referer : '. $_SERVER['HTTP_REFERER']; $msg[] = 'Referer : ' . $_SERVER['HTTP_REFERER'];
$msg[] = 'Method : '. $_SERVER['REQUEST_METHOD']; $msg[] = 'Method : ' . $_SERVER['REQUEST_METHOD'];
$msg[] = 'Request : '. trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF; $msg[] = 'Request : ' . trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF;
$msg[] = ''; $msg[] = '';
bb_log($msg, 'sql_error_tr'); bb_log($msg, 'sql_error_tr');
} }

View file

@ -2,31 +2,33 @@
define('IN_TRACKER', true); define('IN_TRACKER', true);
define('BB_ROOT', './../'); define('BB_ROOT', './../');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
if (!$tr_cfg['scrape']) msg_die('Please disable SCRAPE!'); if (!$tr_cfg['scrape']) {
msg_die('Please disable SCRAPE!');
}
// Recover info_hash // Recover info_hash
if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) if (isset($_GET['?info_hash']) && !isset($_GET['info_hash'])) {
{
$_GET['info_hash'] = $_GET['?info_hash']; $_GET['info_hash'] = $_GET['?info_hash'];
} }
if (!isset($_GET['info_hash']) || strlen($_GET['info_hash']) != 20) if (!isset($_GET['info_hash']) || strlen($_GET['info_hash']) != 20) {
{
msg_die('Invalid info_hash'); msg_die('Invalid info_hash');
} }
$info_hash = $_GET['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([ $output = \Rych\Bencode\Bencode::encode([
'min interval' => (int) 1800, 'min interval' => (int)1800,
'failure reason' => (string) $msg, 'failure reason' => (string)$msg,
'warning message' => (string) $msg, 'warning message' => (string)$msg,
]); ]);
die($output); die($output);
@ -39,16 +41,16 @@ $info_hash_sql = rtrim(DB()->escape($info_hash), ' ');
$row = DB()->fetch_row(" $row = DB()->fetch_row("
SELECT tor.complete_count, snap.seeders, snap.leechers SELECT tor.complete_count, snap.seeders, snap.leechers
FROM ". BB_BT_TORRENTS ." tor FROM " . BB_BT_TORRENTS . " tor
LEFT JOIN ". BB_BT_TRACKER_SNAP ." snap ON (snap.topic_id = tor.topic_id) LEFT JOIN " . BB_BT_TRACKER_SNAP . " snap ON (snap.topic_id = tor.topic_id)
WHERE tor.info_hash = '$info_hash_sql' WHERE tor.info_hash = '$info_hash_sql'
LIMIT 1 LIMIT 1
"); ");
$output['files'][$info_hash] = array( $output['files'][$info_hash] = array(
'complete' => (int) $row['seeders'], 'complete' => (int)$row['seeders'],
'downloaded' => (int) $row['complete_count'], 'downloaded' => (int)$row['complete_count'],
'incomplete' => (int) $row['leechers'], 'incomplete' => (int)$row['leechers'],
); );
echo \Rych\Bencode\Bencode::encode($output); echo \Rych\Bencode\Bencode::encode($output);

View file

@ -16,34 +16,30 @@ $forum_id = $t_data['forum_id'];
set_die_append_msg($forum_id, $topic_id); set_die_append_msg($forum_id, $topic_id);
if ($t_data['seeders'] > 2) if ($t_data['seeders'] > 2) {
{
bb_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders'])); bb_die(sprintf($lang['CALLSEED_HAVE_SEED'], $t_data['seeders']));
} } elseif ($t_data['call_seed_time'] > (TIMENOW - 86400)) {
elseif ($t_data['call_seed_time'] > (TIMENOW - 86400))
{
$time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days'); $time_left = delta_time($t_data['call_seed_time'] + 86400, TIMENOW, 'days');
bb_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left)); bb_die(sprintf($lang['CALLSEED_MSG_SPAM'], $time_left));
} }
$ban_user_id = []; $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) foreach ($sql as $row) {
{ $ban_user_id[] = ',' . $row['ban_userid'];
$ban_user_id[] = ','. $row['ban_userid'];
} }
$ban_user_id = join('', $ban_user_id); $ban_user_id = join('', $ban_user_id);
$user_list = DB()->fetch_rowset(" $user_list = DB()->fetch_rowset("
SELECT DISTINCT dl.user_id, u.user_opt, tr.user_id as active_dl SELECT DISTINCT dl.user_id, u.user_opt, tr.user_id as active_dl
FROM ". BB_BT_DLSTATUS ." dl FROM " . BB_BT_DLSTATUS . " dl
LEFT JOIN ". BB_USERS ." u ON(u.user_id = dl.user_id) 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) LEFT JOIN " . BB_BT_TRACKER . " tr ON(tr.user_id = dl.user_id)
WHERE dl.topic_id = $topic_id WHERE dl.topic_id = $topic_id
AND dl.user_status IN (". DL_STATUS_COMPLETE.", ". DL_STATUS_DOWN.") 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_id NOT IN ({$userdata['user_id']}, " . EXCLUDED_USERS . $ban_user_id . ")
AND u.user_active = 1 AND u.user_active = 1
GROUP BY dl.user_id GROUP BY dl.user_id
"); ");
@ -51,29 +47,26 @@ $user_list = DB()->fetch_rowset("
$subject = sprintf($lang['CALLSEED_SUBJECT'], $t_data['topic_title']); $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)); $message = sprintf($lang['CALLSEED_TEXT'], make_url(TOPIC_URL . $topic_id), $t_data['topic_title'], make_url(DOWNLOAD_URL . $topic_id));
if ($user_list) if ($user_list) {
{ foreach ($user_list as $row) {
foreach ($user_list as $row) if (!empty($row['active_dl'])) {
{ continue;
if (!empty($row['active_dl'])) continue; }
if (bf($row['user_opt'], 'user_opt', 'user_callseed')) if (bf($row['user_opt'], 'user_opt', 'user_callseed')) {
{
send_pm($row['user_id'], $subject, $message, BOT_UID); send_pm($row['user_id'], $subject, $message, BOT_UID);
} }
} }
} } else {
else
{
send_pm($t_data['poster_id'], $subject, $message, BOT_UID); 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); meta_refresh(TOPIC_URL . $topic_id);
bb_die($lang['CALLSEED_MSG_OK']); bb_die($lang['CALLSEED_MSG_OK']);
function topic_info ($topic_id) function topic_info($topic_id)
{ {
global $lang; global $lang;
@ -81,14 +74,13 @@ function topic_info ($topic_id)
SELECT SELECT
tor.poster_id, tor.forum_id, tor.call_seed_time, tor.poster_id, tor.forum_id, tor.call_seed_time,
t.topic_title, sn.seeders t.topic_title, sn.seeders
FROM ". BB_BT_TORRENTS ." tor FROM " . BB_BT_TORRENTS . " tor
LEFT JOIN ". BB_TOPICS ." t USING(topic_id) LEFT JOIN " . BB_TOPICS . " t USING(topic_id)
LEFT JOIN ". BB_BT_TRACKER_SNAP ." sn USING(topic_id) LEFT JOIN " . BB_BT_TRACKER_SNAP . " sn USING(topic_id)
WHERE tor.topic_id = $topic_id WHERE tor.topic_id = $topic_id
"; ";
if (!$torrent = DB()->fetch_row($sql)) if (!$torrent = DB()->fetch_row($sql)) {
{
bb_die($lang['TOPIC_POST_NOT_EXIST']); bb_die($lang['TOPIC_POST_NOT_EXIST']);
} }

View file

@ -1,23 +1,34 @@
<?php <?php
if (isset($_REQUEST['GLOBALS'])) die(); if (isset($_REQUEST['GLOBALS'])) {
die();
}
ignore_user_abort(true); ignore_user_abort(true);
define('TIMESTART', utime()); 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'])) {
if (empty($_SERVER['HTTP_USER_AGENT'])) $_SERVER['HTTP_USER_AGENT'] = ''; $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
if (empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER'] = ''; }
if (empty($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME'] = ''; 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 (!defined('BB_ROOT')) define('BB_ROOT', './'); if (!defined('BB_ROOT')) {
define('BB_ROOT', './');
}
header('X-Frame-Options: SAMEORIGIN'); header('X-Frame-Options: SAMEORIGIN');
// Cloudflare // Cloudflare
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
{
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP']; $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
} }
@ -33,7 +44,7 @@ require_once(BB_ROOT . 'library/config.php');
$di = new \TorrentPier\Di(); $di = new \TorrentPier\Di();
// TODO: Need to get locale from settings // TODO: Need to get locale from settings
$di['settings.locale'] = function($di) { $di['settings.locale'] = function ($di) {
return 'en'; return 'en';
}; };
@ -59,6 +70,7 @@ define('BB_CFG_LOADED', true);
// Load Zend Framework // Load Zend Framework
use Zend\Loader\StandardAutoloader; use Zend\Loader\StandardAutoloader;
$loader = new StandardAutoloader(array('autoregister_zf' => true)); $loader = new StandardAutoloader(array('autoregister_zf' => true));
$loader->register(); $loader->register();
@ -119,8 +131,10 @@ $DBS = new DBS([
/** /**
* TODO: @deprecated * TODO: @deprecated
* @param string $db_alias
* @return mixed
*/ */
function DB ($db_alias = 'db') function DB($db_alias = 'db')
{ {
global $DBS; global $DBS;
return $DBS->get_db_obj($db_alias); return $DBS->get_db_obj($db_alias);
@ -139,15 +153,14 @@ require(INC_DIR . 'datastore/xcache.php');
require(INC_DIR . 'datastore/file.php'); require(INC_DIR . 'datastore/file.php');
// Initialize datastore // Initialize datastore
switch ($di->config->get('datastore_type')) switch ($di->config->get('datastore_type')) {
{
case 'memcache': case 'memcache':
$datastore = new datastore_memcache($di->config->get('cache.memcache'), $di->config->get('cache.prefix')); $datastore = new datastore_memcache($di->config->get('cache.memcache'), $di->config->get('cache.prefix'));
break; break;
case 'sqlite': case 'sqlite':
$default_cfg = array( $default_cfg = array(
'db_file_path' => $di->config->get('cache.db_dir') .'datastore.sqlite.db', 'db_file_path' => $di->config->get('cache.db_dir') . 'datastore.sqlite.db',
'pconnect' => true, 'pconnect' => true,
'con_required' => true, 'con_required' => true,
); );
@ -167,24 +180,23 @@ switch ($di->config->get('datastore_type'))
break; break;
case 'filecache': case 'filecache':
default: $datastore = new datastore_file($di->config->get('cache.db_dir') . 'datastore/', $di->config->get('cache.prefix')); 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; $max_len = 100;
$sql = str_compact($sql); $sql = str_compact($sql);
if (!empty($_COOKIE['sql_log_full'])) if (!empty($_COOKIE['sql_log_full'])) {
{ if (mb_strlen($sql, 'UTF-8') > $max_len) {
if (mb_strlen($sql, 'UTF-8') > $max_len) $sql = mb_substr($sql, 0, 50) . ' [...cut...] ' . mb_substr($sql, -50);
{
$sql = mb_substr($sql, 0, 50) .' [...cut...] '. mb_substr($sql, -50);
} }
} }
@ -192,54 +204,47 @@ function short_query ($sql, $esc_html = false)
} }
// Functions // 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)) if (is_array($msg)) {
{
$msg = join(LOG_LF, $msg); $msg = join(LOG_LF, $msg);
} }
$file_name .= (LOG_EXT) ? '.'. LOG_EXT : ''; $file_name .= (LOG_EXT) ? '.' . LOG_EXT : '';
return file_write($msg, LOG_DIR . $file_name); 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) if (file_exists($file) && $max_size && filesize($file) >= $max_size) {
{ $old_name = $file;
$old_name = $file; $ext = ''; $ext = '';
if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) {
{ $old_name = $matches[1];
$old_name = $matches[1]; $ext = $matches[2]; $ext = $matches[2];
} }
$new_name = $old_name .'_[old]_'. date('Y-m-d_H-i-s_') . getmypid() . $ext; $new_name = $old_name . '_[old]_' . date('Y-m-d_H-i-s_') . getmypid() . $ext;
clearstatcache(); clearstatcache();
if (file_exists($file) && filesize($file) >= $max_size && !file_exists($new_name)) if (file_exists($file) && filesize($file) >= $max_size && !file_exists($new_name)) {
{
rename($file, $new_name); rename($file, $new_name);
} }
} }
if (!$fp = fopen($file, 'ab')) if (!$fp = fopen($file, 'ab')) {
{ if ($dir_created = bb_mkdir(dirname($file))) {
if ($dir_created = bb_mkdir(dirname($file)))
{
$fp = fopen($file, 'ab'); $fp = fopen($file, 'ab');
} }
} }
if ($fp) if ($fp) {
{ if ($lock) {
if ($lock)
{
flock($fp, LOCK_EX); flock($fp, LOCK_EX);
} }
if ($replace_content) if ($replace_content) {
{
ftruncate($fp, 0); ftruncate($fp, 0);
fseek($fp, 0, SEEK_SET); fseek($fp, 0, SEEK_SET);
} }
@ -250,7 +255,7 @@ function file_write ($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $repla
return $bytes_written; return $bytes_written;
} }
function bb_mkdir ($path, $mode = 0777) function bb_mkdir($path, $mode = 0777)
{ {
$old_um = umask(0); $old_um = umask(0);
$dir = mkdir_rec($path, $mode); $dir = mkdir_rec($path, $mode);
@ -258,125 +263,108 @@ function bb_mkdir ($path, $mode = 0777)
return $dir; return $dir;
} }
function mkdir_rec ($path, $mode) function mkdir_rec($path, $mode)
{ {
if (is_dir($path)) if (is_dir($path)) {
{
return ($path !== '.' && $path !== '..') ? is_writable($path) : false; return ($path !== '.' && $path !== '..') ? is_writable($path) : false;
} } else {
else
{
return (mkdir_rec(dirname($path), $mode)) ? mkdir($path, $mode) : false; 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('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '); static $s = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' ');
return str_replace($s, '_', str_compact($fname)); return str_replace($s, '_', str_compact($fname));
} }
function encode_ip ($ip) function encode_ip($ip)
{ {
$d = explode('.', $ip); $d = explode('.', $ip);
return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); 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' // 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_int = is_numeric($ip) ? $ip : ip2int($ip);
$ip_masked = $ip_int | ((1 << (32 - $mask)) - 1); $ip_masked = $ip_int | ((1 << (32 - $mask)) - 1);
return (float) sprintf('%u', $ip_masked); 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 = ''; $str = '';
while (strlen($str) < $len) while (strlen($str) < $len) {
{
$str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', password_hash(uniqid(mt_rand(), true), PASSWORD_BCRYPT))); $str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', password_hash(uniqid(mt_rand(), true), PASSWORD_BCRYPT)));
} }
return substr($str, 0, $len); 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)) if (is_array($var)) {
{ foreach ($var as $k => $v) {
foreach ($var as $k => $v) if (is_array($v)) {
{ if ($one_dimensional) {
if (is_array($v))
{
if ($one_dimensional)
{
unset($var[$k]); unset($var[$k]);
} } elseif ($array_only) {
else if ($array_only)
{
$var[$k] = $fn($v); $var[$k] = $fn($v);
} } else {
else
{
array_deep($var[$k], $fn); array_deep($var[$k], $fn);
} }
} } elseif (!$array_only) {
else if (!$array_only)
{
$var[$k] = $fn($v); $var[$k] = $fn($v);
} }
} }
} } elseif (!$array_only) {
else if (!$array_only)
{
$var = $fn($var); $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) switch ($param) {
{
case 'la': case 'la':
return function_exists('sys_getloadavg') ? join(' ', sys_getloadavg()) : 0; return function_exists('sys_getloadavg') ? join(' ', sys_getloadavg()) : 0;
break; break;
@ -391,36 +379,40 @@ function sys ($param)
} }
} }
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') .'/'; $dir = LOG_DIR . (defined('IN_TRACKER') ? 'dbg_tr/' : 'dbg_bb/') . date('m-d_H') . '/';
return file_write($str, $dir . $file, false, false); 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'); $file = ($file) ? $file : 'req/' . date('m-d');
$str = array(); $str = array();
$str[] = date('m-d H:i:s'); $str[] = date('m-d H:i:s');
if ($prepend_str !== false) $str[] = $prepend_str; if ($prepend_str !== false) {
if (!empty($user->data)) $str[] = $user->id ."\t". html_entity_decode($user->name); $str[] = $prepend_str;
}
if (!empty($user->data)) {
$str[] = $user->id . "\t" . html_entity_decode($user->name);
}
$str[] = sprintf('%-15s', $_SERVER['REMOTE_ADDR']); $str[] = sprintf('%-15s', $_SERVER['REMOTE_ADDR']);
if (isset($_SERVER['REQUEST_URI'])) { if (isset($_SERVER['REQUEST_URI'])) {
@ -433,27 +425,26 @@ function log_request ($file = '', $prepend_str = false, $add_post = true)
$str[] = $_SERVER['HTTP_REFERER']; $str[] = $_SERVER['HTTP_REFERER'];
} }
if (!empty($_POST) && $add_post) $str[] = "post: ". str_compact(urldecode(http_build_query($_POST))); if (!empty($_POST) && $add_post) {
$str[] = "post: " . str_compact(urldecode(http_build_query($_POST)));
}
$str = join("\t", $str) . "\n"; $str = join("\t", $str) . "\n";
bb_log($str, $file); bb_log($str, $file);
} }
// Board init // Board init
if (!defined('IN_TRACKER')) if (!defined('IN_TRACKER')) {
{ require(INC_DIR . 'init_bb.php');
require(INC_DIR .'init_bb.php'); } // Tracker init
} elseif (defined('IN_TRACKER')) {
// 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))); define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? intval($_GET['port']) : mt_rand(1000, 65000)));
function dummy_exit ($interval = 1800) function dummy_exit($interval = 1800)
{ {
$output = \Rych\Bencode\Bencode::encode(array( $output = \Rych\Bencode\Bencode::encode(array(
'interval' => (int) $interval, 'interval' => (int)$interval,
'min interval' => (int) $interval, 'min interval' => (int)$interval,
'peers' => (string) DUMMY_PEER, 'peers' => (string)DUMMY_PEER,
)); ));
die($output); die($output);
@ -462,11 +453,9 @@ else if (defined('IN_TRACKER'))
header('Content-Type: text/plain'); header('Content-Type: text/plain');
header('Pragma: no-cache'); header('Pragma: no-cache');
if (!defined('IN_ADMIN')) if (!defined('IN_ADMIN')) {
{
// Exit if tracker is disabled via ON/OFF trigger // Exit if tracker is disabled via ON/OFF trigger
if (file_exists(BB_DISABLED)) if (file_exists(BB_DISABLED)) {
{
dummy_exit(mt_rand(60, 2400)); dummy_exit(mt_rand(60, 2400));
} }
} }

View file

@ -60,7 +60,7 @@ return [
'handlers' => [ 'handlers' => [
function () { function () {
return new \Monolog\Handler\StreamHandler( return new \Monolog\Handler\StreamHandler(
__DIR__.'/../internal_data/log/app.log', __DIR__ . '/../internal_data/log/app.log',
\Monolog\Logger::DEBUG \Monolog\Logger::DEBUG
); );
} }

View file

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

4
dl.php
View file

@ -36,7 +36,9 @@ if (!$t_data) {
// Auth check // Auth check
$is_auth = auth(AUTH_ALL, $t_data->forum_id, $userdata, $t_data); $is_auth = auth(AUTH_ALL, $t_data->forum_id, $userdata, $t_data);
if (!IS_GUEST) { if (!IS_GUEST) {
if (!$is_auth['auth_download']) login_redirect($di->config->get('dl_url') . $topic_id); if (!$is_auth['auth_download']) {
login_redirect($di->config->get('dl_url') . $topic_id);
}
} elseif (!$di->config->get('tracker.guest_tracker')) { } elseif (!$di->config->get('tracker.guest_tracker')) {
login_redirect($di->config->get('dl_url') . $topic_id); login_redirect($di->config->get('dl_url') . $topic_id);
} }

View file

@ -13,30 +13,20 @@ $mode = $di->request->request->get('mode');
$confirmed = $di->request->request->has('confirm'); $confirmed = $di->request->request->has('confirm');
// Get new DL-status // Get new DL-status
if ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status') if ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status') {
{ if ($di->request->request->has('dl_set_will')) {
if ($di->request->request->has('dl_set_will'))
{
$new_dl_status = DL_STATUS_WILL; $new_dl_status = DL_STATUS_WILL;
$dl_key = 'dlw'; $dl_key = 'dlw';
} } elseif ($di->request->request->has('dl_set_down')) {
elseif ($di->request->request->has('dl_set_down'))
{
$new_dl_status = DL_STATUS_DOWN; $new_dl_status = DL_STATUS_DOWN;
$dl_key = 'dld'; $dl_key = 'dld';
} } elseif ($di->request->request->has('dl_set_complete')) {
elseif ($di->request->request->has('dl_set_complete'))
{
$new_dl_status = DL_STATUS_COMPLETE; $new_dl_status = DL_STATUS_COMPLETE;
$dl_key = 'dlc'; $dl_key = 'dlc';
} } elseif ($di->request->request->has('dl_set_cancel')) {
elseif ($di->request->request->has('dl_set_cancel'))
{
$new_dl_status = DL_STATUS_CANCEL; $new_dl_status = DL_STATUS_CANCEL;
$dl_key = 'dla'; $dl_key = 'dla';
} } else {
else
{
bb_die('Invalid download status'); bb_die('Invalid download status');
} }
} }
@ -44,15 +34,12 @@ if ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')
// Define redirect URL // Define redirect URL
$full_url = isset($_POST['full_url']) ? str_replace('&amp;', '&', htmlspecialchars($_POST['full_url'])) : ''; $full_url = isset($_POST['full_url']) ? str_replace('&amp;', '&', htmlspecialchars($_POST['full_url'])) : '';
if (isset($_POST['redirect_type']) && $_POST['redirect_type'] == 'search') if (isset($_POST['redirect_type']) && $_POST['redirect_type'] == 'search') {
{
$redirect_type = "search.php"; $redirect_type = "search.php";
$redirect = ($full_url) ? $full_url : "$dl_key=1"; $redirect = ($full_url) ? $full_url : "$dl_key=1";
} } else {
else
{
$redirect_type = (!$topic_id) ? "viewforum.php" : "viewtopic.php"; $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"); $redirect = ($full_url) ? $full_url : ((!$topic_id) ? POST_FORUM_URL . "=$forum_id" : POST_TOPIC_URL . "=$topic_id");
} }
// Start session management // Start session management
@ -61,39 +48,32 @@ $user->session_start();
set_die_append_msg(); set_die_append_msg();
// Check if user logged in // Check if user logged in
if (!$userdata['session_logged_in']) if (!$userdata['session_logged_in']) {
{
redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect"); redirect(LOGIN_URL . "?redirect=$redirect_type&$redirect");
} }
// Check if user did not confirm // Check if user did not confirm
if (isset($_POST['cancel']) && $_POST['cancel']) if (isset($_POST['cancel']) && $_POST['cancel']) {
{
redirect("$redirect_type?$redirect"); redirect("$redirect_type?$redirect");
} }
// Delete DL-list // Delete DL-list
if ($mode == 'dl_delete' && $topic_id) if ($mode == 'dl_delete' && $topic_id) {
{ if (!IS_ADMIN) {
if (!IS_ADMIN) $sql = "SELECT forum_id FROM " . BB_TOPICS . " WHERE topic_id = $topic_id LIMIT 1";
{
$sql = "SELECT forum_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id LIMIT 1";
if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) if (!$row = DB()->sql_fetchrow(DB()->sql_query($sql))) {
{
bb_die('Could not obtain forum_id for this topic'); 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']) if (!$is_auth['auth_mod']) {
{
bb_die($lang['NOT_MODERATOR']); bb_die($lang['NOT_MODERATOR']);
} }
} }
if (!$confirmed) if (!$confirmed) {
{
$hidden_fields = array( $hidden_fields = array(
't' => $topic_id, 't' => $topic_id,
'mode' => 'dl_delete', 'mode' => 'dl_delete',
@ -114,49 +94,40 @@ if ($mode == 'dl_delete' && $topic_id)
$req_topics_ary = $topics_ary = array(); $req_topics_ary = $topics_ary = array();
// Get topics selected by user // Get topics selected by user
if ($mode == 'set_topics_dl_status') if ($mode == 'set_topics_dl_status') {
{ if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list'])) {
if (!isset($_POST['dl_topics_id_list']) || !is_array($_POST['dl_topics_id_list']))
{
bb_die($lang['NONE_SELECTED']); bb_die($lang['NONE_SELECTED']);
} }
foreach ($_POST['dl_topics_id_list'] as $topic_id) foreach ($_POST['dl_topics_id_list'] as $topic_id) {
{ $req_topics_ary[] = (int)$topic_id;
$req_topics_ary[] = (int) $topic_id;
} }
} } elseif ($mode == 'set_dl_status') {
elseif ($mode == 'set_dl_status') $req_topics_ary[] = (int)$topic_id;
{
$req_topics_ary[] = (int) $topic_id;
} }
// Get existing topics // Get existing topics
if ($req_topics_sql = join(',', $req_topics_ary)) if ($req_topics_sql = join(',', $req_topics_ary)) {
{ $sql = "SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_id IN($req_topics_sql)";
$sql = "SELECT topic_id FROM ". BB_TOPICS ." WHERE topic_id IN($req_topics_sql)";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$topics_ary[] = $row['topic_id']; $topics_ary[] = $row['topic_id'];
} }
} }
if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) if ($topics_ary && ($mode == 'set_dl_status' || $mode == 'set_topics_dl_status')) {
{
$new_dlstatus_ary = array(); $new_dlstatus_ary = array();
foreach ($topics_ary as $topic_id) foreach ($topics_ary as $topic_id) {
{
$new_dlstatus_ary[] = array( $new_dlstatus_ary[] = array(
'user_id' => (int) $user->id, 'user_id' => (int)$user->id,
'topic_id' => (int) $topic_id, 'topic_id' => (int)$topic_id,
'user_status' => (int) $new_dl_status, 'user_status' => (int)$new_dl_status,
); );
} }
$new_dlstatus_sql = DB()->build_array('MULTI_INSERT', $new_dlstatus_ary); $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");
} }

View file

@ -17,7 +17,9 @@ $mode = $di->request->request->get('mode');
$type = $di->request->request->get('type'); $type = $di->request->request->get('type');
$id = $di->request->query->getInt('id'); $id = $di->request->query->getInt('id');
if (!$mode) bb_simple_die($di->translator->trans('Do not specify a mode for the feed')); if (!$mode) {
bb_simple_die($di->translator->trans('Do not specify a mode for the feed'));
}
if ($mode == 'get_feed_url' && ($type == 'f' || $type == 'u') && $id >= 0) { if ($mode == 'get_feed_url' && ($type == 'f' || $type == 'u') && $id >= 0) {
if ($type == 'f') { if ($type == 'f') {

359
group.php
View file

@ -2,9 +2,9 @@
define('BB_SCRIPT', 'group'); define('BB_SCRIPT', 'group');
define('BB_ROOT', './'); define('BB_ROOT', './');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
require(INC_DIR .'bbcode.php'); require(INC_DIR . 'bbcode.php');
require(INC_DIR .'functions_group.php'); require(INC_DIR . 'functions_group.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -25,21 +25,21 @@ function generate_user_info(&$row, $date_format, $group_mod, &$from, &$posts, &$
$joined = bb_date($row['user_regdate']); $joined = bb_date($row['user_regdate']);
$user_time = (!empty($row['user_time'])) ? bb_date($row['user_time']) : $lang['NONE']; $user_time = (!empty($row['user_time'])) ? bb_date($row['user_time']) : $lang['NONE'];
$posts = ($row['user_posts']) ? $row['user_posts'] : 0; $posts = ($row['user_posts']) ? $row['user_posts'] : 0;
$pm = ($di->config->get('text_buttons')) ? '<a class="txtb" href="'. (PM_URL . "?mode=post&amp;". POST_USERS_URL ."=".$row['user_id']) .'">'. $lang['SEND_PM_TXTB'] .'</a>' : '<a href="' . (PM_URL . "?mode=post&amp;". POST_USERS_URL ."=".$row['user_id']) .'"><img src="' . $images['icon_pm'] . '" alt="' . $lang['SEND_PRIVATE_MESSAGE'] . '" title="' . $lang['SEND_PRIVATE_MESSAGE'] . '" border="0" /></a>'; $pm = ($di->config->get('text_buttons')) ? '<a class="txtb" href="' . (PM_URL . "?mode=post&amp;" . POST_USERS_URL . "=" . $row['user_id']) . '">' . $lang['SEND_PM_TXTB'] . '</a>' : '<a href="' . (PM_URL . "?mode=post&amp;" . POST_USERS_URL . "=" . $row['user_id']) . '"><img src="' . $images['icon_pm'] . '" alt="' . $lang['SEND_PRIVATE_MESSAGE'] . '" title="' . $lang['SEND_PRIVATE_MESSAGE'] . '" border="0" /></a>';
$avatar = get_avatar($row['user_id'], $row['avatar_ext_id'], !bf($row['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50); $avatar = get_avatar($row['user_id'], $row['avatar_ext_id'], !bf($row['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50);
if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || $group_mod) if (bf($row['user_opt'], 'user_opt', 'user_viewemail') || $group_mod) {
{ $email_uri = ($di->config->get('board_email_form')) ? ("profile.php?mode=email&amp;" . POST_USERS_URL . "=" . $row['user_id']) : 'mailto:' . $row['user_email'];
$email_uri = ($di->config->get('board_email_form')) ? ("profile.php?mode=email&amp;". POST_USERS_URL ."=".$row['user_id']) : 'mailto:'. $row['user_email']; $email = '<a class="editable" href="' . $email_uri . '">' . $row['user_email'] . '</a>';
$email = '<a class="editable" href="'. $email_uri .'">'. $row['user_email'] .'</a>'; } else {
$email = '';
} }
else $email = '';
if ($row['user_website']) if ($row['user_website']) {
{ $www = ($di->config->get('text_buttons')) ? '<a class="txtb" href="' . $row['user_website'] . '" target="_userwww">' . $lang['VISIT_WEBSITE_TXTB'] . '</a>' : '<a class="txtb" href="' . $row['user_website'] . '" target="_userwww"><img src="' . $images['icon_www'] . '" alt="' . $lang['VISIT_WEBSITE'] . '" title="' . $lang['VISIT_WEBSITE'] . '" border="0" /></a>';
$www = ($di->config->get('text_buttons')) ? '<a class="txtb" href="'. $row['user_website'] .'" target="_userwww">'. $lang['VISIT_WEBSITE_TXTB'] .'</a>' : '<a class="txtb" href="'. $row['user_website'] .'" target="_userwww"><img src="' . $images['icon_www'] . '" alt="' . $lang['VISIT_WEBSITE'] . '" title="' . $lang['VISIT_WEBSITE'] . '" border="0" /></a>'; } else {
$www = '';
} }
else $www = '';
return; return;
} }
@ -51,27 +51,23 @@ set_die_append_msg();
$group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null; $group_id = isset($_REQUEST[POST_GROUPS_URL]) ? intval($_REQUEST[POST_GROUPS_URL]) : null;
$start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0; $start = isset($_REQUEST['start']) ? abs(intval($_REQUEST['start'])) : 0;
$per_page = $di->config->get('group_members_per_page'); $per_page = $di->config->get('group_members_per_page');
$view_mode = isset($_REQUEST['view']) ? (string) $_REQUEST['view'] : null; $view_mode = isset($_REQUEST['view']) ? (string)$_REQUEST['view'] : null;
$rel_limit = 50; $rel_limit = 50;
$group_info = array(); $group_info = array();
$is_moderator = false; $is_moderator = false;
if ($group_id) if ($group_id) {
{ if (!$group_info = get_group_data($group_id)) {
if (!$group_info = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) {
{
bb_die("Invalid group data [group_id: $group_id]"); bb_die("Invalid group data [group_id: $group_id]");
} }
$is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN);
} }
if (!$group_id) if (!$group_id) {
{
// Show the main screen where the user can select a group. // Show the main screen where the user can select a group.
$groups = array(); $groups = array();
$pending = 10; $pending = 10;
@ -85,16 +81,16 @@ if (!$group_id)
IF(g.group_moderator = ug.user_id, 1, 0) AS is_group_mod, IF(g.group_moderator = ug.user_id, 1, 0) AS is_group_mod,
COUNT(ug2.user_id) AS members, SUM(ug2.user_pending) AS candidates COUNT(ug2.user_id) AS members, SUM(ug2.user_pending) AS candidates
FROM FROM
". BB_GROUPS ." g " . BB_GROUPS . " g
LEFT JOIN LEFT JOIN
". BB_USER_GROUP ." ug ON " . BB_USER_GROUP . " ug ON
ug.group_id = g.group_id ug.group_id = g.group_id
AND ug.user_id = ". $userdata['user_id'] ." AND ug.user_id = " . $userdata['user_id'] . "
LEFT JOIN LEFT JOIN
". BB_USER_GROUP ." ug2 ON " . BB_USER_GROUP . " ug2 ON
ug2.group_id = g.group_id ug2.group_id = g.group_id
LEFT JOIN LEFT JOIN
". BB_USERS ." u ON g.group_moderator = u.user_id " . BB_USERS . " u ON g.group_moderator = u.user_id
WHERE WHERE
g.group_single_user = 0 g.group_single_user = 0
GROUP BY g.group_id GROUP BY g.group_id
@ -105,34 +101,20 @@ if (!$group_id)
g.group_name ASC g.group_name ASC
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{ if ($row['is_group_mod']) {
if ($row['is_group_mod'])
{
$type = 'MOD'; $type = 'MOD';
} } elseif ($row['membership'] == $member) {
else if ($row['membership'] == $member)
{
$type = 'MEMBER'; $type = 'MEMBER';
} } elseif ($row['membership'] == $pending) {
else if ($row['membership'] == $pending)
{
$type = 'PENDING'; $type = 'PENDING';
} } elseif ($row['group_type'] == GROUP_OPEN) {
else if ($row['group_type'] == GROUP_OPEN)
{
$type = 'OPEN'; $type = 'OPEN';
} } elseif ($row['group_type'] == GROUP_CLOSED) {
else if ($row['group_type'] == GROUP_CLOSED)
{
$type = 'CLOSED'; $type = 'CLOSED';
} } elseif ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) {
else if ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN)
{
$type = 'HIDDEN'; $type = 'HIDDEN';
} } else {
else
{
continue; continue;
} }
@ -146,31 +128,27 @@ if (!$group_id)
global $lang; global $lang;
$options = ''; $options = '';
foreach ($params as $name => $data) foreach ($params as $name => $data) {
{
$text = htmlCHR(str_short(rtrim($name), HTML_SELECT_MAX_LENGTH)); $text = htmlCHR(str_short(rtrim($name), HTML_SELECT_MAX_LENGTH));
$members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] .': '. $data['m'] : $lang['NO_GROUP_MEMBERS']; $members = ($data['m']) ? $lang['MEMBERS_IN_GROUP'] . ': ' . $data['m'] : $lang['NO_GROUP_MEMBERS'];
$candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] .': '. $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS']; $candidates = ($data['c']) ? $lang['PENDING_MEMBERS'] . ': ' . $data['c'] : $lang['NO_PENDING_GROUP_MEMBERS'];
$options .= '<li class="pad_2"><a href="'. GROUP_URL . $data['id'] .'" class="med bold">'. $text .'</a></li>'; $options .= '<li class="pad_2"><a href="' . GROUP_URL . $data['id'] . '" class="med bold">' . $text . '</a></li>';
$options .= ($data['rg']) ? '<ul><li class="med">'. $lang['RELEASE_GROUP'] .'</li>' : '<ul>'; $options .= ($data['rg']) ? '<ul><li class="med">' . $lang['RELEASE_GROUP'] . '</li>' : '<ul>';
$options .= '<li class="seedmed">'. $members .'</li>'; $options .= '<li class="seedmed">' . $members . '</li>';
if (IS_AM) if (IS_AM) {
{ $options .= '<li class="leechmed">' . $candidates . '</li>';
$options .= '<li class="leechmed">'. $candidates .'</li>';
} }
$options .= '</ul>'; $options .= '</ul>';
} }
return $options; return $options;
} }
if ($groups) if ($groups) {
{
$s_hidden_fields = ''; $s_hidden_fields = '';
foreach ($groups as $type => $grp) foreach ($groups as $type => $grp) {
{
$template->assign_block_vars('groups', array( $template->assign_block_vars('groups', array(
'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"], 'MEMBERSHIP' => $lang["GROUP_MEMBER_{$type}"],
'GROUP_SELECT' => build_group($grp), 'GROUP_SELECT' => build_group($grp),
@ -183,53 +161,45 @@ if (!$group_id)
'S_USERGROUP_ACTION' => 'group.php', 'S_USERGROUP_ACTION' => 'group.php',
'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_HIDDEN_FIELDS' => $s_hidden_fields,
)); ));
} } else {
else if (IS_ADMIN) {
{
if(IS_ADMIN)
{
redirect('admin/admin_groups.php'); redirect('admin/admin_groups.php');
} else {
bb_die($lang['NO_GROUPS_EXIST']);
} }
else bb_die($lang['NO_GROUPS_EXIST']);
} }
} } elseif (isset($_POST['joingroup']) && $_POST['joingroup']) {
else if (isset($_POST['joingroup']) && $_POST['joingroup']) if ($group_info['group_type'] != GROUP_OPEN) {
{
if ($group_info['group_type'] != GROUP_OPEN)
{
bb_die($lang['THIS_CLOSED_GROUP']); bb_die($lang['THIS_CLOSED_GROUP']);
} }
$sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang $sql = "SELECT g.group_id, g.group_name, ug.user_id, u.user_email, u.username, u.user_lang
FROM ". BB_GROUPS ." g FROM " . BB_GROUPS . " g
LEFT JOIN ". BB_USERS ." u ON(u.user_id = g.group_moderator) LEFT JOIN " . BB_USERS . " u ON(u.user_id = g.group_moderator)
LEFT JOIN ". BB_USER_GROUP ." ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']}) LEFT JOIN " . BB_USER_GROUP . " ug ON(ug.group_id = g.group_id AND ug.user_id = {$userdata['user_id']})
WHERE g.group_id = $group_id WHERE g.group_id = $group_id
AND group_single_user = 0 AND group_single_user = 0
AND g.group_type = ". GROUP_OPEN ." AND g.group_type = " . GROUP_OPEN . "
LIMIT 1"; LIMIT 1";
$row = $moderator = DB()->fetch_row($sql); $row = $moderator = DB()->fetch_row($sql);
if (!$row['group_id']) if (!$row['group_id']) {
{
bb_die($lang['NO_GROUPS_EXIST']); bb_die($lang['NO_GROUPS_EXIST']);
} }
if ($row['user_id']) if ($row['user_id']) {
{
set_die_append_msg(false, false, $group_id); set_die_append_msg(false, false, $group_id);
bb_die($lang['ALREADY_MEMBER_GROUP']); bb_die($lang['ALREADY_MEMBER_GROUP']);
} }
add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW); add_user_into_group($group_id, $userdata['user_id'], 1, TIMENOW);
if ($di->config->get('group_send_email')) if ($di->config->get('group_send_email')) {
{ require(CLASS_DIR . 'emailer.php');
require(CLASS_DIR .'emailer.php');
$emailer = new emailer($di->config->get('smtp_delivery')); $emailer = new emailer($di->config->get('smtp_delivery'));
$emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>");
$emailer->email_address($moderator['username'] ." <{$moderator['user_email']}>"); $emailer->email_address($moderator['username'] . " <{$moderator['user_email']}>");
$emailer->use_template('group_request', $moderator['user_lang']); $emailer->use_template('group_request', $moderator['user_lang']);
@ -246,42 +216,33 @@ else if (isset($_POST['joingroup']) && $_POST['joingroup'])
set_die_append_msg(false, false, $group_id); set_die_append_msg(false, false, $group_id);
bb_die($lang['GROUP_JOINED']); bb_die($lang['GROUP_JOINED']);
} } elseif (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) {
else if (!empty($_POST['unsub']) || !empty($_POST['unsubpending']))
{
delete_user_group($group_id, $userdata['user_id']); delete_user_group($group_id, $userdata['user_id']);
set_die_append_msg(false, false, $group_id); set_die_append_msg(false, false, $group_id);
bb_die($lang['UNSUB_SUCCESS']); bb_die($lang['UNSUB_SUCCESS']);
} } else {
else
{
// Handle Additions, removals, approvals and denials // Handle Additions, removals, approvals and denials
$group_moderator = $group_info['group_moderator']; $group_moderator = $group_info['group_moderator'];
if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) if (!empty($_POST['add']) || !empty($_POST['remove']) || !empty($_POST['approve']) || !empty($_POST['deny'])) {
{ if (!$is_moderator) {
if (!$is_moderator)
{
bb_die($lang['NOT_GROUP_MODERATOR']); bb_die($lang['NOT_GROUP_MODERATOR']);
} }
if (!empty($_POST['add'])) if (!empty($_POST['add'])) {
{ if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true))) {
if (isset($_POST['username']) && !($row = get_userdata($_POST['username'], true)))
{
bb_die($lang['COULD_NOT_ADD_USER']); bb_die($lang['COULD_NOT_ADD_USER']);
} }
add_user_into_group($group_id, $row['user_id']); add_user_into_group($group_id, $row['user_id']);
if ($di->config->get('group_send_email')) if ($di->config->get('group_send_email')) {
{ require(CLASS_DIR . 'emailer.php');
require(CLASS_DIR .'emailer.php');
$emailer = new emailer($di->config->get('smtp_delivery')); $emailer = new emailer($di->config->get('smtp_delivery'));
$emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>");
$emailer->email_address($row['username'] ." <{$row['user_email']}>"); $emailer->email_address($row['username'] . " <{$row['user_email']}>");
$emailer->use_template('group_added', $row['user_lang']); $emailer->use_template('group_added', $row['user_lang']);
@ -294,68 +255,56 @@ else
$emailer->send(); $emailer->send();
$emailer->reset(); $emailer->reset();
} }
} } else {
else if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members']))) {
{
if (((!empty($_POST['approve']) || !empty($_POST['deny'])) && !empty($_POST['pending_members'])) || (!empty($_POST['remove']) && !empty($_POST['members'])))
{
$members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members']; $members = (!empty($_POST['approve']) || !empty($_POST['deny'])) ? $_POST['pending_members'] : $_POST['members'];
$sql_in = array(); $sql_in = array();
foreach ($members as $members_id) foreach ($members as $members_id) {
{ $sql_in[] = (int)$members_id;
$sql_in[] = (int) $members_id;
} }
if (!$sql_in = join(',', $sql_in)) if (!$sql_in = join(',', $sql_in)) {
{
bb_die($lang['NONE_SELECTED']); bb_die($lang['NONE_SELECTED']);
} }
if (!empty($_POST['approve'])) if (!empty($_POST['approve'])) {
{
DB()->query(" DB()->query("
UPDATE ". BB_USER_GROUP ." SET UPDATE " . BB_USER_GROUP . " SET
user_pending = 0 user_pending = 0
WHERE user_id IN($sql_in) WHERE user_id IN($sql_in)
AND group_id = $group_id AND group_id = $group_id
"); ");
update_user_level($sql_in); update_user_level($sql_in);
} } elseif (!empty($_POST['deny']) || !empty($_POST['remove'])) {
else if (!empty($_POST['deny']) || !empty($_POST['remove']))
{
DB()->query(" DB()->query("
DELETE FROM ". BB_USER_GROUP ." DELETE FROM " . BB_USER_GROUP . "
WHERE user_id IN($sql_in) WHERE user_id IN($sql_in)
AND group_id = $group_id AND group_id = $group_id
"); ");
if (!empty($_POST['remove'])) if (!empty($_POST['remove'])) {
{
update_user_level($sql_in); update_user_level($sql_in);
} }
} }
// Email users when they are approved // Email users when they are approved
if (!empty($_POST['approve']) && $di->config->get('group_send_email')) if (!empty($_POST['approve']) && $di->config->get('group_send_email')) {
{
$sql_select = "SELECT username, user_email, user_lang $sql_select = "SELECT username, user_email, user_lang
FROM ". BB_USERS ." FROM " . BB_USERS . "
WHERE user_id IN($sql_in)"; WHERE user_id IN($sql_in)";
if (!$result = DB()->sql_query($sql_select)) if (!$result = DB()->sql_query($sql_select)) {
{
bb_die('Could not get user email information'); bb_die('Could not get user email information');
} }
require(CLASS_DIR .'emailer.php'); require(CLASS_DIR . 'emailer.php');
$emailer = new emailer($di->config->get('smtp_delivery')); $emailer = new emailer($di->config->get('smtp_delivery'));
$emailer->from($di->config->get('sitename') ." <{$di->config->get('board_email')}>"); $emailer->from($di->config->get('sitename') . " <{$di->config->get('board_email')}>");
foreach (DB()->fetch_rowset($sql_select) as $row) foreach (DB()->fetch_rowset($sql_select) as $row) {
{
$emailer->use_template('group_approved', $row['user_lang']); $emailer->use_template('group_approved', $row['user_lang']);
$emailer->email_address($row['username'] ." <{$row['user_email']}>"); $emailer->email_address($row['username'] . " <{$row['user_email']}>");
} }
$emailer->assign_vars(array( $emailer->assign_vars(array(
@ -375,66 +324,50 @@ else
// Get moderator details for this group // Get moderator details for this group
$group_moderator = DB()->fetch_row(" $group_moderator = DB()->fetch_row("
SELECT * SELECT *
FROM ". BB_USERS ." FROM " . BB_USERS . "
WHERE user_id = ". $group_info['group_moderator'] ." WHERE user_id = " . $group_info['group_moderator'] . "
"); ");
// Current user membership // Current user membership
$is_group_member = $is_group_pending_member = false; $is_group_member = $is_group_pending_member = false;
$sql = "SELECT user_pending $sql = "SELECT user_pending
FROM ". BB_USER_GROUP ." FROM " . BB_USER_GROUP . "
WHERE group_id = $group_id WHERE group_id = $group_id
AND user_id = ". $userdata['user_id'] ." AND user_id = " . $userdata['user_id'] . "
LIMIT 1"; LIMIT 1";
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{ if ($row['user_pending'] == 0) {
if ($row['user_pending'] == 0)
{
$is_group_member = true; $is_group_member = true;
} } else {
else
{
$is_group_pending_member = true; $is_group_pending_member = true;
} }
} }
if ($userdata['user_id'] == $group_moderator['user_id']) if ($userdata['user_id'] == $group_moderator['user_id']) {
{
$group_details = $lang['ARE_GROUP_MODERATOR']; $group_details = $lang['ARE_GROUP_MODERATOR'];
$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 . '" />';
} } elseif ($is_group_member || $is_group_pending_member) {
else if ($is_group_member || $is_group_pending_member)
{
$template->assign_vars(array( $template->assign_vars(array(
'SHOW_UNSUBSCRIBE_CONTROLS' => true, 'SHOW_UNSUBSCRIBE_CONTROLS' => true,
'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending', 'CONTROL_NAME' => ($is_group_member) ? 'unsub' : 'unsubpending',
)); ));
$group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP']; $group_details = ($is_group_pending_member) ? $lang['PENDING_THIS_GROUP'] : $lang['MEMBER_THIS_GROUP'];
$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 . '" />';
} } elseif (IS_GUEST) {
else if (IS_GUEST)
{
$group_details = $lang['LOGIN_TO_JOIN']; $group_details = $lang['LOGIN_TO_JOIN'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} } else {
else if ($group_info['group_type'] == GROUP_OPEN) {
{
if ($group_info['group_type'] == GROUP_OPEN)
{
$template->assign_var('SHOW_SUBSCRIBE_CONTROLS'); $template->assign_var('SHOW_SUBSCRIBE_CONTROLS');
$group_details = $lang['THIS_OPEN_GROUP']; $group_details = $lang['THIS_OPEN_GROUP'];
$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 . '" />';
} } elseif ($group_info['group_type'] == GROUP_CLOSED) {
else if ($group_info['group_type'] == GROUP_CLOSED)
{
$group_details = $lang['THIS_CLOSED_GROUP']; $group_details = $lang['THIS_CLOSED_GROUP'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} } elseif ($group_info['group_type'] == GROUP_HIDDEN) {
else if ($group_info['group_type'] == GROUP_HIDDEN)
{
$group_details = $lang['THIS_HIDDEN_GROUP']; $group_details = $lang['THIS_HIDDEN_GROUP'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} }
@ -447,16 +380,11 @@ else
generate_user_info($group_moderator, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); generate_user_info($group_moderator, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar);
$group_type = ''; $group_type = '';
if ($group_info['group_type'] == GROUP_OPEN) if ($group_info['group_type'] == GROUP_OPEN) {
{
$group_type = $lang['GROUP_OPEN']; $group_type = $lang['GROUP_OPEN'];
} } elseif ($group_info['group_type'] == GROUP_CLOSED) {
elseif ($group_info['group_type'] == GROUP_CLOSED)
{
$group_type = $lang['GROUP_CLOSED']; $group_type = $lang['GROUP_CLOSED'];
} } elseif ($group_info['group_type'] == GROUP_HIDDEN) {
elseif ($group_info['group_type'] == GROUP_HIDDEN)
{
$group_type = $lang['GROUP_HIDDEN']; $group_type = $lang['GROUP_HIDDEN'];
} }
@ -482,8 +410,8 @@ else
'MOD_TIME' => (!empty($group_info['mod_time'])) ? bb_date($group_info['mod_time']) : $lang['NONE'], 'MOD_TIME' => (!empty($group_info['mod_time'])) ? bb_date($group_info['mod_time']) : $lang['NONE'],
'U_SEARCH_USER' => "search.php?mode=searchuser", 'U_SEARCH_USER' => "search.php?mode=searchuser",
'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id", 'U_SEARCH_RELEASES' => "tracker.php?srg=$group_id",
'U_GROUP_RELEASES' => "group.php?view=releases&amp;". POST_GROUPS_URL ."=$group_id", 'U_GROUP_RELEASES' => "group.php?view=releases&amp;" . POST_GROUPS_URL . "=$group_id",
'U_GROUP_MEMBERS' => "group.php?view=members&amp;". POST_GROUPS_URL ."=$group_id", 'U_GROUP_MEMBERS' => "group.php?view=members&amp;" . POST_GROUPS_URL . "=$group_id",
'U_GROUP_CONFIG' => "group_edit.php?g=$group_id", 'U_GROUP_CONFIG' => "group_edit.php?g=$group_id",
'RELEASE_GROUP' => ($group_info['release_group']) ? true : false, 'RELEASE_GROUP' => ($group_info['release_group']) ? true : false,
'GROUP_TYPE' => $group_type, 'GROUP_TYPE' => $group_type,
@ -501,13 +429,11 @@ else
'S_GROUP_ACTION' => "group.php?" . POST_GROUPS_URL . "=$group_id", 'S_GROUP_ACTION' => "group.php?" . POST_GROUPS_URL . "=$group_id",
)); ));
switch ($view_mode) switch ($view_mode) {
{
case 'releases': case 'releases':
// TODO: проверить на работу с новыми вложениями // TODO: проверить на работу с новыми вложениями
if (!$group_info['release_group']) if (!$group_info['release_group']) {
{
set_die_append_msg(false, false, $group_id); set_die_append_msg(false, false, $group_id);
bb_die($lang['NOT_A_RELEASE_GROUP']); bb_die($lang['NOT_A_RELEASE_GROUP']);
} }
@ -515,41 +441,39 @@ else
// Count releases for pagination // Count releases for pagination
$all_releases = DB()->fetch_rowset(" $all_releases = DB()->fetch_rowset("
SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank
FROM ". BB_POSTS ." p FROM " . BB_POSTS . " p
LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id)
LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id)
LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id)
WHERE p.poster_rg_id = $group_id WHERE p.poster_rg_id = $group_id
ORDER BY t.topic_time DESC ORDER BY t.topic_time DESC
LIMIT $rel_limit LIMIT $rel_limit
"); ");
$count_releases = count($all_releases); $count_releases = count($all_releases);
generate_pagination(GROUP_URL . $group_id ."&amp;view=releases", $count_releases, $per_page, $start); generate_pagination(GROUP_URL . $group_id . "&amp;view=releases", $count_releases, $per_page, $start);
$sql = " $sql = "
SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank SELECT p.topic_id, p.forum_id, p.poster_id, t.topic_title, t.topic_time, f.forum_name, u.username, u.avatar_ext_id, u.user_opt, u.user_rank
FROM ". BB_POSTS ." p FROM " . BB_POSTS . " p
LEFT JOIN ". BB_TOPICS ." t ON(p.topic_id = t.topic_id) LEFT JOIN " . BB_TOPICS . " t ON(p.topic_id = t.topic_id)
LEFT JOIN ". BB_FORUMS ." f ON(p.forum_id= f.forum_id) LEFT JOIN " . BB_FORUMS . " f ON(p.forum_id= f.forum_id)
LEFT JOIN ". BB_USERS ." u ON(p.poster_id = u.user_id) LEFT JOIN " . BB_USERS . " u ON(p.poster_id = u.user_id)
WHERE p.poster_rg_id = $group_id WHERE p.poster_rg_id = $group_id
ORDER BY t.topic_time DESC ORDER BY t.topic_time DESC
LIMIT $start, $per_page LIMIT $start, $per_page
"; ";
if (!$releases = DB()->fetch_rowset($sql)) if (!$releases = DB()->fetch_rowset($sql)) {
{
set_die_append_msg(false, false, $group_id); set_die_append_msg(false, false, $group_id);
bb_die($lang['NO_SEARCH_MATCH']); bb_die($lang['NO_SEARCH_MATCH']);
} }
foreach ($releases as $i => $release) foreach ($releases as $i => $release) {
{
$row_class = !($i % 2) ? 'row1' : 'row2'; $row_class = !($i % 2) ? 'row1' : 'row2';
$template->assign_block_vars('releases', array( $template->assign_block_vars('releases', array(
'ROW_NUMBER' => $i + ( $start + 1 ), 'ROW_NUMBER' => $i + ($start + 1),
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'RELEASER' => profile_url(array('user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank'])), 'RELEASER' => profile_url(array('user_id' => $release['poster_id'], 'username' => $release['username'], 'user_rank' => $release['user_rank'])),
'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50), 'AVATAR_IMG' => get_avatar($release['poster_id'], $release['avatar_ext_id'], !bf($release['user_opt'], 'user_opt', 'dis_avatar'), '', 50, 50),
@ -571,10 +495,10 @@ else
// Members // Members
$count_members = DB()->fetch_rowset(" $count_members = DB()->fetch_rowset("
SELECT u.username, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time SELECT u.username, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time
FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u
WHERE ug.group_id = $group_id WHERE ug.group_id = $group_id
AND ug.user_pending = 0 AND ug.user_pending = 0
AND ug.user_id <> ". $group_moderator['user_id'] ." AND ug.user_id <> " . $group_moderator['user_id'] . "
AND u.user_id = ug.user_id AND u.user_id = ug.user_id
ORDER BY u.username ORDER BY u.username
"); ");
@ -586,10 +510,10 @@ else
// Members // Members
$group_members = DB()->fetch_rowset(" $group_members = DB()->fetch_rowset("
SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email, ug.user_pending, ug.user_time
FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u
WHERE ug.group_id = $group_id WHERE ug.group_id = $group_id
AND ug.user_pending = 0 AND ug.user_pending = 0
AND ug.user_id <> ". $group_moderator['user_id'] ." AND ug.user_id <> " . $group_moderator['user_id'] . "
AND u.user_id = ug.user_id AND u.user_id = ug.user_id
ORDER BY u.username ORDER BY u.username
LIMIT $start, $per_page LIMIT $start, $per_page
@ -599,18 +523,16 @@ else
generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start); generate_pagination(GROUP_URL . $group_id, $count_members, $per_page, $start);
// Dump out the remaining users // Dump out the remaining users
foreach ($group_members as $i => $member) foreach ($group_members as $i => $member) {
{
$user_id = $member['user_id']; $user_id = $member['user_id'];
generate_user_info($member, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); generate_user_info($member, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar);
if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) if ($group_info['group_type'] != GROUP_HIDDEN || $is_group_member || $is_moderator) {
{
$row_class = !($i % 2) ? 'row1' : 'row2'; $row_class = !($i % 2) ? 'row1' : 'row2';
$template->assign_block_vars('member', array( $template->assign_block_vars('member', array(
'ROW_NUMBER' => $i + ( $start + 1 ), 'ROW_NUMBER' => $i + ($start + 1),
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'USER' => profile_url($member), 'USER' => profile_url($member),
'AVATAR_IMG' => $avatar, 'AVATAR_IMG' => $avatar,
@ -624,31 +546,27 @@ else
'TIME' => $user_time, 'TIME' => $user_time,
)); ));
if ($is_moderator) if ($is_moderator) {
{
$template->assign_block_vars('member.switch_mod_option', array()); $template->assign_block_vars('member.switch_mod_option', array());
} }
} }
} }
// No group members // No group members
if (!$members_count) if (!$members_count) {
{
$template->assign_block_vars('switch_no_members', array()); $template->assign_block_vars('switch_no_members', array());
} }
// No group members // No group members
if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) if ($group_info['group_type'] == GROUP_HIDDEN && !$is_group_member && !$is_moderator) {
{
$template->assign_block_vars('switch_hidden_group', array()); $template->assign_block_vars('switch_hidden_group', array());
} }
// Pending // Pending
if ($is_moderator) if ($is_moderator) {
{
$modgroup_pending_list = DB()->fetch_rowset(" $modgroup_pending_list = DB()->fetch_rowset("
SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email SELECT u.username, u.avatar_ext_id, u.user_rank, u.user_id, u.user_opt, u.user_posts, u.user_regdate, u.user_from, u.user_website, u.user_email
FROM ". BB_USER_GROUP ." ug, ". BB_USERS ." u FROM " . BB_USER_GROUP . " ug, " . BB_USERS . " u
WHERE ug.group_id = $group_id WHERE ug.group_id = $group_id
AND ug.user_pending = 1 AND ug.user_pending = 1
AND u.user_id = ug.user_id AND u.user_id = ug.user_id
@ -658,21 +576,19 @@ else
$modgroup_pending_count = count($modgroup_pending_list); $modgroup_pending_count = count($modgroup_pending_list);
} }
if ($is_moderator && $modgroup_pending_list) if ($is_moderator && $modgroup_pending_list) {
{ foreach ($modgroup_pending_list as $i => $member) {
foreach ($modgroup_pending_list as $i => $member)
{
$user_id = $member['user_id']; $user_id = $member['user_id'];
generate_user_info($member, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar); generate_user_info($member, $di->config->get('default_dateformat'), $is_moderator, $from, $posts, $joined, $pm, $email, $www, $user_time, $avatar);
$row_class = !($i % 2) ? 'row1' : 'row2'; $row_class = !($i % 2) ? 'row1' : 'row2';
$user_select = '<input type="checkbox" name="member[]" value="'. $user_id .'">'; $user_select = '<input type="checkbox" name="member[]" value="' . $user_id . '">';
$template->assign_block_vars('pending', array( $template->assign_block_vars('pending', array(
'ROW_CLASS' => $row_class, 'ROW_CLASS' => $row_class,
'AVATAR_IMG'=> $avatar, 'AVATAR_IMG' => $avatar,
'USER' => profile_url($member), 'USER' => profile_url($member),
'FROM' => $from, 'FROM' => $from,
'JOINED' => $joined, 'JOINED' => $joined,
@ -691,8 +607,7 @@ else
$template->assign_vars(array('MEMBERS' => true)); $template->assign_vars(array('MEMBERS' => true));
} }
if ($is_moderator) if ($is_moderator) {
{
$template->assign_block_vars('switch_mod_option', array()); $template->assign_block_vars('switch_mod_option', array());
$template->assign_block_vars('switch_add_member', array()); $template->assign_block_vars('switch_add_member', array());
} }

View file

@ -2,8 +2,8 @@
define('BB_SCRIPT', 'group_edit'); define('BB_SCRIPT', 'group_edit');
define('BB_ROOT', './'); define('BB_ROOT', './');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
require(INC_DIR .'functions_group.php'); require(INC_DIR . 'functions_group.php');
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -19,57 +19,43 @@ $is_moderator = false;
$submit = !empty($_POST['submit']); $submit = !empty($_POST['submit']);
if ($group_id) if ($group_id) {
{ if (!$group_info = get_group_data($group_id)) {
if (!$group_info = get_group_data($group_id))
{
bb_die($lang['GROUP_NOT_EXIST']); bb_die($lang['GROUP_NOT_EXIST']);
} }
if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) if (!$group_info['group_id'] || !$group_info['group_moderator'] || !$group_info['moderator_name']) {
{
bb_die("Invalid group data [group_id: $group_id]"); bb_die("Invalid group data [group_id: $group_id]");
} }
$is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN); $is_moderator = ($userdata['user_id'] == $group_info['group_moderator'] || IS_ADMIN);
} }
if ($is_moderator) if ($is_moderator) {
{
// Avatar // Avatar
if ($submit) if ($submit) {
{ if (!empty($_FILES['avatar']['name']) && $di->config->get('group_avatars.up_allowed')) {
if (!empty($_FILES['avatar']['name']) && $di->config->get('group_avatars.up_allowed')) require(INC_DIR . 'functions_upload.php');
{
require(INC_DIR .'functions_upload.php');
$upload = new upload_common(); $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']))) 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;
$avatar_ext_id = (int) $upload->file_ext_id; } else {
}
else
{
bb_die(implode($upload->errors)); 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 = ''; $group_type = '';
if ($group_info['group_type'] == GROUP_OPEN) if ($group_info['group_type'] == GROUP_OPEN) {
{
$group_type = $lang['GROUP_OPEN']; $group_type = $lang['GROUP_OPEN'];
} } elseif ($group_info['group_type'] == GROUP_CLOSED) {
elseif ($group_info['group_type'] == GROUP_CLOSED)
{
$group_type = $lang['GROUP_CLOSED']; $group_type = $lang['GROUP_CLOSED'];
} } elseif ($group_info['group_type'] == GROUP_HIDDEN) {
elseif ($group_info['group_type'] == GROUP_HIDDEN)
{
$group_type = $lang['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( $template->assign_vars(array(
'PAGE_TITLE' => $lang['GROUPS'], 'PAGE_TITLE' => $lang['GROUPS'],
@ -101,13 +87,10 @@ if ($is_moderator)
$template->pparse('body'); $template->pparse('body');
require(PAGE_FOOTER); require(PAGE_FOOTER);
} } else {
else
{
$redirect = 'index.php'; $redirect = 'index.php';
if ($group_id) if ($group_id) {
{
$redirect = GROUP_URL . $group_id; $redirect = GROUP_URL . $group_id;
} }
redirect($redirect); redirect($redirect);

147
index.php
View file

@ -23,12 +23,10 @@ $datastore->enqueue(array(
'stats', 'stats',
'moderators', 'moderators',
)); ));
if ($di->config->get('show_latest_news')) if ($di->config->get('show_latest_news')) {
{
$datastore->enqueue('latest_news'); $datastore->enqueue('latest_news');
} }
if ($di->config->get('show_network_news')) if ($di->config->get('show_network_news')) {
{
$datastore->enqueue('network_news'); $datastore->enqueue('network_news');
} }
@ -36,7 +34,7 @@ if ($di->config->get('show_network_news'))
$user->session_start(); $user->session_start();
// Init main vars // 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']; $lastvisit = (IS_GUEST) ? TIMENOW : $userdata['user_lastvisit'];
// Caching output // Caching output
@ -49,24 +47,22 @@ if (IS_GUEST && $cache->has(REQUESTED_PAGE . '_guest_' . $di->config->get('defau
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)); $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 // Topics read tracks
$tracking_topics = get_tracks('topic'); $tracking_topics = get_tracks('topic');
$tracking_forums = get_tracks('forum'); $tracking_forums = get_tracks('forum');
// Statistics // Statistics
if (!$stats = $datastore->get('stats')) if (!$stats = $datastore->get('stats')) {
{
$datastore->update('stats'); $datastore->update('stats');
$stats = $datastore->get('stats'); $stats = $datastore->get('stats');
} }
// Forums data // Forums data
if (!$forums = $datastore->get('cat_forums')) if (!$forums = $datastore->get('cat_forums')) {
{
$datastore->update('cat_forums'); $datastore->update('cat_forums');
$forums = $datastore->get('cat_forums'); $forums = $datastore->get('cat_forums');
} }
@ -78,8 +74,7 @@ $excluded_forums_csv = $user->get_excluded_forums(AUTH_VIEW);
$only_new = $user->opt_js['only_new']; $only_new = $user->opt_js['only_new'];
// Validate requested category id // Validate requested category id
if ($viewcat && !($viewcat =& $forums['c'][$viewcat]['cat_id'])) if ($viewcat && !($viewcat =& $forums['c'][$viewcat]['cat_id'])) {
{
redirect("index.php"); redirect("index.php");
} }
@ -114,11 +109,11 @@ $sql = "
t.topic_id AS last_topic_id, t.topic_title AS last_topic_title, 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, 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 IF(p.poster_id = $anon, p.post_username, u.username) AS last_post_username
FROM ". BB_CATEGORIES ." c FROM " . BB_CATEGORIES . " c
INNER JOIN ". BB_FORUMS ." f ON($forums_join_sql) INNER JOIN " . BB_FORUMS . " f ON($forums_join_sql)
$join_p_type ". BB_POSTS ." p ON($posts_join_sql) $join_p_type " . BB_POSTS . " p ON($posts_join_sql)
$join_t_type ". BB_TOPICS ." t ON($topics_join_sql) $join_t_type " . BB_TOPICS . " t ON($topics_join_sql)
LEFT JOIN ". BB_USERS ." u ON(u.user_id = p.poster_id) LEFT JOIN " . BB_USERS . " u ON(u.user_id = p.poster_id)
ORDER BY c.cat_order, f.forum_order ORDER BY c.cat_order, f.forum_order
"; ";
@ -172,26 +167,20 @@ $cat_forums = $cache->get($cache_name);
// Obtain list of moderators // Obtain list of moderators
$moderators = array(); $moderators = array();
if (!$mod = $datastore->get('moderators')) if (!$mod = $datastore->get('moderators')) {
{
$datastore->update('moderators'); $datastore->update('moderators');
$mod = $datastore->get('moderators'); $mod = $datastore->get('moderators');
} }
if (!empty($mod)) if (!empty($mod)) {
{ foreach ($mod['mod_users'] as $forum_id => $user_ids) {
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 ($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 ($mod['mod_groups'] as $forum_id => $group_ids) {
{ foreach ($group_ids as $group_id) {
foreach ($group_ids as $group_id) $moderators[$forum_id][] = '<a href="' . GROUP_URL . $group_id . '">' . $mod['name_groups'][$group_id] . '</a>';
{
$moderators[$forum_id][] = '<a href="'. GROUP_URL . $group_id .'">'. $mod['name_groups'][$group_id] .'</a>';
} }
} }
} }
@ -201,8 +190,7 @@ $datastore->rm('moderators');
// Build index page // Build index page
$forums_count = 0; $forums_count = 0;
foreach ($cat_forums as $cid => $c) foreach ($cat_forums as $cid => $c) {
{
$template->assign_block_vars('h_c', array( $template->assign_block_vars('h_c', array(
'H_C_ID' => $cid, 'H_C_ID' => $cid,
'H_C_TITLE' => $cat_title_html[$cid], 'H_C_TITLE' => $cat_title_html[$cid],
@ -213,8 +201,7 @@ foreach ($cat_forums as $cid => $c)
'H_C_AL_MESS' => ($hide_cat_opt && !$showhide) ? true : false, 'H_C_AL_MESS' => ($hide_cat_opt && !$showhide) ? true : false,
)); ));
if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) if (!$showhide && isset($hide_cat_user[$cid]) && !$viewcat) {
{
continue; continue;
} }
@ -224,10 +211,8 @@ foreach ($cat_forums as $cid => $c)
'U_VIEWCAT' => CAT_URL . $cid, 'U_VIEWCAT' => CAT_URL . $cid,
)); ));
foreach ($c['f'] as $fid => $f) foreach ($c['f'] as $fid => $f) {
{ if (!$fname_html =& $forum_name_html[$fid]) {
if (!$fname_html =& $forum_name_html[$fid])
{
continue; continue;
} }
$is_sf = $f['forum_parent']; $is_sf = $f['forum_parent'];
@ -236,13 +221,11 @@ foreach ($cat_forums as $cid => $c)
$new = is_unread($f['last_post_time'], $f['last_topic_id'], $f['forum_id']) ? '_new' : ''; $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}"]; $folder_image = ($is_sf) ? $images["icon_minipost{$new}"] : $images["forum{$new}"];
if ($f['forum_status'] == FORUM_LOCKED) if ($f['forum_status'] == FORUM_LOCKED) {
{
$folder_image = ($is_sf) ? $images['icon_minipost'] : $images['forum_locked']; $folder_image = ($is_sf) ? $images['icon_minipost'] : $images['forum_locked'];
} }
if ($is_sf) if ($is_sf) {
{
$template->assign_block_vars('c.f.sf', array( $template->assign_block_vars('c.f.sf', array(
'SF_ID' => $fid, 'SF_ID' => $fid,
'SF_NAME' => $fname_html, 'SF_NAME' => $fname_html,
@ -263,8 +246,7 @@ foreach ($cat_forums as $cid => $c)
'FORUM_FOLDER_ALT' => ($new) ? $lang['NEW'] : $lang['OLD'], 'FORUM_FOLDER_ALT' => ($new) ? $lang['NEW'] : $lang['OLD'],
)); ));
if ($f['last_post_id']) if ($f['last_post_id']) {
{
$template->assign_block_vars('c.f.last', array( $template->assign_block_vars('c.f.last', array(
'LAST_TOPIC_ID' => $f['last_topic_id'], 'LAST_TOPIC_ID' => $f['last_topic_id'],
'LAST_TOPIC_TIP' => $f['last_topic_title'], 'LAST_TOPIC_TIP' => $f['last_topic_title'],
@ -291,7 +273,7 @@ $template->assign_vars(array(
// Tracker stats // Tracker stats
'TORRENTS_STAT' => ($di->config->get('tor_stats')) ? sprintf($lang['TORRENTS_STAT'], $stats['torrentcount'], humn_size($stats['size'])) : '', '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']) : '', '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') : '', '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'), 'SHOW_MOD_INDEX' => $di->config->get('show_mod_index'),
'FORUM_IMG' => $images['forum'], 'FORUM_IMG' => $images['forum'],
'FORUM_NEW_IMG' => $images['forum_new'], 'FORUM_NEW_IMG' => $images['forum_new'],
@ -310,16 +292,13 @@ $template->assign_vars(array(
)); ));
// Set tpl vars for bt_userdata // Set tpl vars for bt_userdata
if ($di->config->get('bt_show_dl_stat_on_index') && !IS_GUEST) if ($di->config->get('bt_show_dl_stat_on_index') && !IS_GUEST) {
{
show_bt_userdata($userdata['user_id']); show_bt_userdata($userdata['user_id']);
} }
// Latest news // Latest news
if ($di->config->get('show_latest_news')) if ($di->config->get('show_latest_news')) {
{ if (!$latest_news = $datastore->get('latest_news')) {
if (!$latest_news = $datastore->get('latest_news'))
{
$datastore->update('latest_news'); $datastore->update('latest_news');
$latest_news = $datastore->get('latest_news'); $latest_news = $datastore->get('latest_news');
} }
@ -328,8 +307,7 @@ if ($di->config->get('show_latest_news'))
'SHOW_LATEST_NEWS' => true, 'SHOW_LATEST_NEWS' => true,
)); ));
foreach ($latest_news as $news) foreach ($latest_news as $news) {
{
$template->assign_block_vars('news', array( $template->assign_block_vars('news', array(
'NEWS_TOPIC_ID' => $news['topic_id'], 'NEWS_TOPIC_ID' => $news['topic_id'],
'NEWS_TITLE' => str_short($news['topic_title'], $di->config->get('max_news_title')), 'NEWS_TITLE' => str_short($news['topic_title'], $di->config->get('max_news_title')),
@ -340,10 +318,8 @@ if ($di->config->get('show_latest_news'))
} }
// Network news // Network news
if ($di->config->get('show_network_news')) if ($di->config->get('show_network_news')) {
{ if (!$network_news = $datastore->get('network_news')) {
if (!$network_news = $datastore->get('network_news'))
{
$datastore->update('network_news'); $datastore->update('network_news');
$network_news = $datastore->get('network_news'); $network_news = $datastore->get('network_news');
} }
@ -352,8 +328,7 @@ if ($di->config->get('show_network_news'))
'SHOW_NETWORK_NEWS' => true, 'SHOW_NETWORK_NEWS' => true,
)); ));
foreach ($network_news as $net) foreach ($network_news as $net) {
{
$template->assign_block_vars('net', array( $template->assign_block_vars('net', array(
'NEWS_TOPIC_ID' => $net['topic_id'], 'NEWS_TOPIC_ID' => $net['topic_id'],
'NEWS_TITLE' => str_short($net['topic_title'], $di->config->get('max_net_title')), 'NEWS_TITLE' => str_short($net['topic_title'], $di->config->get('max_net_title')),
@ -363,44 +338,39 @@ if ($di->config->get('show_network_news'))
} }
} }
if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) {
{
$week_list = $today_list = array(); $week_list = $today_list = array();
$week_all = $today_all = false; $week_all = $today_all = false;
if ($stats['birthday_week_list']) if ($stats['birthday_week_list']) {
{
shuffle($stats['birthday_week_list']); shuffle($stats['birthday_week_list']);
foreach ($stats['birthday_week_list'] as $i => $week) foreach ($stats['birthday_week_list'] as $i => $week) {
{ if ($i >= 5) {
if ($i >= 5)
{
$week_all = true; $week_all = true;
continue; continue;
} }
$week_list[] = profile_url($week) .' <span class="small">('. birthday_age($week['user_birthday']-1) .')</span>'; $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_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; $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'));
} }
else $week_list = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('birthday_check_day'));
if ($stats['birthday_today_list']) if ($stats['birthday_today_list']) {
{
shuffle($stats['birthday_today_list']); shuffle($stats['birthday_today_list']);
foreach ($stats['birthday_today_list'] as $i => $today) foreach ($stats['birthday_today_list'] as $i => $today) {
{ if ($i >= 5) {
if ($i >= 5)
{
$today_all = true; $today_all = true;
continue; continue;
} }
$today_list[] = profile_url($today) .' <span class="small">('. birthday_age($today['user_birthday']) .')</span>'; $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_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; $today_list = $lang['BIRTHDAY_TODAY'] . join(', ', $today_list) . $today_all;
} else {
$today_list = $lang['NOBIRTHDAY_TODAY'];
} }
else $today_list = $lang['NOBIRTHDAY_TODAY'];
$template->assign_vars(array( $template->assign_vars(array(
'WHOSBIRTHDAY_WEEK' => $week_list, 'WHOSBIRTHDAY_WEEK' => $week_list,
@ -409,13 +379,10 @@ if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled
} }
// Allow cron // Allow cron
if (IS_AM) if (IS_AM) {
{ if (file_exists(CRON_RUNNING)) {
if (file_exists(CRON_RUNNING)) if (file_exists(CRON_ALLOWED)) {
{ unlink(CRON_ALLOWED);
if (file_exists(CRON_ALLOWED))
{
unlink (CRON_ALLOWED);
} }
rename(CRON_RUNNING, CRON_ALLOWED); rename(CRON_RUNNING, CRON_ALLOWED);
} }
@ -424,6 +391,8 @@ if (IS_AM)
// Display page // Display page
define('SHOW_ONLINE', $show_online_users); define('SHOW_ONLINE', $show_online_users);
if (isset($_GET['map'])) $template->assign_vars(array('PAGE_TITLE' => $lang['FORUM_MAP'])); if (isset($_GET['map'])) {
$template->assign_vars(array('PAGE_TITLE' => $lang['FORUM_MAP']));
}
print_page('index.tpl'); print_page('index.tpl');

View file

@ -2,7 +2,7 @@
define('BB_SCRIPT', 'info'); define('BB_SCRIPT', 'info');
define('BB_ROOT', './'); define('BB_ROOT', './');
require(BB_ROOT .'common.php'); require(BB_ROOT . 'common.php');
// Start session management // Start session management
$user->session_start(); $user->session_start();
@ -11,10 +11,9 @@ global $lang;
$info = array(); $info = array();
$html_dir = LANG_DIR . 'html/'; $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) switch ($req_mode) {
{
case 'advert': case 'advert':
$info['title'] = $lang['ADVERT']; $info['title'] = $lang['ADVERT'];
$info['src'] = 'advert.html'; $info['src'] = 'advert.html';
@ -44,20 +43,31 @@ $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $h
?><!DOCTYPE html> ?><!DOCTYPE html>
<html dir="ltr"> <html dir="ltr">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="Content-Style-Type" content="text/css"/>
<link rel="stylesheet" href="styles/templates/default/css/main.css" type="text/css"> <link rel="stylesheet" href="styles/templates/default/css/main.css" type="text/css">
</head> </head>
<body> <body>
<style type="text/css"> <style type="text/css">
#infobox-wrap { width: 760px; } #infobox-wrap {
#infobox-body { width: 760px;
background: #FFFFFF; color: #000000; padding: 1em; }
height: 400px; overflow: auto; border: 1px inset #000000;
} #infobox-body {
#infobox-body p { margin-top: 1em; margin-bottom: 1em; } background: #FFFFFF;
color: #000000;
padding: 1em;
height: 400px;
overflow: auto;
border: 1px inset #000000;
}
#infobox-body p {
margin-top: 1em;
margin-bottom: 1em;
}
</style> </style>
<br /> <br/>
<div id="infobox-wrap" class="bCenter row1"> <div id="infobox-wrap" class="bCenter row1">
<fieldset class="pad_6"> <fieldset class="pad_6">
<legend class="med bold mrg_2 warnColor1"><?php echo mb_strtoupper($info['title'], 'UTF-8'); ?></legend> <legend class="med bold mrg_2 warnColor1"><?php echo mb_strtoupper($info['title'], 'UTF-8'); ?></legend>
@ -65,7 +75,8 @@ $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $h
<?php require($require); ?> <?php require($require); ?>
</div> </div>
</fieldset> </fieldset>
<p class="gen tRight pad_6"><a href="javascript:window.close();" class="gen">[ <?php echo $lang['LOCK']; ?> ]</a></p> <p class="gen tRight pad_6"><a href="javascript:window.close();" class="gen">[ <?php echo $lang['LOCK']; ?> ]</a>
</p>
</div><!--/infobox-wrap--> </div><!--/infobox-wrap-->
</body> </body>
</html> </html>

View file

@ -1,37 +1,36 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $user; global $lang, $user;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$user_id = (int) $this->request['user_id']; $user_id = (int)$this->request['user_id'];
if (!$user_id || !($u_data = get_userdata($user_id))) if (!$user_id || !($u_data = get_userdata($user_id))) {
{
$this->ajax_die('Invalid user_id'); $this->ajax_die('Invalid user_id');
} }
if (!IS_ADMIN && $user_id != $user->id) if (!IS_ADMIN && $user_id != $user->id) {
{
$this->ajax_die($lang['NOT_ADMIN']); $this->ajax_die($lang['NOT_ADMIN']);
} }
switch ($mode) switch ($mode) {
{
case 'delete': case 'delete':
delete_avatar($user_id, $u_data['avatar_ext_id']); delete_avatar($user_id, $u_data['avatar_ext_id']);
$new_ext_id = 0; $new_ext_id = 0;
$response = '<img src="'. $di->config->get('avatars.upload_path') . $di->config->get('avatars.no_avatar') .'" alt="'. $user_id .'" />'; $response = '<img src="' . $di->config->get('avatars.upload_path') . $di->config->get('avatars.no_avatar') . '" alt="' . $user_id . '" />';
break; break;
default: default:
$this->ajax_die('Invalid mode'); $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); cache_rm_user_sessions($user_id);

View file

@ -1,91 +1,96 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang; global $userdata, $lang;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!isset($this->request['topic_id'])) $this->ajax_die('Invalid topic_id'); if (!isset($this->request['topic_id'])) {
$this->ajax_die('Invalid topic_id');
}
$topic_id = (int) $this->request['topic_id']; $topic_id = (int)$this->request['topic_id'];
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
if ($di->config->get('tor_comment')) if ($di->config->get('tor_comment')) {
{ $comment = (string)$this->request['comment'];
$comment = (string) $this->request['comment'];
} }
$tor = DB()->fetch_row(" $tor = DB()->fetch_row("
SELECT SELECT
tor.poster_id, tor.forum_id, tor.tor_status, tor.checked_time, tor.checked_user_id, f.cat_id, t.topic_title 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 FROM " . BB_BT_TORRENTS . " tor
INNER JOIN ". BB_FORUMS ." f ON(f.forum_id = tor.forum_id) INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = tor.forum_id)
INNER JOIN ". BB_TOPICS ." t ON(t.topic_id = tor.topic_id) INNER JOIN " . BB_TOPICS . " t ON(t.topic_id = tor.topic_id)
WHERE tor.topic_id = $topic_id WHERE tor.topic_id = $topic_id
LIMIT 1 LIMIT 1
"); ");
if (!$tor) $this->ajax_die($lang['TORRENT_FAILED']); if (!$tor) {
$this->ajax_die($lang['TORRENT_FAILED']);
}
switch ($mode) switch ($mode) {
{
case 'status': case 'status':
$new_status = (int) $this->request['status']; $new_status = (int)$this->request['status'];
// Валидность статуса // Валидность статуса
if (!isset($lang['TOR_STATUS_NAME'][$new_status])) $this->ajax_die($lang['TOR_STATUS_FAILED']); if (!isset($lang['TOR_STATUS_NAME'][$new_status])) {
if (!isset($this->request['status'])) $this->ajax_die($lang['TOR_DONT_CHANGE']); $this->ajax_die($lang['TOR_STATUS_FAILED']);
if (!IS_AM) $this->ajax_die($lang['NOT_MODERATOR']); }
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) if ($tor['tor_status'] == $new_status) {
{
$this->ajax_die($lang['TOR_STATUS_DUB']); $this->ajax_die($lang['TOR_STATUS_DUB']);
} }
// Запрет на изменение/присвоение CH-статуса модератором // Запрет на изменение/присвоение CH-статуса модератором
if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) if ($new_status == TOR_CLOSED_CPHOLD && !IS_ADMIN) {
{
$this->ajax_die($lang['TOR_DONT_CHANGE']); $this->ajax_die($lang['TOR_DONT_CHANGE']);
} }
// Права на изменение статуса // Права на изменение статуса
if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) {
{ if (!IS_ADMIN) {
if (!IS_ADMIN) $this->verify_mod_rights($tor['forum_id']); $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 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']); $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 ($tor['tor_status'] != TOR_NOT_APPROVED && $tor['checked_user_id'] != $userdata['user_id'] && $tor['checked_time'] + 2 * 3600 > TIMENOW) {
{ if (empty($this->request['confirmed'])) {
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['TOR_STATUS_OF'] ." {$lang['TOR_STATUS_NAME'][$tor['tor_status']]}\n\n"; $msg .= $lang['PROCEED'] . '?';
$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); $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 ($di->config->get('tor_comment') && (($comment && $comment != $lang['COMMENT']) || in_array($new_status, $di->config->get('tor_reply')))) {
{ if ($tor['poster_id'] > 0) {
if ($tor['poster_id'] > 0)
{
$subject = sprintf($lang['TOR_MOD_TITLE'], $tor['topic_title']); $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]); $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']); send_pm($tor['poster_id'], $subject, $message, $userdata['user_id']);
cache_rm_user_sessions($tor['poster_id']); cache_rm_user_sessions($tor['poster_id']);
@ -94,12 +99,16 @@ switch ($mode)
break; break;
case 'status_reply': case 'status_reply':
if (!$di->config->get('tor_comment')) $this->ajax_die($lang['MODULE_OFF']); if (!$di->config->get('tor_comment')) {
$this->ajax_die($lang['MODULE_OFF']);
}
$subject = sprintf($lang['TOR_AUTH_TITLE'], $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']); $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']); send_pm($tor['checked_user_id'], $subject, $message, $userdata['user_id']);
cache_rm_user_sessions($tor['checked_user_id']); cache_rm_user_sessions($tor['checked_user_id']);

View file

@ -1,42 +1,35 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
if (!isset($this->request['t'])) if (!isset($this->request['t'])) {
{
$this->ajax_die('Invalid AJAX topic'); $this->ajax_die('Invalid AJAX topic');
} }
if (!isset($this->request['u'])) if (!isset($this->request['u'])) {
{
//$this->ajax_die('Invalid AJAX user'); //$this->ajax_die('Invalid AJAX user');
} }
if (!isset($this->request['type'])) if (!isset($this->request['type'])) {
{
$this->ajax_die('Invalid AJAX 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']; //$req_uid = (int) $this->request['u'];
$type = (string) $this->request['type']; $type = (string)$this->request['type'];
$title = $url = ''; $title = $url = '';
switch ($type) switch ($type) {
{
case 'set_gold'; case 'set_gold';
case 'set_silver'; case 'set_silver';
case 'unset_silver_gold'; case 'unset_silver_gold';
if ($type == 'set_silver') if ($type == 'set_silver') {
{
$tor_type = TOR_TYPE_SILVER; $tor_type = TOR_TYPE_SILVER;
} } elseif ($type == 'set_gold') {
elseif ($type == 'set_gold')
{
$tor_type = TOR_TYPE_GOLD; $tor_type = TOR_TYPE_GOLD;
} } else {
else
{
$tor_type = 0; $tor_type = 0;
} }
change_tor_type($topic_id, $tor_type); change_tor_type($topic_id, $tor_type);
@ -55,13 +48,17 @@ switch ($type)
break; break;
case 'del_torrent'; case 'del_torrent';
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_TORRENT']); if (empty($this->request['confirmed'])) {
$this->prompt_for_confirm($lang['DEL_TORRENT']);
}
delete_torrent($topic_id); delete_torrent($topic_id);
$url = make_url(TOPIC_URL . $topic_id); $url = make_url(TOPIC_URL . $topic_id);
break; break;
case 'del_torrent_move_topic'; case 'del_torrent_move_topic';
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']); if (empty($this->request['confirmed'])) {
$this->prompt_for_confirm($lang['DEL_MOVE_TORRENT']);
}
delete_torrent($topic_id); delete_torrent($topic_id);
$url = make_url("modcp.php?t=$topic_id&mode=move"); $url = make_url("modcp.php?t=$topic_id&mode=move");
break; break;

View file

@ -1,33 +1,31 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $bf, $lang; 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); $new_opt = \Zend\Json\Json::decode($this->request['user_opt'], \Zend\Json\Json::TYPE_ARRAY);
if (!$user_id || !($u_data = get_userdata($user_id))) if (!$user_id || !($u_data = get_userdata($user_id))) {
{
$this->ajax_die('invalid user_id'); $this->ajax_die('invalid user_id');
} }
if (!is_array($new_opt)) if (!is_array($new_opt)) {
{
$this->ajax_die('invalid new_opt'); $this->ajax_die('invalid new_opt');
} }
foreach ($bf['user_opt'] as $opt_name => $opt_bit) foreach ($bf['user_opt'] as $opt_name => $opt_bit) {
{ if (isset($new_opt[$opt_name])) {
if (isset($new_opt[$opt_name]))
{
setbit($u_data['user_opt'], $opt_bit, !empty($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

@ -1,27 +1,27 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $datastore, $lang; global $datastore, $lang;
$ranks = $datastore->get('ranks'); $ranks = $datastore->get('ranks');
$rank_id = intval($this->request['rank_id']); $rank_id = intval($this->request['rank_id']);
if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) {
{
$this->ajax_die("invalid user_id: $user_id"); $this->ajax_die("invalid user_id: $user_id");
} }
if ($rank_id != 0 && !isset($ranks[$rank_id])) if ($rank_id != 0 && !isset($ranks[$rank_id])) {
{
$this->ajax_die("invalid rank_id: $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); 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['html'] = ($rank_id) ? $lang['AWARDED_RANK'] . "<b> $user_rank </b>" : $lang['SHOT_RANK'];
$this->response['rank_name'] = ($rank_id) ? $user_rank : $lang['USER']; $this->response['rank_name'] = ($rank_id) ? $user_rank : $lang['USER'];

View file

@ -1,30 +1,28 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang; global $userdata, $lang;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!($group_id = intval($this->request['group_id'])) || !($group_info = get_group_data($group_id))) if (!($group_id = intval($this->request['group_id'])) || !($group_info = get_group_data($group_id))) {
{
$this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']); $this->ajax_die($lang['NO_GROUP_ID_SPECIFIED']);
} }
if (!$mode = (string) $this->request['mode']) if (!$mode = (string)$this->request['mode']) {
{
$this->ajax_die('No mode specified'); $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']) if (!IS_ADMIN && $userdata['user_id'] != $group_info['group_moderator']) {
{
$this->ajax_die($lang['ONLY_FOR_MOD']); $this->ajax_die($lang['ONLY_FOR_MOD']);
} }
switch ($mode) switch ($mode) {
{
case 'group_name': case 'group_name':
case 'group_signature': case 'group_signature':
case 'group_description': case 'group_description':
@ -52,4 +50,4 @@ switch ($mode)
} }
$value_sql = DB()->escape($value, true); $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

@ -1,79 +1,74 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) {
{
$this->ajax_die($lang['NO_USER_ID_SPECIFIED']); $this->ajax_die($lang['NO_USER_ID_SPECIFIED']);
} }
if (!$field = (string) $this->request['field']) if (!$field = (string)$this->request['field']) {
{
$this->ajax_die('invalid profile field'); $this->ajax_die('invalid profile field');
} }
$table = BB_USERS; $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) switch ($field) {
{
case 'username': case 'username':
require_once(INC_DIR .'functions_validate.php'); require_once(INC_DIR . 'functions_validate.php');
$value = clean_username($value); $value = clean_username($value);
if ($err = validate_username($value)) if ($err = validate_username($value)) {
{
$this->ajax_die(strip_tags($err)); $this->ajax_die(strip_tags($err));
} }
$this->response['new_value'] = $this->request['value']; $this->response['new_value'] = $this->request['value'];
break; break;
case 'user_email': case 'user_email':
require_once(INC_DIR .'functions_validate.php'); require_once(INC_DIR . 'functions_validate.php');
$value = htmlCHR($value); $value = htmlCHR($value);
if ($err = validate_email($value)) if ($err = validate_email($value)) {
{
$this->ajax_die($err); $this->ajax_die($err);
} }
$this->response['new_value'] = $this->request['value']; $this->response['new_value'] = $this->request['value'];
break; break;
case 'user_website': case 'user_website':
if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) if ($value == '' || preg_match('#^https?://[\w\#!$%&~/.\-;:=,?@а-яА-Я\[\]+]+$#iu', $value)) {
{
$this->response['new_value'] = htmlCHR($value); $this->response['new_value'] = htmlCHR($value);
} else {
$this->ajax_die($lang['WEBSITE_ERROR']);
} }
else $this->ajax_die($lang['WEBSITE_ERROR']);
break; break;
case 'user_gender': case 'user_gender':
if (!$di->config->get('gender')) $this->ajax_die($lang['MODULE_OFF']); if (!$di->config->get('gender')) {
if (!isset($lang['GENDER_SELECT'][$value])) $this->ajax_die($lang['MODULE_OFF']);
{ }
$this->ajax_die($lang['ERROR']); if (!isset($lang['GENDER_SELECT'][$value])) {
$this->ajax_die($lang['ERROR']);
} else {
$this->response['new_value'] = $lang['GENDER_SELECT'][$value];
} }
else $this->response['new_value'] = $lang['GENDER_SELECT'][$value];
break; break;
case 'user_birthday': case 'user_birthday':
if (!$di->config->get('birthday_enabled')) $this->ajax_die($lang['MODULE_OFF']); if (!$di->config->get('birthday_enabled')) {
$this->ajax_die($lang['MODULE_OFF']);
}
$birthday_date = date_parse($value); $birthday_date = date_parse($value);
if (!empty($birthday_date['year'])) if (!empty($birthday_date['year'])) {
{ if (strtotime($value) >= TIMENOW) {
if (strtotime($value) >= TIMENOW)
{
$this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']); $this->ajax_die($lang['WRONG_BIRTHDAY_FORMAT']);
} } elseif (bb_date(TIMENOW, 'Y', 'false') - $birthday_date['year'] > $di->config->get('birthday_max_age')) {
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'))); $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')) {
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->ajax_die(sprintf($lang['BIRTHDAY_TO_LOW'], $di->config->get('birthday_min_age')));
} }
} }
@ -82,24 +77,21 @@ switch ($field)
break; break;
case 'user_icq': case 'user_icq':
if ($value && !preg_match('#^\d{6,15}$#', $value)) if ($value && !preg_match('#^\d{6,15}$#', $value)) {
{
$this->ajax_die($lang['ICQ_ERROR']); $this->ajax_die($lang['ICQ_ERROR']);
} }
$this->response['new_value'] = $this->request['value']; $this->response['new_value'] = $this->request['value'];
break; break;
case 'user_skype': case 'user_skype':
if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) if ($value && !preg_match("#^[a-zA-Z0-9_.\-@,]{6,32}$#", $value)) {
{
$this->ajax_die($lang['SKYPE_ERROR']); $this->ajax_die($lang['SKYPE_ERROR']);
} }
$this->response['new_value'] = $this->request['value']; $this->response['new_value'] = $this->request['value'];
break; break;
case 'user_twitter': case 'user_twitter':
if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) if ($value && !preg_match("#^[a-zA-Z0-9_]{1,15}$#", $value)) {
{
$this->ajax_die($lang['TWITTER_ERROR']); $this->ajax_die($lang['TWITTER_ERROR']);
} }
$this->response['new_value'] = $this->request['value']; $this->response['new_value'] = $this->request['value'];
@ -115,8 +107,7 @@ switch ($field)
case 'user_regdate': case 'user_regdate':
case 'user_lastvisit': case 'user_lastvisit':
$tz = TIMENOW + (3600 * $di->config->get('board_timezone')); $tz = TIMENOW + (3600 * $di->config->get('board_timezone'));
if ((($value = strtotime($value, $tz)) < $di->config->get('board_startdate')) || ($value > TIMENOW)) if ((($value = strtotime($value, $tz)) < $di->config->get('board_startdate')) || ($value > TIMENOW)) {
{
$this->ajax_die($lang['INVALID_DATE'] . $this->request['value']); $this->ajax_die($lang['INVALID_DATE'] . $this->request['value']);
} }
$this->response['new_value'] = bb_date($value, 'Y-m-d H:i', false); $this->response['new_value'] = bb_date($value, 'Y-m-d H:i', false);
@ -126,15 +117,15 @@ switch ($field)
case 'u_down_total': case 'u_down_total':
case 'u_up_release': case 'u_up_release':
case 'u_up_bonus': case 'u_up_bonus':
if (!IS_ADMIN) $this->ajax_die($lang['NOT_ADMIN']); if (!IS_ADMIN) {
$this->ajax_die($lang['NOT_ADMIN']);
}
$table = BB_BT_USERS; $table = BB_BT_USERS;
$value = (float) str_replace(',', '.', $this->request['value']); $value = (float)str_replace(',', '.', $this->request['value']);
foreach (array('KB'=>1,'MB'=>2,'GB'=>3,'TB'=>4) as $s => $m) foreach (array('KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4) as $s => $m) {
{ if (strpos($this->request['value'], $s) !== false) {
if (strpos($this->request['value'], $s) !== false)
{
$value *= pow(1024, $m); $value *= pow(1024, $m);
break; break;
} }
@ -142,19 +133,18 @@ switch ($field)
$value = sprintf('%.0f', $value); $value = sprintf('%.0f', $value);
$this->response['new_value'] = humn_size($value, null, null, ' '); $this->response['new_value'] = humn_size($value, null, null, ' ');
if (!$btu = get_bt_userdata($user_id)) if (!$btu = get_bt_userdata($user_id)) {
{ require(INC_DIR . 'functions_torrent.php');
require(INC_DIR .'functions_torrent.php');
generate_passkey($user_id, true); generate_passkey($user_id, true);
$btu = get_bt_userdata($user_id); $btu = get_bt_userdata($user_id);
} }
$btu[$field] = $value; $btu[$field] = $value;
$this->response['update_ids']['u_ratio'] = (string) get_bt_ratio($btu); $this->response['update_ids']['u_ratio'] = (string)get_bt_ratio($btu);
break; break;
case 'user_points': case 'user_points':
$value = htmlCHR($value); $value = htmlCHR($value);
$value = (float) str_replace(',', '.', $this->request['value']); $value = (float)str_replace(',', '.', $this->request['value']);
$value = sprintf('%.2f', $value); $value = sprintf('%.2f', $value);
$this->response['new_value'] = $value; $this->response['new_value'] = $value;
break; break;
@ -166,6 +156,6 @@ switch ($field)
$value_sql = DB()->escape($value, true); $value_sql = DB()->escape($value, true);
DB()->query("UPDATE $table SET $field = $value_sql WHERE user_id = $user_id LIMIT 1"); 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

@ -1,25 +1,25 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang; 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 ($req_uid == $userdata['user_id'] || IS_ADMIN) {
{ if (empty($this->request['confirmed'])) {
if (empty($this->request['confirmed']))
{
$this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']); $this->prompt_for_confirm($lang['BT_GEN_PASSKEY_NEW']);
} }
if (!$passkey = generate_passkey($req_uid, IS_ADMIN)) if (!$passkey = generate_passkey($req_uid, IS_ADMIN)) {
{
$this->ajax_die('Could not insert passkey'); $this->ajax_die('Could not insert passkey');
} }
tracker_rm_user($req_uid); tracker_rm_user($req_uid);
$this->response['passkey'] = $passkey; $this->response['passkey'] = $passkey;
} else {
$this->ajax_die($lang['NOT_AUTHORISED']);
} }
else $this->ajax_die($lang['NOT_AUTHORISED']);

View file

@ -1,65 +1,55 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $user; global $lang, $user;
if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) if (!($user_id = intval($this->request['user_id'])) || !($profiledata = get_userdata($user_id))) {
{
$this->ajax_die("invalid user_id: $user_id"); $this->ajax_die("invalid user_id: $user_id");
} }
if (!$mode = (string) $this->request['mode']) if (!$mode = (string)$this->request['mode']) {
{
$this->ajax_die('invalid mode (empty)'); $this->ajax_die('invalid mode (empty)');
} }
switch ($mode) switch ($mode) {
{
case 'get_group_list': case 'get_group_list':
$sql = " $sql = "
SELECT ug.user_pending, g.group_id, g.group_type, g.group_name, g.group_moderator, self.user_id AS can_view 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 FROM " . BB_USER_GROUP . " ug
INNER JOIN ". BB_GROUPS ." g ON(g.group_id = ug.group_id AND g.group_single_user = 0) 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) 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 WHERE ug.user_id = $user_id
ORDER BY g.group_name ORDER BY g.group_name
"; ";
$html = array(); $html = array();
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$class = ($row['user_pending']) ? 'med' : 'med bold'; $class = ($row['user_pending']) ? 'med' : 'med bold';
$class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : ''; $class .= ($row['group_moderator'] == $user_id) ? ' colorMod' : '';
$href = "group.php?g={$row['group_id']}"; $href = "group.php?g={$row['group_id']}";
if (IS_ADMIN) if (IS_ADMIN) {
{
$href .= "&amp;u=$user_id"; $href .= "&amp;u=$user_id";
$link = '<a href="'. $href .'" class="'. $class .'" target="_blank">'. htmlCHR($row['group_name']) .'</a>'; $link = '<a href="' . $href . '" class="' . $class . '" target="_blank">' . htmlCHR($row['group_name']) . '</a>';
$html[] = $link; $html[] = $link;
} } else {
else
{
// скрытая группа и сам юзер не является ее членом // скрытая группа и сам юзер не является ее членом
if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) if ($row['group_type'] == GROUP_HIDDEN && !$row['can_view']) {
{
continue; continue;
} }
if ($row['group_moderator'] == $user->id) if ($row['group_moderator'] == $user->id) {
{
$class .= ' selfMod'; $class .= ' selfMod';
$href .= "&amp;u=$user_id"; // сам юзер модератор этой группы $href .= "&amp;u=$user_id"; // сам юзер модератор этой группы
} }
$link = '<a href="'. $href .'" class="'. $class .'" target="_blank">'. htmlCHR($row['group_name']) .'</a>'; $link = '<a href="' . $href . '" class="' . $class . '" target="_blank">' . htmlCHR($row['group_name']) . '</a>';
$html[] = $link; $html[] = $link;
} }
} }
if ($html) if ($html) {
{ $this->response['group_list_html'] = '<ul><li>' . join('</li><li>', $html) . '</li></ul>';
$this->response['group_list_html'] = '<ul><li>'. join('</li><li>', $html) .'</li></ul>'; } else {
}
else
{
$this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN']; $this->response['group_list_html'] = $lang['GROUP_LIST_HIDDEN'];
} }
break; break;

View file

@ -1,32 +1,32 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata, $datastore; global $lang, $userdata, $datastore;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$html = ''; $html = '';
switch($mode) switch ($mode) {
{
case 'birthday_week': case 'birthday_week':
$stats = $datastore->get('stats'); $stats = $datastore->get('stats');
$datastore->enqueue(array( $datastore->enqueue(array(
'stats', 'stats',
)); ));
if ($stats['birthday_week_list']) if ($stats['birthday_week_list']) {
{ foreach ($stats['birthday_week_list'] as $week) {
foreach($stats['birthday_week_list'] as $week) $html[] = profile_url($week) . ' <span class="small">(' . birthday_age($week['user_birthday']) . ')</span>';
{
$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)); $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'));
} }
else $html = sprintf($lang['NOBIRTHDAY_WEEK'], $di->config->get('birthday_check_day'));
break; break;
case 'birthday_today': case 'birthday_today':
@ -35,19 +35,18 @@ switch($mode)
'stats', 'stats',
)); ));
if ($stats['birthday_today_list']) if ($stats['birthday_today_list']) {
{ foreach ($stats['birthday_today_list'] as $today) {
foreach($stats['birthday_today_list'] as $today) $html[] = profile_url($today) . ' <span class="small">(' . birthday_age($today['user_birthday']) . ')</span>';
{
$html[] = profile_url($today) .' <span class="small">('. birthday_age($today['user_birthday']) .')</span>';
} }
$html = $lang['BIRTHDAY_TODAY'] . join(', ', $html); $html = $lang['BIRTHDAY_TODAY'] . join(', ', $html);
} else {
$html = $lang['NOBIRTHDAY_TODAY'];
} }
else $html = $lang['NOBIRTHDAY_TODAY'];
break; break;
case 'get_forum_mods': case 'get_forum_mods':
$forum_id = (int) $this->request['forum_id']; $forum_id = (int)$this->request['forum_id'];
$datastore->enqueue(array( $datastore->enqueue(array(
'moderators', 'moderators',
@ -56,19 +55,15 @@ switch($mode)
$moderators = array(); $moderators = array();
$mod = $datastore->get('moderators'); $mod = $datastore->get('moderators');
if (isset($mod['mod_users'][$forum_id])) if (isset($mod['mod_users'][$forum_id])) {
{ foreach ($mod['mod_users'][$forum_id] as $user_id) {
foreach ($mod['mod_users'][$forum_id] as $user_id) $moderators[] = '<a href="' . PROFILE_URL . $user_id . '">' . $mod['name_users'][$user_id] . '</a>';
{
$moderators[] = '<a href="'. PROFILE_URL . $user_id .'">'. $mod['name_users'][$user_id] .'</a>';
} }
} }
if (isset($mod['mod_groups'][$forum_id])) if (isset($mod['mod_groups'][$forum_id])) {
{ foreach ($mod['mod_groups'][$forum_id] as $group_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>';
{
$moderators[] = '<a href="'. "group.php?". POST_GROUPS_URL ."=". $group_id .'">'. $mod['name_groups'][$group_id] .'</a>';
} }
} }
@ -79,49 +74,53 @@ switch($mode)
break; break;
case 'change_tz': case 'change_tz':
$tz = (int) $this->request['tz']; $tz = (int)$this->request['tz'];
if ($tz < -12) $tz = -12; if ($tz < -12) {
if ($tz > 13) $tz = 13; $tz = -12;
}
if ($tz > 13) {
$tz = 13;
}
DB()->query("UPDATE " . BB_USERS . " SET user_timezone = $tz WHERE user_id = " . $userdata['user_id'] . " LIMIT 1"); DB()->query("UPDATE " . BB_USERS . " SET user_timezone = $tz WHERE user_id = " . $userdata['user_id'] . " LIMIT 1");
cache_rm_user_sessions($userdata['user_id']); cache_rm_user_sessions($userdata['user_id']);
break; break;
case 'get_traf_stats': case 'get_traf_stats':
$user_id = (int) $this->request['user_id']; $user_id = (int)$this->request['user_id'];
$btu = get_bt_userdata($user_id); $btu = get_bt_userdata($user_id);
$profiledata = get_userdata($user_id); $profiledata = get_userdata($user_id);
$speed_up = ($btu['speed_up']) ? humn_size($btu['speed_up']).'/s' : '0 KB/s'; $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'; $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>'; $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"> <tr class="row3">
<th style="padding: 0;"></th> <th style="padding: 0;"></th>
<th>'. $lang['DOWNLOADED'] .'</th> <th>' . $lang['DOWNLOADED'] . '</th>
<th>'. $lang['UPLOADED'] .'</th> <th>' . $lang['UPLOADED'] . '</th>
<th>'. $lang['RELEASED'] .'</th> <th>' . $lang['RELEASED'] . '</th>
<th>'. $lang['BONUS'] .'</th>'; <th>' . $lang['BONUS'] . '</th>';
$html .= ($di->config->get('seed_bonus_enabled')) ? '<th>'. $lang['SEED_BONUS'] .'</th>' : ''; $html .= ($di->config->get('seed_bonus_enabled')) ? '<th>' . $lang['SEED_BONUS'] . '</th>' : '';
$html .= '</tr> $html .= '</tr>
<tr class="row1"> <tr class="row1">
<td>'. $lang['TOTAL_TRAF'] .'</td> <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_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_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_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>'; <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 .= ($di->config->get('seed_bonus_enabled')) ? '<td id="user_points"><span class="editable bold points">' . $profiledata['user_points'] . '</b></td>' : '';
$html .= '</tr> $html .= '</tr>
<tr class="row5"> <tr class="row5">
<td colspan="1">'. $lang['SPEED'] .'</td> <td colspan="1">' . $lang['SPEED'] . '</td>
<td colspan="2">'. $lang['DL_DL_SPEED'] .': '. $speed_down .'</span></td> <td colspan="2">' . $lang['DL_DL_SPEED'] . ': ' . $speed_down . '</span></td>
<td colspan="2">'. $lang['DL_UL_SPEED'] .': '. $speed_up .'</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 .= ($di->config->get('seed_bonus_enabled')) ? '<td colspan="1"></td>' : '';
$html .= '</tr>'; $html .= '</tr>';
$this->response['user_ratio'] = ' $this->response['user_ratio'] = '
<th><a href="'. $di->config->get('ratio_url_help') .'" class="bold">'. $lang['USER_RATIO'] .'</a>:</th> <th><a href="' . $di->config->get('ratio_url_help') . '" class="bold">' . $lang['USER_RATIO'] . '</a>:</th>
<td>'. $user_ratio .'</td> <td>' . $user_ratio . '</td>
'; ';
break; break;
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang; global $userdata, $lang;
@ -10,15 +12,14 @@ $di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */ /** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache; $cache = $di->cache;
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
switch ($mode) switch ($mode) {
{
case 'clear_cache': 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;
@ -28,7 +29,7 @@ switch ($mode)
$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;
@ -40,16 +41,14 @@ switch ($mode)
$match_len = strlen($match); $match_len = strlen($match);
$dir = $template->cachedir; $dir = $template->cachedir;
$res = opendir($dir); $res = opendir($dir);
while (($file = readdir($res)) !== false) while (($file = readdir($res)) !== false) {
{ if (substr($file, 0, $match_len) === $match) {
if (substr($file, 0, $match_len) === $match)
{
unlink($dir . $file); unlink($dir . $file);
} }
} }
closedir($res); 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;
@ -57,32 +56,30 @@ switch ($mode)
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")) 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", "####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) 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", $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;
@ -91,7 +88,7 @@ switch ($mode)
sync('topic', 'all'); sync('topic', 'all');
sync_all_forums(); 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;
@ -99,7 +96,7 @@ switch ($mode)
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;
@ -107,7 +104,7 @@ switch ($mode)
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;
} }

View file

@ -1,70 +1,85 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang; global $userdata, $lang;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$user_id = $this->request['user_id']; $user_id = $this->request['user_id'];
switch ($mode) switch ($mode) {
{
case 'delete_profile': case 'delete_profile':
if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DELETE_ME']); if ($userdata['user_id'] == $user_id) {
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['USER_DELETE_CONFIRM']); $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) if ($user_id != BOT_UID) {
{
delete_user_sessions($user_id); delete_user_sessions($user_id);
user_delete($user_id); user_delete($user_id);
$this->response['info'] = $lang['USER_DELETED']; $this->response['info'] = $lang['USER_DELETED'];
} else {
$this->ajax_die($lang['USER_DELETE_CSV']);
} }
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']) && $userdata['user_id'] == $user_id) {
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_ALL_POSTS_CONFIRM']); $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) if (IS_ADMIN) {
{ $user_topics = DB()->fetch_rowset("SELECT topic_id FROM " . BB_TOPICS . " WHERE topic_poster = $user_id", 'topic_id');
$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_topics = topic_delete($user_topics);
$deleted_posts = post_delete('user', $user_id); $deleted_posts = post_delete('user', $user_id);
$this->response['info'] = $lang['USER_DELETED_POSTS']; $this->response['info'] = $lang['USER_DELETED_POSTS'];
} else {
$this->ajax_die($lang['NOT_ADMIN']);
} }
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']) && $userdata['user_id'] == $user_id) {
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['DELETE_USER_POSTS_CONFIRM']); $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) if (IS_ADMIN) {
{
post_delete('user', $user_id); post_delete('user', $user_id);
$this->response['info'] = $lang['USER_DELETED_POSTS']; $this->response['info'] = $lang['USER_DELETED_POSTS'];
} else {
$this->ajax_die($lang['NOT_ADMIN']);
} }
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'];
@ -72,10 +87,14 @@ switch ($mode)
case 'user_deactivate': case 'user_deactivate':
if ($userdata['user_id'] == $user_id) $this->ajax_die($lang['USER_DEACTIVATE_ME']); if ($userdata['user_id'] == $user_id) {
if (empty($this->request['confirmed'])) $this->prompt_for_confirm($lang['ACTIVATE_CONFIRM']); $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); DB()->query("UPDATE " . BB_USERS . " SET user_active = '0' WHERE user_id = " . $user_id);
delete_user_sessions($user_id); delete_user_sessions($user_id);
$this->response['info'] = $lang['USER_ACTIVATE_OFF']; $this->response['info'] = $lang['USER_ACTIVATE_OFF'];

View file

@ -1,30 +1,29 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata, $lang, $datastore; global $userdata, $lang, $datastore;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
switch ($mode) switch ($mode) {
{
case 'tor_status': case 'tor_status':
$topics = (string) $this->request['topic_ids']; $topics = (string)$this->request['topic_ids'];
$status = (int) $this->request['status']; $status = (int)$this->request['status'];
// Валидность статуса // Валидность статуса
if (!isset($lang['TOR_STATUS_NAME'][$status])) if (!isset($lang['TOR_STATUS_NAME'][$status])) {
{
$this->ajax_die($lang['STATUS_DOES_EXIST'] . $new_status); $this->ajax_die($lang['STATUS_DOES_EXIST'] . $new_status);
} }
$topic_ids = explode(',', $topics); $topic_ids = explode(',', $topics);
foreach($topic_ids as $topic_id) foreach ($topic_ids as $topic_id) {
{
change_tor_status($topic_id, $status); change_tor_status($topic_id, $status);
} }
@ -33,34 +32,35 @@ switch ($mode)
break; break;
case 'edit_topic_title': case 'edit_topic_title':
$topic_id = (int) $this->request['topic_id']; $topic_id = (int)$this->request['topic_id'];
$topic_title = (string) $this->request['topic_title']; $topic_title = (string)$this->request['topic_title'];
$new_title = clean_title($topic_title); $new_title = clean_title($topic_title);
if (!$topic_id) $this->ajax_die($lang['INVALID_TOPIC_ID']); if (!$topic_id) {
if ($new_title == '') $this->ajax_die($lang['DONT_MESSAGE_TITLE']); $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")) 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->ajax_die($lang['INVALID_TOPIC_ID_DB']);
} }
$this->verify_mod_rights($t_data['forum_id']); $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'))); $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')) if (isset($news_forums[$t_data['forum_id']]) && $di->config->get('show_latest_news')) {
{
$datastore->enqueue('latest_news'); $datastore->enqueue('latest_news');
$datastore->update('latest_news'); $datastore->update('latest_news');
} }
$net_forums = array_flip(explode(',', $di->config->get('network_news_forum_id'))); $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')) if (isset($net_forums[$t_data['forum_id']]) && $di->config->get('show_network_news')) {
{
$datastore->enqueue('network_news'); $datastore->enqueue('network_news');
$datastore->update('network_news'); $datastore->update('network_news');
} }
@ -70,63 +70,62 @@ switch ($mode)
break; break;
case 'profile_ip': case 'profile_ip':
$user_id = (int) $this->request['user_id']; $user_id = (int)$this->request['user_id'];
$profiledata = get_userdata($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']}' WHERE user_reg_ip = '{$profiledata['user_reg_ip']}'
AND user_reg_ip != '' AND user_reg_ip != ''
AND user_id != {$profiledata['user_id']} AND user_id != {$profiledata['user_id']}
ORDER BY username ASC"); 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']}' WHERE user_last_ip = '{$profiledata['user_last_ip']}'
AND user_last_ip != '' AND user_last_ip != ''
AND user_id != {$profiledata['user_id']}"); AND user_id != {$profiledata['user_id']}");
$link_reg_ip = $link_last_ip = ''; $link_reg_ip = $link_last_ip = '';
if (!empty($reg_ip)) if (!empty($reg_ip)) {
{ $link_reg_ip .= $lang['OTHER_IP'] . ' ';
$link_reg_ip .= $lang['OTHER_IP'] .' '; foreach ($reg_ip as $row) {
foreach ($reg_ip as $row) $link_reg_ip .= profile_url($row) . ' ';
{
$link_reg_ip .= profile_url($row) .' ';
} }
} }
if (!empty($last_ip)) if (!empty($last_ip)) {
{ $link_last_ip .= $lang['OTHER_IP'] . ' ';
$link_last_ip .= $lang['OTHER_IP'] .' '; foreach ($last_ip as $row) {
foreach ($last_ip as $row) $link_last_ip .= profile_url($row) . ' ';
{
$link_last_ip .= profile_url($row) .' ';
} }
} }
if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) $reg_ip = $last_ip = $lang['HIDDEN']; if ($profiledata['user_level'] == ADMIN && !IS_ADMIN) {
elseif ($profiledata['user_level'] == MOD && IS_MOD) $reg_ip = $last_ip = $lang['HIDDEN']; $reg_ip = $last_ip = $lang['HIDDEN'];
else } elseif ($profiledata['user_level'] == MOD && IS_MOD) {
{ $reg_ip = $last_ip = $lang['HIDDEN'];
} else {
$user_reg_ip = decode_ip($profiledata['user_reg_ip']); $user_reg_ip = decode_ip($profiledata['user_reg_ip']);
$user_last_ip = decode_ip($profiledata['user_last_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>'; $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>'; $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"> <br /><table class="mod_ip bCenter borderless" cellspacing="1">
<tr class="row5" > <tr class="row5" >
<td>'. $lang['REG_IP'] .'</td> <td>' . $lang['REG_IP'] . '</td>
<td class="tCenter">'. $reg_ip .'</td> <td class="tCenter">' . $reg_ip . '</td>
<td><div>'. $link_reg_ip .'</div></td> <td><div>' . $link_reg_ip . '</div></td>
</tr> </tr>
<tr class="row4"> <tr class="row4">
<td>'. $lang['LAST_IP'] .'</td> <td>' . $lang['LAST_IP'] . '</td>
<td class="tCenter">'. $last_ip .'</td> <td class="tCenter">' . $last_ip . '</td>
<td><div>'. $link_last_ip .'</div></td> <td><div>' . $link_last_ip . '</div></td>
</tr> </tr>
</table><br /> </table><br />
'; ';

View file

@ -1,21 +1,27 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata; global $lang, $userdata;
$post_id = (int) $this->request['post_id']; $post_id = (int)$this->request['post_id'];
$mc_type = (int) $this->request['mc_type']; $mc_type = (int)$this->request['mc_type'];
$mc_text = (string) $this->request['mc_text']; $mc_text = (string)$this->request['mc_text'];
if (!$mc_text = prepare_message($mc_text)) $this->ajax_die($lang['EMPTY_MESSAGE']); if (!$mc_text = prepare_message($mc_text)) {
$this->ajax_die($lang['EMPTY_MESSAGE']);
}
$post = DB()->fetch_row(" $post = DB()->fetch_row("
SELECT SELECT
p.post_id, p.poster_id p.post_id, p.poster_id
FROM ". BB_POSTS ." p FROM " . BB_POSTS . " p
WHERE p.post_id = $post_id WHERE p.post_id = $post_id
"); ");
if (!$post) $this->ajax_die('not post'); if (!$post) {
$this->ajax_die('not post');
}
$data = array( $data = array(
'mc_comment' => ($mc_type) ? $mc_text : '', 'mc_comment' => ($mc_type) ? $mc_text : '',
@ -23,19 +29,17 @@ $data = array(
'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0, 'mc_user_id' => ($mc_type) ? $userdata['user_id'] : 0,
); );
$sql_args = DB()->build_array('UPDATE', $data); $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']) if ($mc_type && $post['poster_id'] != $userdata['user_id']) {
{
$subject = sprintf($lang['MC_COMMENT_PM_SUBJECT'], $lang['MC_COMMENT'][$mc_type]['type']); $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); $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); send_pm($post['poster_id'], $subject, $message);
cache_rm_user_sessions($post['poster_id']); cache_rm_user_sessions($post['poster_id']);
} }
switch($mc_type) switch ($mc_type) {
{
case 1: // Комментарий case 1: // Комментарий
$mc_class = 'success'; $mc_class = 'success';
break; break;

View file

@ -1,108 +1,97 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata; global $lang, $userdata;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!isset($this->request['type'])) if (!isset($this->request['type'])) {
{
$this->ajax_die('empty type'); $this->ajax_die('empty type');
} }
if (isset($this->request['post_id'])) if (isset($this->request['post_id'])) {
{ $post_id = (int)$this->request['post_id'];
$post_id = (int) $this->request['post_id'];
$post = DB()->fetch_row("SELECT t.*, f.*, p.*, pt.post_text $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 FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f, " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt
WHERE p.post_id = $post_id WHERE p.post_id = $post_id
AND t.topic_id = p.topic_id AND t.topic_id = p.topic_id
AND f.forum_id = t.forum_id AND f.forum_id = t.forum_id
AND p.post_id = pt.post_id AND p.post_id = pt.post_id
LIMIT 1"); 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 ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) {
{
$this->ajax_die($lang['TOPIC_LOCKED']); $this->ajax_die($lang['TOPIC_LOCKED']);
} }
} } elseif (isset($this->request['topic_id'])) {
elseif (isset($this->request['topic_id'])) $topic_id = (int)$this->request['topic_id'];
{
$topic_id = (int) $this->request['topic_id'];
$post = DB()->fetch_row("SELECT t.*, f.* $post = DB()->fetch_row("SELECT t.*, f.*
FROM ". BB_TOPICS ." t, ". BB_FORUMS ." f FROM " . BB_TOPICS . " t, " . BB_FORUMS . " f
WHERE t.topic_id = $topic_id WHERE t.topic_id = $topic_id
AND f.forum_id = t.forum_id AND f.forum_id = t.forum_id
LIMIT 1"); 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')) if (!defined('WORD_LIST_OBTAINED')) {
{
$orig_word = array(); $orig_word = array();
$replace_word = array(); $replace_word = array();
obtain_word_list($orig_word, $replace_word); obtain_word_list($orig_word, $replace_word);
define('WORD_LIST_OBTAINED', true); define('WORD_LIST_OBTAINED', true);
} }
switch($this->request['type']) switch ($this->request['type']) {
{
case 'delete'; 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 ($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'])) {
if (empty($this->request['confirmed']))
{
$this->prompt_for_confirm($lang['CONFIRM_DELETE']); $this->prompt_for_confirm($lang['CONFIRM_DELETE']);
} }
post_delete($post_id); post_delete($post_id);
// Update atom feed // Update atom feed
update_atom('topic', (int) $this->request['topic_id']); update_atom('topic', (int)$this->request['topic_id']);
$this->response['hide'] = true; $this->response['hide'] = true;
$this->response['post_id'] = $post_id; $this->response['post_id'] = $post_id;
} } else {
else
{
$this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type']))); $this->ajax_die(sprintf($lang['SORRY_AUTH_DELETE'], strip_tags($is_auth['auth_delete_type'])));
} }
break; break;
case 'reply'; case 'reply';
if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) {
{
$this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT']));
} } elseif (!$is_auth['auth_reply']) {
elseif(!$is_auth['auth_reply'])
{
$this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); $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']); $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"; $message = "[quote=\"" . $quote_username . "\"][qpost=" . $post['post_id'] . "]" . $post['post_text'] . "[/quote]\r";
// hide user passkey // hide user passkey
$message = preg_replace('#(?<=\?uk=)[a-zA-Z0-9]{10}(?=&)#', 'passkey', $message); $message = preg_replace('#(?<=\?uk=)[a-zA-Z0-9]{10}(?=&)#', 'passkey', $message);
// hide sid // hide sid
$message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]{12}#', 'sid', $message); $message = preg_replace('#(?<=[\?&;]sid=)[a-zA-Z0-9]{12}#', 'sid', $message);
if (!empty($orig_word)) if (!empty($orig_word)) {
{
$message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : ''; $message = (!empty($message)) ? preg_replace($orig_word, $replace_word, $message) : '';
} }
if ($post['post_id'] == $post['topic_first_post_id']) if ($post['post_id'] == $post['topic_first_post_id']) {
{ $message = "[quote]" . $post['topic_title'] . "[/quote]\r";
$message = "[quote]". $post['topic_title'] ."[/quote]\r";
} }
if (mb_strlen($message, 'UTF-8') > 1000) if (mb_strlen($message, 'UTF-8') > 1000) {
{ $this->response['redirect'] = make_url(POSTING_URL . '?mode=quote&p=' . $post_id);
$this->response['redirect'] = make_url(POSTING_URL.'?mode=quote&p='. $post_id);
} }
$this->response['quote'] = true; $this->response['quote'] = true;
@ -110,8 +99,10 @@ switch($this->request['type'])
break; break;
case 'view_message': case 'view_message':
$message = (string) $this->request['message']; $message = (string)$this->request['message'];
if(!trim($message)) $this->ajax_die($lang['EMPTY_MESSAGE']); if (!trim($message)) {
$this->ajax_die($lang['EMPTY_MESSAGE']);
}
$message = htmlCHR($message, false, ENT_NOQUOTES); $message = htmlCHR($message, false, ENT_NOQUOTES);
$this->response['message_html'] = bbcode2html($message); $this->response['message_html'] = bbcode2html($message);
@ -120,39 +111,29 @@ switch($this->request['type'])
case 'edit': case 'edit':
case 'editor': case 'editor':
if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) if (bf($userdata['user_opt'], 'user_opt', 'dis_post_edit')) {
{
$this->ajax_die($lang['POST_EDIT_CANNOT']); $this->ajax_die($lang['POST_EDIT_CANNOT']);
} }
if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) if ($post['poster_id'] != $userdata['user_id'] && !$is_auth['auth_mod']) {
{
$this->ajax_die($lang['EDIT_OWN_POSTS']); $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)) 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);
$this->response['redirect'] = make_url(POSTING_URL.'?mode=editpost&p='. $post_id); } elseif ($this->request['type'] == 'editor') {
} $text = (string)$this->request['text'];
elseif ($this->request['type'] == 'editor')
{
$text = (string) $this->request['text'];
$text = prepare_message($text); $text = prepare_message($text);
if (mb_strlen($text) > 2) if (mb_strlen($text) > 2) {
{ if ($text != $post['post_text']) {
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 ($di->config->get('max_smilies')) if ($count_smilies > $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'))); $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"); 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']) 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");
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_text = str_replace('\n', "\n", $text);
$s_topic_title = str_replace('\n', "\n", $post['topic_title']); $s_topic_title = str_replace('\n', "\n", $post['topic_title']);
@ -162,54 +143,50 @@ switch($this->request['type'])
'post_text' => $text, 'post_text' => $text,
)); ));
} }
} else {
$this->ajax_die($lang['EMPTY_MESSAGE']);
} }
else $this->ajax_die($lang['EMPTY_MESSAGE']);
// Update atom feed // Update atom feed
update_atom('topic', (int) $this->request['topic_id']); update_atom('topic', (int)$this->request['topic_id']);
$this->response['html'] = bbcode2html($text); $this->response['html'] = bbcode2html($text);
} } else {
else
{
$is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post); $is_auth = auth(AUTH_ALL, $post['forum_id'], $userdata, $post);
if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) {
{
$this->ajax_die($lang['TOPIC_LOCKED']); $this->ajax_die($lang['TOPIC_LOCKED']);
} } elseif (!$is_auth['auth_edit']) {
elseif (!$is_auth['auth_edit'])
{
$this->ajax_die(sprintf($lang['SORRY_AUTH_EDIT'], strip_tags($is_auth['auth_edit_type']))); $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="mode" value="editpost" />';
$hidden_form .= '<input type="hidden" name="'. POST_POST_URL .'" value="'. $post_id .'" />'; $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="subject" value="' . $post['topic_title'] . '" />';
$this->response['text'] = ' $this->response['text'] = '
<form action="'. POSTING_URL .'" method="post" name="post"> <form action="' . POSTING_URL . '" method="post" name="post">
'. $hidden_form .' ' . $hidden_form . '
<div class="buttons mrg_4"> <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="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="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="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="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="' . $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="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['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['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="' . $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="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="' . $lang['QUOTE_SEL'] . '" name="quoteselected" title="' . $lang['QUOTE_SELECTED'] . '" onclick="bbcode.onclickQuoteSel();" />&nbsp;
</div> </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"> <div class="mrg_4 tCenter">
<input title="Alt+Enter" name="preview" type="submit" value="'. $lang['PREVIEW'] .'"> <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 . ');" value="' . $lang['CANCEL'] . '">
<input type="button" onclick="edit_post('. $post_id .', \'editor\', $(\'#message-'. $post_id .'\').val()); return false;" class="bold" value="'. $lang['SUBMIT'] .'"> <input type="button" onclick="edit_post(' . $post_id . ', \'editor\', $(\'#message-' . $post_id . '\').val()); return false;" class="bold" value="' . $lang['SUBMIT'] . '">
</div><hr> </div><hr>
<script type="text/javascript"> <script type="text/javascript">
var bbcode = new BBCode("message-'. $post_id .'"); var bbcode = new BBCode("message-' . $post_id . '");
var ctrl = "ctrl"; var ctrl = "ctrl";
bbcode.addTag("codeB", "b", null, "B", ctrl); bbcode.addTag("codeB", "b", null, "B", ctrl);
@ -231,77 +208,64 @@ switch($this->request['type'])
break; break;
case 'add': case 'add':
if (!isset($this->request['topic_id'])) if (!isset($this->request['topic_id'])) {
{
$this->ajax_die('empty topic_id'); $this->ajax_die('empty topic_id');
} }
if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) if (bf($userdata['user_opt'], 'user_opt', 'dis_post')) {
{
$this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT'])); $this->ajax_die(strip_tags($lang['RULES_REPLY_CANNOT']));
} } elseif (!$is_auth['auth_reply']) {
elseif (!$is_auth['auth_reply'])
{
$this->ajax_die(sprintf($lang['SORRY_AUTH_REPLY'], strip_tags($is_auth['auth_reply_type']))); $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']) if ($post['topic_status'] == TOPIC_LOCKED && !$is_auth['auth_mod']) {
{
$this->ajax_die($lang['TOPIC_LOCKED']); $this->ajax_die($lang['TOPIC_LOCKED']);
} }
$message = (string) $this->request['message']; $message = (string)$this->request['message'];
$message = prepare_message($message); $message = prepare_message($message);
// Flood control // Flood control
$where_sql = (IS_GUEST) ? "p.poster_ip = '". USER_IP ."'" : "p.poster_id = {$userdata['user_id']}"; $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"; $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 (($row = DB()->fetch_row($sql)) && $row['last_post_time']) {
{ if ($userdata['user_level'] == USER) {
if ($userdata['user_level'] == USER) if (TIMENOW - $row['last_post_time'] < $di->config->get('flood_interval')) {
{
if (TIMENOW - $row['last_post_time'] < $di->config->get('flood_interval'))
{
$this->ajax_die($lang['FLOOD_ERROR']); $this->ajax_die($lang['FLOOD_ERROR']);
} }
} }
} }
// Double Post Control // Double Post Control
if (!empty($row['last_post_time']) && !IS_AM) if (!empty($row['last_post_time']) && !IS_AM) {
{
$sql = " $sql = "
SELECT pt.post_text SELECT pt.post_text
FROM ". BB_POSTS ." p, ". BB_POSTS_TEXT ." pt FROM " . BB_POSTS . " p, " . BB_POSTS_TEXT . " pt
WHERE $where_sql 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 AND pt.post_id = p.post_id
LIMIT 1 LIMIT 1
"; ";
if ($row = DB()->fetch_row($sql)) if ($row = DB()->fetch_row($sql)) {
{
$last_msg = DB()->escape($row['post_text']); $last_msg = DB()->escape($row['post_text']);
if ($last_msg == $message) if ($last_msg == $message) {
{
$this->ajax_die($lang['DOUBLE_POST_ERROR']); $this->ajax_die($lang['DOUBLE_POST_ERROR']);
} }
} }
} }
if ($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'));
$count_smilies = substr_count(bbcode2html($message), '<img class="smile" src="'. $di->config->get('smilies_path')); if ($count_smilies > $di->config->get('max_smilies')) {
if ($count_smilies > $di->config->get('max_smilies'))
{
$this->ajax_die(sprintf($lang['MAX_SMILIES_PER_POST'], $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 ."')"); 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(); $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_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']);
@ -313,14 +277,13 @@ switch($this->request['type'])
'post_text' => $message, 'post_text' => $message,
)); ));
if ($di->config->get('topic_notify_enabled')) if ($di->config->get('topic_notify_enabled')) {
{
$notify = !empty($this->request['notify']); $notify = !empty($this->request['notify']);
user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify); user_notification('reply', $post, $post['topic_title'], $post['forum_id'], $topic_id, $notify);
} }
// Update atom feed // Update atom feed
update_atom('topic', (int) $this->request['topic_id']); update_atom('topic', (int)$this->request['topic_id']);
$this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id"); $this->response['redirect'] = make_url(POST_URL . "$post_id#$post_id");
break; break;

View file

@ -1,55 +1,57 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$map = new sitemap(); $map = new sitemap();
$html = ''; $html = '';
switch ($mode) switch ($mode) {
{
case 'create': case 'create':
$map->create(); $map->create();
if (file_exists(SITEMAP_DIR. 'sitemap.xml')) 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>';
$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 { } else {
$html .= $lang['SITEMAP_NOT_CREATED']; $html .= $lang['SITEMAP_NOT_CREATED'];
} }
break; break;
case 'search_update': case 'search_update':
if (!file_exists(SITEMAP_DIR. 'sitemap.xml')) $map->create(); 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) { 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>'; $html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Google: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else { } 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>'; $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) { 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>'; $html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Yandex: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else { } 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>'; $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)) { 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>'; $html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Bing: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else { } 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>'; $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) { 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>'; $html .= '<br />' . $lang['SITEMAP_NOTIFY_SEARCH'] . ' Weblogs: <font style="color: green;">' . $lang['SITEMAP_SENT'] . '</font>';
} else { } 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>'; $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; break;
} }

View file

@ -1,76 +1,71 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $userdata; global $userdata;
if (!IS_SUPER_ADMIN) $this->ajax_die('not auth'); if (!IS_SUPER_ADMIN) {
$this->ajax_die('not auth');
}
array_deep($this->request, 'trim'); array_deep($this->request, 'trim');
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$sql_error = false; $sql_error = false;
// установка / начальная валидация значений // установка / начальная валидация значений
switch ($mode) switch ($mode) {
{
case 'load': case 'load':
case 'save': case 'save':
if (!$tpl_id = (int) $this->request['tpl_id']) if (!$tpl_id = (int)$this->request['tpl_id']) {
{
$this->ajax_die('Выбранный шаблон не найден, создайте новый (empty 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")) if (!$tpl_data = DB()->fetch_row("SELECT * FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1")) {
{
$this->ajax_die("Шаблон [id: $tpl_id] не найден в БД"); $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД");
} }
break; break;
} }
switch ($mode) switch ($mode) {
{
case 'save': case 'save':
case 'new': case 'new':
if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) if (!$tpl_name = htmlCHR(str_compact($this->request['tpl_name']))) {
{
$this->ajax_die('не заполнено название шаблона'); $this->ajax_die('не заполнено название шаблона');
} }
$tpl_name = substr($tpl_name, 0, 60); $tpl_name = substr($tpl_name, 0, 60);
if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) if (!$tpl_src_form = htmlCHR($this->request['tpl_src_form'])) {
{
$this->ajax_die('не заполнен скрипт формы шаблона'); $this->ajax_die('не заполнен скрипт формы шаблона');
} }
if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) if (!$tpl_src_title = htmlCHR($this->request['tpl_src_title'])) {
{
$this->ajax_die('не заполнен формат названия темы'); $this->ajax_die('не заполнен формат названия темы');
} }
$tpl_src_title = str_compact($tpl_src_title); $tpl_src_title = str_compact($tpl_src_title);
if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) if (!$tpl_src_msg = htmlCHR($this->request['tpl_src_msg'])) {
{
$this->ajax_die('не заполнен формат создания сообщения'); $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); preg_match('#\d+#', (string)$this->request['tpl_rules'], $m);
$tpl_rules_post_id = isset($m[0]) ? (int) $m[0] : 0; $tpl_rules_post_id = isset($m[0]) ? (int)$m[0] : 0;
$sql_args = array( $sql_args = array(
'tpl_name' => (string) $tpl_name, 'tpl_name' => (string)$tpl_name,
'tpl_src_form' => (string) $tpl_src_form, 'tpl_src_form' => (string)$tpl_src_form,
'tpl_src_title' => (string) $tpl_src_title, 'tpl_src_title' => (string)$tpl_src_title,
'tpl_src_msg' => (string) $tpl_src_msg, 'tpl_src_msg' => (string)$tpl_src_msg,
'tpl_comment' => (string) $tpl_comment, 'tpl_comment' => (string)$tpl_comment,
'tpl_rules_post_id' => (int) $tpl_rules_post_id, 'tpl_rules_post_id' => (int)$tpl_rules_post_id,
'tpl_last_edit_tm' => (int) TIMENOW, 'tpl_last_edit_tm' => (int)TIMENOW,
'tpl_last_edit_by' => (int) $userdata['user_id'], 'tpl_last_edit_by' => (int)$userdata['user_id'],
); );
break; break;
} }
// выполнение // выполнение
switch ($mode) switch ($mode) {
{
// загрузка шаблона // загрузка шаблона
case 'load': case 'load':
$this->response['val']['tpl-name-save'] = $tpl_data['tpl_name']; $this->response['val']['tpl-name-save'] = $tpl_data['tpl_name'];
@ -87,54 +82,45 @@ switch ($mode)
$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-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['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']; $this->response['tpl_rules_href'] = POST_URL . $tpl_data['tpl_rules_post_id'] . '#' . $tpl_data['tpl_rules_post_id'];
break; break;
// включение / отключение шаблона в форуме // включение / отключение шаблона в форуме
case 'assign': case 'assign':
if (!$tpl_id = (int) $this->request['tpl_id']) if (!$tpl_id = (int)$this->request['tpl_id']) {
{
$this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)'); $this->ajax_die('Выбранный шаблон не найден, создайте новый (empty tpl_id)');
} }
if (!$forum_id = (int) $this->request['forum_id']) if (!$forum_id = (int)$this->request['forum_id']) {
{
$this->ajax_die('empty forum_id'); $this->ajax_die('empty forum_id');
} }
if (!forum_exists($forum_id)) if (!forum_exists($forum_id)) {
{
$this->ajax_die("нет такого форума [id: $forum_id]"); $this->ajax_die("нет такого форума [id: $forum_id]");
} }
// отключение // отключение
if ($tpl_id == -1) if ($tpl_id == -1) {
{
$new_tpl_id = 0; $new_tpl_id = 0;
$this->response['msg'] = 'Шаблоны в этом форуме отключены'; $this->response['msg'] = 'Шаблоны в этом форуме отключены';
} } // включение
// включение else {
else if (!$tpl_name = DB()->fetch_row("SELECT tpl_name FROM " . BB_TOPIC_TPL . " WHERE tpl_id = $tpl_id LIMIT 1", 'tpl_name')) {
{
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] не найден в БД"); $this->ajax_die("Шаблон [id: $tpl_id] не найден в БД");
} }
$new_tpl_id = $tpl_id; $new_tpl_id = $tpl_id;
$this->response['msg'] = "Включен шаблон $tpl_name"; $this->response['msg'] = "Включен шаблон $tpl_name";
} }
DB()->query("UPDATE ". BB_FORUMS ." SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1"); DB()->query("UPDATE " . BB_FORUMS . " SET forum_tpl_id = $new_tpl_id WHERE forum_id = $forum_id LIMIT 1");
break; break;
// сохранение изменений // сохранение изменений
case 'save': case 'save':
if ($tpl_data['tpl_last_edit_tm'] > $this->request['tpl_l_ed_tst'] && $tpl_data['tpl_last_edit_by'] != $userdata['user_id']) 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'])); $last_edit_by_username = get_username(intval($tpl_data['tpl_last_edit_by']));
$msg = "Изменения не были сохранены!\n\n"; $msg = "Изменения не были сохранены!\n\n";
$msg .= 'Шаблон был отредактирован: '. html_entity_decode($last_edit_by_username) .', '. delta_time($tpl_data['tpl_last_edit_tm']) ." назад\n\n"; $msg .= 'Шаблон был отредактирован: ' . html_entity_decode($last_edit_by_username) . ', ' . delta_time($tpl_data['tpl_last_edit_tm']) . " назад\n\n";
$this->ajax_die($msg); $this->ajax_die($msg);
} }
$sql = "UPDATE ". BB_TOPIC_TPL ." SET ". DB()->build_array('UPDATE', $sql_args) ." WHERE tpl_id = $tpl_id LIMIT 1"; $sql = "UPDATE " . BB_TOPIC_TPL . " SET " . DB()->build_array('UPDATE', $sql_args) . " WHERE tpl_id = $tpl_id LIMIT 1";
if (!DB()->query($sql)) if (!DB()->query($sql)) {
{
$sql_error = DB()->sql_error(); $sql_error = DB()->sql_error();
} }
$this->response['tpl_id'] = $tpl_id; $this->response['tpl_id'] = $tpl_id;
@ -145,9 +131,8 @@ switch ($mode)
// создание нового шаблона // создание нового шаблона
case 'new': case 'new':
$sql = "INSERT INTO ". BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args); $sql = "INSERT INTO " . BB_TOPIC_TPL . DB()->build_array('INSERT', $sql_args);
if (!DB()->query($sql)) if (!DB()->query($sql)) {
{
$sql_error = DB()->sql_error(); $sql_error = DB()->sql_error();
} }
break; break;
@ -158,10 +143,10 @@ switch ($mode)
} }
// возможный дубль названия шаблона // возможный дубль названия шаблона
if ($sql_error) if ($sql_error) {
{ if ($sql_error['code'] == 1062) {
if ($sql_error['code'] == 1062) // Duplicate entry // Duplicate entry
{
$this->ajax_die('Шаблон с таким названием уже существует, выберите другое название'); $this->ajax_die('Шаблон с таким названием уже существует, выберите другое название');
} }
$this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}"); $this->ajax_die("db error {$sql_error['code']}: {$sql_error['message']}");

View file

@ -1,70 +1,54 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata; global $lang, $userdata;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$mode = (string) $this->request['mode']; $mode = (string)$this->request['mode'];
$html = '<img src="./styles/images/good.gif">'; $html = '<img src="./styles/images/good.gif">';
switch($mode) switch ($mode) {
{
case 'check_name': case 'check_name':
$username = clean_username($this->request['username']); $username = clean_username($this->request['username']);
if (empty($username)) if (empty($username)) {
{ $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_A_NAME'] . '</span>';
$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>';
elseif($err = validate_username($username))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $err .'</span>';
} }
break; break;
case 'check_email': case 'check_email':
$email = (string) $this->request['email']; $email = (string)$this->request['email'];
if (empty($email)) if (empty($email)) {
{ $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_E_MAIL'] . '</span>';
$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>';
elseif($err = validate_email($email))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $err .'</span>';
} }
break; break;
case 'check_pass': case 'check_pass':
$pass = (string) $this->request['pass']; $pass = (string)$this->request['pass'];
$pass_confirm = (string) $this->request['pass_confirm']; $pass_confirm = (string)$this->request['pass_confirm'];
if (empty($pass) || empty($pass_confirm)) if (empty($pass) || empty($pass_confirm)) {
{ $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS'] . '</span>';
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_PASS'] .'</span>'; } else {
} if ($pass != $pass_confirm) {
else $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS_ERR'] . '</span>';
{ } else {
if ($pass != $pass_confirm) 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>';
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">'. $lang['CHOOSE_PASS_ERR'] .'</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 } 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']; $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>'; $html = '<img src="./styles/images/good.gif"> <span class="seedmed bold">' . $text . '</span>';
} }
} }
} }

View file

@ -1,15 +1,16 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $user, $lang; global $user, $lang;
$post_id = (int) $this->request['post_id']; $post_id = (int)$this->request['post_id'];
$topic_id = (int) $this->request['topic_id']; $topic_id = (int)$this->request['topic_id'];
if (!$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');
$post_id = DB()->fetch_row("SELECT topic_first_post_id FROM ". BB_TOPICS ." WHERE topic_id = $topic_id", 'topic_first_post_id');
} }
$sql = " $sql = "
@ -17,33 +18,27 @@ $sql = "
p.*, p.*,
h.post_html, IF(h.post_html IS NULL, pt.post_text, NULL) AS post_text, h.post_html, IF(h.post_html IS NULL, pt.post_text, NULL) AS post_text,
f.auth_read f.auth_read
FROM ". BB_POSTS ." p FROM " . BB_POSTS . " p
INNER JOIN ". BB_POSTS_TEXT ." pt ON(pt.post_id = p.post_id) 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) 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) INNER JOIN " . BB_FORUMS . " f ON(f.forum_id = p.forum_id)
WHERE WHERE
p.post_id = $post_id p.post_id = $post_id
LIMIT 1 LIMIT 1
"; ";
if (!$post_data = DB()->fetch_row($sql)) if (!$post_data = DB()->fetch_row($sql)) {
{
$this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']);
} }
// Auth check // Auth check
if ($post_data['auth_read'] == AUTH_REG) if ($post_data['auth_read'] == AUTH_REG) {
{ if (IS_GUEST) {
if (IS_GUEST)
{
$this->ajax_die($lang['NEED_TO_LOGIN_FIRST']); $this->ajax_die($lang['NEED_TO_LOGIN_FIRST']);
} }
} } elseif ($post_data['auth_read'] != AUTH_ALL) {
elseif ($post_data['auth_read'] != AUTH_ALL)
{
$is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data); $is_auth = auth(AUTH_READ, $post_data['forum_id'], $user->data, $post_data);
if (!$is_auth['auth_read']) if (!$is_auth['auth_read']) {
{
$this->ajax_die($lang['TOPIC_POST_NOT_EXIST']); $this->ajax_die($lang['TOPIC_POST_NOT_EXIST']);
} }
} }

View file

@ -1,14 +1,15 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
if (!isset($this->request['t'])) if (!isset($this->request['t'])) {
{
$this->ajax_die('empty topic_id'); // TODO: перевести $this->ajax_die('empty topic_id'); // TODO: перевести
} }
$topic_id = (int) $this->request['t']; $topic_id = (int)$this->request['t'];
global $bnc_error; global $bnc_error;
$bnc_error = 0; $bnc_error = 0;
@ -16,14 +17,10 @@ $bnc_error = 0;
// Получение торрент-файла // Получение торрент-файла
$file_path = get_attach_path($topic_id, 8); $file_path = get_attach_path($topic_id, 8);
if (($file_contents = @file_get_contents($file_path)) === false) if (($file_contents = @file_get_contents($file_path)) === false) {
{ if (IS_AM) {
if (IS_AM) $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] . "\n\n" . htmlCHR($file_path));
{ } else {
$this->ajax_die($lang['ERROR_NO_ATTACHMENT'] ."\n\n". htmlCHR($file_path));
}
else
{
$this->ajax_die($lang['ERROR_NO_ATTACHMENT']); $this->ajax_die($lang['ERROR_NO_ATTACHMENT']);
} }
} }
@ -31,12 +28,15 @@ if (($file_contents = @file_get_contents($file_path)) === false)
// Построение списка // Построение списка
$tor_filelist = build_tor_filelist($file_contents); $tor_filelist = build_tor_filelist($file_contents);
function build_tor_filelist ($file_contents) /**
* @param $file_contents
* @return string
*/
function build_tor_filelist($file_contents)
{ {
global $lang; global $lang;
if (!$tor = bdecode($file_contents)) if (!$tor = bdecode($file_contents)) {
{
return $lang['TORFILE_INVALID']; return $lang['TORFILE_INVALID'];
} }
@ -45,87 +45,87 @@ function build_tor_filelist ($file_contents)
return $torrent->get_filelist(); return $torrent->get_filelist();
} }
/**
* Class torrent
*/
class torrent class torrent
{ {
var $tor_decoded = array(); public $tor_decoded = array();
var $files_ary = array('/' => ''); public $files_ary = array('/' => '');
var $multiple = null; public $multiple = null;
var $root_dir = ''; public $root_dir = '';
var $files_html = ''; public $files_html = '';
function torrent ($decoded_file_contents) /**
* torrent constructor.
* @param $decoded_file_contents
* @return torrent
*/
public function torrent($decoded_file_contents)
{ {
$this->tor_decoded = $decoded_file_contents; $this->tor_decoded = $decoded_file_contents;
} }
function get_filelist () /**
* @return string
*/
public function get_filelist()
{ {
$this->build_filelist_array(); $this->build_filelist_array();
if ($this->multiple) if ($this->multiple) {
{ if ($this->files_ary['/'] !== '') {
if ($this->files_ary['/'] !== '')
{
$this->files_ary = array_merge($this->files_ary, $this->files_ary['/']); $this->files_ary = array_merge($this->files_ary, $this->files_ary['/']);
unset($this->files_ary['/']); unset($this->files_ary['/']);
} }
$filelist = $this->build_filelist_html(); $filelist = $this->build_filelist_html();
return "<div class=\"tor-root-dir\">{$this->root_dir}</div>$filelist"; return "<div class=\"tor-root-dir\">{$this->root_dir}</div>$filelist";
} } else {
else
{
return join('', $this->files_ary['/']); return join('', $this->files_ary['/']);
} }
} }
function build_filelist_array () /**
* Torrent file list builder
*/
public function build_filelist_array()
{ {
$info = $this->tor_decoded['info']; $info = $this->tor_decoded['info'];
if (isset($info['name.utf-8'])) if (isset($info['name.utf-8'])) {
{
$info['name'] =& $info['name.utf-8']; $info['name'] =& $info['name.utf-8'];
} }
if (isset($info['files']) && is_array($info['files'])) if (isset($info['files']) && is_array($info['files'])) {
{ $this->root_dir = isset($info['name']) ? '../' . clean_tor_dirname($info['name']) : '...';
$this->root_dir = isset($info['name']) ? '../'. clean_tor_dirname($info['name']) : '...';
$this->multiple = true; $this->multiple = true;
foreach ($info['files'] as $f) foreach ($info['files'] as $f) {
{ if (isset($f['path.utf-8'])) {
if (isset($f['path.utf-8']))
{
$f['path'] =& $f['path.utf-8']; $f['path'] =& $f['path.utf-8'];
} }
if (!isset($f['path']) || !is_array($f['path'])) if (!isset($f['path']) || !is_array($f['path'])) {
{
continue; continue;
} }
array_deep($f['path'], 'clean_tor_dirname'); array_deep($f['path'], 'clean_tor_dirname');
$length = isset($f['length']) ? (float) $f['length'] : 0; $length = isset($f['length']) ? (float)$f['length'] : 0;
$subdir_count = count($f['path']) - 1; $subdir_count = count($f['path']) - 1;
if ($subdir_count > 0) if ($subdir_count > 0) {
{
$name = array_pop($f['path']); $name = array_pop($f['path']);
$cur_files_ary =& $this->files_ary; $cur_files_ary =& $this->files_ary;
for ($i=0,$j=1; $i < $subdir_count; $i++,$j++) for ($i = 0, $j = 1; $i < $subdir_count; $i++, $j++) {
{
$subdir = $f['path'][$i]; $subdir = $f['path'][$i];
if (!isset($cur_files_ary[$subdir])) if (!isset($cur_files_ary[$subdir])) {
{
$cur_files_ary[$subdir] = array(); $cur_files_ary[$subdir] = array();
} }
$cur_files_ary =& $cur_files_ary[$subdir]; $cur_files_ary =& $cur_files_ary[$subdir];
if ($j == $subdir_count) if ($j == $subdir_count) {
{ if (is_string($cur_files_ary)) {
if (is_string($cur_files_ary))
{
$GLOBALS['bnc_error'] = 1; $GLOBALS['bnc_error'] = 1;
break(1); break(1);
} }
@ -133,27 +133,28 @@ class torrent
} }
} }
@natsort($cur_files_ary); @natsort($cur_files_ary);
} } else {
else
{
$name = $f['path'][0]; $name = $f['path'][0];
$this->files_ary['/'][] = $this->build_file_item($name, $length); $this->files_ary['/'][] = $this->build_file_item($name, $length);
natsort($this->files_ary['/']); natsort($this->files_ary['/']);
} }
} }
} } else {
else
{
$this->multiple = false; $this->multiple = false;
$name = isset($info['name']) ? clean_tor_dirname($info['name']) : ''; $name = isset($info['name']) ? clean_tor_dirname($info['name']) : '';
$length = isset($info['length']) ? (float) $info['length'] : 0; $length = isset($info['length']) ? (float)$info['length'] : 0;
$this->files_ary['/'][] = $this->build_file_item($name, $length); $this->files_ary['/'][] = $this->build_file_item($name, $length);
natsort($this->files_ary['/']); natsort($this->files_ary['/']);
} }
} }
function build_file_item ($name, $length) /**
* @param $name
* @param $length
* @return string
*/
public function build_file_item($name, $length)
{ {
global $images, $lang; global $images, $lang;
@ -162,27 +163,35 @@ class torrent
$magnet_name = $magnet_ext = ''; $magnet_name = $magnet_ext = '';
if ($di->config->get('magnet_links_enabled')) 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_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>';
$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 () /**
* @return string
*/
public function build_filelist_html()
{ {
global $html; global $html;
return $html->array2html($this->files_ary); return $html->array2html($this->files_ary);
} }
} }
function clean_tor_dirname ($dirname) /**
* @param $dirname
* @return mixed
*/
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;

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$domain_name = 'torrentpier.me'; // enter here your primary domain name of your site $domain_name = 'torrentpier.me'; // enter here your primary domain name of your site
$domain_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : $domain_name; $domain_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : $domain_name;
@ -86,7 +88,7 @@ $config = [
'handlers' => [ 'handlers' => [
function () { function () {
return new \Monolog\Handler\StreamHandler( return new \Monolog\Handler\StreamHandler(
__DIR__.'/../internal_data/log/app.log', __DIR__ . '/../internal_data/log/app.log',
\Monolog\Logger::DEBUG \Monolog\Logger::DEBUG
); );
} }
@ -110,7 +112,7 @@ $config = [
// Cache // Cache
'cache' => [ 'cache' => [
'db_dir' => realpath(BB_ROOT) .'/internal_data/cache/filecache/', 'db_dir' => realpath(BB_ROOT) . '/internal_data/cache/filecache/',
'prefix' => 'tp_', // Префикс кеша ('tp_') 'prefix' => 'tp_', // Префикс кеша ('tp_')
'memcache' => [ 'memcache' => [
'host' => '127.0.0.1', 'host' => '127.0.0.1',
@ -233,7 +235,7 @@ $config = [
// TODO: заменить + глобальный объект user // TODO: заменить + глобальный объект user
'session_update_intrv' => 180, // sec 'session_update_intrv' => 180, // sec
'user_session_duration' => 1800, // sec 'user_session_duration' => 1800, // sec
'admin_session_duration' => 6*3600, // sec 'admin_session_duration' => 6 * 3600, // sec
'user_session_gc_ttl' => 1800, // number of seconds that a staled session entry may remain in sessions table 'user_session_gc_ttl' => 1800, // number of seconds that a staled session entry may remain in sessions table
'session_cache_gc_ttl' => 1200, // sec 'session_cache_gc_ttl' => 1200, // sec
'max_last_visit_days' => 14, // days 'max_last_visit_days' => 14, // days
@ -416,7 +418,7 @@ $config = [
// Avatars // Avatars
'avatars' => [ 'avatars' => [
'allowed_ext' => ['gif','jpg','jpeg','png'], // разрешенные форматы файлов 'allowed_ext' => ['gif', 'jpg', 'jpeg', 'png'], // разрешенные форматы файлов
'bot_avatar' => 'gallery/bot.gif', // аватара бота 'bot_avatar' => 'gallery/bot.gif', // аватара бота
'max_size' => 100 * 1024, // размер аватары в байтах 'max_size' => 100 * 1024, // размер аватары в байтах
'max_height' => 100, // высота аватара в px 'max_height' => 100, // высота аватара в px
@ -428,7 +430,7 @@ $config = [
// Group avatars // Group avatars
'group_avatars' => [ 'group_avatars' => [
'allowed_ext' => ['gif','jpg','jpeg','png'], // разрешенные форматы файлов 'allowed_ext' => ['gif', 'jpg', 'jpeg', 'png'], // разрешенные форматы файлов
'max_size' => 300 * 1024, // размер аватары в байтах 'max_size' => 300 * 1024, // размер аватары в байтах
'max_height' => 300, // высота аватара в px 'max_height' => 300, // высота аватара в px
'max_width' => 300, // ширина аватара в px 'max_width' => 300, // ширина аватара в px
@ -448,7 +450,7 @@ $config = [
// Atom feed // Atom feed
'atom' => [ 'atom' => [
'path' => INT_DATA_DIR .'atom', // without ending slash 'path' => INT_DATA_DIR . 'atom', // without ending slash
'url' => './internal_data/atom',// without ending slash 'url' => './internal_data/atom',// without ending slash
], ],

View file

@ -1,33 +1,35 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// Ratio limits // Ratio limits
define('TR_RATING_LIMITS', true); // ON/OFF define('TR_RATING_LIMITS', true); // ON/OFF
define('MIN_DL_FOR_RATIO', 10737418240); // 10 GB in bytes, 0 - disable define('MIN_DL_FOR_RATIO', 10737418240); // 10 GB in bytes, 0 - disable
// Path (trailing slash '/' at the end: XX_PATH - without, XX_DIR - with) // Path (trailing slash '/' at the end: XX_PATH - without, XX_DIR - with)
define('BB_PATH', realpath(BB_ROOT) ); define('BB_PATH', realpath(BB_ROOT));
define('ADMIN_DIR', BB_PATH .'/admin/' ); define('ADMIN_DIR', BB_PATH . '/admin/');
define('DATA_DIR', BB_PATH .'/data/' ); define('DATA_DIR', BB_PATH . '/data/');
define('INT_DATA_DIR', BB_PATH .'/internal_data/' ); define('INT_DATA_DIR', BB_PATH . '/internal_data/');
define('AJAX_HTML_DIR', BB_ROOT .'/internal_data/ajax_html/' ); define('AJAX_HTML_DIR', BB_ROOT . '/internal_data/ajax_html/');
define('CACHE_DIR', BB_PATH .'/internal_data/cache/' ); define('CACHE_DIR', BB_PATH . '/internal_data/cache/');
define('LOG_DIR', BB_PATH .'/internal_data/log/' ); define('LOG_DIR', BB_PATH . '/internal_data/log/');
define('SITEMAP_DIR', BB_PATH .'/internal_data/sitemap/' ); define('SITEMAP_DIR', BB_PATH . '/internal_data/sitemap/');
define('TRIGGERS_DIR', BB_PATH .'/internal_data/triggers/' ); define('TRIGGERS_DIR', BB_PATH . '/internal_data/triggers/');
define('AJAX_DIR', BB_ROOT .'/library/ajax/' ); define('AJAX_DIR', BB_ROOT . '/library/ajax/');
define('CFG_DIR', BB_PATH .'/library/config/' ); define('CFG_DIR', BB_PATH . '/library/config/');
define('INC_DIR', BB_PATH .'/library/includes/' ); define('INC_DIR', BB_PATH . '/library/includes/');
define('CLASS_DIR', BB_PATH .'/library/includes/classes/'); define('CLASS_DIR', BB_PATH . '/library/includes/classes/');
define('CORE_DIR', BB_PATH .'/library/includes/core/' ); define('CORE_DIR', BB_PATH . '/library/includes/core/');
define('UCP_DIR', BB_PATH .'/library/includes/ucp/' ); define('UCP_DIR', BB_PATH . '/library/includes/ucp/');
define('LANG_ROOT_DIR', BB_PATH .'/library/language/' ); define('LANG_ROOT_DIR', BB_PATH . '/library/language/');
define('IMAGES_DIR', BB_PATH .'/styles/images/' ); define('IMAGES_DIR', BB_PATH . '/styles/images/');
define('TEMPLATES_DIR', BB_PATH .'/styles/templates/' ); define('TEMPLATES_DIR', BB_PATH . '/styles/templates/');
// Templates // Templates
define('ADMIN_TPL_DIR', TEMPLATES_DIR .'/admin/'); define('ADMIN_TPL_DIR', TEMPLATES_DIR . '/admin/');
// Debug // Debug
define('DBG_LOG', false); // enable forum debug (off on production) define('DBG_LOG', false); // enable forum debug (off on production)
@ -50,13 +52,13 @@ define('LOG_MAX_SIZE', 1048576); // bytes
ini_set('error_reporting', E_ALL); ini_set('error_reporting', E_ALL);
ini_set('display_errors', 0); ini_set('display_errors', 0);
ini_set('log_errors', 1); ini_set('log_errors', 1);
ini_set('error_log', LOG_DIR .'php_err.log'); ini_set('error_log', LOG_DIR . 'php_err.log');
// Triggers // Triggers
define('BB_ENABLED', TRIGGERS_DIR .'$on'); define('BB_ENABLED', TRIGGERS_DIR . '$on');
define('BB_DISABLED', TRIGGERS_DIR .'$off'); define('BB_DISABLED', TRIGGERS_DIR . '$off');
define('CRON_ALLOWED', TRIGGERS_DIR .'cron_allowed'); define('CRON_ALLOWED', TRIGGERS_DIR . 'cron_allowed');
define('CRON_RUNNING', TRIGGERS_DIR .'cron_running'); define('CRON_RUNNING', TRIGGERS_DIR . 'cron_running');
// Misc // Misc
define('MEM_USAGE', function_exists('memory_get_usage')); define('MEM_USAGE', function_exists('memory_get_usage'));

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$datastore->enqueue(array( $datastore->enqueue(array(
'smile_replacements', 'smile_replacements',
@ -11,73 +13,80 @@ $page_cfg['include_bbcode_js'] = true;
// //
// BBCode templates // BBCode templates
// //
function get_bbcode_tpl () /**
* @return array
*/
function get_bbcode_tpl()
{ {
$bbcode_tpl = array(); $bbcode_tpl = array();
// Quote // Quote
$bbcode_tpl['quote_open'] = <<<HTML $bbcode_tpl['quote_open'] = <<<HTML
<div class="q-wrap"> <div class="q-wrap">
<div class="q"> <div class="q">
HTML; HTML;
$bbcode_tpl['quote_username_open'] = <<<HTML $bbcode_tpl['quote_username_open'] = <<<HTML
<div class="q-wrap"> <div class="q-wrap">
<div class="q" head="\\1"> <div class="q" head="\\1">
HTML; HTML;
$bbcode_tpl['quote_close'] = <<<HTML $bbcode_tpl['quote_close'] = <<<HTML
</div> </div>
</div> </div>
HTML; HTML;
// Code // Code
$bbcode_tpl['code_open'] = <<<HTML $bbcode_tpl['code_open'] = <<<HTML
<div class="c-wrap"> <div class="c-wrap">
<div class="c-body"> <div class="c-body">
HTML; HTML;
$bbcode_tpl['code_close'] = <<<HTML $bbcode_tpl['code_close'] = <<<HTML
</div> </div>
</div> </div>
HTML; HTML;
// Spoiler // Spoiler
$bbcode_tpl['spoiler_open'] = <<<HTML $bbcode_tpl['spoiler_open'] = <<<HTML
<div class="sp-wrap"> <div class="sp-wrap">
<div class="sp-body"> <div class="sp-body">
HTML; HTML;
$bbcode_tpl['spoiler_title_open'] = <<<HTML $bbcode_tpl['spoiler_title_open'] = <<<HTML
<div class="sp-wrap"> <div class="sp-wrap">
<div class="sp-body" title="\\1"> <div class="sp-body" title="\\1">
<h3 class="sp-title">\\1</h3> <h3 class="sp-title">\\1</h3>
HTML; HTML;
$bbcode_tpl['spoiler_close'] = <<<HTML $bbcode_tpl['spoiler_close'] = <<<HTML
</div> </div>
</div> </div>
HTML; HTML;
// Image // Image
$bbcode_tpl['img'] = <<<HTML $bbcode_tpl['img'] = <<<HTML
<var class="postImg" title="$1">&#10;</var> <var class="postImg" title="$1">&#10;</var>
HTML; HTML;
$bbcode_tpl['img_aligned'] = <<<HTML $bbcode_tpl['img_aligned'] = <<<HTML
<var class="postImg postImgAligned img-\\1" title="\\2">&#10;</var> <var class="postImg postImgAligned img-\\1" title="\\2">&#10;</var>
HTML; HTML;
// HR // HR
$bbcode_tpl['hr'] = <<<HTML $bbcode_tpl['hr'] = <<<HTML
<span class="post-hr">-</span> <span class="post-hr">-</span>
HTML; HTML;
array_deep($bbcode_tpl, 'bbcode_tpl_compact'); array_deep($bbcode_tpl, 'bbcode_tpl_compact');
return $bbcode_tpl; return $bbcode_tpl;
} }
function bbcode_tpl_compact ($text) /**
* @param $text
* @return mixed
*/
function bbcode_tpl_compact($text)
{ {
$text = str_compact($text); $text = str_compact($text);
$text = str_replace('> <', '><', $text); $text = str_replace('> <', '><', $text);
@ -85,7 +94,11 @@ function bbcode_tpl_compact ($text)
} }
// prepare a posted message for entry into the database // prepare a posted message for entry into the database
function prepare_message ($message) /**
* @param $message
* @return mixed|string
*/
function prepare_message($message)
{ {
$message = bbcode::clean_up($message); $message = bbcode::clean_up($message);
$message = htmlCHR($message, false, ENT_NOQUOTES); $message = htmlCHR($message, false, ENT_NOQUOTES);
@ -94,6 +107,9 @@ function prepare_message ($message)
// Fill smiley templates (or just the variables) with smileys // Fill smiley templates (or just the variables) with smileys
// Either in a window or inline // Either in a window or inline
/**
* @param $mode
*/
function generate_smilies($mode) function generate_smilies($mode)
{ {
global $template, $lang, $datastore; global $template, $lang, $datastore;
@ -107,32 +123,26 @@ function generate_smilies($mode)
$data = $datastore->get('smile_replacements'); $data = $datastore->get('smile_replacements');
if ($sql = $data['smile']) if ($sql = $data['smile']) {
{
$num_smilies = 0; $num_smilies = 0;
$rowset = array(); $rowset = array();
foreach ($sql as $row) foreach ($sql as $row) {
{ if (empty($rowset[$row['smile_url']])) {
if (empty($rowset[$row['smile_url']]))
{
$rowset[$row['smile_url']]['code'] = addslashes($row['code']); $rowset[$row['smile_url']]['code'] = addslashes($row['code']);
$rowset[$row['smile_url']]['emoticon'] = $row['emoticon']; $rowset[$row['smile_url']]['emoticon'] = $row['emoticon'];
$num_smilies++; $num_smilies++;
} }
} }
if ($num_smilies) if ($num_smilies) {
{
$smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1; $smilies_split_row = ($mode == 'inline') ? $inline_columns - 1 : $window_columns - 1;
$s_colspan = 0; $s_colspan = 0;
$row = 0; $row = 0;
$col = 0; $col = 0;
while (list($smile_url, $data) = each($rowset)) while (list($smile_url, $data) = each($rowset)) {
{ if (!$col) {
if (!$col)
{
$template->assign_block_vars('smilies_row', array()); $template->assign_block_vars('smilies_row', array());
} }
@ -144,27 +154,22 @@ function generate_smilies($mode)
$s_colspan = max($s_colspan, $col + 1); $s_colspan = max($s_colspan, $col + 1);
if ($col == $smilies_split_row) if ($col == $smilies_split_row) {
{ if ($mode == 'inline' && $row == $inline_rows - 1) {
if ($mode == 'inline' && $row == $inline_rows - 1)
{
break; break;
} }
$col = 0; $col = 0;
$row++; $row++;
} } else {
else
{
$col++; $col++;
} }
} }
if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) if ($mode == 'inline' && $num_smilies > $inline_rows * $inline_columns) {
{
$template->assign_block_vars('switch_smilies_extra', array()); $template->assign_block_vars('switch_smilies_extra', array());
$template->assign_vars(array( $template->assign_vars(array(
'U_MORE_SMILIES' => POSTING_URL ."?mode=smilies", 'U_MORE_SMILIES' => POSTING_URL . "?mode=smilies",
)); ));
} }
@ -175,58 +180,49 @@ function generate_smilies($mode)
} }
} }
if ($mode == 'window') if ($mode == 'window') {
{
print_page('posting_smilies.tpl', 'simple'); print_page('posting_smilies.tpl', 'simple');
} }
} }
/** /**
* Strips away [quote] tags and their contents from the specified string * Strips away [quote] tags and their contents from the specified string
* *
* @param string Text to be stripped of quote tags * @param string Text to be stripped of quote tags
* *
* @return string * @return string
*/ */
function strip_quotes ($text) function strip_quotes($text)
{ {
$lowertext = strtolower($text); $lowertext = strtolower($text);
// find all [quote tags // find all [quote tags
$start_pos = array(); $start_pos = array();
$curpos = 0; $curpos = 0;
do do {
{
$pos = strpos($lowertext, '[quote', $curpos); $pos = strpos($lowertext, '[quote', $curpos);
if ($pos !== false) if ($pos !== false) {
{
$start_pos["$pos"] = 'start'; $start_pos["$pos"] = 'start';
$curpos = $pos + 6; $curpos = $pos + 6;
} }
} } while ($pos !== false);
while ($pos !== false);
if (sizeof($start_pos) == 0) if (sizeof($start_pos) == 0) {
{
return $text; return $text;
} }
// find all [/quote] tags // find all [/quote] tags
$end_pos = array(); $end_pos = array();
$curpos = 0; $curpos = 0;
do do {
{
$pos = strpos($lowertext, '[/quote', $curpos); $pos = strpos($lowertext, '[/quote', $curpos);
if ($pos !== false) if ($pos !== false) {
{
$end_pos["$pos"] = 'end'; $end_pos["$pos"] = 'end';
$curpos = $pos + 8; $curpos = $pos + 8;
} }
} } while ($pos !== false);
while ($pos !== false);
if (sizeof($end_pos) == 0) if (sizeof($end_pos) == 0) {
{
return $text; return $text;
} }
@ -234,30 +230,23 @@ function strip_quotes ($text)
$pos_list = $start_pos + $end_pos; $pos_list = $start_pos + $end_pos;
ksort($pos_list); ksort($pos_list);
do do {
{
// build a stack that represents when a quote tag is opened // build a stack that represents when a quote tag is opened
// and add non-quote text to the new string // and add non-quote text to the new string
$stack = array(); $stack = array();
$newtext = '[...] '; $newtext = '[...] ';
$substr_pos = 0; $substr_pos = 0;
foreach ($pos_list AS $pos => $type) foreach ($pos_list as $pos => $type) {
{
$stacksize = sizeof($stack); $stacksize = sizeof($stack);
if ($type == 'start') if ($type == 'start') {
{
// empty stack, so add from the last close tag or the beginning of the string // empty stack, so add from the last close tag or the beginning of the string
if ($stacksize == 0) if ($stacksize == 0) {
{
$newtext .= substr($text, $substr_pos, $pos - $substr_pos); $newtext .= substr($text, $substr_pos, $pos - $substr_pos);
} }
array_push($stack, $pos); array_push($stack, $pos);
} } else {
else
{
// pop off the latest opened tag // pop off the latest opened tag
if ($stacksize) if ($stacksize) {
{
array_pop($stack); array_pop($stack);
$substr_pos = $pos + 8; $substr_pos = $pos + 8;
} }
@ -270,15 +259,12 @@ function strip_quotes ($text)
// check to see if there's a stack remaining, remove those points // check to see if there's a stack remaining, remove those points
// as key points, and repeat. Allows emulation of a non-greedy-type // as key points, and repeat. Allows emulation of a non-greedy-type
// recursion. // recursion.
if ($stack) if ($stack) {
{ foreach ($stack as $pos) {
foreach ($stack AS $pos)
{
unset($pos_list["$pos"]); unset($pos_list["$pos"]);
} }
} }
} } while ($stack);
while ($stack);
return $newtext; return $newtext;
} }
@ -296,29 +282,25 @@ function strip_quotes ($text)
* @internal param \If $boolean true, use the fast-and-dirty method rather than the shiny and nice method * @internal param \If $boolean true, use the fast-and-dirty method rather than the shiny and nice method
* *
*/ */
function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true) function strip_bbcode($message, $stripquotes = true, $fast_and_dirty = false, $showlinks = true)
{ {
$find = array(); $find = array();
$replace = array(); $replace = array();
if ($stripquotes) if ($stripquotes) {
{
// [quote=username] and [quote] // [quote=username] and [quote]
$message = strip_quotes($message); $message = strip_quotes($message);
} }
// a really quick and rather nasty way of removing bbcode // a really quick and rather nasty way of removing bbcode
if ($fast_and_dirty) if ($fast_and_dirty) {
{
// any old thing in square brackets // any old thing in square brackets
$find[] = '#\[.*/?\]#siU'; $find[] = '#\[.*/?\]#siU';
$replace = ''; $replace = '';
$message = preg_replace($find, $replace, $message); $message = preg_replace($find, $replace, $message);
} } // the preferable way to remove bbcode
// the preferable way to remove bbcode else {
else
{
// simple links // simple links
$find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU'; $find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU';
$replace[] = '\3'; $replace[] = '\3';
@ -335,8 +317,7 @@ function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $
$message = preg_replace($find, $replace, $message); $message = preg_replace($find, $replace, $message);
// strip out all other instances of [x]...[/x] // strip out all other instances of [x]...[/x]
while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) while (preg_match('#\[([a-z]+)\s*?(?:[^\]]*?)\](.*?)(\[/\1\])#is', $message, $m)) {
{
$message = str_replace($m[0], $m[2], $message); $message = str_replace($m[0], $m[2], $message);
} }
@ -347,7 +328,11 @@ function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $
return $message; return $message;
} }
function extract_search_words ($text) /**
* @param $text
* @return mixed|string
*/
function extract_search_words($text)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -383,28 +368,31 @@ function extract_search_words ($text)
// short & long words 2 // short & long words 2
$text_out = array(); $text_out = array();
foreach ($text as $word) foreach ($text as $word) {
{ if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) {
if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) $text_out[] = $word; $text_out[] = $word;
}
} }
$text = $text_out; $text = $text_out;
if (sizeof($text) > $max_words_count) if (sizeof($text) > $max_words_count) {
{ # shuffle($text);
# shuffle($text);
$text = array_splice($text, 0, $max_words_count); $text = array_splice($text, 0, $max_words_count);
} }
return $text; return $text;
} }
function replace_synonyms ($text) /**
* @param $text
* @return mixed
*/
function replace_synonyms($text)
{ {
static $syn_match = null, $syn_replace = null; static $syn_match = null, $syn_replace = null;
if (is_null($syn_match)) if (is_null($syn_match)) {
{ preg_match_all("#(\w+) (\w+)(\r?\n|$)#", file_get_contents(LANG_DIR . 'search_synonyms.txt'), $m);
preg_match_all("#(\w+) (\w+)(\r?\n|$)#", file_get_contents(LANG_DIR .'search_synonyms.txt'), $m);
$syn_match = $m[2]; $syn_match = $m[2];
$syn_replace = $m[1]; $syn_replace = $m[1];
@ -416,36 +404,42 @@ function replace_synonyms ($text)
return ($syn_match && $syn_replace) ? str_replace($syn_match, $syn_replace, $text) : $text; return ($syn_match && $syn_replace) ? str_replace($syn_match, $syn_replace, $text) : $text;
} }
function add_search_words ($post_id, $post_message, $topic_title = '', $only_return_words = false) /**
* @param $post_id
* @param $post_message
* @param string $topic_title
* @param bool $only_return_words
* @return string
*/
function add_search_words($post_id, $post_message, $topic_title = '', $only_return_words = false)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$text = $topic_title .' '. $post_message; $text = $topic_title . ' ' . $post_message;
$words = ($text) ? extract_search_words($text) : array(); $words = ($text) ? extract_search_words($text) : array();
if ($only_return_words || $di->config->get('sphinx_enabled')) if ($only_return_words || $di->config->get('sphinx_enabled')) {
{
return join("\n", $words); return join("\n", $words);
} } else {
else DB()->query("DELETE FROM " . BB_POSTS_SEARCH . " WHERE post_id = $post_id");
{
DB()->query("DELETE FROM ". BB_POSTS_SEARCH ." WHERE post_id = $post_id");
if ($words_sql = DB()->escape(join("\n", $words))) if ($words_sql = DB()->escape(join("\n", $words))) {
{ DB()->query("REPLACE INTO " . BB_POSTS_SEARCH . " (post_id, search_words) VALUES ($post_id, '$words_sql')");
DB()->query("REPLACE INTO ". BB_POSTS_SEARCH ." (post_id, search_words) VALUES ($post_id, '$words_sql')");
} }
} }
} }
/**
* Class bbcode
*/
class bbcode class bbcode
{ {
var $tpl = array(); // шаблоны для замены тегов public $tpl = array(); // шаблоны для замены тегов
var $smilies = null; // смайлы public $smilies = null; // смайлы
var $found_spam = null; // найденные спам "слова" public $found_spam = null; // найденные спам "слова"
var $del_words = array(); // см. get_words_rate() public $del_words = array(); // см. get_words_rate()
var $tidy_cfg = array( public $tidy_cfg = array(
'drop-empty-paras' => false, 'drop-empty-paras' => false,
'fix-uri' => false, 'fix-uri' => false,
'force-output' => true, 'force-output' => true,
@ -463,7 +457,7 @@ class bbcode
'show-warnings' => false, 'show-warnings' => false,
'wrap' => 0, 'wrap' => 0,
); );
var $block_tags = array( public $block_tags = array(
'align', 'align',
'br', 'br',
'clear', 'clear',
@ -473,17 +467,17 @@ class bbcode
'quote', 'quote',
'spoiler', 'spoiler',
); );
var $preg = array(); public $preg = array();
var $str = array(); public $str = array();
var $preg_search = array(); public $preg_search = array();
var $preg_repl = array(); public $preg_repl = array();
var $str_search = array(); public $str_search = array();
var $str_repl = array(); public $str_repl = array();
/** /**
* Constructor * Constructor
*/ */
function bbcode () public function bbcode()
{ {
$this->tpl = get_bbcode_tpl(); $this->tpl = get_bbcode_tpl();
@ -493,7 +487,7 @@ class bbcode
/** /**
* init_replacements * init_replacements
*/ */
function init_replacements () public function init_replacements()
{ {
$tpl = $this->tpl; $tpl = $this->tpl;
$img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?'; $img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?';
@ -559,7 +553,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function bbcode2html ($text) public function bbcode2html($text)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -569,8 +563,7 @@ class bbcode
$text = $this->spam_filter($text); $text = $this->spam_filter($text);
// Tag parse // Tag parse
if (strpos($text, '[') !== false) if (strpos($text, '[') !== false) {
{
// [code] // [code]
$text = preg_replace_callback('#(\s*)\[code\](.+?)\[/code\](\s*)#s', array(&$this, 'code_callback'), $text); $text = preg_replace_callback('#(\s*)\[code\](.+?)\[/code\](\s*)#s', array(&$this, 'code_callback'), $text);
@ -599,8 +592,7 @@ class bbcode
$text = $this->new_line2html($text); $text = $this->new_line2html($text);
$text = trim($text); $text = trim($text);
if ($di->config->get('tidy_post')) if ($di->config->get('tidy_post')) {
{
$text = $this->tidy($text); $text = $this->tidy($text);
} }
@ -614,7 +606,7 @@ class bbcode
* *
* @return mixed|string * @return mixed|string
*/ */
static function clean_up ($text) public static function clean_up($text)
{ {
$text = trim($text); $text = trim($text);
$text = str_replace("\r", '', $text); $text = str_replace("\r", '', $text);
@ -630,7 +622,7 @@ class bbcode
* *
* @return mixed|string * @return mixed|string
*/ */
private function spam_filter ($text) private function spam_filter($text)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -638,18 +630,15 @@ class bbcode
static $spam_words = null; static $spam_words = null;
static $spam_replace = ' СПАМ'; static $spam_replace = ' СПАМ';
if (isset($this)) if (isset($this)) {
{
$found_spam =& $this->found_spam; $found_spam =& $this->found_spam;
} }
// set $spam_words and $spam_replace // set $spam_words and $spam_replace
if (!$di->config->get('spam_filter_file_path')) if (!$di->config->get('spam_filter_file_path')) {
{
return $text; return $text;
} }
if (is_null($spam_words)) if (is_null($spam_words)) {
{
$spam_words = file_get_contents($di->config->get('spam_filter_file_path')); $spam_words = file_get_contents($di->config->get('spam_filter_file_path'));
$spam_words = strtolower($spam_words); $spam_words = strtolower($spam_words);
$spam_words = explode("\n", $spam_words); $spam_words = explode("\n", $spam_words);
@ -664,22 +653,17 @@ class bbcode
$msg_search = strtolower($msg_decoded); $msg_search = strtolower($msg_decoded);
foreach ($spam_words as $spam_str) foreach ($spam_words as $spam_str) {
{ if (!$spam_str = trim($spam_str)) {
if (!$spam_str = trim($spam_str))
{
continue; continue;
} }
if (strpos($msg_search, $spam_str) !== false) if (strpos($msg_search, $spam_str) !== false) {
{
$found_spam[] = $spam_str; $found_spam[] = $spam_str;
} }
} }
if ($found_spam) if ($found_spam) {
{
$spam_exp = array(); $spam_exp = array();
foreach ($found_spam as $keyword) foreach ($found_spam as $keyword) {
{
$spam_exp[] = preg_quote($keyword, '/'); $spam_exp[] = preg_quote($keyword, '/');
} }
$spam_exp = join('|', $spam_exp); $spam_exp = join('|', $spam_exp);
@ -698,7 +682,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function code_callback ($m) public function code_callback($m)
{ {
$code = trim($m[2]); $code = trim($m[2]);
$code = str_replace(' ', '&nbsp; ', $code); $code = str_replace(' ', '&nbsp; ', $code);
@ -715,7 +699,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function url_callback ($m) public function url_callback($m)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -723,14 +707,13 @@ class bbcode
$url = trim($m[1]); $url = trim($m[1]);
$url_name = (isset($m[2])) ? trim($m[2]) : $url; $url_name = (isset($m[2])) ? trim($m[2]) : $url;
if (!preg_match("#^https?://#isu", $url) && !preg_match("/^#/", $url)) $url = 'http://' . $url; if (!preg_match("#^https?://#isu", $url) && !preg_match("/^#/", $url)) {
$url = 'http://' . $url;
if (in_array(parse_url($url, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled'))
{
$link = "<a href=\"$url\" class=\"postLink\">$url_name</a>";
} }
else
{ if (in_array(parse_url($url, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) {
$link = "<a href=\"$url\" class=\"postLink\">$url_name</a>";
} else {
$link = "<a href=\"$url\" class=\"postLink\" rel=\"nofollow\">$url_name</a>"; $link = "<a href=\"$url\" class=\"postLink\" rel=\"nofollow\">$url_name</a>";
} }
@ -744,7 +727,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function escape_tiltes_callback ($m) public function escape_tiltes_callback($m)
{ {
$tilte = substr($m[3], 0, 250); $tilte = substr($m[3], 0, 250);
$tilte = str_replace(array('[', ']', ':', ')', '"'), array('&#91;', '&#93;', '&#58;', '&#41;', '&#34;'), $tilte); $tilte = str_replace(array('[', ']', ':', ')', '"'), array('&#91;', '&#93;', '&#58;', '&#41;', '&#34;'), $tilte);
@ -760,7 +743,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function make_clickable ($text) public function make_clickable($text)
{ {
$url_regexp = "# $url_regexp = "#
(?<![\"'=]) (?<![\"'=])
@ -784,7 +767,7 @@ class bbcode
// Remove our padding.. // Remove our padding..
$ret = substr(substr($ret, 0, -1), 1); $ret = substr(substr($ret, 0, -1), 1);
return($ret); return ($ret);
} }
/** /**
@ -794,21 +777,18 @@ class bbcode
* *
* @return string * @return string
*/ */
function make_url_clickable_callback ($m) public function make_url_clickable_callback($m)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$max_len = 70; $max_len = 70;
$href = $m[1]; $href = $m[1];
$name = (mb_strlen($href, 'UTF-8') > $max_len) ? mb_substr($href, 0, $max_len - 19) .'...'. mb_substr($href, -16) : $href; $name = (mb_strlen($href, 'UTF-8') > $max_len) ? mb_substr($href, 0, $max_len - 19) . '...' . mb_substr($href, -16) : $href;
if (in_array(parse_url($href, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) if (in_array(parse_url($href, PHP_URL_HOST), $di->config->get('nofollow.allowed_url')) || $di->config->get('nofollow.disabled')) {
{
$link = "<a href=\"$href\" class=\"postLink\">$name</a>"; $link = "<a href=\"$href\" class=\"postLink\">$name</a>";
} } else {
else
{
$link = "<a href=\"$href\" class=\"postLink\" rel=\"nofollow\">$name</a>"; $link = "<a href=\"$href\" class=\"postLink\" rel=\"nofollow\">$name</a>";
} }
@ -822,16 +802,14 @@ class bbcode
* *
* @return mixed * @return mixed
*/ */
function smilies_pass ($text) public function smilies_pass($text)
{ {
global $datastore; global $datastore;
if (is_null($this->smilies)) if (is_null($this->smilies)) {
{
$this->smilies = $datastore->get('smile_replacements'); $this->smilies = $datastore->get('smile_replacements');
} }
if ($this->smilies) if ($this->smilies) {
{
$parsed_text = preg_replace($this->smilies['orig'], $this->smilies['repl'], $text, 101, $smilies_cnt); $parsed_text = preg_replace($this->smilies['orig'], $this->smilies['repl'], $text, 101, $smilies_cnt);
$text = ($smilies_cnt <= 100) ? $parsed_text : $text; $text = ($smilies_cnt <= 100) ? $parsed_text : $text;
} }
@ -846,7 +824,7 @@ class bbcode
* *
* @return mixed * @return mixed
*/ */
function new_line2html ($text) public function new_line2html($text)
{ {
$text = preg_replace('#\n{2,}#', '<span class="post-br"><br /></span>', $text); $text = preg_replace('#\n{2,}#', '<span class="post-br"><br /></span>', $text);
$text = str_replace("\n", '<br />', $text); $text = str_replace("\n", '<br />', $text);
@ -860,47 +838,52 @@ class bbcode
* *
* @return string * @return string
*/ */
function tidy ($text) public function tidy($text)
{ {
$text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8');
return $text; return $text;
} }
} }
function bbcode2html ($text) /**
* @param $text
* @return string
*/
function bbcode2html($text)
{ {
global $bbcode; global $bbcode;
if (!isset($bbcode)) if (!isset($bbcode)) {
{
$bbcode = new bbcode(); $bbcode = new bbcode();
} }
$orig_word = array(); $orig_word = array();
$replacement_word = array(); $replacement_word = array();
obtain_word_list($orig_word, $replacement_word); obtain_word_list($orig_word, $replacement_word);
if ( count($orig_word) ) if (count($orig_word)) {
{
$text = preg_replace($orig_word, $replacement_word, $text); $text = preg_replace($orig_word, $replacement_word, $text);
} }
return $bbcode->bbcode2html($text); return $bbcode->bbcode2html($text);
} }
/**
* Class words_rate
*/
class words_rate class words_rate
{ {
var $dbg_mode = false; public $dbg_mode = false;
var $words_rate = 0; public $words_rate = 0;
var $deleted_words = array(); public $deleted_words = array();
var $del_text_hl = ''; public $del_text_hl = '';
var $words_del_exp = ''; public $words_del_exp = '';
var $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; public $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#';
function words_rate () public function words_rate()
{ {
// слова начинающиеся на.. // слова начинающиеся на..
$del_list = file_get_contents(BB_ROOT .'/library/words_rate_del_list.txt'); $del_list = file_get_contents(BB_ROOT . '/library/words_rate_del_list.txt');
$del_list = str_compact($del_list); $del_list = str_compact($del_list);
$del_list = str_replace(' ', '|', preg_quote($del_list, '/')); $del_list = str_replace(' ', '|', preg_quote($del_list, '/'));
$del_exp = '/\b('.$del_list.')[\w\-]*/i'; $del_exp = '/\b(' . $del_list . ')[\w\-]*/i';
$this->words_del_exp = $del_exp; $this->words_del_exp = $del_exp;
} }
@ -912,41 +895,35 @@ class words_rate
* *
* @return int * @return int
*/ */
function get_words_rate ($text) public function get_words_rate($text)
{ {
$this->words_rate = 127; // максимальное значение по умолчанию $this->words_rate = 127; // максимальное значение по умолчанию
$this->deleted_words = array(); $this->deleted_words = array();
$this->del_text_hl = $text; $this->del_text_hl = $text;
// длинное сообщение // длинное сообщение
if (strlen($text) > 600) if (strlen($text) > 600) {
{
return $this->words_rate; return $this->words_rate;
} }
// вырезаем цитаты если содержит +1 // вырезаем цитаты если содержит +1
if (preg_match('#\+\d+#', $text)) if (preg_match('#\+\d+#', $text)) {
{
$text = strip_quotes($text); $text = strip_quotes($text);
} }
// содержит ссылку // содержит ссылку
if (strpos($text, '://')) if (strpos($text, '://')) {
{
return $this->words_rate; return $this->words_rate;
} }
// вопрос // вопрос
if ($questions = preg_match_all('#\w\?+#', $text, $m)) if ($questions = preg_match_all('#\w\?+#', $text, $m)) {
{ if ($questions >= 1) {
if ($questions >= 1)
{
return $this->words_rate; return $this->words_rate;
} }
} }
if ($this->dbg_mode) if ($this->dbg_mode) {
{
preg_match_all($this->words_del_exp, $text, $this->deleted_words); preg_match_all($this->words_del_exp, $text, $this->deleted_words);
$text_dbg = preg_replace($this->words_del_exp, '<span class="del-word">$0</span>', $text); $text_dbg = preg_replace($this->words_del_exp, '<span class="del-word">$0</span>', $text);
$this->del_text_hl = '<div class="prune-post">'. $text_dbg . '</div>'; $this->del_text_hl = '<div class="prune-post">' . $text_dbg . '</div>';
} }
$text = preg_replace($this->words_del_exp, '', $text); $text = preg_replace($this->words_del_exp, '', $text);
@ -957,8 +934,7 @@ class words_rate
$words_count = preg_match_all($this->words_cnt_exp, $text, $m); $words_count = preg_match_all($this->words_cnt_exp, $text, $m);
if ($words_count !== false && $words_count < 127) if ($words_count !== false && $words_count < 127) {
{
$this->words_rate = ($words_count == 0) ? 1 : $words_count; $this->words_rate = ($words_count == 0) ? 1 : $words_count;
} }
@ -966,49 +942,63 @@ class words_rate
} }
} }
function get_words_rate ($text) /**
* @param $text
* @return int
*/
function get_words_rate($text)
{ {
static $wr = null; static $wr = null;
if (!isset($wr)) if (!isset($wr)) {
{
$wr = new words_rate(); $wr = new words_rate();
} }
return $wr->get_words_rate($text); return $wr->get_words_rate($text);
} }
function hide_passkey ($str) /**
* @param $str
* @return mixed
*/
function hide_passkey($str)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
return preg_replace("#\?{$di->config->get('passkey_key')}=[a-zA-Z0-9]{". BT_AUTH_KEY_LENGTH ."}#", "?{$di->config->get('passkey_key')}=passkey", $str); return preg_replace("#\?{$di->config->get('passkey_key')}=[a-zA-Z0-9]{" . BT_AUTH_KEY_LENGTH . "}#", "?{$di->config->get('passkey_key')}=passkey", $str);
} }
function get_parsed_post ($postrow, $mode = 'full', $return_chars = 600) /**
* @param $postrow
* @param string $mode
* @param int $return_chars
* @return string
*/
function get_parsed_post($postrow, $mode = 'full', $return_chars = 600)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if ($di->config->get('use_posts_cache') && !empty($postrow['post_html'])) if ($di->config->get('use_posts_cache') && !empty($postrow['post_html'])) {
{
return $postrow['post_html']; return $postrow['post_html'];
} }
$message = bbcode2html($postrow['post_text']); $message = bbcode2html($postrow['post_text']);
// Posts cache // Posts cache
if ($di->config->get('use_posts_cache')) if ($di->config->get('use_posts_cache')) {
{
DB()->shutdown['post_html'][] = array( DB()->shutdown['post_html'][] = array(
'post_id' => (int) $postrow['post_id'], 'post_id' => (int)$postrow['post_id'],
'post_html' => (string) $message, 'post_html' => (string)$message,
); );
} }
return $message; return $message;
} }
function update_post_html ($postrow) /**
* @param $postrow
*/
function update_post_html($postrow)
{ {
DB()->query("DELETE FROM ". BB_POSTS_HTML ." WHERE post_id = ". (int) $postrow['post_id'] ." LIMIT 1"); DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_id = " . (int)$postrow['post_id'] . " LIMIT 1");
} }

View file

@ -1,19 +1,24 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
use Zend\Mail; }
class emailer class emailer
{ {
var $msg, $subject, $extra_headers; public $msg, $subject, $extra_headers;
var $addresses, $reply_to, $from; public $addresses, $reply_to, $from;
var $use_smtp; public $use_smtp;
var $tpl_msg = array(); public $tpl_msg = array();
var $vars = array(); public $vars = array();
function emailer ($use_smtp/*$tpl_name, $sbj, $to_address*/) /**
* emailer constructor.
* @param $use_smtp
* @return emailer
*/
public function emailer($use_smtp/*$tpl_name, $sbj, $to_address*/)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -24,7 +29,10 @@ class emailer
$this->use_smtp = $use_smtp; $this->use_smtp = $use_smtp;
} }
function set_default_vars () /**
* Установка стандартных замен в письмах
*/
public function set_default_vars()
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -37,7 +45,10 @@ class emailer
} }
// Resets all the data (address, template file, etc etc to default // Resets all the data (address, template file, etc etc to default
function reset () /**
* Сброс
*/
public function reset()
{ {
$this->addresses = array(); $this->addresses = array();
$this->msg = $this->extra_headers = ''; $this->msg = $this->extra_headers = '';
@ -45,74 +56,94 @@ class emailer
} }
// Sets an email address to send to // Sets an email address to send to
function email_address ($address) /**
* @param $address
*/
public function email_address($address)
{ {
$this->addresses['to'] = trim($address); $this->addresses['to'] = trim($address);
} }
function cc ($address) /**
* @param $address
*/
public function cc($address)
{ {
$this->addresses['cc'][] = trim($address); $this->addresses['cc'][] = trim($address);
} }
function bcc ($address) /**
* @param $address
*/
public function bcc($address)
{ {
$this->addresses['bcc'][] = trim($address); $this->addresses['bcc'][] = trim($address);
} }
function replyto ($address) /**
* @param $address
*/
public function replyto($address)
{ {
$this->reply_to = trim($address); $this->reply_to = trim($address);
} }
function from ($address) /**
* @param $address
*/
public function from($address)
{ {
$this->from = trim($address); $this->from = trim($address);
} }
// set up subject for mail // set up subject for mail
function set_subject ($subject = '') /**
* @param string $subject
*/
public function set_subject($subject = '')
{ {
$this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
} }
// set up extra mail headers // set up extra mail headers
function extra_headers ($headers) /**
* @param $headers
*/
public function extra_headers($headers)
{ {
$this->extra_headers .= trim($headers) . "\n"; $this->extra_headers .= trim($headers) . "\n";
} }
function use_template ($template_file, $template_lang = '') /**
* @param $template_file
* @param string $template_lang
* @return bool
*/
public function use_template($template_file, $template_lang = '')
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (trim($template_file) == '') if (trim($template_file) == '') {
{
bb_die('No template file set'); bb_die('No template file set');
} }
if (trim($template_lang) == '') if (trim($template_lang) == '') {
{
$template_lang = $di->config->get('default_lang'); $template_lang = $di->config->get('default_lang');
} }
if (empty($this->tpl_msg[$template_lang . $template_file])) if (empty($this->tpl_msg[$template_lang . $template_file])) {
{ $tpl_file = LANG_ROOT_DIR . "$template_lang/email/$template_file.html";
$tpl_file = LANG_ROOT_DIR ."$template_lang/email/$template_file.html";
if (!file_exists(bb_realpath($tpl_file))) if (!file_exists(bb_realpath($tpl_file))) {
{ $tpl_file = LANG_ROOT_DIR . "{$di->config->get('default_lang')}/email/$template_file.html";
$tpl_file = LANG_ROOT_DIR ."{$di->config->get('default_lang')}/email/$template_file.html";
if (!file_exists(bb_realpath($tpl_file))) if (!file_exists(bb_realpath($tpl_file))) {
{
bb_die('Could not find email template file :: ' . $template_file); bb_die('Could not find email template file :: ' . $template_file);
} }
} }
if (!($fd = fopen($tpl_file, 'r'))) if (!($fd = fopen($tpl_file, 'r'))) {
{
bb_die('Failed opening template file :: ' . $tpl_file); bb_die('Failed opening template file :: ' . $tpl_file);
} }
@ -126,41 +157,45 @@ class emailer
} }
// assign variables // assign variables
function assign_vars ($vars) /**
* @param $vars
*/
public function assign_vars($vars)
{ {
$this->vars = array_merge($this->vars, $vars); $this->vars = array_merge($this->vars, $vars);
} }
// Send the mail out to the recipients set previously in var $this->address // Send the mail out to the recipients set previously in var $this->address
function send ($email_format = 'text') /**
* @param string $email_format
* @return bool
*/
public function send($email_format = 'text')
{ {
global $userdata; global $userdata;
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if ($di->config->get('emailer_disabled')) if ($di->config->get('emailer_disabled')) {
{
return false; return false;
} }
// Escape all quotes // Escape all quotes
$this->msg = str_replace ("'", "\'", $this->msg); $this->msg = str_replace("'", "\'", $this->msg);
$this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg); $this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->msg);
// Set vars // Set vars
reset ($this->vars); reset($this->vars);
while (list($key, $val) = each($this->vars)) while (list($key, $val) = each($this->vars)) {
{
$$key = $val; $$key = $val;
} }
eval("\$this->msg = '$this->msg';"); eval("\$this->msg = '$this->msg';");
// Clear vars // Clear vars
reset ($this->vars); reset($this->vars);
while (list($key, $val) = each($this->vars)) while (list($key, $val) = each($this->vars)) {
{
unset($$key); unset($$key);
} }
@ -168,29 +203,22 @@ class emailer
// do this here because the subject may contain a variable // do this here because the subject may contain a variable
$drop_header = ''; $drop_header = '';
$match = array(); $match = array();
if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match)) {
{
$this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject'); $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : 'No Subject');
$drop_header .= '[\r\n]*?' . preg_quote($match[1], '#'); $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
} } else {
else
{
$this->subject = (($this->subject != '') ? $this->subject : 'No Subject'); $this->subject = (($this->subject != '') ? $this->subject : 'No Subject');
} }
if (preg_match('#^(Charset:(.*?))$#m', $this->msg, $match)) 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')); $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], '#'); $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
} } else {
else
{
$this->encoding = trim($di->config->get('lang.' . $userdata['user_lang'] . '.encoding')); $this->encoding = trim($di->config->get('lang.' . $userdata['user_lang'] . '.encoding'));
} }
$this->subject = $this->encode($this->subject); $this->subject = $this->encode($this->subject);
if ($drop_header != '') if ($drop_header != '') {
{
$this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg)); $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg));
} }
@ -204,35 +232,33 @@ class emailer
$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" : ''); $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 // Send message
if ($this->use_smtp) if ($this->use_smtp) {
{ if (!defined('SMTP_INCLUDED')) {
if (!defined('SMTP_INCLUDED')) include(INC_DIR . 'smtp.php');
{
include(INC_DIR .'smtp.php');
} }
$result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers); $result = smtpmail($to, $this->subject, $this->msg, $this->extra_headers);
} } else {
else
{
$to = ($to == '') ? ' ' : $to; $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? // Did it work?
if (!$result) if (!$result) {
{
bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result); bb_die('Failed sending email :: ' . (($this->use_smtp) ? 'SMTP' : 'PHP') . ' :: ' . $result);
} }
return true; return true;
} }
function encode ($str) /**
{ * @param $str
if ($this->encoding == '') * @return string
*/
public function encode($str)
{ {
if ($this->encoding == '') {
return $str; return $str;
} }

View file

@ -1,21 +1,31 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class sitemap class sitemap
{ {
var $home = ''; public $home = '';
var $limit = 0; public $limit = 0;
var $topic_priority = '0.5'; public $topic_priority = '0.5';
var $stat_priority = '0.5'; public $stat_priority = '0.5';
var $priority = '0.6'; public $priority = '0.6';
var $cat_priority = '0.7'; public $cat_priority = '0.7';
function sitemap () { /**
* sitemap constructor.
*/
public function sitemap()
{
$this->home = make_url(); $this->home = make_url();
} }
function build_map () { /**
* @return string
*/
public function build_map()
{
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $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_static();
$map .= $this->get_forum(); $map .= $this->get_forum();
@ -25,7 +35,12 @@ class sitemap
return $map; return $map;
} }
function build_index ($count) { /**
* @param $count
* @return string
*/
public function build_index($count)
{
$lm = date('c'); $lm = date('c');
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $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"; $map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap1.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
@ -38,7 +53,11 @@ class sitemap
return $map; return $map;
} }
function build_stat () { /**
* @return string
*/
public function build_stat()
{
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $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_static();
$map .= $this->get_forum(); $map .= $this->get_forum();
@ -47,7 +66,12 @@ class sitemap
return $map; return $map;
} }
function build_map_topic ($n) { /**
* @param $n
* @return string
*/
public 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 = "<?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 .= $this->get_topic($n);
$map .= "</urlset>"; $map .= "</urlset>";
@ -55,7 +79,11 @@ class sitemap
return $map; return $map;
} }
function get_forum () { /**
* @return string
*/
public function get_forum()
{
global $datastore; global $datastore;
$this->priority = $this->cat_priority; $this->priority = $this->cat_priority;
@ -73,15 +101,23 @@ class sitemap
$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)) { while ($row = DB()->sql_fetchrow($sql)) {
if (function_exists('seo_url')) $loc = $this->home . seo_url(FORUM_URL . $row['forum_id'], $row['forum_name']); if (function_exists('seo_url')) {
else $loc = $this->home . FORUM_URL . $row['forum_id']; $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); $xml .= $this->get_xml($loc, $lm);
} }
return $xml; return $xml;
} }
function get_topic ($page = false) { /**
* @param bool $page
* @return string
*/
public function get_topic($page = false)
{
global $datastore; global $datastore;
$xml = ''; $xml = '';
@ -92,7 +128,9 @@ class sitemap
$page = $page * 40000; $page = $page * 40000;
$this->limit = " LIMIT {$page},40000"; $this->limit = " LIMIT {$page},40000";
} else { } else {
if ($this->limit < 1) $this->limit = false; if ($this->limit < 1) {
$this->limit = false;
}
if ($this->limit) { if ($this->limit) {
$this->limit = " LIMIT 0," . $this->limit; $this->limit = " LIMIT 0," . $this->limit;
} else { } else {
@ -111,15 +149,22 @@ class sitemap
$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)) { while ($row = DB()->sql_fetchrow($sql)) {
if (function_exists('seo_url')) $loc = $this->home . seo_url(TOPIC_URL . $row['topic_id'], $row['topic_title']); if (function_exists('seo_url')) {
else $loc = $this->home . TOPIC_URL . $row['topic_id']; $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'])); $xml .= $this->get_xml($loc, date('c', $row['topic_time']));
} }
return $xml; return $xml;
} }
function get_static () { /**
* @return string
*/
public function get_static()
{
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -143,7 +188,13 @@ class sitemap
return $xml; return $xml;
} }
function get_xml ($loc, $lm) { /**
* @param $loc
* @param $lm
* @return string
*/
public function get_xml($loc, $lm)
{
$xml = "\t<url>\n"; $xml = "\t<url>\n";
$xml .= "\t\t<loc>$loc</loc>\n"; $xml .= "\t\t<loc>$loc</loc>\n";
$xml .= "\t\t<lastmod>$lm</lastmod>\n"; $xml .= "\t\t<lastmod>$lm</lastmod>\n";
@ -153,9 +204,15 @@ class sitemap
return $xml; return $xml;
} }
function send_url ($url, $map) { /**
* @param $url
* @param $map
* @return bool|mixed|string
*/
public function send_url($url, $map)
{
$data = false; $data = false;
$file = $url.urlencode($map); $file = $url . urlencode($map);
if (function_exists('curl_init')) { if (function_exists('curl_init')) {
$ch = curl_init(); $ch = curl_init();
@ -175,41 +232,47 @@ class sitemap
} }
} }
function create () { /**
* Создание карты сайта
*/
public function create()
{
$row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS);
if (!$this->limit) $this->limit = $row['count']; if (!$this->limit) {
$this->limit = $row['count'];
}
if ($this->limit > 40000) { if ($this->limit > 40000) {
$pages_count = ceil($row['count'] / 40000); $pages_count = ceil($row['count'] / 40000);
$sitemap = $this->build_index($pages_count); $sitemap = $this->build_index($pages_count);
$handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); $handler = fopen(SITEMAP_DIR . "sitemap.xml", "wb+");
fwrite($handler, $sitemap); fwrite($handler, $sitemap);
fclose($handler); fclose($handler);
chmod(SITEMAP_DIR. "sitemap.xml", 0666); chmod(SITEMAP_DIR . "sitemap.xml", 0666);
$sitemap = $this->build_stat(); $sitemap = $this->build_stat();
$handler = fopen(SITEMAP_DIR. "sitemap1.xml", "wb+"); $handler = fopen(SITEMAP_DIR . "sitemap1.xml", "wb+");
fwrite($handler, $sitemap); fwrite($handler, $sitemap);
fclose($handler); fclose($handler);
chmod(SITEMAP_DIR. "sitemap.xml", 0666); chmod(SITEMAP_DIR . "sitemap.xml", 0666);
for ($i = 0; $i < $pages_count; $i++) { for ($i = 0; $i < $pages_count; $i++) {
$t = $i + 2; $t = $i + 2;
$n = $i + 1; $n = $i + 1;
$sitemap = $this->build_map_topic($n); $sitemap = $this->build_map_topic($n);
$handler = fopen(SITEMAP_DIR. "sitemap{$t}.xml", "wb+"); $handler = fopen(SITEMAP_DIR . "sitemap{$t}.xml", "wb+");
fwrite($handler, $sitemap); fwrite($handler, $sitemap);
fclose($handler); fclose($handler);
chmod(SITEMAP_DIR. "sitemap{$t}.xml", 0666); chmod(SITEMAP_DIR . "sitemap{$t}.xml", 0666);
} }
} else { } else {
$sitemap = $this->build_map(); $sitemap = $this->build_map();
$handler = fopen(SITEMAP_DIR. "sitemap.xml", "wb+"); $handler = fopen(SITEMAP_DIR . "sitemap.xml", "wb+");
fwrite($handler, $sitemap); fwrite($handler, $sitemap);
fclose($handler); fclose($handler);
chmod(SITEMAP_DIR. "sitemap.xml", 0666); chmod(SITEMAP_DIR . "sitemap.xml", 0666);
} }
$params['sitemap_time'] = TIMENOW; $params['sitemap_time'] = TIMENOW;

View file

@ -1,37 +1,46 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class DBS class dbs
{ {
var $cfg = array(); // $srv_name => $srv_cfg public $cfg = array(); // $srv_name => $srv_cfg
var $srv = array(); // $srv_name => $db_obj public $srv = array(); // $srv_name => $db_obj
var $alias = array(); // $srv_alias => $srv_name public $alias = array(); // $srv_alias => $srv_name
var $log_file = 'sql_queries'; public $log_file = 'sql_queries';
var $log_counter = 0; public $log_counter = 0;
var $num_queries = 0; public $num_queries = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
function DBS ($cfg) /**
* dbs constructor.
* @param $cfg
* @return dbs
*/
public function DBS($cfg)
{ {
$this->cfg = $cfg['db']; $this->cfg = $cfg['db'];
$this->alias = $cfg['db_alias']; $this->alias = $cfg['db_alias'];
foreach ($this->cfg as $srv_name => $srv_cfg) foreach ($this->cfg as $srv_name => $srv_cfg) {
{
$this->srv[$srv_name] = null; $this->srv[$srv_name] = null;
} }
} }
// получение/инициализация класса для сервера $srv_name // получение/инициализация класса для сервера $srv_name
function get_db_obj ($srv_name_or_alias = 'db1') /**
* @param string $srv_name_or_alias
* @return mixed
*/
public function get_db_obj($srv_name_or_alias = 'db1')
{ {
$srv_name = $this->get_srv_name($srv_name_or_alias); $srv_name = $this->get_srv_name($srv_name_or_alias);
if (!is_object($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] = new sql_db($this->cfg[$srv_name]);
$this->srv[$srv_name]->db_server = $srv_name; $this->srv[$srv_name]->db_server = $srv_name;
} }
@ -39,18 +48,17 @@ class DBS
} }
// определение имени сервера // определение имени сервера
function get_srv_name ($name) /**
{ * @param $name
if (isset($this->alias[$name])) * @return mixed|string
*/
public function get_srv_name($name)
{ {
if (isset($this->alias[$name])) {
$srv_name = $this->alias[$name]; $srv_name = $this->alias[$name];
} } elseif (isset($this->cfg[$name])) {
else if (isset($this->cfg[$name]))
{
$srv_name = $name; $srv_name = $name;
} } else {
else
{
$srv_name = 'db1'; $srv_name = 'db1';
} }
return $srv_name; return $srv_name;

File diff suppressed because it is too large Load diff

View file

@ -1,38 +1,35 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); 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 // Get cron jobs
$cron_jobs = DB()->fetch_rowset(" $cron_jobs = DB()->fetch_rowset("
SELECT * FROM ". BB_CRON ." SELECT * FROM " . BB_CRON . "
WHERE cron_active = 1 WHERE cron_active = 1
AND next_run <= NOW() AND next_run <= NOW()
ORDER BY run_order ORDER BY run_order
"); ");
// Run cron jobs // Run cron jobs
if ($cron_jobs) if ($cron_jobs) {
{ bb_log(date('H:i:s - ') . getmypid() . ' --x- RUN jobs' . LOG_LF, CRON_LOG_DIR . 'cron_check');
bb_log(date('H:i:s - ') . getmypid() .' --x- RUN jobs'. LOG_LF, CRON_LOG_DIR .'cron_check');
foreach ($cron_jobs as $job) foreach ($cron_jobs as $job) {
{ if ($job['disable_board']) {
if ($job['disable_board'])
{
cron_disable_board(); cron_disable_board();
sleep(10); sleep(10);
break; break;
} }
} }
require(CRON_DIR .'cron_run.php'); require(CRON_DIR . 'cron_run.php');
// Update cron_last_check // Update cron_last_check
bb_update_config(array('cron_last_check' => (TIMENOW + 10))); bb_update_config(array('cron_last_check' => (TIMENOW + 10)));
} } else {
else bb_log(date('H:i:s - ') . getmypid() . ' --x- no active jobs found ----------------------------------------------' . LOG_LF, CRON_LOG_DIR . 'cron_check');
{
bb_log(date('H:i:s - ') . getmypid() .' --x- no active jobs found ----------------------------------------------'. LOG_LF, CRON_LOG_DIR .'cron_check');
} }

View file

@ -1,26 +1,26 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// //
// Functions // Functions
// //
function cron_get_file_lock () /**
* @return bool
*/
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');
# 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); $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING);
} } elseif (file_exists(CRON_RUNNING)) {
elseif (file_exists(CRON_RUNNING))
{
cron_release_deadlock(); cron_release_deadlock();
} } elseif (!file_exists(CRON_ALLOWED) && !file_exists(CRON_RUNNING)) {
elseif (!file_exists(CRON_ALLOWED) && !file_exists(CRON_RUNNING))
{
file_write('', CRON_ALLOWED); file_write('', CRON_ALLOWED);
$lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING); $lock_obtained = rename(CRON_ALLOWED, CRON_RUNNING);
} }
@ -28,17 +28,17 @@ function cron_get_file_lock ()
return $lock_obtained; return $lock_obtained;
} }
function cron_track_running ($mode) /**
* @param $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') if ($mode == 'start') {
{
cron_touch_lock_file(CRON_RUNNING); cron_touch_lock_file(CRON_RUNNING);
file_write('', CRON_STARTMARK); file_write('', CRON_STARTMARK);
} } elseif ($mode == 'end') {
elseif ($mode == 'end')
{
unlink(CRON_STARTMARK); unlink(CRON_STARTMARK);
} }
} }
@ -46,8 +46,7 @@ function cron_track_running ($mode)
// //
// Run cron // Run cron
// //
if (cron_get_file_lock()) if (cron_get_file_lock()) {
{
ignore_user_abort(true); ignore_user_abort(true);
register_shutdown_function('cron_release_file_lock'); register_shutdown_function('cron_release_file_lock');
register_shutdown_function('cron_enable_board'); register_shutdown_function('cron_enable_board');
@ -56,12 +55,11 @@ if (cron_get_file_lock())
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')) if (defined('IN_CRON')) {
{ bb_log(date('H:i:s - ') . getmypid() . ' --x- ALL jobs FINISHED *************************************************' . LOG_LF, CRON_LOG_DIR . 'cron_check');
bb_log(date('H:i:s - ') . getmypid() .' --x- ALL jobs FINISHED *************************************************'. LOG_LF, CRON_LOG_DIR .'cron_check');
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
define('IN_CRON', true); define('IN_CRON', true);
@ -31,19 +33,16 @@ DB()->add_shutdown_query("
"); ");
// $cron_jobs obtained in cron_check.php // $cron_jobs obtained in cron_check.php
foreach ($cron_jobs as $job) foreach ($cron_jobs as $job) {
{
$job_script = CRON_JOB_DIR . basename($job['cron_script']); $job_script = CRON_JOB_DIR . basename($job['cron_script']);
if (file_exists($job_script)) if (file_exists($job_script)) {
{
$cron_start_time = utime(); $cron_start_time = utime();
$cron_runtime_log = ''; $cron_runtime_log = '';
$cron_write_log = (CRON_LOG_ENABLED && (CRON_FORCE_LOG || $job['log_enabled'] >= 1)); $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']); $cron_sql_log_file = CRON_LOG_DIR . 'SQL-' . basename($job['cron_script']);
if ($cron_write_log) if ($cron_write_log) {
{
$msg = array(); $msg = array();
$msg[] = 'start'; $msg[] = 'start';
$msg[] = date('m-d'); $msg[] = date('m-d');
@ -55,42 +54,38 @@ foreach ($cron_jobs as $job)
bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE);
} }
if ($job['log_sql_queries']) if ($job['log_sql_queries']) {
{
DB()->log_next_query(100000, $cron_sql_log_file); DB()->log_next_query(100000, $cron_sql_log_file);
} }
set_time_limit(600); set_time_limit(600);
require($job_script); require($job_script);
if ($job['log_sql_queries']) if ($job['log_sql_queries']) {
{
DB()->log_next_query(0); DB()->log_next_query(0);
bb_log(LOG_LF, $cron_sql_log_file); bb_log(LOG_LF, $cron_sql_log_file);
} }
if ($cron_write_log) if ($cron_write_log) {
{
$msg = array(); $msg = array();
$msg[] = ' end'; $msg[] = ' end';
$msg[] = date('m-d'); $msg[] = date('m-d');
$msg[] = date('H:i:s'); $msg[] = date('H:i:s');
$msg[] = sprintf('%-4s', round(sys('la'), 1)); $msg[] = sprintf('%-4s', round(sys('la'), 1));
$msg[] = sprintf('%05d', getmypid()); $msg[] = sprintf('%05d', getmypid());
$msg[] = round(utime() - $cron_start_time) .'/'. round(utime() - TIMESTART) . ' sec'; $msg[] = round(utime() - $cron_start_time) . '/' . round(utime() - TIMESTART) . ' sec';
$msg = join(LOG_SEPR, $msg); $msg = join(LOG_SEPR, $msg);
$msg .= LOG_LF .'------=-------=----------=------=-------=----------'; $msg .= LOG_LF . '------=-------=----------=------=-------=----------';
bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE); bb_log($msg . LOG_LF, CRON_LOG_DIR . CRON_LOG_FILE);
if ($cron_runtime_log) if ($cron_runtime_log) {
{
$runtime_log_file = ($job['log_file']) ? $job['log_file'] : $job['cron_script']; $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)); bb_log($cron_runtime_log . LOG_LF, CRON_LOG_DIR . basename($runtime_log_file));
} }
} }
DB()->query(" DB()->query("
UPDATE ". BB_CRON ." SET UPDATE " . BB_CRON . " SET
last_run = NOW(), last_run = NOW(),
run_counter = run_counter + 1, run_counter = run_counter + 1,
next_run = next_run =
@ -116,14 +111,11 @@ foreach ($cron_jobs as $job)
sleep(1); sleep(1);
if (utime() - TIMESTART > 600) if (utime() - TIMESTART > 600) {
{
return; // чтобы daily скрипты не блокировали надолго interval'ные return; // чтобы daily скрипты не блокировали надолго interval'ные
} }
} } else {
else $cron_err_msg = "Can not run \"{$job['cron_title']}\" : file \"$job_script\" not found" . LOG_LF;
{
$cron_err_msg = "Can not run \"{$job['cron_title']}\" : file \"$job_script\" not found". LOG_LF;
bb_log($cron_err_msg, 'cron_error'); bb_log($cron_err_msg, 'cron_error');
} }
} }

View file

@ -1,11 +1,13 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
require_once(INC_DIR .'functions_admin.php'); require_once(INC_DIR . 'functions_admin.php');
// Синхронизация // Синхронизация
sync('topic', 'all'); sync('topic', 'all');
@ -13,29 +15,25 @@ sync('user_posts', 'all');
sync_all_forums(); sync_all_forums();
// Чистка bb_poll_users // Чистка bb_poll_users
if ($poll_max_days = (int) $di->config->get('poll_max_days')) if ($poll_max_days = (int)$di->config->get('poll_max_days')) {
{
$per_cycle = 20000; $per_cycle = 20000;
$row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM ". BB_POLL_USERS); $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']; $start_id = (int)$row['start_id'];
$finish_id = (int) $row['finish_id']; $finish_id = (int)$row['finish_id'];
while (true) while (true) {
{
set_time_limit(600); set_time_limit(600);
$end_id = $start_id + $per_cycle - 1; $end_id = $start_id + $per_cycle - 1;
DB()->query(" DB()->query("
DELETE FROM ". BB_POLL_USERS ." DELETE FROM " . BB_POLL_USERS . "
WHERE topic_id BETWEEN $start_id AND $end_id WHERE topic_id BETWEEN $start_id AND $end_id
AND vote_dt < DATE_SUB(NOW(), INTERVAL $poll_max_days DAY) AND vote_dt < DATE_SUB(NOW(), INTERVAL $poll_max_days DAY)
"); ");
if ($end_id > $finish_id) if ($end_id > $finish_id) {
{
break; break;
} }
if (!($start_id % ($per_cycle*10))) if (!($start_id % ($per_cycle * 10))) {
{
sleep(1); sleep(1);
} }
$start_id += $per_cycle; $start_id += $per_cycle;
@ -43,10 +41,9 @@ if ($poll_max_days = (int) $di->config->get('poll_max_days'))
} }
// Чистка user_newpasswd // Чистка 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'))) 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)");
DB()->query("DELETE FROM ". BB_POSTS_HTML ." WHERE post_html_time < DATE_SUB(NOW(), INTERVAL $posts_days DAY)");
} }

View file

@ -1,24 +1,24 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
// Delete staled dl-status records // Delete staled dl-status records
$keeping_dlstat = array( $keeping_dlstat = array(
DL_STATUS_WILL => (int) $di->config->get('dl_will_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_DOWN => (int)$di->config->get('dl_down_days_keep'),
DL_STATUS_COMPLETE => (int) $di->config->get('dl_complete_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_CANCEL => (int)$di->config->get('dl_cancel_days_keep'),
); );
$delete_dlstat_sql = array(); $delete_dlstat_sql = array();
foreach ($keeping_dlstat as $dl_status => $days_to_keep) foreach ($keeping_dlstat as $dl_status => $days_to_keep) {
{ if ($days_to_keep) {
if ($days_to_keep)
{
$delete_dlstat_sql[] = " $delete_dlstat_sql[] = "
user_status = $dl_status user_status = $dl_status
AND AND
@ -27,42 +27,40 @@ foreach ($keeping_dlstat as $dl_status => $days_to_keep)
} }
} }
if ($delete_dlstat_sql = join(') OR (', $delete_dlstat_sql)) if ($delete_dlstat_sql = join(') OR (', $delete_dlstat_sql)) {
{ DB()->query("DELETE QUICK FROM " . BB_BT_DLSTATUS . " WHERE ($delete_dlstat_sql)");
DB()->query("DELETE QUICK FROM ". BB_BT_DLSTATUS ." WHERE ($delete_dlstat_sql)");
} }
// Delete orphans // Delete orphans
DB()->query(" DB()->query("
DELETE QUICK dl DELETE QUICK dl
FROM ". BB_BT_DLSTATUS ." dl FROM " . BB_BT_DLSTATUS . " dl
LEFT JOIN ". BB_USERS ." u USING(user_id) LEFT JOIN " . BB_USERS . " u USING(user_id)
WHERE u.user_id IS NULL WHERE u.user_id IS NULL
"); ");
DB()->query(" DB()->query("
DELETE QUICK dl DELETE QUICK dl
FROM ". BB_BT_DLSTATUS ." dl FROM " . BB_BT_DLSTATUS . " dl
LEFT JOIN ". BB_TOPICS ." t USING(topic_id) LEFT JOIN " . BB_TOPICS . " t USING(topic_id)
WHERE t.topic_id IS NULL WHERE t.topic_id IS NULL
"); ");
// Tor-Stats cleanup // Tor-Stats cleanup
if ($torstat_days_keep = intval($di->config->get('torstat_days_keep'))) 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 FROM ". BB_BT_TORSTAT ." WHERE last_modified_torstat < DATE_SUB(NOW(), INTERVAL $torstat_days_keep DAY)");
} }
DB()->query(" DB()->query("
DELETE QUICK tst DELETE QUICK tst
FROM ". BB_BT_TORSTAT ." tst FROM " . BB_BT_TORSTAT . " tst
LEFT JOIN ". BB_BT_TORRENTS ." tor USING(topic_id) LEFT JOIN " . BB_BT_TORRENTS . " tor USING(topic_id)
WHERE tor.topic_id IS NULL WHERE tor.topic_id IS NULL
"); ");
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_BT_USERS ." " . BB_BT_USERS . "
SET SET
up_yesterday = up_today, up_yesterday = up_today,
down_yesterday = down_today, down_yesterday = down_today,
@ -73,7 +71,7 @@ DB()->query("
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_BT_USERS ." " . BB_BT_USERS . "
SET SET
up_today = 0, up_today = 0,
down_today = 0, down_today = 0,

View file

@ -1,13 +1,15 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $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(" DB()->query("
DELETE FROM ". BB_LOG ." DELETE FROM " . BB_LOG . "
WHERE log_time < ". (TIMENOW - 86400*$log_days_keep) ." WHERE log_time < " . (TIMENOW - 86400 * $log_days_keep) . "
"); ");

View file

@ -1,10 +1,12 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$search_results_expire = TIMENOW - 3*3600; $search_results_expire = TIMENOW - 3 * 3600;
DB()->query(" DB()->query("
DELETE FROM ". BB_SEARCH ." DELETE FROM " . BB_SEARCH . "
WHERE search_time < $search_results_expire WHERE search_time < $search_results_expire
"); ");

View file

@ -1,5 +1,7 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$datastore->update('cat_forums'); $datastore->update('cat_forums');

View file

@ -1,5 +1,7 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$datastore->update('stats'); $datastore->update('stats');

View file

@ -1,18 +1,20 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// Lock tables // Lock tables
DB()->lock(array( DB()->lock(array(
BB_TOPICS .' t', BB_TOPICS . ' t',
BUF_TOPIC_VIEW .' buf', BUF_TOPIC_VIEW . ' buf',
)); ));
// Flash buffered records // Flash buffered records
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_TOPICS ." t, " . BB_TOPICS . " t,
". BUF_TOPIC_VIEW ." buf " . BUF_TOPIC_VIEW . " buf
SET SET
t.topic_views = t.topic_views + buf.topic_views t.topic_views = t.topic_views + buf.topic_views
WHERE WHERE
@ -20,7 +22,7 @@ DB()->query("
"); ");
// Delete buffered records // Delete buffered records
DB()->query("DELETE buf FROM ". BUF_TOPIC_VIEW ." buf"); DB()->query("DELETE buf FROM " . BUF_TOPIC_VIEW . " buf");
// Unlock tables // Unlock tables
DB()->unlock(); DB()->unlock();

View file

@ -1,18 +1,18 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
require_once(INC_DIR .'functions_admin.php'); require_once(INC_DIR . 'functions_admin.php');
if ($di->config->get('prune_enable')) if ($di->config->get('prune_enable')) {
{ $sql = "SELECT forum_id, prune_days FROM " . BB_FORUMS . " WHERE prune_days != 0";
$sql = "SELECT forum_id, prune_days FROM ". BB_FORUMS ." WHERE prune_days != 0";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{ topic_delete('prune', $row['forum_id'], (TIMENOW - 86400 * $row['prune_days']));
topic_delete('prune', $row['forum_id'], (TIMENOW - 86400*$row['prune_days']));
} }
} }

View file

@ -1,58 +1,53 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
require_once(INC_DIR .'functions_admin.php'); require_once(INC_DIR . 'functions_admin.php');
$users_per_cycle = 1000; $users_per_cycle = 1000;
while (true) while (true) {
{
set_time_limit(600); 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'))) if ($not_activated_days = intval($di->config->get('user_not_activated_days_keep'))) {
{ $sql = DB()->fetch_rowset("SELECT user_id FROM " . BB_USERS . "
$sql = DB()->fetch_rowset("SELECT user_id FROM ". BB_USERS ."
WHERE user_level = 0 WHERE user_level = 0
AND user_lastvisit = 0 AND user_lastvisit = 0
AND user_session_time = 0 AND user_session_time = 0
AND user_regdate <= ". (TIMENOW - 86400 * $not_activated_days) ." AND user_regdate <= " . (TIMENOW - 86400 * $not_activated_days) . "
AND user_id NOT IN(". EXCLUDED_USERS .") AND user_id NOT IN(" . EXCLUDED_USERS . ")
LIMIT $users_per_cycle"); LIMIT $users_per_cycle");
foreach ($sql as $row) foreach ($sql as $row) {
{
$not_activated_users[] = $row['user_id']; $not_activated_users[] = $row['user_id'];
} }
} }
if ($not_active_days = intval($di->config->get('user_not_active_days_keep'))) if ($not_active_days = intval($di->config->get('user_not_active_days_keep'))) {
{ $sql = DB()->fetch_rowset("SELECT user_id FROM " . BB_USERS . "
$sql = DB()->fetch_rowset("SELECT user_id FROM ". BB_USERS ."
WHERE user_level = 0 WHERE user_level = 0
AND user_posts = 0 AND user_posts = 0
AND user_lastvisit <= ". (TIMENOW - 86400 * $not_active_days) ." AND user_lastvisit <= " . (TIMENOW - 86400 * $not_active_days) . "
AND user_id NOT IN(". EXCLUDED_USERS .") AND user_id NOT IN(" . EXCLUDED_USERS . ")
LIMIT $users_per_cycle"); LIMIT $users_per_cycle");
foreach ($sql as $row) foreach ($sql as $row) {
{
$not_active_users[] = $row['user_id']; $not_active_users[] = $row['user_id'];
} }
} }
if ($prune_users = $not_activated_users + $not_active_users) if ($prune_users = $not_activated_users + $not_active_users) {
{
user_delete($prune_users); user_delete($prune_users);
} }
if (count($prune_users) < $users_per_cycle) if (count($prune_users) < $users_per_cycle) {
{
break; break;
} }

View file

@ -1,17 +1,18 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if ($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');
$prune_time = TIMENOW - 86400*$di->config->get('topic_moved_days_keep');
DB()->query(" DB()->query("
DELETE FROM ". BB_TOPICS ." DELETE FROM " . BB_TOPICS . "
WHERE topic_status = ". TOPIC_MOVED ." WHERE topic_status = " . TOPIC_MOVED . "
AND topic_time < $prune_time AND topic_time < $prune_time
"); ");
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -13,20 +15,20 @@ $admin_session_gc_time = $admin_session_expire_time;
// ############################ Tables LOCKED ################################ // ############################ Tables LOCKED ################################
DB()->lock(array( DB()->lock(array(
BB_USERS .' u', BB_USERS . ' u',
BB_SESSIONS .' s', BB_SESSIONS . ' s',
)); ));
// Update user's session time // Update user's session time
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_USERS ." u, " . BB_USERS . " u,
". BB_SESSIONS ." s " . BB_SESSIONS . " s
SET SET
u.user_session_time = IF(u.user_session_time < s.session_time, s.session_time, u.user_session_time) u.user_session_time = IF(u.user_session_time < s.session_time, s.session_time, u.user_session_time)
WHERE WHERE
u.user_id = s.session_user_id u.user_id = s.session_user_id
AND s.session_user_id != ". GUEST_UID ." AND s.session_user_id != " . GUEST_UID . "
AND ( AND (
(s.session_time < $user_session_expire_time AND s.session_admin = 0) (s.session_time < $user_session_expire_time AND s.session_admin = 0)
OR OR
@ -42,7 +44,7 @@ sleep(5);
// Delete staled sessions // Delete staled sessions
DB()->query(" DB()->query("
DELETE s DELETE s
FROM ". BB_SESSIONS ." s FROM " . BB_SESSIONS . " s
WHERE WHERE
(s.session_time < $user_session_gc_time AND s.session_admin = 0) (s.session_time < $user_session_gc_time AND s.session_admin = 0)
OR OR

View file

@ -1,14 +1,15 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
require(CLASS_DIR .'sitemap.php'); require(CLASS_DIR . 'sitemap.php');
$map = new sitemap(); $map = new sitemap();
$map->create(); $map->create();
if (file_exists(BB_ROOT. "/sitemap/sitemap.xml")) if (file_exists(BB_ROOT . "/sitemap/sitemap.xml")) {
{
$map_link = make_url('/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://google.com/webmasters/sitemaps/ping?sitemap=", $map_link);

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -12,17 +14,16 @@ define('OLD_BB_BT_LAST_TORSTAT', 'old_bt_last_torstat');
define('NEW_BB_BT_LAST_USERSTAT', 'new_bt_last_userstat'); define('NEW_BB_BT_LAST_USERSTAT', 'new_bt_last_userstat');
define('OLD_BB_BT_LAST_USERSTAT', 'old_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 " . 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 " . 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_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_USERSTAT . " LIKE " . BB_BT_LAST_USERSTAT);
DB()->expect_slow_query(600); DB()->expect_slow_query(600);
// Update dlstat (part 1) // Update dlstat (part 1)
if ($tr_cfg['update_dlstat']) if ($tr_cfg['update_dlstat']) {
{
// ############################ Tables LOCKED ################################ // ############################ Tables LOCKED ################################
DB()->lock(array( DB()->lock(array(
BB_BT_TRACKER, BB_BT_TRACKER,
@ -31,17 +32,17 @@ if ($tr_cfg['update_dlstat'])
// Get PER TORRENT user's dlstat from tracker // Get PER TORRENT user's dlstat from tracker
DB()->query(" DB()->query("
INSERT INTO ". NEW_BB_BT_LAST_TORSTAT ." INSERT INTO " . NEW_BB_BT_LAST_TORSTAT . "
(topic_id, user_id, dl_status, up_add, down_add, release_add, speed_up, speed_down) (topic_id, user_id, dl_status, up_add, down_add, release_add, speed_up, speed_down)
SELECT 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) 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) WHERE (up_add != 0 OR down_add != 0)
GROUP BY topic_id, user_id GROUP BY topic_id, user_id
"); ");
// Reset up/down additions in tracker // Reset up/down additions in tracker
DB()->query("UPDATE ". BB_BT_TRACKER ." SET up_add = 0, down_add = 0"); DB()->query("UPDATE " . BB_BT_TRACKER . " SET up_add = 0, down_add = 0");
DB()->unlock(); DB()->unlock();
// ############################ Tables UNLOCKED ############################## // ############################ Tables UNLOCKED ##############################
@ -49,60 +50,57 @@ if ($tr_cfg['update_dlstat'])
// Update last seeder info in BUF // Update last seeder info in BUF
DB()->query(" DB()->query("
REPLACE INTO ". BUF_LAST_SEEDER ." REPLACE INTO " . BUF_LAST_SEEDER . "
(topic_id, seeder_last_seen) (topic_id, seeder_last_seen)
SELECT SELECT
topic_id, ". TIMENOW ." topic_id, " . TIMENOW . "
FROM ". BB_BT_TRACKER ." FROM " . BB_BT_TRACKER . "
WHERE seeder = 1 WHERE seeder = 1
GROUP BY topic_id GROUP BY topic_id
"); ");
// Clean peers table // Clean peers table
if ($tr_cfg['autoclean']) if ($tr_cfg['autoclean']) {
{
$announce_interval = max(intval($di->config->get('announce_interval')), 60); $announce_interval = max(intval($di->config->get('announce_interval')), 60);
$expire_factor = max(floatval($tr_cfg['expire_factor']), 1); $expire_factor = max(floatval($tr_cfg['expire_factor']), 1);
$peer_expire_time = TIMENOW - floor($announce_interval * $expire_factor); $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) // Update dlstat (part 2)
if ($tr_cfg['update_dlstat']) if ($tr_cfg['update_dlstat']) {
{
// Set "only 1 seeder" bonus // Set "only 1 seeder" bonus
DB()->query(" DB()->query("
UPDATE UPDATE
". NEW_BB_BT_LAST_TORSTAT ." tb, " . NEW_BB_BT_LAST_TORSTAT . " tb,
". BB_BT_TRACKER_SNAP ." sn " . BB_BT_TRACKER_SNAP . " sn
SET SET
tb.bonus_add = tb.up_add tb.bonus_add = tb.up_add
WHERE WHERE
tb.topic_id = sn.topic_id tb.topic_id = sn.topic_id
AND sn.seeders = 1 AND sn.seeders = 1
AND tb.up_add != 0 AND tb.up_add != 0
AND tb.dl_status = ". DL_STATUS_COMPLETE ." AND tb.dl_status = " . DL_STATUS_COMPLETE . "
"); ");
// Get SUMMARIZED user's dlstat // Get SUMMARIZED user's dlstat
DB()->query(" DB()->query("
INSERT INTO ". NEW_BB_BT_LAST_USERSTAT ." INSERT INTO " . NEW_BB_BT_LAST_USERSTAT . "
(user_id, up_add, down_add, release_add, bonus_add, speed_up, speed_down) (user_id, up_add, down_add, release_add, bonus_add, speed_up, speed_down)
SELECT SELECT
user_id, SUM(up_add), SUM(down_add), SUM(release_add), SUM(bonus_add), SUM(speed_up), SUM(speed_down) 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 GROUP BY user_id
"); ");
// Update TOTAL user's dlstat // Update TOTAL user's dlstat
// This is not needed if Ocelot enabled. It's important. // This is not needed if Ocelot enabled. It's important.
if (!$di->config->get('ocelot.enabled')) if (!$di->config->get('ocelot.enabled')) {
{
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_BT_USERS ." u, " . BB_BT_USERS . " u,
". NEW_BB_BT_LAST_USERSTAT ." ub " . NEW_BB_BT_LAST_USERSTAT . " ub
SET SET
u.u_up_total = u.u_up_total + ub.up_add, u.u_up_total = u.u_up_total + ub.up_add,
u.u_down_total = u.u_down_total + ub.down_add, u.u_down_total = u.u_down_total + ub.down_add,
@ -119,42 +117,42 @@ if ($tr_cfg['update_dlstat'])
// Delete from dl_list what exists in BUF but not exsits in NEW // Delete from dl_list what exists in BUF but not exsits in NEW
DB()->query(" DB()->query("
DELETE dl DELETE dl
FROM ". BB_BT_DLSTATUS ." dl FROM " . BB_BT_DLSTATUS . " dl
INNER JOIN ". NEW_BB_BT_LAST_TORSTAT ." buf USING(user_id, topic_id) INNER JOIN " . NEW_BB_BT_LAST_TORSTAT . " buf USING(user_id, topic_id)
WHERE buf.user_id IS NULL WHERE buf.user_id IS NULL
AND buf.topic_id IS NULL AND buf.topic_id IS NULL
"); ");
// Update DL-Status // Update DL-Status
DB()->query(" DB()->query("
REPLACE INTO ". BB_BT_DLSTATUS ." REPLACE INTO " . BB_BT_DLSTATUS . "
(user_id, topic_id, user_status) (user_id, topic_id, user_status)
SELECT SELECT
user_id, topic_id, dl_status 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) // Update PER TORRENT DL-Status (for "completed" counter)
DB()->query(" DB()->query("
INSERT IGNORE INTO ". BB_BT_TORSTAT ." INSERT IGNORE INTO " . BB_BT_TORSTAT . "
(topic_id, user_id) (topic_id, user_id)
SELECT SELECT
topic_id, user_id topic_id, user_id
FROM ". NEW_BB_BT_LAST_TORSTAT ." FROM " . NEW_BB_BT_LAST_TORSTAT . "
WHERE dl_status = ". DL_STATUS_COMPLETE ." WHERE dl_status = " . DL_STATUS_COMPLETE . "
"); ");
} }
DB()->query(" DB()->query("
RENAME TABLE RENAME TABLE
". BB_BT_LAST_TORSTAT ." TO ". OLD_BB_BT_LAST_TORSTAT .", " . BB_BT_LAST_TORSTAT . " TO " . OLD_BB_BT_LAST_TORSTAT . ",
". NEW_BB_BT_LAST_TORSTAT ." TO ". 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(" DB()->query("
RENAME TABLE RENAME TABLE
". BB_BT_LAST_USERSTAT ." TO ". OLD_BB_BT_LAST_USERSTAT .", " . BB_BT_LAST_USERSTAT . " TO " . OLD_BB_BT_LAST_USERSTAT . ",
". NEW_BB_BT_LAST_USERSTAT ." TO ". 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

@ -1,42 +1,41 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if ($di->config->get('ocelot.enabled')) if ($di->config->get('ocelot.enabled')) {
{
// Update TORRENT "completed" counters // Update TORRENT "completed" counters
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_BT_TORRENTS ." tor, " . BB_BT_TORRENTS . " tor,
". BB_BT_TRACKER_SNAP. " snap " . BB_BT_TRACKER_SNAP . " snap
SET SET
tor.complete_count = snap.complete tor.complete_count = snap.complete
WHERE WHERE
tor.topic_id = snap.topic_id tor.topic_id = snap.topic_id
"); ");
} } else {
else
{
// Get complete counts // Get complete counts
DB()->query(" DB()->query("
CREATE TEMPORARY TABLE tmp_complete_count CREATE TEMPORARY TABLE tmp_complete_count
SELECT SELECT
topic_id, COUNT(*) AS compl_cnt topic_id, COUNT(*) AS compl_cnt
FROM ". BB_BT_TORSTAT ." FROM " . BB_BT_TORSTAT . "
WHERE completed = 0 WHERE completed = 0
GROUP BY topic_id GROUP BY topic_id
"); ");
// Update USER "completed" counters // Update USER "completed" counters
DB()->query("UPDATE ". BB_BT_TORSTAT ." SET completed = 1"); DB()->query("UPDATE " . BB_BT_TORSTAT . " SET completed = 1");
// Update TORRENT "completed" counters // Update TORRENT "completed" counters
DB()->query(" DB()->query("
UPDATE UPDATE
". BB_BT_TORRENTS ." tor, " . BB_BT_TORRENTS . " tor,
tmp_complete_count tmp tmp_complete_count tmp
SET SET
tor.complete_count = tor.complete_count + tmp.compl_cnt tor.complete_count = tor.complete_count + tmp.compl_cnt

View file

@ -1,44 +1,43 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (empty($di->config->get('seeder_last_seen_days_keep')) || empty($di->config->get('seeder_never_seen_days_keep'))) if (empty($di->config->get('seeder_last_seen_days_keep')) || empty($di->config->get('seeder_never_seen_days_keep'))) {
{
return; return;
} }
$last_seen_time = TIMENOW - 86400*$di->config->get('seeder_last_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'); $never_seen_time = TIMENOW - 86400 * $di->config->get('seeder_never_seen_days_keep');
$limit_sql = 3000; $limit_sql = 3000;
$topics_sql = []; $topics_sql = [];
$sql = "SELECT topic_id $sql = "SELECT topic_id
FROM ". BB_BT_TORRENTS ." FROM " . BB_BT_TORRENTS . "
WHERE reg_time < $never_seen_time WHERE reg_time < $never_seen_time
AND seeder_last_seen < $last_seen_time AND seeder_last_seen < $last_seen_time
LIMIT $limit_sql"; LIMIT $limit_sql";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$topics_sql[] = $row['topic_id']; $topics_sql[] = $row['topic_id'];
} }
$dead_tor_sql = join(',', $topics_sql); $dead_tor_sql = join(',', $topics_sql);
if ($dead_tor_sql) if ($dead_tor_sql) {
{
// Delete torstat // Delete torstat
DB()->query(" DB()->query("
DELETE FROM ". BB_BT_TORSTAT ." DELETE FROM " . BB_BT_TORSTAT . "
WHERE topic_id IN($dead_tor_sql) WHERE topic_id IN($dead_tor_sql)
"); ");
// Remove torrents // Remove torrents
DB()->query(" DB()->query("
DELETE FROM ". BB_BT_TORRENTS ." DELETE FROM " . BB_BT_TORRENTS . "
WHERE topic_id IN($dead_tor_sql) WHERE topic_id IN($dead_tor_sql)
"); ");
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -10,8 +12,7 @@ DB()->expect_slow_query(600);
// //
// Make tracker snapshot // Make tracker snapshot
// //
if (!$di->config->get('ocelot.enabled')) if (!$di->config->get('ocelot.enabled')) {
{
define('NEW_BB_BT_TRACKER_SNAP', 'new_tracker_snap'); define('NEW_BB_BT_TRACKER_SNAP', 'new_tracker_snap');
define('OLD_BB_BT_TRACKER_SNAP', 'old_tracker_snap'); define('OLD_BB_BT_TRACKER_SNAP', 'old_tracker_snap');
@ -20,19 +21,17 @@ if (!$di->config->get('ocelot.enabled'))
} }
$per_cycle = 50000; $per_cycle = 50000;
$row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finish_id FROM ". BB_BT_TRACKER); $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']; $start_id = (int)$row['start_id'];
$finish_id = (int) $row['finish_id']; $finish_id = (int)$row['finish_id'];
while (true) while (true) {
{
set_time_limit(600); set_time_limit(600);
$end_id = $start_id + $per_cycle - 1; $end_id = $start_id + $per_cycle - 1;
$val = array(); $val = array();
if (!$di->config->get('ocelot.enabled')) if (!$di->config->get('ocelot.enabled')) {
{
$sql = " $sql = "
SELECT SELECT
topic_id, SUM(seeder) AS seeders, (COUNT(*) - SUM(seeder)) AS leechers, topic_id, SUM(seeder) AS seeders, (COUNT(*) - SUM(seeder)) AS leechers,
@ -41,9 +40,7 @@ while (true)
WHERE topic_id BETWEEN $start_id AND $end_id WHERE topic_id BETWEEN $start_id AND $end_id
GROUP BY topic_id GROUP BY topic_id
"; ";
} } else {
else
{
$sql = " $sql = "
SELECT SELECT
topic_id, SUM(speed_up) AS speed_up, SUM(speed_down) AS speed_down topic_id, SUM(speed_up) AS speed_up, SUM(speed_down) AS speed_down
@ -53,54 +50,46 @@ while (true)
"; ";
} }
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$val[] = join(',', $row); $val[] = join(',', $row);
} }
if ($val) if ($val) {
{ if (!$di->config->get('ocelot.enabled')) {
if (!$di->config->get('ocelot.enabled'))
{
DB()->query(" DB()->query("
REPLACE INTO " . NEW_BB_BT_TRACKER_SNAP . " REPLACE INTO " . NEW_BB_BT_TRACKER_SNAP . "
(topic_id, seeders, leechers, speed_up, speed_down) (topic_id, seeders, leechers, speed_up, speed_down)
VALUES(" . join('),(', $val) . ") VALUES(" . join('),(', $val) . ")
"); ");
} } else {
else
{
DB()->query(" DB()->query("
INSERT INTO " . BB_BT_TRACKER_SNAP . " INSERT INTO " . BB_BT_TRACKER_SNAP . "
(topic_id, speed_up, speed_down) (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) ON DUPLICATE KEY UPDATE speed_up = VALUES(speed_up), speed_down = VALUES(speed_down)
"); ");
} }
} }
if ($end_id > $finish_id) if ($end_id > $finish_id) {
{
break; break;
} }
if (!($start_id % ($per_cycle*10))) if (!($start_id % ($per_cycle * 10))) {
{
sleep(1); sleep(1);
} }
$start_id += $per_cycle; $start_id += $per_cycle;
} }
if (!$di->config->get('ocelot.enabled')) if (!$di->config->get('ocelot.enabled')) {
{
DB()->query(" DB()->query("
RENAME TABLE RENAME TABLE
". BB_BT_TRACKER_SNAP ." TO ". OLD_BB_BT_TRACKER_SNAP .", " . BB_BT_TRACKER_SNAP . " TO " . OLD_BB_BT_TRACKER_SNAP . ",
". NEW_BB_BT_TRACKER_SNAP ." TO ". 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,36 +98,34 @@ if (!$di->config->get('ocelot.enabled'))
define('NEW_BB_BT_DLSTATUS_SNAP', 'new_dlstatus_snap'); define('NEW_BB_BT_DLSTATUS_SNAP', 'new_dlstatus_snap');
define('OLD_BB_BT_DLSTATUS_SNAP', 'old_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')) if ($di->config->get('bt_show_dl_list') && $di->config->get('bt_dl_list_only_count')) {
{
DB()->query(" DB()->query("
INSERT INTO ". NEW_BB_BT_DLSTATUS_SNAP ." INSERT INTO " . NEW_BB_BT_DLSTATUS_SNAP . "
(topic_id, dl_status, users_count) (topic_id, dl_status, users_count)
SELECT SELECT
topic_id, user_status, COUNT(*) topic_id, user_status, COUNT(*)
FROM ". BB_BT_DLSTATUS ." FROM " . BB_BT_DLSTATUS . "
WHERE user_status != ". DL_STATUS_RELEASER ." WHERE user_status != " . DL_STATUS_RELEASER . "
GROUP BY topic_id, user_status GROUP BY topic_id, user_status
"); ");
} }
DB()->query(" DB()->query("
RENAME TABLE RENAME TABLE
". BB_BT_DLSTATUS_SNAP ." TO ". OLD_BB_BT_DLSTATUS_SNAP .", " . BB_BT_DLSTATUS_SNAP . " TO " . OLD_BB_BT_DLSTATUS_SNAP . ",
". NEW_BB_BT_DLSTATUS_SNAP ." TO ". 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 // TORHELP
// //
if ($di->config->get('torhelp_enabled')) if ($di->config->get('torhelp_enabled')) {
{
$tor_min_seeders = 0; // "<=" $tor_min_seeders = 0; // "<="
$tor_min_leechers = 2; // ">=" $tor_min_leechers = 2; // ">="
$tor_min_completed = 10; // ">=" $tor_min_completed = 10; // ">="
@ -151,43 +138,41 @@ if ($di->config->get('torhelp_enabled'))
define('NEW_BB_BT_TORHELP', 'new_torhelp'); define('NEW_BB_BT_TORHELP', 'new_torhelp');
define('OLD_BB_BT_TORHELP', 'old_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 // Select users
$sql = " $sql = "
SELECT DISTINCT session_user_id AS uid SELECT DISTINCT session_user_id AS uid
FROM ". BB_SESSIONS ." FROM " . BB_SESSIONS . "
WHERE session_time > (UNIX_TIMESTAMP() - $user_last_seen_online*60) 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 ORDER BY session_time DESC
LIMIT $users_limit LIMIT $users_limit
"; ";
$online_users_ary = array(); $online_users_ary = array();
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$online_users_ary[] = $row['uid']; $online_users_ary[] = $row['uid'];
} }
if ($online_users_csv = join(',', $online_users_ary)) if ($online_users_csv = join(',', $online_users_ary)) {
{
DB()->query(" DB()->query("
INSERT INTO ". NEW_BB_BT_TORHELP ." (user_id, topic_id_csv) INSERT INTO " . NEW_BB_BT_TORHELP . " (user_id, topic_id_csv)
SELECT SELECT
dl.user_id, GROUP_CONCAT(dl.topic_id) dl.user_id, GROUP_CONCAT(dl.topic_id)
FROM ". BB_BT_TRACKER_SNAP ." trsn FROM " . BB_BT_TRACKER_SNAP . " trsn
INNER JOIN ". BB_BT_TORRENTS ." tor ON (tor.topic_id = trsn.topic_id) 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) INNER JOIN " . BB_BT_DLSTATUS . " dl ON (dl.topic_id = tor.topic_id)
WHERE WHERE
trsn.seeders <= $tor_min_seeders trsn.seeders <= $tor_min_seeders
AND trsn.leechers >= $tor_min_leechers 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.complete_count >= $tor_min_completed
AND tor.seeder_last_seen <= (UNIX_TIMESTAMP() - $tor_seed_last_seen_days*86400) AND tor.seeder_last_seen <= (UNIX_TIMESTAMP() - $tor_seed_last_seen_days*86400)
AND dl.user_id IN($online_users_csv) 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) AND dl.last_modified_dlstatus > DATE_SUB(NOW(), INTERVAL $tor_downloaded_days_ago DAY)
GROUP BY dl.user_id GROUP BY dl.user_id
LIMIT 10000 LIMIT 10000
@ -196,11 +181,11 @@ if ($di->config->get('torhelp_enabled'))
DB()->query(" DB()->query("
RENAME TABLE RENAME TABLE
". BB_BT_TORHELP ." TO ". OLD_BB_BT_TORHELP .", " . BB_BT_TORHELP . " TO " . OLD_BB_BT_TORHELP . ",
". NEW_BB_BT_TORHELP ." TO ". 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

@ -1,14 +1,15 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
DB()->expect_slow_query(600); DB()->expect_slow_query(600);
if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_points') && $di->config->get('seed_bonus_release')) if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_points') && $di->config->get('seed_bonus_release')) {
{
DB()->query(" DB()->query("
CREATE TEMPORARY TABLE tmp_bonus ( CREATE TEMPORARY TABLE tmp_bonus (
user_id INT UNSIGNED NOT NULL DEFAULT '0', user_id INT UNSIGNED NOT NULL DEFAULT '0',
@ -20,7 +21,7 @@ if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_point
DB()->query("INSERT INTO tmp_bonus DB()->query("INSERT INTO tmp_bonus
SELECT bt.user_id, count(bt.seeder) AS release_count 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 WHERE tor.topic_id = bt.topic_id
AND tor.size > $tor_size AND tor.size > $tor_size
AND bt.seeder > 0 AND bt.seeder > 0
@ -30,16 +31,17 @@ if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_point
$seed_bonus = unserialize($di->config->get('seed_bonus_points')); $seed_bonus = unserialize($di->config->get('seed_bonus_points'));
$seed_release = unserialize($di->config->get('seed_bonus_release')); $seed_release = unserialize($di->config->get('seed_bonus_release'));
foreach($seed_bonus as $i => $points) foreach ($seed_bonus as $i => $points) {
{ if (!$points || !$seed_release[$i]) {
if (!$points || !$seed_release[$i]) continue; continue;
}
$user_points = ((float) $points / 4); $user_points = ((float)$points / 4);
$release = (int) $seed_release[$i]; $release = (int)$seed_release[$i];
$user_regdate = (TIMENOW - $di->config->get('seed_bonus_user_regdate') * 86400); $user_regdate = (TIMENOW - $di->config->get('seed_bonus_user_regdate') * 86400);
DB()->query(" DB()->query("
UPDATE ". BB_USERS ." u, ". BB_BT_USERS ." bu, tmp_bonus b UPDATE " . BB_USERS . " u, " . BB_BT_USERS . " bu, tmp_bonus b
SET SET
u.user_points = u.user_points + '$user_points', u.user_points = u.user_points + '$user_points',
bu.points_today = bu.points_today + '$user_points', bu.points_today = bu.points_today + '$user_points',
@ -50,7 +52,7 @@ if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_point
AND b.release_count <= $release AND b.release_count <= $release
AND u.user_regdate < $user_regdate AND u.user_regdate < $user_regdate
AND u.user_active = 1 AND u.user_active = 1
AND u.user_id not IN(". EXCLUDED_USERS .") AND u.user_id not IN(" . EXCLUDED_USERS . ")
"); ");
} }

View file

@ -1,15 +1,17 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
DB()->query(" DB()->query("
UPDATE UPDATE
". BUF_LAST_SEEDER ." b, " . BUF_LAST_SEEDER . " b,
". BB_BT_TORRENTS ." tor " . BB_BT_TORRENTS . " tor
SET SET
tor.seeder_last_seen = b.seeder_last_seen tor.seeder_last_seen = b.seeder_last_seen
WHERE WHERE
tor.topic_id = b.topic_id tor.topic_id = b.topic_id
"); ");
DB()->query("TRUNCATE TABLE ". BUF_LAST_SEEDER); DB()->query("TRUNCATE TABLE " . BUF_LAST_SEEDER);

View file

@ -1,32 +1,31 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
require_once(INC_DIR .'functions_atom.php'); require_once(INC_DIR . 'functions_atom.php');
$timecheck = TIMENOW - 600; $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 (file_exists($di->config->get('atom.path') . '/f/0.atom')) {
{ if (filemtime($di->config->get('atom.path') . '/f/0.atom') <= $timecheck) {
if (filemtime($di->config->get('atom.path') .'/f/0.atom') <= $timecheck) update_forum_feed(0, $forums_data); update_forum_feed(0, $forums_data);
} }
else } else {
{
update_forum_feed(0, $forums_data); update_forum_feed(0, $forums_data);
} }
foreach ($forums_data as $forum_data) foreach ($forums_data as $forum_data) {
{ if (file_exists($di->config->get('atom.path') . '/f/' . $forum_data['forum_id'] . '.atom')) {
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);
if (filemtime($di->config->get('atom.path') .'/f/'. $forum_data['forum_id'] .'.atom') <= $timecheck) update_forum_feed($forum_data['forum_id'], $forum_data);
} }
else } else {
{
update_forum_feed($forum_data['forum_id'], $forum_data); update_forum_feed($forum_data['forum_id'], $forum_data);
} }
} }

View file

@ -1,23 +1,34 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_apc extends datastore_common class datastore_apc extends datastore_common
{ {
var $engine = 'APC'; public $engine = 'APC';
var $prefix = null; public $prefix = null;
function datastore_apc ($prefix = null) /**
{ * datastore_apc constructor.
if (!$this->is_installed()) * @param null $prefix
* @return datastore_apc
*/
public function datastore_apc($prefix = null)
{ {
if (!$this->is_installed()) {
die('Error: APC extension not installed'); die('Error: APC extension not installed');
} }
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store ($title, $var) /**
* @param $title
* @param $var
* @return bool
*/
public function store($title, $var)
{ {
$this->data[$title] = $var; $this->data[$title] = $var;
@ -27,13 +38,15 @@ class datastore_apc extends datastore_common
$this->cur_query = null; $this->cur_query = null;
$this->num_queries++; $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) */
public function clean()
{ {
foreach ($this->known_items as $title => $script_name) {
$this->cur_query = "cache->rm('$title')"; $this->cur_query = "cache->rm('$title')";
$this->debug('start'); $this->debug('start');
$this->debug('stop'); $this->debug('stop');
@ -44,16 +57,17 @@ class datastore_apc extends datastore_common
} }
} }
function _fetch_from_store () /**
{ * Получение из кеша
if (!$items = $this->queued_items) */
public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');
trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR);
} }
foreach ($items as $item) foreach ($items as $item) {
{
$this->cur_query = "cache->get('$item')"; $this->cur_query = "cache->get('$item')";
$this->debug('start'); $this->debug('start');
$this->debug('stop'); $this->debug('stop');
@ -64,7 +78,10 @@ class datastore_apc extends datastore_common
} }
} }
function is_installed () /**
* @return bool
*/
public function is_installed()
{ {
return function_exists('apc_fetch'); return function_exists('apc_fetch');
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
global $bf; global $bf;
@ -38,57 +40,49 @@ $forum_store_fields += array_flip(array(
)); ));
// Categories // 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) foreach (DB()->fetch_rowset($sql) as $row) {
{
$data['c'][$row['cat_id']] = $row; $data['c'][$row['cat_id']] = $row;
$data['cat_title_html'][$row['cat_id']] = htmlCHR($row['cat_title']); $data['cat_title_html'][$row['cat_id']] = htmlCHR($row['cat_title']);
} }
$sql = " $sql = "
SELECT f.* SELECT f.*
FROM ". BB_FORUMS ." f, ". BB_CATEGORIES ." c FROM " . BB_FORUMS . " f, " . BB_CATEGORIES . " c
WHERE f.cat_id = c.cat_id WHERE f.cat_id = c.cat_id
ORDER BY c.cat_order, f.forum_order ORDER BY c.cat_order, f.forum_order
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$fid = $row['forum_id']; $fid = $row['forum_id'];
$not_auth =& $data['not_auth_forums']; $not_auth =& $data['not_auth_forums'];
// Find not auth forums // Find not auth forums
if ($row['auth_view'] != AUTH_ALL) if ($row['auth_view'] != AUTH_ALL) {
{
$not_auth['guest_view'][] = $fid; $not_auth['guest_view'][] = $fid;
} }
if ($row['auth_view'] != AUTH_ALL && $row['auth_view'] != AUTH_REG) if ($row['auth_view'] != AUTH_ALL && $row['auth_view'] != AUTH_REG) {
{
$not_auth['user_view'][] = $fid; $not_auth['user_view'][] = $fid;
} }
if ($row['auth_read'] != AUTH_ALL) if ($row['auth_read'] != AUTH_ALL) {
{
$not_auth['guest_read'][] = $fid; $not_auth['guest_read'][] = $fid;
} }
if ($row['auth_read'] != AUTH_ALL && $row['auth_read'] != AUTH_REG) if ($row['auth_read'] != AUTH_ALL && $row['auth_read'] != AUTH_REG) {
{
$not_auth['user_read'][] = $fid; $not_auth['user_read'][] = $fid;
} }
$data['forum'][$fid] = $row; $data['forum'][$fid] = $row;
// Store forums data // Store forums data
if ($parent_id = $row['forum_parent']) if ($parent_id = $row['forum_parent']) {
{
$parent =& $data['f'][$parent_id]; $parent =& $data['f'][$parent_id];
$parent['subforums'][] = $fid; $parent['subforums'][] = $fid;
$parent['forum_posts'] += $row['forum_posts']; $parent['forum_posts'] += $row['forum_posts'];
$parent['forum_topics'] += $row['forum_topics']; $parent['forum_topics'] += $row['forum_topics'];
} }
if ($row['allow_reg_tracker']) if ($row['allow_reg_tracker']) {
{
$data['tracker_forums'][] = $fid; $data['tracker_forums'][] = $fid;
} }
@ -98,8 +92,7 @@ foreach (DB()->fetch_rowset($sql) as $row)
// Forum ids in cat // Forum ids in cat
$data['c'][$row['cat_id']]['forums'][] = $fid; $data['c'][$row['cat_id']]['forums'][] = $fid;
} }
foreach ($data['not_auth_forums'] as $key => $val) foreach ($data['not_auth_forums'] as $key => $val) {
{
$data['not_auth_forums'][$key] = join(',', $val); $data['not_auth_forums'][$key] = join(',', $val);
} }
$data['tracker_forums'] = join(',', $data['tracker_forums']); $data['tracker_forums'] = join(',', $data['tracker_forums']);
@ -116,8 +109,8 @@ $data = array(
$this->store('jumpbox', $data); $this->store('jumpbox', $data);
file_write($data['guest'], AJAX_HTML_DIR .'jumpbox_guest.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); file_write($data['user'], AJAX_HTML_DIR . 'jumpbox_user.html', false, true, true);
// //
// viewtopic_forum_select // viewtopic_forum_select
@ -131,13 +124,12 @@ $this->store('viewtopic_forum_select', $data);
// //
// latest_news // latest_news
// //
if ($di->config->get('show_latest_news') && ($news_forum_ids = $di->config->get('latest_news_forum_id'))) 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); $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 SELECT topic_id, topic_time, topic_title, forum_id
FROM ". BB_TOPICS ." FROM " . BB_TOPICS . "
WHERE forum_id IN ($news_forum_ids) WHERE forum_id IN ($news_forum_ids)
AND topic_moved_id = 0 AND topic_moved_id = 0
ORDER BY topic_time DESC ORDER BY topic_time DESC
@ -150,13 +142,12 @@ if ($di->config->get('show_latest_news') && ($news_forum_ids = $di->config->get(
// //
// Network_news // Network_news
// //
if ($di->config->get('show_network_news') && ($net_forum_ids = $di->config->get('network_news_forum_id'))) 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); $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 SELECT topic_id, topic_time, topic_title, forum_id
FROM ". BB_TOPICS ." FROM " . BB_TOPICS . "
WHERE forum_id IN ($net_forum_ids) WHERE forum_id IN ($net_forum_ids)
AND topic_moved_id = 0 AND topic_moved_id = 0
ORDER BY topic_time DESC ORDER BY topic_time DESC

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$data = array( $data = array(
'name_users' => array(), // only by personal permissions 'name_users' => array(), // only by personal permissions
@ -17,12 +19,12 @@ $sql = "
SELECT SELECT
aa.forum_id, u.user_id, u.username aa.forum_id, u.user_id, u.username
FROM FROM
". BB_AUTH_ACCESS ." aa, " . BB_AUTH_ACCESS . " aa,
". BB_USER_GROUP ." ug, " . BB_USER_GROUP . " ug,
". BB_GROUPS ." g, " . BB_GROUPS . " g,
". BB_USERS ." u " . BB_USERS . " u
WHERE WHERE
aa.forum_perm & ". BF_AUTH_MOD ." aa.forum_perm & " . BF_AUTH_MOD . "
AND ug.group_id = aa.group_id AND ug.group_id = aa.group_id
AND ug.user_pending = 0 AND ug.user_pending = 0
AND g.group_id = ug.group_id AND g.group_id = ug.group_id
@ -34,8 +36,7 @@ $sql = "
u.username u.username
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$data['name_users'][$row['user_id']] = $row['username']; $data['name_users'][$row['user_id']] = $row['username'];
$data['mod_users'][$row['forum_id']][] = $row['user_id']; $data['mod_users'][$row['forum_id']][] = $row['user_id'];
} }
@ -46,21 +47,20 @@ $sql = "
SELECT SELECT
aa.forum_id, g.group_id, g.group_name aa.forum_id, g.group_id, g.group_name
FROM FROM
". BB_AUTH_ACCESS ." aa, " . BB_AUTH_ACCESS . " aa,
". BB_GROUPS ." g " . BB_GROUPS . " g
WHERE WHERE
aa.forum_perm & ". BF_AUTH_MOD ." aa.forum_perm & " . BF_AUTH_MOD . "
AND g.group_id = aa.group_id AND g.group_id = aa.group_id
AND g.group_single_user = 0 AND g.group_single_user = 0
AND g.group_type != ". GROUP_HIDDEN ." AND g.group_type != " . GROUP_HIDDEN . "
GROUP BY GROUP BY
aa.forum_id, g.group_id aa.forum_id, g.group_id
ORDER BY ORDER BY
g.group_name g.group_name
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$data['name_groups'][$row['group_id']] = $row['group_name']; $data['name_groups'][$row['group_id']] = $row['group_name'];
$data['mod_groups'][$row['forum_id']][] = $row['group_id']; $data['mod_groups'][$row['forum_id']][] = $row['group_id'];
} }
@ -70,12 +70,12 @@ $sql = "
SELECT SELECT
u.user_id, u.username u.user_id, u.username
FROM FROM
". BB_AUTH_ACCESS ." aa, " . BB_AUTH_ACCESS . " aa,
". BB_USER_GROUP ." ug, " . BB_USER_GROUP . " ug,
". BB_GROUPS ." g, " . BB_GROUPS . " g,
". BB_USERS ." u " . BB_USERS . " u
WHERE WHERE
aa.forum_perm & ". BF_AUTH_MOD ." aa.forum_perm & " . BF_AUTH_MOD . "
AND ug.group_id = aa.group_id AND ug.group_id = aa.group_id
AND ug.user_pending = 0 AND ug.user_pending = 0
AND g.group_id = ug.group_id AND g.group_id = ug.group_id
@ -86,21 +86,19 @@ $sql = "
u.username u.username
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$data['moderators'][$row['user_id']] = $row['username']; $data['moderators'][$row['user_id']] = $row['username'];
} }
// admins // admins
$sql = " $sql = "
SELECT user_id, username SELECT user_id, username
FROM ". BB_USERS ." FROM " . BB_USERS . "
WHERE user_level = ". ADMIN ." WHERE user_level = " . ADMIN . "
ORDER BY username ORDER BY username
"; ";
foreach (DB()->fetch_rowset($sql) as $row) foreach (DB()->fetch_rowset($sql) as $row) {
{
$data['admins'][$row['user_id']] = $row['username']; $data['admins'][$row['user_id']] = $row['username'];
} }

View file

@ -1,13 +1,14 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$ranks = array(); $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) foreach (DB()->fetch_rowset($sql) as $row) {
{
$ranks[$row['rank_id']] = $row; $ranks[$row['rank_id']] = $row;
} }

View file

@ -1,19 +1,20 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
$smilies = []; $smilies = [];
$rowset = DB()->fetch_rowset("SELECT * FROM ". BB_SMILIES); $rowset = DB()->fetch_rowset("SELECT * FROM " . BB_SMILIES);
sort($rowset); sort($rowset);
foreach ($rowset as $smile) foreach ($rowset as $smile) {
{ $smilies['orig'][] = '#(?<=^|\W)' . preg_quote($smile['code'], '#') . '(?=$|\W)#';
$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['repl'][] = ' <img class="smile" src="'. $di->config->get('smilies_path') .'/'. $smile['smile_url'] .'" alt="'. $smile['emoticon'] .'" align="absmiddle" border="0" />';
$smilies['smile'][] = $smile; $smilies['smile'][] = $smile;
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -8,28 +10,27 @@ $di = \TorrentPier\Di::getInstance();
$data = []; $data = [];
// usercount // 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']); $data['usercount'] = commify($row['usercount']);
// newestuser // 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; $data['newestuser'] = $row;
// post/topic count // 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['postcount'] = commify($row['postcount']);
$data['topiccount'] = commify($row['topiccount']); $data['topiccount'] = commify($row['topiccount']);
// Tracker stats // Tracker stats
if ($di->config->get('tor_stats')) if ($di->config->get('tor_stats')) {
{
// torrents stat // torrents stat
$row = DB()->fetch_row("SELECT COUNT(topic_id) AS torrentcount, SUM(size) AS size FROM ". BB_BT_TORRENTS); $row = DB()->fetch_row("SELECT COUNT(topic_id) AS torrentcount, SUM(size) AS size FROM " . BB_BT_TORRENTS);
$data['torrentcount'] = commify($row['torrentcount']); $data['torrentcount'] = commify($row['torrentcount']);
$data['size'] = $row['size']; $data['size'] = $row['size'];
// peers stat // 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); $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['seeders'] = commify($row['seeders']);
$data['leechers'] = commify($row['leechers']); $data['leechers'] = commify($row['leechers']);
$data['peers'] = commify($row['seeders'] + $row['leechers']); $data['peers'] = commify($row['seeders'] + $row['leechers']);
@ -37,11 +38,10 @@ if ($di->config->get('tor_stats'))
} }
// gender stat // gender stat
if ($di->config->get('gender')) 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 . ")");
$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 . ")");
$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 . ")");
$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['male'] = $male['male'];
$data['female'] = $female['female']; $data['female'] = $female['female'];
@ -49,27 +49,24 @@ if ($di->config->get('gender'))
} }
// birthday stat // birthday stat
if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled')) {
{
$sql = DB()->fetch_rowset("SELECT user_id, username, user_rank , user_birthday $sql = DB()->fetch_rowset("SELECT user_id, username, user_rank , user_birthday
FROM ". BB_USERS ." FROM " . BB_USERS . "
WHERE user_id NOT IN(". EXCLUDED_USERS .") WHERE user_id NOT IN(" . EXCLUDED_USERS . ")
AND user_birthday != '0000-00-00' AND user_birthday != '0000-00-00'
AND user_active = 1 AND user_active = 1
ORDER BY user_level DESC, username ORDER BY user_level DESC, username
"); ");
$date_today = bb_date(TIMENOW, 'md', false); $date_today = bb_date(TIMENOW, 'md', false);
$date_forward = bb_date(TIMENOW + ($di->config->get('birthday_check_day')*86400), '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) foreach ($sql as $row) {
{
$user_birthday = date('md', strtotime($row['user_birthday'])); $user_birthday = date('md', strtotime($row['user_birthday']));
if ($user_birthday > $date_today && $user_birthday <= $date_forward) if ($user_birthday > $date_today && $user_birthday <= $date_forward) {
{
// user are having birthday within the next days // user are having birthday within the next days
$birthday_week_list[] = array( $birthday_week_list[] = array(
'user_id' => $row['user_id'], 'user_id' => $row['user_id'],
@ -77,9 +74,7 @@ if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled
'user_rank' => $row['user_rank'], 'user_rank' => $row['user_rank'],
'user_birthday' => $row['user_birthday'], 'user_birthday' => $row['user_birthday'],
); );
} } elseif ($user_birthday == $date_today) {
elseif ($user_birthday == $date_today)
{
//user have birthday today //user have birthday today
$birthday_today_list[] = array( $birthday_today_list[] = array(
'user_id' => $row['user_id'], 'user_id' => $row['user_id'],

View file

@ -1,30 +1,32 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_common class datastore_common
{ {
/** /**
* Директория с builder-скриптами (внутри INC_DIR) * Директория с builder-скриптами (внутри INC_DIR)
*/ */
var $ds_dir = 'datastore/'; public $ds_dir = 'datastore/';
/** /**
* Готовая к употреблению data * Готовая к употреблению data
* array('title' => data) * array('title' => data)
*/ */
var $data = array(); public $data = array();
/** /**
* Список элементов, которые будут извлечены из хранилища при первом же запросе get() * Список элементов, которые будут извлечены из хранилища при первом же запросе get()
* до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем * до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем
* всех элементов одним запросом * всех элементов одним запросом
* array('title1', 'title2'...) * array('title1', 'title2'...)
*/ */
var $queued_items = array(); public $queued_items = array();
/** /**
* 'title' => 'builder script name' inside "includes/datastore" dir * 'title' => 'builder script name' inside "includes/datastore" dir
*/ */
var $known_items = array( public $known_items = array(
'cat_forums' => 'build_cat_forums.php', 'cat_forums' => 'build_cat_forums.php',
'jumpbox' => 'build_cat_forums.php', 'jumpbox' => 'build_cat_forums.php',
'viewtopic_forum_select' => 'build_cat_forums.php', 'viewtopic_forum_select' => 'build_cat_forums.php',
@ -39,63 +41,76 @@ class datastore_common
/** /**
* Constructor * Constructor
*/ */
function datastore_common () {} public function datastore_common()
{
}
/** /**
* @param array(item1_title, item2_title...) or single item's title * @param array(item1_title, item2_title...) or single item's title
*/ */
function enqueue ($items) public function enqueue($items)
{
foreach ((array) $items as $item)
{ {
foreach ((array)$items as $item) {
// игнор уже поставленного в очередь либо уже извлеченного // игнор уже поставленного в очередь либо уже извлеченного
if (!in_array($item, $this->queued_items) && !isset($this->data[$item])) if (!in_array($item, $this->queued_items) && !isset($this->data[$item])) {
{
$this->queued_items[] = $item; $this->queued_items[] = $item;
} }
} }
} }
function &get ($title) /**
{ * @param $title
if (!isset($this->data[$title])) * @return mixed
*/
public function &get($title)
{ {
if (!isset($this->data[$title])) {
$this->enqueue($title); $this->enqueue($title);
$this->_fetch(); $this->_fetch();
} }
return $this->data[$title]; return $this->data[$title];
} }
function store ($item_name, $item_data) {} /**
* @param $item_name
* @param $item_data
*/
public function store($item_name, $item_data)
{
}
function rm ($items) /**
{ * @param $items
foreach ((array) $items as $item) */
public function rm($items)
{ {
foreach ((array)$items as $item) {
unset($this->data[$item]); unset($this->data[$item]);
} }
} }
function update ($items) /**
{ * @param $items
if ($items == 'all') */
public function update($items)
{ {
if ($items == 'all') {
$items = array_keys(array_unique($this->known_items)); $items = array_keys(array_unique($this->known_items));
} }
foreach ((array) $items as $item) foreach ((array)$items as $item) {
{
$this->_build_item($item); $this->_build_item($item);
} }
} }
function _fetch () /**
* Получение
*/
public function _fetch()
{ {
$this->_fetch_from_store(); $this->_fetch_from_store();
foreach ($this->queued_items as $title) foreach ($this->queued_items as $title) {
{ if (!isset($this->data[$title]) || $this->data[$title] === false) {
if (!isset($this->data[$title]) || $this->data[$title] === false)
{
$this->_build_item($title); $this->_build_item($title);
} }
} }
@ -103,40 +118,50 @@ class datastore_common
$this->queued_items = array(); $this->queued_items = array();
} }
function _fetch_from_store () {} /**
* Получение из кеша
function _build_item ($title) */
public function _fetch_from_store()
{ {
if (!empty($this->known_items[$title]))
{
require(INC_DIR . $this->ds_dir . $this->known_items[$title]);
} }
else
/**
* @param $title
*/
public 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); trigger_error("Unknown datastore item: $title", E_USER_ERROR);
} }
} }
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $cur_query_time = 0; public $cur_query_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
function debug ($mode, $cur_query = null) /**
* @param $mode
* @param null $cur_query
*/
public function debug($mode, $cur_query = null)
{ {
if (!$this->dbg_enabled) return; if (!$this->dbg_enabled) {
return;
}
$id =& $this->dbg_id; $id =& $this->dbg_id;
$dbg =& $this->dbg[$id]; $dbg =& $this->dbg[$id];
if ($mode == 'start') if ($mode == 'start') {
{
$this->sql_starttime = utime(); $this->sql_starttime = utime();
$dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query); $dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query);
@ -144,9 +169,7 @@ class datastore_common
$dbg['file'] = $this->debug_find_source('file'); $dbg['file'] = $this->debug_find_source('file');
$dbg['line'] = $this->debug_find_source('line'); $dbg['line'] = $this->debug_find_source('line');
$dbg['time'] = ''; $dbg['time'] = '';
} } elseif ($mode == 'stop') {
else if ($mode == 'stop')
{
$this->cur_query_time = utime() - $this->sql_starttime; $this->cur_query_time = utime() - $this->sql_starttime;
$this->sql_timetotal += $this->cur_query_time; $this->sql_timetotal += $this->cur_query_time;
$dbg['time'] = $this->cur_query_time; $dbg['time'] = $this->cur_query_time;
@ -154,17 +177,21 @@ class datastore_common
} }
} }
function debug_find_source ($mode = '') /**
* @param string $mode
* @return string
*/
public function debug_find_source($mode = '')
{ {
foreach (debug_backtrace() as $trace) foreach (debug_backtrace() as $trace) {
{ if ($trace['file'] !== __FILE__) {
if ($trace['file'] !== __FILE__) switch ($mode) {
{ case 'file':
switch ($mode) return $trace['file'];
{ case 'line':
case 'file': return $trace['file']; return $trace['line'];
case 'line': return $trace['line']; default:
default: return hide_bb_path($trace['file']) .'('. $trace['line'] .')'; return hide_bb_path($trace['file']) . '(' . $trace['line'] . ')';
} }
} }
} }

View file

@ -1,21 +1,34 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_file extends datastore_common class datastore_file extends datastore_common
{ {
var $dir = null; public $dir = null;
var $prefix = null; public $prefix = null;
var $engine = 'Filecache'; public $engine = 'Filecache';
function datastore_file ($dir, $prefix = null) /**
* datastore_file constructor.
* @param $dir
* @param null $prefix
* @return datastore_file
*/
public function datastore_file($dir, $prefix = null)
{ {
$this->prefix = $prefix; $this->prefix = $prefix;
$this->dir = $dir; $this->dir = $dir;
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function store ($title, $var) /**
* @param $title
* @param $var
* @return bool
*/
public function store($title, $var)
{ {
$this->cur_query = "cache->set('$title')"; $this->cur_query = "cache->set('$title')";
$this->debug('start'); $this->debug('start');
@ -33,21 +46,20 @@ class datastore_file extends datastore_common
$this->cur_query = null; $this->cur_query = null;
$this->num_queries++; $this->num_queries++;
return (bool) file_write($filecache, $filename, false, true, true); return (bool)file_write($filecache, $filename, false, true, true);
} }
function clean () /**
* Очистка
*/
public function clean()
{ {
$dir = $this->dir; $dir = $this->dir;
if (is_dir($dir)) if (is_dir($dir)) {
{ if ($dh = opendir($dir)) {
if ($dh = opendir($dir)) while (($file = readdir($dh)) !== false) {
{ if ($file != "." && $file != "..") {
while (($file = readdir($dh)) !== false)
{
if ($file != "." && $file != "..")
{
$filename = $dir . $file; $filename = $dir . $file;
unlink($filename); unlink($filename);
@ -58,16 +70,17 @@ class datastore_file extends datastore_common
} }
} }
function _fetch_from_store () /**
{ * Получение из кеша
if (!$items = $this->queued_items) */
public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');
trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR);
} }
foreach($items as $item) foreach ($items as $item) {
{
$filename = $this->dir . $this->prefix . $item . '.php'; $filename = $this->dir . $this->prefix . $item . '.php';
$this->cur_query = "cache->get('$item')"; $this->cur_query = "cache->get('$item')";
@ -76,8 +89,7 @@ class datastore_file extends datastore_common
$this->cur_query = null; $this->cur_query = null;
$this->num_queries++; $this->num_queries++;
if(file_exists($filename)) if (file_exists($filename)) {
{
require($filename); require($filename);
$this->data[$item] = $filecache; $this->data[$item] = $filecache;

View file

@ -1,19 +1,26 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_memcache extends datastore_common class datastore_memcache extends datastore_common
{ {
var $cfg = null; public $cfg = null;
var $memcache = null; public $memcache = null;
var $connected = false; public $connected = false;
var $engine = 'Memcache'; public $engine = 'Memcache';
var $prefix = null; public $prefix = null;
function datastore_memcache ($cfg, $prefix = null) /**
{ * datastore_memcache constructor.
if (!$this->is_installed()) * @param $cfg
* @param null $prefix
* @return datastore_memcache
*/
public function datastore_memcache($cfg, $prefix = null)
{ {
if (!$this->is_installed()) {
die('Error: Memcached extension not installed'); die('Error: Memcached extension not installed');
} }
@ -23,22 +30,25 @@ class datastore_memcache extends datastore_common
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function connect () /**
* Подключение
*/
public function connect()
{ {
$connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect';
$this->cur_query = $connect_type .' '. $this->cfg['host'] .':'. $this->cfg['port']; $this->cur_query = $connect_type . ' ' . $this->cfg['host'] . ':' . $this->cfg['port'];
$this->debug('start'); $this->debug('start');
if ($this->memcache->$connect_type($this->cfg['host'], $this->cfg['port'])) if ($this->memcache->$connect_type($this->cfg['host'], $this->cfg['port'])) {
{
$this->connected = true; $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']) if (!$this->connected && $this->cfg['con_required']) {
{
die('Could not connect to memcached server'); die('Could not connect to memcached server');
} }
@ -46,9 +56,16 @@ class datastore_memcache extends datastore_common
$this->cur_query = null; $this->cur_query = null;
} }
function store ($title, $var) /**
* @param $title
* @param $var
* @return bool
*/
public function store($title, $var)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) {
$this->connect();
}
$this->data[$title] = $var; $this->data[$title] = $var;
$this->cur_query = "cache->set('$title')"; $this->cur_query = "cache->set('$title')";
@ -57,14 +74,18 @@ class datastore_memcache extends datastore_common
$this->cur_query = null; $this->cur_query = null;
$this->num_queries++; $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) public function clean()
{ {
if (!$this->connected) {
$this->connect();
}
foreach ($this->known_items as $title => $script_name) {
$this->cur_query = "cache->rm('$title')"; $this->cur_query = "cache->rm('$title')";
$this->debug('start'); $this->debug('start');
$this->debug('stop'); $this->debug('stop');
@ -75,17 +96,20 @@ class datastore_memcache extends datastore_common
} }
} }
function _fetch_from_store () /**
{ * Получение из кеша
if (!$items = $this->queued_items) */
public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');
trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR); trigger_error("Datastore: item '$item' already enqueued [$src]", E_USER_ERROR);
} }
if (!$this->connected) $this->connect(); if (!$this->connected) {
foreach ($items as $item) $this->connect();
{ }
foreach ($items as $item) {
$this->cur_query = "cache->get('$item')"; $this->cur_query = "cache->get('$item')";
$this->debug('start'); $this->debug('start');
$this->debug('stop'); $this->debug('stop');
@ -96,7 +120,10 @@ class datastore_memcache extends datastore_common
} }
} }
function is_installed () /**
* @return bool
*/
public function is_installed()
{ {
return class_exists('Memcache'); return class_exists('Memcache');
} }

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