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,7 +1,6 @@
<?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;
@ -18,39 +17,38 @@ $return_links = array(
'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,

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;
} }
@ -15,9 +14,11 @@ 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);
} }
@ -96,23 +99,19 @@ $sql = "SELECT 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"' : '';
@ -122,8 +121,7 @@ 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) {
{
$$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));
} }

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,7 +48,9 @@ $default_cfg_num = array(
'limit_leech_ips' => 0, 'limit_leech_ips' => 0,
); );
// Set template vars /**
* Set template vars
*/
set_tpl_vars($default_cfg_str, $tr_cfg); set_tpl_vars($default_cfg_str, $tr_cfg);
set_tpl_vars_lang($default_cfg_str); set_tpl_vars_lang($default_cfg_str);

View file

@ -1,8 +1,9 @@
<?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;
} }
@ -12,32 +13,32 @@ $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,13 +48,11 @@ $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,
@ -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,8 +83,7 @@ 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');
@ -100,8 +97,7 @@ switch ($mode)
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,26 +8,20 @@ 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'];
@ -37,50 +30,40 @@ if (isset($_POST['add_name']))
$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,14 +10,11 @@ $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']);
} }
@ -29,8 +25,7 @@ if (isset($_REQUEST['submit']))
$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,20 +19,20 @@ $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'] . ']',
@ -41,70 +40,53 @@ $simple_auth_types = array(
$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;
} }
} }
@ -115,10 +97,8 @@ if( isset($_POST['submit']) )
$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');
} }
} }
@ -129,47 +109,36 @@ 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
// */
// 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"); $forum_rows = DB()->fetch_rowset("SELECT * FROM " . BB_FORUMS . " $forum_sql");
if (empty($forum_id)) 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,19 +147,16 @@ 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,19 +169,12 @@ 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>';
} }

View file

@ -1,24 +1,23 @@
<?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'] . ']',
@ -26,9 +25,9 @@ $simple_auth_types = array(
$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,81 +40,61 @@ $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;
} }
} }
@ -126,27 +105,20 @@ if( isset($_POST['submit']) )
$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;
} }
} }
@ -156,10 +128,8 @@ if( isset($_POST['submit']) )
$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,16 +151,14 @@ $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
@ -201,8 +168,7 @@ if( empty($forum_id) && empty($cat_id) )
'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,16 +178,14 @@ 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(
@ -229,23 +193,18 @@ if( empty($forum_id) && empty($cat_id) )
'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');
} }
@ -297,23 +252,18 @@ else
'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,12 +280,10 @@ 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>';
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['FORUMS']['MANAGE'] = basename(__FILE__); $module['FORUMS']['MANAGE'] = basename(__FILE__);
return; return;
} }
@ -19,7 +18,7 @@ array_deep($_POST, 'trim');
$s = ''; $s = '';
$default_forum_auth = array( $default_forum_auth = [
'auth_view' => AUTH_ALL, 'auth_view' => AUTH_ALL,
'auth_read' => AUTH_ALL, 'auth_read' => AUTH_ALL,
'auth_post' => AUTH_REG, 'auth_post' => AUTH_REG,
@ -32,25 +31,22 @@ $default_forum_auth = array(
'auth_pollcreate' => AUTH_REG, 'auth_pollcreate' => AUTH_REG,
'auth_attachments' => AUTH_REG, 'auth_attachments' => AUTH_REG,
'auth_download' => AUTH_REG, 'auth_download' => AUTH_REG,
); ];
$mode = ($_REQUEST['mode']) ? (string)$_REQUEST['mode'] : ''; $mode = ($_REQUEST['mode']) ? (string)$_REQUEST['mode'] : '';
$cat_forums = get_cat_forums(); $cat_forums = get_cat_forums();
if ($orphan_sf_sql = get_orphan_sf()) if ($orphan_sf_sql = get_orphan_sf()) {
{ fix_orphan_sf($orphan_sf_sql, true);
fix_orphan_sf($orphan_sf_sql, TRUE);
} }
$forum_parent = $cat_id = 0; $forum_parent = $cat_id = 0;
$forumname = ''; $forumname = '';
if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory'])) {
{
$mode = (isset($_REQUEST['addforum'])) ? "addforum" : "addcat"; $mode = (isset($_REQUEST['addforum'])) ? "addforum" : "addcat";
if ($mode == 'addforum' && isset($_POST['addforum']) && isset($_POST['forumname']) && is_array($_POST['addforum'])) if ($mode == 'addforum' && isset($_POST['addforum']) && isset($_POST['forumname']) && is_array($_POST['addforum'])) {
{
$req_cat_id = array_keys($_POST['addforum']); $req_cat_id = array_keys($_POST['addforum']);
$cat_id = $req_cat_id[0]; $cat_id = $req_cat_id[0];
$forumname = stripslashes($_POST['forumname'][$cat_id]); $forumname = stripslashes($_POST['forumname'][$cat_id]);
@ -59,17 +55,14 @@ if (isset($_REQUEST['addforum']) || isset($_REQUEST['addcategory']))
$show_main_page = false; $show_main_page = false;
if ($mode) if ($mode) {
{ switch ($mode) {
switch ($mode)
{
case 'addforum': case 'addforum':
case 'editforum': case 'editforum':
// //
// Show form to create/modify a forum // Show form to create/modify a forum
// //
if ($mode == 'editforum') if ($mode == 'editforum') {
{
// $newmode determines if we are going to INSERT or UPDATE after posting? // $newmode determines if we are going to INSERT or UPDATE after posting?
$l_title = $lang['EDIT_FORUM']; $l_title = $lang['EDIT_FORUM'];
@ -93,9 +86,7 @@ if ($mode)
$allow_reg_tracker = $row['allow_reg_tracker']; $allow_reg_tracker = $row['allow_reg_tracker'];
$allow_porno_topic = $row['allow_porno_topic']; $allow_porno_topic = $row['allow_porno_topic'];
$self_moderated = $row['self_moderated']; $self_moderated = $row['self_moderated'];
} } else {
else
{
$l_title = $lang['CREATE_FORUM']; $l_title = $lang['CREATE_FORUM'];
$newmode = 'createforum'; $newmode = 'createforum';
$buttonvalue = $lang['CREATE_FORUM']; $buttonvalue = $lang['CREATE_FORUM'];
@ -113,21 +104,17 @@ if ($mode)
$self_moderated = 0; $self_moderated = 0;
} }
if (isset($_REQUEST['forum_parent'])) if (isset($_REQUEST['forum_parent'])) {
{
$forum_parent = intval($_REQUEST['forum_parent']); $forum_parent = intval($_REQUEST['forum_parent']);
if ($parent = get_forum_data($forum_parent)) if ($parent = get_forum_data($forum_parent)) {
{
$cat_id = $parent['cat_id']; $cat_id = $parent['cat_id'];
} }
} } elseif (isset($_REQUEST['c'])) {
else if (isset($_REQUEST['c']))
{
$cat_id = (int)$_REQUEST['c']; $cat_id = (int)$_REQUEST['c'];
} }
$catlist = get_list('category', $cat_id, TRUE); $catlist = get_list('category', $cat_id, true);
$forumlocked = $forumunlocked = ''; $forumlocked = $forumunlocked = '';
$forumstatus == (FORUM_LOCKED) ? $forumlocked = 'selected="selected"' : $forumunlocked = 'selected="selected"'; $forumstatus == (FORUM_LOCKED) ? $forumlocked = 'selected="selected"' : $forumunlocked = 'selected="selected"';
@ -194,24 +181,19 @@ if ($mode)
$allow_porno_topic = (int)$_POST['allow_porno_topic']; $allow_porno_topic = (int)$_POST['allow_porno_topic'];
$self_moderated = (int)$_POST['self_moderated']; $self_moderated = (int)$_POST['self_moderated'];
if (!$forum_name) if (!$forum_name) {
{
bb_die('Can not create a forum without a name'); bb_die('Can not create a forum without a name');
} }
if ($forum_parent) if ($forum_parent) {
{ if (!$parent = get_forum_data($forum_parent)) {
if (!$parent = get_forum_data($forum_parent))
{
bb_die('Parent forum with id <b>' . $forum_parent . '</b> not found'); bb_die('Parent forum with id <b>' . $forum_parent . '</b> not found');
} }
$cat_id = $parent['cat_id']; $cat_id = $parent['cat_id'];
$forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id'];
$forum_order = $parent['forum_order'] + 5; $forum_order = $parent['forum_order'] + 5;
} } else {
else
{
$max_order = get_max_forum_order($cat_id); $max_order = get_max_forum_order($cat_id);
$forum_order = $max_order + 5; $forum_order = $max_order + 5;
} }
@ -219,8 +201,7 @@ if ($mode)
// Default permissions of public forum // Default permissions of public forum
$field_sql = $value_sql = ''; $field_sql = $value_sql = '';
foreach ($default_forum_auth as $field => $value) foreach ($default_forum_auth as $field => $value) {
{
$field_sql .= ", $field"; $field_sql .= ", $field";
$value_sql .= ", $value"; $value_sql .= ", $value";
} }
@ -267,15 +248,12 @@ if ($mode)
$old_cat_id = $forum_data['cat_id']; $old_cat_id = $forum_data['cat_id'];
$forum_order = $forum_data['forum_order']; $forum_order = $forum_data['forum_order'];
if (!$forum_name) if (!$forum_name) {
{
bb_die('Can not modify a forum without a name'); bb_die('Can not modify a forum without a name');
} }
if ($forum_parent) if ($forum_parent) {
{ if (!$parent = get_forum_data($forum_parent)) {
if (!$parent = get_forum_data($forum_parent))
{
bb_die('Parent forum with id <b>' . $forum_parent . '</b> not found'); bb_die('Parent forum with id <b>' . $forum_parent . '</b> not found');
} }
@ -283,18 +261,13 @@ if ($mode)
$forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id']; $forum_parent = ($parent['forum_parent']) ? $parent['forum_parent'] : $parent['forum_id'];
$forum_order = $parent['forum_order'] + 5; $forum_order = $parent['forum_order'] + 5;
if ($forum_id == $forum_parent) if ($forum_id == $forum_parent) {
{
bb_die('Ambiguous forum ID. Please select other parent forum'); bb_die('Ambiguous forum ID. Please select other parent forum');
} }
} } elseif ($cat_id != $old_cat_id) {
else if ($cat_id != $old_cat_id)
{
$max_order = get_max_forum_order($cat_id); $max_order = get_max_forum_order($cat_id);
$forum_order = $max_order + 5; $forum_order = $max_order + 5;
} } elseif ($forum_data['forum_parent']) {
else if ($forum_data['forum_parent'])
{
$old_parent = $forum_data['forum_parent']; $old_parent = $forum_data['forum_parent'];
$forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5; $forum_order = $cat_forums[$old_cat_id]['f'][$old_parent]['forum_order'] - 5;
} }
@ -321,8 +294,7 @@ if ($mode)
WHERE forum_id = $forum_id WHERE forum_id = $forum_id
"); ");
if ($cat_id != $old_cat_id) if ($cat_id != $old_cat_id) {
{
change_sf_cat($forum_id, $cat_id, $forum_order); change_sf_cat($forum_id, $cat_id, $forum_order);
renumber_order('forum', $cat_id); renumber_order('forum', $cat_id);
} }
@ -346,8 +318,7 @@ if ($mode)
// //
// Create a category in the DB // Create a category in the DB
// //
if (!$new_cat_title = trim($_POST['categoryname'])) if (!$new_cat_title = trim($_POST['categoryname'])) {
{
bb_die('Category name is empty'); bb_die('Category name is empty');
} }
@ -396,8 +367,7 @@ if ($mode)
// //
// Modify a category in the DB // Modify a category in the DB
// //
if (!$new_cat_title = trim($_POST['cat_title'])) if (!$new_cat_title = trim($_POST['cat_title'])) {
{
bb_die('Category name is empty'); bb_die('Category name is empty');
} }
@ -406,8 +376,7 @@ if ($mode)
$row = get_info('category', $cat_id); $row = get_info('category', $cat_id);
$cur_cat_title = $row['cat_title']; $cur_cat_title = $row['cat_title'];
if ($cur_cat_title && $cur_cat_title !== $new_cat_title) if ($cur_cat_title && $cur_cat_title !== $new_cat_title) {
{
check_name_dup('cat', $new_cat_title); check_name_dup('cat', $new_cat_title);
$new_cat_title_sql = DB()->escape($new_cat_title); $new_cat_title_sql = DB()->escape($new_cat_title);
@ -465,19 +434,15 @@ if ($mode)
$from_id = (int)$_POST['from_id']; $from_id = (int)$_POST['from_id'];
$to_id = (int)$_POST['to_id']; $to_id = (int)$_POST['to_id'];
if ($to_id == -1) if ($to_id == -1) {
{
// Delete everything from forum // Delete everything from forum
topic_delete('prune', $from_id, 0, true); topic_delete('prune', $from_id, 0, true);
} } else {
else
{
// Move all posts // Move all posts
$sql = "SELECT * FROM " . BB_FORUMS . " WHERE forum_id IN($from_id, $to_id)"; $sql = "SELECT * FROM " . BB_FORUMS . " WHERE forum_id IN($from_id, $to_id)";
$result = DB()->query($sql); $result = DB()->query($sql);
if (DB()->num_rows($result) != 2) if (DB()->num_rows($result) != 2) {
{
bb_die('Ambiguous forum ID'); bb_die('Ambiguous forum ID');
} }
@ -488,15 +453,13 @@ if ($mode)
$start_id = (int)$row['start_id']; $start_id = (int)$row['start_id'];
$finish_id = (int)$row['finish_id']; $finish_id = (int)$row['finish_id'];
$per_cycle = 10000; $per_cycle = 10000;
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("
UPDATE " . BB_POSTS . " SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id UPDATE " . BB_POSTS . " SET forum_id = $to_id WHERE post_id BETWEEN $start_id AND $end_id AND forum_id = $from_id
"); ");
if ($end_id > $finish_id) if ($end_id > $finish_id) {
{
break; break;
} }
$start_id += $per_cycle; $start_id += $per_cycle;
@ -526,16 +489,12 @@ if ($mode)
$catinfo = get_info('category', $cat_id); $catinfo = get_info('category', $cat_id);
$categories_count = $catinfo['number']; $categories_count = $catinfo['number'];
if ($categories_count == 1) if ($categories_count == 1) {
{
$row = DB()->fetch_row("SELECT COUNT(*) AS forums_count FROM " . BB_FORUMS); $row = DB()->fetch_row("SELECT COUNT(*) AS forums_count FROM " . BB_FORUMS);
if ($row['forums_count'] > 0) if ($row['forums_count'] > 0) {
{
bb_die($lang['MUST_DELETE_FORUMS']); bb_die($lang['MUST_DELETE_FORUMS']);
} } else {
else
{
$template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']); $template->assign_var('NOWHERE_TO_MOVE', $lang['NOWHERE_TO_MOVE']);
} }
} }
@ -565,8 +524,7 @@ if ($mode)
$from_id = (int)$_POST['from_id']; $from_id = (int)$_POST['from_id'];
$to_id = (int)$_POST['to_id']; $to_id = (int)$_POST['to_id'];
if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) if ($from_id == $to_id || !cat_exists($from_id) || !cat_exists($to_id)) {
{
bb_die('Bad input'); bb_die('Bad input');
} }
@ -605,60 +563,46 @@ if ($mode)
$cat_id = $forum_info['cat_id']; $cat_id = $forum_info['cat_id'];
$move_down_forum_id = FALSE; $move_down_forum_id = false;
$forums = $cat_forums[$cat_id]['f_ord']; $forums = $cat_forums[$cat_id]['f_ord'];
$forum_order = $forum_info['forum_order']; $forum_order = $forum_info['forum_order'];
$prev_forum = (isset($forums[$forum_order - 10])) ? $forums[$forum_order - 10] : FALSE; $prev_forum = (isset($forums[$forum_order - 10])) ? $forums[$forum_order - 10] : false;
$next_forum = (isset($forums[$forum_order + 10])) ? $forums[$forum_order + 10] : FALSE; $next_forum = (isset($forums[$forum_order + 10])) ? $forums[$forum_order + 10] : false;
// move selected forum ($forum_id) UP // move selected forum ($forum_id) UP
if ($move < 0 && $prev_forum) if ($move < 0 && $prev_forum) {
{ if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent']) {
if ($forum_info['forum_parent'] && $prev_forum['forum_parent'] != $forum_info['forum_parent'])
{
$show_main_page = true; $show_main_page = true;
break; break;
} } elseif ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) {
else if ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order))
{
$move_up_forum_id = $forum_id; $move_up_forum_id = $forum_id;
$move_down_ord_val = (get_sf_count($forum_id) + 1) * 10; $move_down_ord_val = (get_sf_count($forum_id) + 1) * 10;
$move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val;
$move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order']; $move_down_forum_order = $cat_forums[$cat_id]['f'][$move_down_forum_id]['forum_order'];
} }
} } // move selected forum ($forum_id) DOWN
// move selected forum ($forum_id) DOWN elseif ($move > 0 && $next_forum) {
else if ($move > 0 && $next_forum) if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent']) {
{
if ($forum_info['forum_parent'] && $next_forum['forum_parent'] != $forum_info['forum_parent'])
{
$show_main_page = true; $show_main_page = true;
break; break;
} } elseif ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) {
else if ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order))
{
$move_down_forum_id = $forum_id; $move_down_forum_id = $forum_id;
$move_down_forum_order = $forum_order; $move_down_forum_order = $forum_order;
$move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10; $move_down_ord_val = (get_sf_count($move_up_forum_id) + 1) * 10;
$move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val; $move_up_ord_val = ((get_sf_count($move_down_forum_id) + 1) * 10) + $move_down_ord_val;
} }
} } else {
else
{
$show_main_page = true; $show_main_page = true;
break; break;
} }
if ($forum_info['forum_parent']) if ($forum_info['forum_parent']) {
{
DB()->query(" DB()->query("
UPDATE " . BB_FORUMS . " SET UPDATE " . BB_FORUMS . " SET
forum_order = forum_order + $move forum_order = forum_order + $move
WHERE forum_id = $forum_id WHERE forum_id = $forum_id
"); ");
} } elseif ($move_down_forum_id) {
else if ($move_down_forum_id)
{
DB()->query(" DB()->query("
UPDATE " . BB_FORUMS . " SET UPDATE " . BB_FORUMS . " SET
forum_order = forum_order + $move_down_ord_val forum_order = forum_order + $move_down_ord_val
@ -715,8 +659,7 @@ if ($mode)
} }
} }
if (!$mode || $show_main_page) if (!$mode || $show_main_page) {
{
$template->assign_vars(array( $template->assign_vars(array(
'TPL_FORUMS_LIST' => true, 'TPL_FORUMS_LIST' => true,
@ -725,42 +668,32 @@ if (!$mode || $show_main_page)
)); ));
$sql = "SELECT cat_id, cat_title, cat_order FROM " . BB_CATEGORIES . " ORDER BY cat_order"; $sql = "SELECT cat_id, cat_title, cat_order FROM " . BB_CATEGORIES . " ORDER BY cat_order";
if (!$q_categories = DB()->sql_query($sql)) if (!$q_categories = DB()->sql_query($sql)) {
{
bb_die('Could not query categories list'); bb_die('Could not query categories list');
} }
if ($total_categories = DB()->num_rows($q_categories)) if ($total_categories = DB()->num_rows($q_categories)) {
{
$category_rows = DB()->sql_fetchrowset($q_categories); $category_rows = DB()->sql_fetchrowset($q_categories);
$where_cat_sql = $req_cat_id = ''; $where_cat_sql = $req_cat_id = '';
if ($c =& $_REQUEST['c']) if ($c =& $_REQUEST['c']) {
{ if ($c !== 'all') {
if ($c !== 'all')
{
$req_cat_id = (int)$c; $req_cat_id = (int)$c;
$where_cat_sql = "WHERE cat_id = $req_cat_id"; $where_cat_sql = "WHERE cat_id = $req_cat_id";
} } else {
else
{
$req_cat_id = 'all'; $req_cat_id = 'all';
} }
} } else {
else
{
$where_cat_sql = "WHERE cat_id = '-1'"; $where_cat_sql = "WHERE cat_id = '-1'";
} }
$sql = "SELECT * FROM " . BB_FORUMS . " $where_cat_sql ORDER BY cat_id, forum_order"; $sql = "SELECT * FROM " . BB_FORUMS . " $where_cat_sql ORDER BY cat_id, forum_order";
if (!$q_forums = DB()->sql_query($sql)) if (!$q_forums = DB()->sql_query($sql)) {
{
bb_die('Could not query forums information'); bb_die('Could not query forums information');
} }
if ($total_forums = DB()->num_rows($q_forums)) if ($total_forums = DB()->num_rows($q_forums)) {
{
$forum_rows = DB()->sql_fetchrowset($q_forums); $forum_rows = DB()->sql_fetchrowset($q_forums);
} }
@ -776,8 +709,7 @@ if (!$mode || $show_main_page)
'FORUMS_COUNT' => $total_forums, 'FORUMS_COUNT' => $total_forums,
)); ));
for ($i = 0; $i < $total_categories; $i++) for ($i = 0; $i < $total_categories; $i++) {
{
$cat_id = $category_rows[$i]['cat_id']; $cat_id = $category_rows[$i]['cat_id'];
$template->assign_block_vars("c", array( $template->assign_block_vars("c", array(
@ -795,16 +727,13 @@ if (!$mode || $show_main_page)
'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&amp;c=$cat_id", 'U_CREATE_FORUM' => "admin_forums.php?mode=addforum&amp;c=$cat_id",
)); ));
for ($j = 0; $j < $total_forums; $j++) for ($j = 0; $j < $total_forums; $j++) {
{
$forum_id = $forum_rows[$j]['forum_id']; $forum_id = $forum_rows[$j]['forum_id'];
$bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1; $bgr_class = (!($j % 2)) ? $bgr_class_2 : $bgr_class_1;
$row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\""; $row_bgr = " class=\"$bgr_class\" onmouseover=\"this.className='$bgr_class_over';\" onmouseout=\"this.className='$bgr_class';\"";
if ($forum_rows[$j]['cat_id'] == $cat_id) if ($forum_rows[$j]['cat_id'] == $cat_id) {
{
$template->assign_block_vars("c.f", array( $template->assign_block_vars("c.f", array(
'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']), 'FORUM_NAME' => htmlCHR($forum_rows[$j]['forum_name']),
'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']), 'FORUM_DESC' => htmlCHR($forum_rows[$j]['forum_desc']),
@ -829,7 +758,6 @@ if (!$mode || $show_main_page)
'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&amp;move=15&amp;f=$forum_id&amp;c=$req_cat_id", 'U_FORUM_MOVE_DOWN' => "admin_forums.php?mode=forum_order&amp;move=15&amp;f=$forum_id&amp;c=$req_cat_id",
'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&amp;f=$forum_id", 'U_FORUM_RESYNC' => "admin_forums.php?mode=forum_sync&amp;f=$forum_id",
)); ));
}// if ... forumid == catid }// if ... forumid == catid
} // for ... forums } // for ... forums
} // for ... categories } // for ... categories
@ -838,11 +766,14 @@ if (!$mode || $show_main_page)
print_page('admin_forums.tpl', 'admin'); print_page('admin_forums.tpl', 'admin');
// Functions /**
* @param $mode
* @param $id
* @return mixed
*/
function get_info($mode, $id) function get_info($mode, $id)
{ {
switch($mode) switch ($mode) {
{
case 'category': case 'category':
$table = BB_CATEGORIES; $table = BB_CATEGORIES;
$idfield = 'cat_id'; $idfield = 'cat_id';
@ -858,8 +789,7 @@ function get_info ($mode, $id)
break; break;
} }
$sql = "SELECT count(*) as total FROM $table"; $sql = "SELECT count(*) as total FROM $table";
if( !$result = DB()->sql_query($sql) ) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get forum / category information #1'); bb_die('Could not get forum / category information #1');
} }
$count = DB()->sql_fetchrow($result); $count = DB()->sql_fetchrow($result);
@ -867,13 +797,11 @@ function get_info ($mode, $id)
$sql = "SELECT * FROM $table WHERE $idfield = $id"; $sql = "SELECT * FROM $table WHERE $idfield = $id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get forum / category information #2'); bb_die('Could not get forum / category information #2');
} }
if (DB()->num_rows($result) != 1) if (DB()->num_rows($result) != 1) {
{
bb_die('Forum / category does not exist or multiple forums / categories with ID ' . $id); bb_die('Forum / category does not exist or multiple forums / categories with ID ' . $id);
} }
@ -882,10 +810,15 @@ function get_info ($mode, $id)
return $return; return $return;
} }
/**
* @param $mode
* @param $id
* @param $select
* @return string
*/
function get_list($mode, $id, $select) function get_list($mode, $id, $select)
{ {
switch($mode) switch ($mode) {
{
case 'category': case 'category':
$table = BB_CATEGORIES; $table = BB_CATEGORIES;
$idfield = 'cat_id'; $idfield = 'cat_id';
@ -906,24 +839,20 @@ function get_list ($mode, $id, $select)
} }
$sql = "SELECT * FROM $table"; $sql = "SELECT * FROM $table";
if( $select == 0 ) if ($select == 0) {
{
$sql .= " WHERE $idfield <> $id"; $sql .= " WHERE $idfield <> $id";
} }
$sql .= " ORDER BY $order"; $sql .= " ORDER BY $order";
if( !$result = DB()->sql_query($sql) ) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get list of categories / forums #1'); bb_die('Could not get list of categories / forums #1');
} }
$catlist = ''; $catlist = '';
while( $row = DB()->sql_fetchrow($result) ) while ($row = DB()->sql_fetchrow($result)) {
{
$s = ''; $s = '';
if ($row[$idfield] == $id) if ($row[$idfield] == $id) {
{
$s = ' selected="selected"'; $s = ' selected="selected"';
} }
$catlist .= '<option value="' . $row[$idfield] . '"' . $s . '>&nbsp;' . htmlCHR(str_short($row[$namefield], 60)) . '</option>\n'; $catlist .= '<option value="' . $row[$idfield] . '"' . $s . '>&nbsp;' . htmlCHR(str_short($row[$namefield], 60)) . '</option>\n';
@ -932,10 +861,13 @@ function get_list ($mode, $id, $select)
return ($catlist); return ($catlist);
} }
/**
* @param $mode
* @param int $cat
*/
function renumber_order($mode, $cat = 0) function renumber_order($mode, $cat = 0)
{ {
switch($mode) switch ($mode) {
{
case 'category': case 'category':
$table = BB_CATEGORIES; $table = BB_CATEGORIES;
$idfield = 'cat_id'; $idfield = 'cat_id';
@ -956,43 +888,40 @@ function renumber_order ($mode, $cat = 0)
} }
$sql = "SELECT * FROM $table"; $sql = "SELECT * FROM $table";
if( $cat != 0) if ($cat != 0) {
{
$sql .= " WHERE $catfield = $cat"; $sql .= " WHERE $catfield = $cat";
} }
$sql .= " ORDER BY $orderfield ASC"; $sql .= " ORDER BY $orderfield ASC";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get list of categories / forums #2'); bb_die('Could not get list of categories / forums #2');
} }
$i = 10; $i = 10;
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield]; $sql = "UPDATE $table SET $orderfield = $i WHERE $idfield = " . $row[$idfield];
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not update order fields'); bb_die('Could not update order fields');
} }
$i += 10; $i += 10;
} }
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get list of categories / forums #3'); bb_die('Could not get list of categories / forums #3');
} }
} }
function get_cat_forums ($cat_id = FALSE) /**
* @param bool $cat_id
* @return array
*/
function get_cat_forums($cat_id = false)
{ {
$forums = array(); $forums = array();
$where_sql = ''; $where_sql = '';
if ($cat_id = intval($cat_id)) if ($cat_id = intval($cat_id)) {
{
$where_sql = "AND f.cat_id = $cat_id"; $where_sql = "AND f.cat_id = $cat_id";
} }
@ -1002,15 +931,12 @@ function get_cat_forums ($cat_id = FALSE)
$where_sql $where_sql
ORDER BY c.cat_order, f.cat_id, f.forum_order"; ORDER BY c.cat_order, f.cat_id, f.forum_order";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not get list of categories / forums #4'); bb_die('Could not get list of categories / forums #4');
} }
if ($rowset = DB()->sql_fetchrowset($result)) if ($rowset = DB()->sql_fetchrowset($result)) {
{ foreach ($rowset as $rid => $row) {
foreach ($rowset as $rid => $row)
{
$forums[$row['cat_id']]['cat_title'] = $row['cat_title']; $forums[$row['cat_id']]['cat_title'] = $row['cat_title'];
$forums[$row['cat_id']]['f'][$row['forum_id']] = $row; $forums[$row['cat_id']]['f'][$row['forum_id']] = $row;
$forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row; $forums[$row['cat_id']]['f_ord'][$row['forum_order']] = $row;
@ -1020,18 +946,19 @@ function get_cat_forums ($cat_id = FALSE)
return $forums; return $forums;
} }
/**
* @param $forum_id
* @return int
*/
function get_sf_count($forum_id) function get_sf_count($forum_id)
{ {
global $cat_forums; global $cat_forums;
$sf_count = 0; $sf_count = 0;
foreach ($cat_forums as $cid => $c) foreach ($cat_forums as $cid => $c) {
{ foreach ($c['f'] as $fid => $f) {
foreach ($c['f'] as $fid => $f) if ($f['forum_parent'] == $forum_id) {
{
if ($f['forum_parent'] == $forum_id)
{
$sf_count++; $sf_count++;
} }
} }
@ -1040,39 +967,48 @@ function get_sf_count ($forum_id)
return $sf_count; return $sf_count;
} }
/**
* @param $forums
* @param $curr_forum_order
* @return bool
*/
function get_prev_root_forum_id($forums, $curr_forum_order) function get_prev_root_forum_id($forums, $curr_forum_order)
{ {
$i = $curr_forum_order - 10; $i = $curr_forum_order - 10;
while ($i > 0) while ($i > 0) {
{ if (isset($forums[$i]) && !$forums[$i]['forum_parent']) {
if (isset($forums[$i]) && !$forums[$i]['forum_parent'])
{
return $forums[$i]['forum_id']; return $forums[$i]['forum_id'];
} }
$i = $i - 10; $i = $i - 10;
} }
return FALSE; return false;
} }
/**
* @param $forums
* @param $curr_forum_order
* @return bool
*/
function get_next_root_forum_id($forums, $curr_forum_order) function get_next_root_forum_id($forums, $curr_forum_order)
{ {
$i = $curr_forum_order + 10; $i = $curr_forum_order + 10;
$limit = (count($forums) * 10) + 10; $limit = (count($forums) * 10) + 10;
while ($i < $limit) while ($i < $limit) {
{ if (isset($forums[$i]) && !$forums[$i]['forum_parent']) {
if (isset($forums[$i]) && !$forums[$i]['forum_parent'])
{
return $forums[$i]['forum_id']; return $forums[$i]['forum_id'];
} }
$i = $i + 10; $i = $i + 10;
} }
return FALSE; return false;
} }
/**
* @return string
*/
function get_orphan_sf() function get_orphan_sf()
{ {
global $cat_forums; global $cat_forums;
@ -1080,19 +1016,13 @@ function get_orphan_sf ()
$last_root = 0; $last_root = 0;
$bad_sf_ary = array(); $bad_sf_ary = array();
foreach ($cat_forums as $cid => $c) foreach ($cat_forums as $cid => $c) {
{ foreach ($c['f'] as $fid => $f) {
foreach ($c['f'] as $fid => $f) if ($f['forum_parent']) {
{ if ($f['forum_parent'] != $last_root) {
if ($f['forum_parent'])
{
if ($f['forum_parent'] != $last_root)
{
$bad_sf_ary[] = $f['forum_id']; $bad_sf_ary[] = $f['forum_id'];
} }
} } else {
else
{
$last_root = $f['forum_id']; $last_root = $f['forum_id'];
} }
} }
@ -1101,33 +1031,33 @@ function get_orphan_sf ()
return implode(',', $bad_sf_ary); return implode(',', $bad_sf_ary);
} }
function fix_orphan_sf ($orphan_sf_sql = '', $show_mess = FALSE) /**
* @param string $orphan_sf_sql
* @param bool $show_mess
* @return string
*/
function fix_orphan_sf($orphan_sf_sql = '', $show_mess = false)
{ {
global $lang; global $lang;
$done_mess = ''; $done_mess = '';
if (!$orphan_sf_sql) if (!$orphan_sf_sql) {
{
$orphan_sf_sql = get_orphan_sf(); $orphan_sf_sql = get_orphan_sf();
} }
if ($orphan_sf_sql) if ($orphan_sf_sql) {
{
$sql = "UPDATE " . BB_FORUMS . " SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)"; $sql = "UPDATE " . BB_FORUMS . " SET forum_parent = 0, show_on_index = 1 WHERE forum_id IN($orphan_sf_sql)";
if (!DB()->sql_query($sql)) if (!DB()->sql_query($sql)) {
{
bb_die('Could not change subforums data'); bb_die('Could not change subforums data');
} }
if ($affectedrows = DB()->affected_rows()) if ($affectedrows = DB()->affected_rows()) {
{
$done_mess = 'Subforums data corrected. <b>' . $affectedrows . '</b> orphan subforum(s) moved to root level.'; $done_mess = 'Subforums data corrected. <b>' . $affectedrows . '</b> orphan subforum(s) moved to root level.';
} }
if ($show_mess) if ($show_mess) {
{
$message = $done_mess . '<br /><br />'; $message = $done_mess . '<br /><br />';
$message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.php">', '</a>') . '<br /><br />'; $message .= sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.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>');
@ -1138,20 +1068,23 @@ function fix_orphan_sf ($orphan_sf_sql = '', $show_mess = FALSE)
return $done_mess; return $done_mess;
} }
/**
* @param $mode
* @param int $exclude
* @param int $select
* @return string
*/
function sf_get_list($mode, $exclude = 0, $select = 0) function sf_get_list($mode, $exclude = 0, $select = 0)
{ {
global $cat_forums, $forum_parent; global $cat_forums, $forum_parent;
$opt = ''; $opt = '';
if ($mode == 'forum') if ($mode == 'forum') {
{ foreach ($cat_forums as $cid => $c) {
foreach ($cat_forums as $cid => $c)
{
$opt .= '<optgroup label="&nbsp;' . htmlCHR($c['cat_title']) . '">'; $opt .= '<optgroup label="&nbsp;' . htmlCHR($c['cat_title']) . '">';
foreach ($c['f'] as $fid => $f) foreach ($c['f'] as $fid => $f) {
{
$selected = ($fid == $select) ? HTML_SELECTED : ''; $selected = ($fid == $select) ? HTML_SELECTED : '';
$disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : ''; $disabled = ($fid == $exclude && !$forum_parent) ? HTML_DISABLED : '';
$style = ($disabled) ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : ''); $style = ($disabled) ? ' style="color: gray" ' : (($fid == $exclude) ? ' style="color: darkred" ' : '');
@ -1165,24 +1098,29 @@ function sf_get_list ($mode, $exclude = 0, $select = 0)
return $opt; return $opt;
} }
/**
* @param $forum_id
* @return bool
*/
function get_forum_data($forum_id) function get_forum_data($forum_id)
{ {
global $cat_forums; global $cat_forums;
foreach ($cat_forums as $cid => $c) foreach ($cat_forums as $cid => $c) {
{ foreach ($c['f'] as $fid => $f) {
foreach ($c['f'] as $fid => $f) if ($fid == $forum_id) {
{
if ($fid == $forum_id)
{
return $f; return $f;
} }
} }
} }
return FALSE; return false;
} }
/**
* @param $cat_id
* @return int
*/
function get_max_forum_order($cat_id) function get_max_forum_order($cat_id)
{ {
$row = DB()->fetch_row(" $row = DB()->fetch_row("
@ -1194,25 +1132,27 @@ function get_max_forum_order ($cat_id)
return intval($row['max_forum_order']); return intval($row['max_forum_order']);
} }
/**
* @param $mode
* @param $name
* @param bool $die_on_error
* @return mixed
*/
function check_name_dup($mode, $name, $die_on_error = true) function check_name_dup($mode, $name, $die_on_error = true)
{ {
$name_sql = DB()->escape($name); $name_sql = DB()->escape($name);
if ($mode == 'cat') if ($mode == 'cat') {
{
$what_checked = 'category'; $what_checked = 'category';
$sql = "SELECT cat_id FROM " . BB_CATEGORIES . " WHERE cat_title = '$name_sql'"; $sql = "SELECT cat_id FROM " . BB_CATEGORIES . " WHERE cat_title = '$name_sql'";
} } else {
else
{
$what_checked = 'forum'; $what_checked = 'forum';
$sql = "SELECT forum_id FROM " . BB_FORUMS . " WHERE forum_name = '$name_sql'"; $sql = "SELECT forum_id FROM " . BB_FORUMS . " WHERE forum_name = '$name_sql'";
} }
$name_is_dup = DB()->fetch_row($sql); $name_is_dup = DB()->fetch_row($sql);
if ($name_is_dup && $die_on_error) if ($name_is_dup && $die_on_error) {
{
bb_die('This ' . $what_checked . ' name taken, please choose something else'); bb_die('This ' . $what_checked . ' name taken, please choose something else');
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['GROUPS']['MANAGE'] = basename(__FILE__); $module['GROUPS']['MANAGE'] = basename(__FILE__);
return; return;
} }
@ -12,12 +11,9 @@ 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' => '',
@ -68,13 +62,9 @@ if (!empty($_POST['edit']) || !empty($_POST['new']))
'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
@ -85,27 +75,21 @@ else if (!empty($_POST['group_update']))
$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']);
} }
@ -118,22 +102,18 @@ else if (!empty($_POST['group_update']))
'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']);
} }
} }
@ -148,9 +128,7 @@ else if (!empty($_POST['group_update']))
$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);
@ -166,15 +144,11 @@ else if (!empty($_POST['group_update']))
$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,16 +140,13 @@ 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));
} }
@ -176,10 +162,8 @@ $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));
} }
@ -205,14 +189,11 @@ $sql = "SELECT l.*, u.*
$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,23 +221,19 @@ 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'];
} }
@ -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;
} }
@ -16,26 +15,28 @@ $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
@ -45,9 +46,7 @@ if (isset($_POST['submit']))
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 . "
@ -58,8 +57,7 @@ if (isset($_POST['submit']))
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')}>");
@ -87,8 +85,7 @@ $sql = "SELECT group_id, 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;
} }
@ -84,9 +68,7 @@ if ($mode != '')
'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,21 +92,16 @@ 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']);
} }
} }
@ -139,17 +114,14 @@ if ($mode != '')
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 = '-';
} }

View file

@ -1,13 +1,16 @@
<?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');
@ -30,11 +33,9 @@ $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 . "
@ -62,21 +63,16 @@ $session_posts_processed = ( $mode == 'refresh' ) ? get_processed_posts('session
$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;
} }
@ -85,43 +81,35 @@ else
$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;
} }
} }
@ -131,10 +119,8 @@ else
$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);
} }
@ -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'];
@ -196,8 +179,7 @@ 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));
} }
@ -205,10 +187,8 @@ if ($mode == 'submit' || $mode == 'refresh')
$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,
@ -223,9 +203,9 @@ if ($mode == 'submit' || $mode == 'refresh')
'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
@ -253,8 +233,7 @@ 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;
@ -273,9 +252,9 @@ 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'];
@ -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));
} }
@ -358,9 +335,8 @@ 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;
@ -372,43 +348,35 @@ else // show the input page
$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());
} }
@ -456,8 +422,7 @@ function get_db_sizes ()
$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'];
} }
@ -497,17 +462,13 @@ 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 {
else
{
$sql = "SELECT * FROM " . BB_SEARCH_REBUILD . " ORDER BY rebuild_session_id DESC LIMIT 1"; $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];
} }
@ -521,13 +482,10 @@ 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'];
} }
@ -538,13 +496,10 @@ function get_processed_posts ($mode = 'session')
// 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;
} }
@ -557,12 +512,10 @@ 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,10 +535,8 @@ 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;
} }
@ -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;
} }

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,36 +37,28 @@ 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; $sql = "SELECT code FROM " . BB_SMILIES;
if (!$result = DB()->sql_query($sql)) 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;
} }
@ -83,46 +66,35 @@ if (isset($_GET['import_pack']) || isset($_POST['import_pack']))
$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,12 +150,9 @@ 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>';
} }
@ -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');
@ -232,22 +188,17 @@ else if ( $mode != '' )
$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>';
@ -276,8 +227,7 @@ else if ( $mode != '' )
$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');
@ -308,8 +257,7 @@ else if ( $mode != '' )
$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']);

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;
} }
@ -12,8 +11,7 @@ $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,7 +1,6 @@
<?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;
@ -38,13 +37,11 @@ $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'];
@ -56,25 +53,19 @@ if ($submit && $mode == 'user')
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");
} }
@ -88,13 +79,10 @@ if ($submit && $mode == 'user')
$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
@ -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));
} }
} }
@ -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));
} }
} }
@ -176,26 +157,20 @@ 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');
} }
@ -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'];
@ -237,20 +209,16 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_id))
'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],
@ -315,18 +282,14 @@ if ($mode == 'user' && (!empty($_POST['username']) || $user_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,
)); ));
} } 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');
} }
@ -335,21 +298,18 @@ else if ($mode == 'group' && $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'];
@ -364,20 +324,16 @@ else if ($mode == 'group' && $group_id)
'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],
@ -428,19 +383,14 @@ 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'),

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

View file

@ -1,7 +1,6 @@
<?php <?php
if (!empty($setmodules)) if (!empty($setmodules)) {
{
$module['USERS']['SEARCH'] = basename(__FILE__); $module['USERS']['SEARCH'] = basename(__FILE__);
return; return;
} }
@ -16,41 +15,34 @@ require(INC_DIR .'functions_selects.php');
$total_sql = ''; $total_sql = '';
if (!isset($_REQUEST['dosearch'])) if (!isset($_REQUEST['dosearch'])) {
{
$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 ASC"; ORDER BY group_name ASC";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select group data #1'); bb_die('Could not select group data #1');
} }
$group_list = ''; $group_list = '';
if (DB()->num_rows($result) != 0) if (DB()->num_rows($result) != 0) {
{
$template->assign_block_vars('groups_exist', array()); $template->assign_block_vars('groups_exist', array());
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$group_list .= '<option value="' . $row['group_id'] . '">' . strip_tags(htmlspecialchars($row['group_name'])) . '</option>'; $group_list .= '<option value="' . $row['group_id'] . '">' . strip_tags(htmlspecialchars($row['group_name'])) . '</option>';
} }
} }
$sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_special = 1 ORDER BY rank_title"; $sql = "SELECT * FROM " . BB_RANKS . " WHERE rank_special = 1 ORDER BY rank_title";
if (!($result = DB()->sql_query($sql))) if (!($result = DB()->sql_query($sql))) {
{
bb_die('Could not obtain ranks data'); bb_die('Could not obtain ranks data');
} }
$rank_select_box = ''; $rank_select_box = '';
if (DB()->num_rows($result) != 0) if (DB()->num_rows($result) != 0) {
{
$template->assign_block_vars('ranks_exist', array()); $template->assign_block_vars('ranks_exist', array());
while( $row = DB()->sql_fetchrow($result) ) while ($row = DB()->sql_fetchrow($result)) {
{
$rank = $row['rank_title']; $rank = $row['rank_title'];
$rank_id = $row['rank_id']; $rank_id = $row['rank_id'];
$rank_select_box .= '<option value="' . $rank_id . '">' . $rank . '</option>'; $rank_select_box .= '<option value="' . $rank_id . '">' . $rank . '</option>';
@ -64,24 +56,20 @@ if (!isset($_REQUEST['dosearch']))
FROM ( " . BB_FORUMS . " AS f INNER JOIN " . BB_CATEGORIES . " AS c ON c.cat_id = f.cat_id ) FROM ( " . BB_FORUMS . " AS f INNER JOIN " . BB_CATEGORIES . " AS c ON c.cat_id = f.cat_id )
ORDER BY c.cat_order, f.forum_order ASC"; ORDER BY c.cat_order, f.forum_order ASC";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select forum data'); bb_die('Could not select forum data');
} }
$forums = array(); $forums = array();
if (DB()->num_rows($result) != 0) if (DB()->num_rows($result) != 0) {
{
$template->assign_block_vars('forums_exist', array()); $template->assign_block_vars('forums_exist', array());
$last_cat_id = -1; $last_cat_id = -1;
$forums_list = ''; $forums_list = '';
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{ if ($row['cat_id'] != $last_cat_id) {
if ($row['cat_id'] != $last_cat_id)
{
$forums_list .= '<optgroup label="' . htmlCHR($row['cat_title']) . '">'; $forums_list .= '<optgroup label="' . htmlCHR($row['cat_title']) . '">';
$last_cat_id = $row['cat_id']; $last_cat_id = $row['cat_id'];
} }
@ -93,8 +81,7 @@ if (!isset($_REQUEST['dosearch']))
$lastvisited = array(1, 7, 14, 30, 60, 120, 365, 500, 730, 1000); $lastvisited = array(1, 7, 14, 30, 60, 120, 365, 500, 730, 1000);
$lastvisited_list = ''; $lastvisited_list = '';
foreach ($lastvisited as $days) foreach ($lastvisited as $days) {
{
$lastvisited_list .= '<option value="' . $days . '">' . $days . ' ' . (($days > 1) ? $lang['DAYS'] : $lang['DAY']) . '</option>'; $lastvisited_list .= '<option value="' . $days . '">' . $days . ' ' . (($days > 1) ? $lang['DAYS'] : $lang['DAY']) . '</option>';
} }
@ -113,81 +100,59 @@ if (!isset($_REQUEST['dosearch']))
'S_SEARCH_ACTION' => 'admin_user_search.php', 'S_SEARCH_ACTION' => 'admin_user_search.php',
)); ));
} } else {
else
{
$mode = ''; $mode = '';
// validate mode // validate mode
if (isset($_REQUEST['search_username'])) if (isset($_REQUEST['search_username'])) {
{
$mode = 'search_username'; $mode = 'search_username';
} } elseif (isset($_REQUEST['search_email'])) {
elseif (isset($_REQUEST['search_email']))
{
$mode = 'search_email'; $mode = 'search_email';
} } elseif (isset($_REQUEST['search_ip'])) {
elseif (isset($_REQUEST['search_ip']))
{
$mode = 'search_ip'; $mode = 'search_ip';
} } elseif (isset($_REQUEST['search_joindate'])) {
elseif (isset($_REQUEST['search_joindate']))
{
$mode = 'search_joindate'; $mode = 'search_joindate';
} } elseif (isset($_REQUEST['search_group'])) {
elseif (isset($_REQUEST['search_group']))
{
$mode = 'search_group'; $mode = 'search_group';
} } elseif (isset($_REQUEST['search_rank'])) {
elseif (isset($_REQUEST['search_rank']))
{
$mode = 'search_rank'; $mode = 'search_rank';
} } elseif (isset($_REQUEST['search_postcount'])) {
elseif (isset($_REQUEST['search_postcount']))
{
$mode = 'search_postcount'; $mode = 'search_postcount';
} } elseif (isset($_REQUEST['search_userfield'])) {
elseif (isset($_REQUEST['search_userfield']))
{
$mode = 'search_userfield'; $mode = 'search_userfield';
} } elseif (isset($_REQUEST['search_lastvisited'])) {
elseif (isset($_REQUEST['search_lastvisited']))
{
$mode = 'search_lastvisited'; $mode = 'search_lastvisited';
} } elseif (isset($_REQUEST['search_language'])) {
elseif (isset($_REQUEST['search_language']))
{
$mode = 'search_language'; $mode = 'search_language';
} } elseif (isset($_REQUEST['search_timezone'])) {
elseif (isset($_REQUEST['search_timezone']))
{
$mode = 'search_timezone'; $mode = 'search_timezone';
} } elseif (isset($_REQUEST['search_moderators'])) {
elseif (isset($_REQUEST['search_moderators']))
{
$mode = 'search_moderators'; $mode = 'search_moderators';
} } elseif (isset($_REQUEST['search_misc'])) {
elseif (isset($_REQUEST['search_misc']))
{
$mode = 'search_misc'; $mode = 'search_misc';
} }
// validate fields (that they exist) // validate fields (that they exist)
switch ($mode) switch ($mode) {
{
case 'search_username': case 'search_username':
$username = $_REQUEST['username']; $username = $_REQUEST['username'];
if (!$username) bb_die($lang['SEARCH_INVALID_USERNAME']); if (!$username) {
bb_die($lang['SEARCH_INVALID_USERNAME']);
}
break; break;
case 'search_email': case 'search_email':
$email = $_REQUEST['email']; $email = $_REQUEST['email'];
if (!$email) bb_die($lang['SEARCH_INVALID_EMAIL']); if (!$email) {
bb_die($lang['SEARCH_INVALID_EMAIL']);
}
break; break;
case 'search_ip': case 'search_ip':
$ip_address = $_REQUEST['ip_address']; $ip_address = $_REQUEST['ip_address'];
if (!$ip_address) bb_die($lang['SEARCH_INVALID_IP']); if (!$ip_address) {
bb_die($lang['SEARCH_INVALID_IP']);
}
break; break;
case 'search_joindate': case 'search_joindate':
@ -195,55 +160,75 @@ else
$date_day = $_REQUEST['date_day']; $date_day = $_REQUEST['date_day'];
$date_month = $_REQUEST['date_month']; $date_month = $_REQUEST['date_month'];
$date_year = $_REQUEST['date_year']; $date_year = $_REQUEST['date_year'];
if (!($date_type || $date_day || $date_month || $date_year)) bb_die($lang['SEARCH_INVALID_DATE']); if (!($date_type || $date_day || $date_month || $date_year)) {
bb_die($lang['SEARCH_INVALID_DATE']);
}
break; break;
case 'search_group': case 'search_group':
$group_id = $_REQUEST['group_id']; $group_id = $_REQUEST['group_id'];
if (!$group_id) bb_die($lang['SEARCH_INVALID_GROUP']); if (!$group_id) {
bb_die($lang['SEARCH_INVALID_GROUP']);
}
break; break;
case 'search_rank': case 'search_rank':
$rank_id = $_REQUEST['rank_id']; $rank_id = $_REQUEST['rank_id'];
if (!$rank_id) bb_die($lang['SEARCH_INVALID_RANK']); if (!$rank_id) {
bb_die($lang['SEARCH_INVALID_RANK']);
}
break; break;
case 'search_postcount': case 'search_postcount':
$postcount_type = $_REQUEST['postcount_type']; $postcount_type = $_REQUEST['postcount_type'];
$postcount_value = $_REQUEST['postcount_value']; $postcount_value = $_REQUEST['postcount_value'];
if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) bb_die($lang['SEARCH_INVALID_POSTCOUNT']); if (!$postcount_type || (!$postcount_value && $postcount_value != 0)) {
bb_die($lang['SEARCH_INVALID_POSTCOUNT']);
}
break; break;
case 'search_userfield': case 'search_userfield':
$userfield_type = $_REQUEST['userfield_type']; $userfield_type = $_REQUEST['userfield_type'];
$userfield_value = $_REQUEST['userfield_value']; $userfield_value = $_REQUEST['userfield_value'];
if (!$userfield_type || !$userfield_value) bb_die($lang['SEARCH_INVALID_USERFIELD']); if (!$userfield_type || !$userfield_value) {
bb_die($lang['SEARCH_INVALID_USERFIELD']);
}
break; break;
case 'search_lastvisited': case 'search_lastvisited':
$lastvisited_days = $_REQUEST['lastvisited_days']; $lastvisited_days = $_REQUEST['lastvisited_days'];
$lastvisited_type = $_REQUEST['lastvisited_type']; $lastvisited_type = $_REQUEST['lastvisited_type'];
if (!$lastvisited_days || !$lastvisited_type) bb_die($lang['SEARCH_INVALID_LASTVISITED']); if (!$lastvisited_days || !$lastvisited_type) {
bb_die($lang['SEARCH_INVALID_LASTVISITED']);
}
break; break;
case 'search_language': case 'search_language':
$language_type = $_REQUEST['language_type']; $language_type = $_REQUEST['language_type'];
if (!$language_type) bb_die($lang['SEARCH_INVALID_LANGUAGE']); if (!$language_type) {
bb_die($lang['SEARCH_INVALID_LANGUAGE']);
}
break; break;
case 'search_timezone': case 'search_timezone':
$timezone_type = $_REQUEST['timezone_type']; $timezone_type = $_REQUEST['timezone_type'];
if (!$timezone_type && $timezone_type != 0) bb_die($lang['SEARCH_INVALID_TIMEZONE']); if (!$timezone_type && $timezone_type != 0) {
bb_die($lang['SEARCH_INVALID_TIMEZONE']);
}
break; break;
case 'search_moderators': case 'search_moderators':
$moderators_forum = $_REQUEST['moderators_forum']; $moderators_forum = $_REQUEST['moderators_forum'];
if (!$moderators_forum) bb_die($lang['SEARCH_INVALID_MODERATORS']); if (!$moderators_forum) {
bb_die($lang['SEARCH_INVALID_MODERATORS']);
}
break; break;
case 'search_misc': case 'search_misc':
$misc = $_REQUEST['misc']; $misc = $_REQUEST['misc'];
if (!$misc) bb_die($lang['SEARCH_INVALID']); if (!$misc) {
bb_die($lang['SEARCH_INVALID']);
}
break; break;
default: default:
@ -258,8 +243,7 @@ else
$lower_e = ')'; $lower_e = ')';
// validate data & prepare sql // validate data & prepare sql
switch($mode) switch ($mode) {
{
case 'search_username': case 'search_username':
$base_url .= '&search_username=true&username=' . rawurlencode(stripslashes($username)); $base_url .= '&search_username=true&username=' . rawurlencode(stripslashes($username));
@ -267,16 +251,15 @@ else
$username = preg_replace('/\*/', '%', trim(strip_tags(strtolower($username)))); $username = preg_replace('/\*/', '%', trim(strip_tags(strtolower($username))));
if (strstr($username, '%')) if (strstr($username, '%')) {
{
$op = 'LIKE'; $op = 'LIKE';
} } else {
else
{
$op = '='; $op = '=';
} }
if ($username == '') bb_die($lang['SEARCH_INVALID_USERNAME']); if ($username == '') {
bb_die($lang['SEARCH_INVALID_USERNAME']);
}
$total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}username{$lower_e} $op '" . DB()->escape($username) . "' AND user_id <> " . GUEST_UID; $total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}username{$lower_e} $op '" . DB()->escape($username) . "' AND user_id <> " . GUEST_UID;
$select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '" . DB()->escape($username) . "' AND u.user_id <> " . GUEST_UID; $select_sql .= " WHERE {$lower_b}u.username{$lower_e} $op '" . DB()->escape($username) . "' AND u.user_id <> " . GUEST_UID;
@ -289,16 +272,15 @@ else
$email = preg_replace('/\*/', '%', trim(strip_tags(strtolower($email)))); $email = preg_replace('/\*/', '%', trim(strip_tags(strtolower($email))));
if (strstr($email, '%')) if (strstr($email, '%')) {
{
$op = 'LIKE'; $op = 'LIKE';
} } else {
else
{
$op = '='; $op = '=';
} }
if ($email == '') bb_die($lang['SEARCH_INVALID_EMAIL']); if ($email == '') {
bb_die($lang['SEARCH_INVALID_EMAIL']);
}
$total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}user_email{$lower_e} $op '" . DB()->escape($email) . "' AND user_id <> " . GUEST_UID; $total_sql .= "SELECT COUNT(user_id) AS total FROM " . BB_USERS . " WHERE {$lower_b}user_email{$lower_e} $op '" . DB()->escape($email) . "' AND user_id <> " . GUEST_UID;
$select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '" . DB()->escape($email) . "' AND u.user_id <> " . GUEST_UID; $select_sql .= " WHERE {$lower_b}u.user_email{$lower_e} $op '" . DB()->escape($email) . "' AND u.user_id <> " . GUEST_UID;
@ -315,16 +297,12 @@ else
$users = array(); $users = array();
// Let's see if they entered a full valid IPv4 address // Let's see if they entered a full valid IPv4 address
if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) {
{
$ip = encode_ip($ip_address); $ip = encode_ip($ip_address);
$users[] = $ip; $users[] = $ip;
} } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address)) {
elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address))
{
$ip_split = explode('.', $ip_address); $ip_split = explode('.', $ip_address);
switch (count($ip_split)) switch (count($ip_split)) {
{
case 4: case 4:
$users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".255"); $users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".255");
break; break;
@ -335,47 +313,35 @@ else
$users[] = encode_ip($ip_split[0] . ".255.255.255"); $users[] = encode_ip($ip_split[0] . ".255.255.255");
break; break;
} }
} } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) {
elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address))
{
$range = preg_split('/[-\s]+/', $ip_address); $range = preg_split('/[-\s]+/', $ip_address);
$start_range = explode('.', $range[0]); $start_range = explode('.', $range[0]);
$end_range = explode('.', $range[1]); $end_range = explode('.', $range[1]);
if (($start_range[0].$start_range[1].$start_range[2] != $end_range[0].$end_range[1].$end_range[2]) || ($start_range[3] > $end_range[3])) bb_die($lang['SEARCH_INVALID_IP']); if (($start_range[0] . $start_range[1] . $start_range[2] != $end_range[0] . $end_range[1] . $end_range[2]) || ($start_range[3] > $end_range[3])) {
for ($i = $start_range[3]; $i <= $end_range[3]; $i++) bb_die($lang['SEARCH_INVALID_IP']);
{ }
for ($i = $start_range[3]; $i <= $end_range[3]; $i++) {
$users[] = encode_ip($start_range[0] . "." . $start_range[1] . "." . $start_range[2] . "." . $i); $users[] = encode_ip($start_range[0] . "." . $start_range[1] . "." . $start_range[2] . "." . $i);
} }
} } else {
else
{
bb_die($lang['SEARCH_INVALID_IP']); bb_die($lang['SEARCH_INVALID_IP']);
} }
$ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = ''; $ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = '';
foreach ($users as $address) foreach ($users as $address) {
{ if (preg_match('/(ff){1,3}$/i', $address)) {
if (preg_match('/(ff){1,3}$/i', $address)) if (preg_match('/[0-9a-f]{2}ffffff/i', $address)) {
{
if (preg_match('/[0-9a-f]{2}ffffff/i', $address))
{
$ip_start = substr($address, 0, 2); $ip_start = substr($address, 0, 2);
} } elseif (preg_match('/[0-9a-f]{4}ffff/i', $address)) {
elseif (preg_match('/[0-9a-f]{4}ffff/i', $address))
{
$ip_start = substr($address, 0, 4); $ip_start = substr($address, 0, 4);
} } elseif (preg_match('/[0-9a-f]{6}ff/i', $address)) {
elseif (preg_match('/[0-9a-f]{6}ff/i', $address))
{
$ip_start = substr($address, 0, 6); $ip_start = substr($address, 0, 6);
} }
$ip_like_sql_flylast = $ip_like_sql . ($ip_like_sql != '') ? " OR user_last_ip LIKE '" . $ip_start . "%'" : "user_last_ip LIKE '" . $ip_start . "%'"; $ip_like_sql_flylast = $ip_like_sql . ($ip_like_sql != '') ? " OR user_last_ip LIKE '" . $ip_start . "%'" : "user_last_ip LIKE '" . $ip_start . "%'";
$ip_like_sql_flyreg = $ip_like_sql . ($ip_like_sql != '') ? " OR user_reg_ip LIKE '" . $ip_start . "%'" : "user_reg_ip LIKE '" . $ip_start . "%'"; $ip_like_sql_flyreg = $ip_like_sql . ($ip_like_sql != '') ? " OR user_reg_ip LIKE '" . $ip_start . "%'" : "user_reg_ip LIKE '" . $ip_start . "%'";
$ip_like_sql .= ($ip_like_sql != '') ? " OR poster_ip LIKE '" . $ip_start . "%'" : "poster_ip LIKE '" . $ip_start . "%'"; $ip_like_sql .= ($ip_like_sql != '') ? " OR poster_ip LIKE '" . $ip_start . "%'" : "poster_ip LIKE '" . $ip_start . "%'";
} } else {
else
{
$ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'"; $ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'";
} }
} }
@ -384,29 +350,26 @@ else
$where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : ""; $where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : "";
$where_sql .= ($ip_like_sql != '') ? ($where_sql != "") ? " OR $ip_like_sql" : "$ip_like_sql" : ""; $where_sql .= ($ip_like_sql != '') ? ($where_sql != "") ? " OR $ip_like_sql" : "$ip_like_sql" : "";
if (!$where_sql) bb_die('invalid request'); if (!$where_sql) {
bb_die('invalid request');
}
// start search // start search
$no_result_search = false; $no_result_search = false;
$ip_users_sql = ''; $ip_users_sql = '';
$sql = "SELECT poster_id FROM " . BB_POSTS . " WHERE poster_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY poster_id"; $sql = "SELECT poster_id FROM " . BB_POSTS . " WHERE poster_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY poster_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not count users #1'); bb_die('Could not count users #1');
} }
if (DB()->num_rows($result) == 0) if (DB()->num_rows($result) == 0) {
{
$no_result_search = true; $no_result_search = true;
} } else {
else
{
$total_pages['total'] = DB()->num_rows($result); $total_pages['total'] = DB()->num_rows($result);
$total_sql = NULL; $total_sql = null;
$ip_users_sql = ''; $ip_users_sql = '';
while($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$ip_users_sql .= ($ip_users_sql == '') ? $row['poster_id'] : ', ' . $row['poster_id']; $ip_users_sql .= ($ip_users_sql == '') ? $row['poster_id'] : ', ' . $row['poster_id'];
} }
} }
@ -414,17 +377,16 @@ else
$where_sql .= ($ip_in_sql != '') ? "user_last_ip IN ($ip_in_sql)" : ""; $where_sql .= ($ip_in_sql != '') ? "user_last_ip IN ($ip_in_sql)" : "";
$where_sql .= ($ip_like_sql_flylast != '') ? ($where_sql != "") ? " OR $ip_like_sql_flylast" : "$ip_like_sql_flylast" : ""; $where_sql .= ($ip_like_sql_flylast != '') ? ($where_sql != "") ? " OR $ip_like_sql_flylast" : "$ip_like_sql_flylast" : "";
$sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; $sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not count users #2'); bb_die('Could not count users #2');
} }
if (DB()->num_rows($result) != 0) if (DB()->num_rows($result) != 0) {
{ if ($no_result_search == true) {
if ($no_result_search == true) $no_result_search = false; $no_result_search = false;
}
$total_pages['total'] = DB()->num_rows($result); $total_pages['total'] = DB()->num_rows($result);
$total_sql = NULL; $total_sql = null;
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id'];
} }
} }
@ -432,22 +394,20 @@ else
$where_sql .= ($ip_in_sql != '') ? "user_reg_ip IN ($ip_in_sql)" : ""; $where_sql .= ($ip_in_sql != '') ? "user_reg_ip IN ($ip_in_sql)" : "";
$where_sql .= ($ip_like_sql_flyreg != '') ? ($where_sql != "") ? " OR $ip_like_sql_flyreg" : "$ip_like_sql_flyreg" : ""; $where_sql .= ($ip_like_sql_flyreg != '') ? ($where_sql != "") ? " OR $ip_like_sql_flyreg" : "$ip_like_sql_flyreg" : "";
$sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id"; $sql = "SELECT user_id FROM " . BB_USERS . " WHERE user_id <> " . GUEST_UID . " AND ($where_sql) GROUP BY user_id";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not count users #3'); bb_die('Could not count users #3');
} }
if (DB()->num_rows($result) != 0) if (DB()->num_rows($result) != 0) {
{ if ($no_result_search == true) {
if ($no_result_search == true) $no_result_search = false; $no_result_search = false;
}
$total_pages['total'] = DB()->num_rows($result); $total_pages['total'] = DB()->num_rows($result);
$total_sql = NULL; $total_sql = null;
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id']; $ip_users_sql .= ($ip_users_sql == '') ? $row['user_id'] : ', ' . $row['user_id'];
} }
} }
if ($no_result_search == true) if ($no_result_search == true) {
{
bb_die($lang['SEARCH_NO_RESULTS']); bb_die($lang['SEARCH_NO_RESULTS']);
} }
@ -459,29 +419,25 @@ else
$date_type = trim(strtolower($date_type)); $date_type = trim(strtolower($date_type));
if ($date_type != 'before' && $date_type != 'after') if ($date_type != 'before' && $date_type != 'after') {
{
bb_die($lang['SEARCH_INVALID_DATE']); bb_die($lang['SEARCH_INVALID_DATE']);
} }
$date_day = intval($date_day); $date_day = intval($date_day);
if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) if (!preg_match('/^([1-9]|[0-2][0-9]|3[0-1])$/', $date_day)) {
{
bb_die($lang['SEARCH_INVALID_DAY']); bb_die($lang['SEARCH_INVALID_DAY']);
} }
$date_month = intval($date_month); $date_month = intval($date_month);
if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) if (!preg_match('/^(0?[1-9]|1[0-2])$/', $date_month)) {
{
bb_die($lang['SEARCH_INVALID_MONTH']); bb_die($lang['SEARCH_INVALID_MONTH']);
} }
$date_year = intval($date_year); $date_year = intval($date_year);
if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) if (!preg_match('/^(20[0-9]{2}|19[0-9]{2})$/', $date_year)) {
{
bb_die($lang['SEARCH_INVALID_YEAR']); bb_die($lang['SEARCH_INVALID_YEAR']);
} }
@ -489,12 +445,9 @@ else
$time = mktime(0, 0, 0, $date_month, $date_day, $date_year); $time = mktime(0, 0, 0, $date_month, $date_day, $date_year);
if ($date_type == 'before') if ($date_type == 'before') {
{
$arg = '<'; $arg = '<';
} } else {
else
{
$arg = '>'; $arg = '>';
} }
@ -507,20 +460,17 @@ else
$base_url .= '&search_group=true&group_id=' . rawurlencode($group_id); $base_url .= '&search_group=true&group_id=' . rawurlencode($group_id);
if (!$group_id) if (!$group_id) {
{
bb_die($lang['SEARCH_INVALID_GROUP']); bb_die($lang['SEARCH_INVALID_GROUP']);
} }
$sql = "SELECT group_name FROM " . BB_GROUPS . " WHERE group_id = $group_id AND group_single_user = 0"; $sql = "SELECT group_name FROM " . BB_GROUPS . " WHERE group_id = $group_id AND group_single_user = 0";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select group data #2'); bb_die('Could not select group data #2');
} }
if (DB()->num_rows($result)==0) if (DB()->num_rows($result) == 0) {
{
bb_die($lang['SEARCH_INVALID_GROUP']); bb_die($lang['SEARCH_INVALID_GROUP']);
} }
@ -545,20 +495,17 @@ else
$base_url .= '&search_rank=true&rank_id=' . rawurlencode($rank_id); $base_url .= '&search_rank=true&rank_id=' . rawurlencode($rank_id);
if (!$rank_id) if (!$rank_id) {
{
bb_die($lang['SEARCH_INVALID_RANK']); bb_die($lang['SEARCH_INVALID_RANK']);
} }
$sql = "SELECT rank_title FROM " . BB_RANKS . " WHERE rank_id = $rank_id AND rank_special = 1"; $sql = "SELECT rank_title FROM " . BB_RANKS . " WHERE rank_id = $rank_id AND rank_special = 1";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select rank data'); bb_die('Could not select rank data');
} }
if (DB()->num_rows($result)==0) if (DB()->num_rows($result) == 0) {
{
bb_die($lang['SEARCH_INVALID_RANK']); bb_die($lang['SEARCH_INVALID_RANK']);
} }
@ -581,8 +528,7 @@ else
$base_url .= '&search_postcount=true&postcount_type=' . rawurlencode($postcount_type) . '&postcount_value=' . rawurlencode(stripslashes($postcount_value)); $base_url .= '&search_postcount=true&postcount_type=' . rawurlencode($postcount_type) . '&postcount_value=' . rawurlencode(stripslashes($postcount_value));
switch($postcount_type) switch ($postcount_type) {
{
case 'greater': case 'greater':
$postcount_value = intval($postcount_value); $postcount_value = intval($postcount_value);
@ -611,15 +557,13 @@ else
break; break;
case 'equals': case 'equals':
// looking for a - // looking for a -
if (strstr($postcount_value, '-')) if (strstr($postcount_value, '-')) {
{
$range = preg_split('/[-\s]+/', $postcount_value); $range = preg_split('/[-\s]+/', $postcount_value);
$range_begin = intval($range[0]); $range_begin = intval($range[0]);
$range_end = intval($range[1]); $range_end = intval($range[1]);
if ($range_begin > $range_end) if ($range_begin > $range_end) {
{
bb_die($lang['SEARCH_INVALID_POSTCOUNT']); bb_die($lang['SEARCH_INVALID_POSTCOUNT']);
} }
@ -634,9 +578,7 @@ else
$select_sql .= " WHERE u.user_posts >= $range_begin $select_sql .= " WHERE u.user_posts >= $range_begin
AND u.user_posts <= $range_end AND u.user_posts <= $range_end
AND u.user_id <> " . GUEST_UID; AND u.user_id <> " . GUEST_UID;
} } else {
else
{
$postcount_value = intval($postcount_value); $postcount_value = intval($postcount_value);
$text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value); $text = sprintf($lang['SEARCH_FOR_POSTCOUNT_EQUALS'], $postcount_value);
@ -662,21 +604,19 @@ else
$userfield_value = preg_replace('/\*/', '%', trim(strip_tags(strtolower($userfield_value)))); $userfield_value = preg_replace('/\*/', '%', trim(strip_tags(strtolower($userfield_value))));
if (strstr($userfield_value, '%')) if (strstr($userfield_value, '%')) {
{
$op = 'LIKE'; $op = 'LIKE';
} } else {
else
{
$op = '='; $op = '=';
} }
if ($userfield_value == '') bb_die($lang['SEARCH_INVALID_USERFIELD']); if ($userfield_value == '') {
bb_die($lang['SEARCH_INVALID_USERFIELD']);
}
$userfield_type = trim(strtolower($userfield_type)); $userfield_type = trim(strtolower($userfield_type));
switch ($userfield_type) switch ($userfield_type) {
{
case 'icq': case 'icq':
$text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'], $text); $text = sprintf($lang['SEARCH_FOR_USERFIELD_ICQ'], $text);
$field = 'user_icq'; $field = 'user_icq';
@ -726,8 +666,7 @@ else
$lastvisited_seconds = (TIMENOW - ((($lastvisited_days * 24) * 60) * 60)); $lastvisited_seconds = (TIMENOW - ((($lastvisited_days * 24) * 60) * 60));
switch($lastvisited_type) switch ($lastvisited_type) {
{
case 'in': case 'in':
$text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], $lastvisited_days, (($lastvisited_days > 1) ? $lang['DAYS'] : $lang['DAY'])); $text = sprintf($lang['SEARCH_FOR_LASTVISITED_INTHELAST'], $lastvisited_days, (($lastvisited_days > 1) ? $lang['DAYS'] : $lang['DAY']));
@ -761,8 +700,7 @@ else
$language_type = trim(strtolower(stripslashes($language_type))); $language_type = trim(strtolower(stripslashes($language_type)));
if ($language_type == '') if ($language_type == '') {
{
bb_die($lang['SEARCH_INVALID_LANGUAGE']); bb_die($lang['SEARCH_INVALID_LANGUAGE']);
} }
@ -798,13 +736,11 @@ else
$sql = "SELECT forum_name FROM " . BB_FORUMS . " WHERE forum_id = " . $moderators_forum; $sql = "SELECT forum_name FROM " . BB_FORUMS . " WHERE forum_id = " . $moderators_forum;
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select forum data'); bb_die('Could not select forum data');
} }
if (DB()->num_rows($result)==0) if (DB()->num_rows($result) == 0) {
{
bb_die($lang['SEARCH_INVALID_MODERATORS']); bb_die($lang['SEARCH_INVALID_MODERATORS']);
} }
@ -837,8 +773,7 @@ else
$base_url .= '&search_misc=true&misc=' . rawurlencode(stripslashes($misc)); $base_url .= '&search_misc=true&misc=' . rawurlencode(stripslashes($misc));
switch ($misc) switch ($misc) {
{
case 'admins': case 'admins':
$text = $lang['SEARCH_FOR_ADMINS']; $text = $lang['SEARCH_FOR_ADMINS'];
@ -893,8 +828,7 @@ else
$select_sql .= " ORDER BY "; $select_sql .= " ORDER BY ";
switch (strtolower($_GET['sort'])) switch (strtolower($_GET['sort'])) {
{
case 'regdate': case 'regdate':
$sort = 'regdate'; $sort = 'regdate';
$select_sql .= 'u.user_regdate'; $select_sql .= 'u.user_regdate';
@ -921,8 +855,7 @@ else
$select_sql .= 'u.username'; $select_sql .= 'u.username';
} }
switch ($_GET['order']) switch ($_GET['order']) {
{
case 'DESC': case 'DESC':
$order = 'DESC'; $order = 'DESC';
$o_order = 'ASC'; $o_order = 'ASC';
@ -937,17 +870,13 @@ else
$page = (isset($_GET['page'])) ? intval($_GET['page']) : intval(trim($_POST['page'])); $page = (isset($_GET['page'])) ? intval($_GET['page']) : intval(trim($_POST['page']));
if ($page < 1) if ($page < 1) {
{
$page = 1; $page = 1;
} }
if ($page == 1) if ($page == 1) {
{
$offset = 0; $offset = 0;
} } else {
else
{
$offset = (($page - 1) * $di->config->get('topics_per_page')); $offset = (($page - 1) * $di->config->get('topics_per_page'));
} }
@ -955,17 +884,14 @@ else
$select_sql .= " $limit"; $select_sql .= " $limit";
if (!is_null($total_sql)) if (!is_null($total_sql)) {
{ if (!$result = DB()->sql_query($total_sql)) {
if (!$result = DB()->sql_query($total_sql))
{
bb_die('Could not count users'); bb_die('Could not count users');
} }
$total_pages = DB()->sql_fetchrow($result); $total_pages = DB()->sql_fetchrow($result);
if ($total_pages['total'] == 0) if ($total_pages['total'] == 0) {
{
bb_die($lang['SEARCH_NO_RESULTS']); bb_die($lang['SEARCH_NO_RESULTS']);
} }
} }
@ -973,16 +899,13 @@ else
$pagination = ''; $pagination = '';
if ($page > 1) if ($page > 1) {
{
$pagination .= '<a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page - 1) . '">' . $lang['PREVIOUS'] . '</a>'; $pagination .= '<a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page - 1) . '">' . $lang['PREVIOUS'] . '</a>';
} }
if ($page < $num_pages) if ($page < $num_pages) {
{
$pagination .= ($pagination == '') ? '<a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page + 1) . '">' . $lang['NEXT'] . '</a>' : ' | <a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page + 1) . '">' . $lang['NEXT'] . '</a>'; $pagination .= ($pagination == '') ? '<a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page + 1) . '">' . $lang['NEXT'] . '</a>' : ' | <a href="' . $base_url . '&sort=' . $sort . '&order=' . $order . '&page=' . ($page + 1) . '">' . $lang['NEXT'] . '</a>';
} }
if ($num_pages > 2) if ($num_pages > 2) {
{
$pagination .= '&nbsp;&nbsp;<input type="text" name="page" maxlength="5" size="2" class="post" />&nbsp;<input type="submit" name="submit" value="' . $lang['GO'] . '" class="post" />'; $pagination .= '&nbsp;&nbsp;<input type="text" name="page" maxlength="5" size="2" class="post" />&nbsp;<input type="submit" name="submit" value="' . $lang['GO'] . '" class="post" />';
} }
$template->assign_vars(array( $template->assign_vars(array(
@ -1001,8 +924,7 @@ else
'S_POST_ACTION' => "$base_url&sort=$sort&order=$order" 'S_POST_ACTION' => "$base_url&sort=$sort&order=$order"
)); ));
if (!$result = DB()->sql_query($select_sql)) if (!$result = DB()->sql_query($select_sql)) {
{
bb_die('Could not select user data'); bb_die('Could not select user data');
} }
@ -1010,15 +932,13 @@ else
$users_sql = ''; $users_sql = '';
foreach ($rowset as $array) foreach ($rowset as $array) {
{
$users_sql .= ($users_sql == '') ? $array['user_id'] : ', ' . $array['user_id']; $users_sql .= ($users_sql == '') ? $array['user_id'] : ', ' . $array['user_id'];
} }
$sql = "SELECT ban_userid AS user_id FROM " . BB_BANLIST . " WHERE ban_userid IN ($users_sql)"; $sql = "SELECT ban_userid AS user_id FROM " . BB_BANLIST . " WHERE ban_userid IN ($users_sql)";
if (!$result = DB()->sql_query($sql)) if (!$result = DB()->sql_query($sql)) {
{
bb_die('Could not select banned data'); bb_die('Could not select banned data');
} }
@ -1026,13 +946,11 @@ else
$banned = array(); $banned = array();
while ($row = DB()->sql_fetchrow($result)) while ($row = DB()->sql_fetchrow($result)) {
{
$banned[$row['user_id']] = true; $banned[$row['user_id']] = true;
} }
for ($i = 0; $i < count($rowset); $i++) for ($i = 0; $i < count($rowset); $i++) {
{
$row_class = !($i % 2) ? 'row1' : 'row2'; $row_class = !($i % 2) ? 'row1' : 'row2';
$template->assign_block_vars('userrow', array( $template->assign_block_vars('userrow', array(

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,9 +57,7 @@ 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,
@ -82,61 +77,47 @@ 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'];
} }
} }
@ -144,14 +125,10 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
} }
} }
$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,
)); ));
@ -185,8 +161,7 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
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);
@ -196,35 +171,28 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
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++;
@ -266,16 +232,12 @@ elseif (isset($_GET['pane']) && $_GET['pane'] == 'right')
)); ));
} }
} }
} } 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

@ -8,18 +8,15 @@ 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

@ -6,7 +6,9 @@ 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';
@ -18,25 +20,19 @@ $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";

View file

@ -9,9 +9,11 @@ $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'));
@ -38,14 +40,12 @@ DB()->query("
$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
@ -55,8 +55,7 @@ $stat += DB()->fetch_row("SELECT COUNT(*) AS tor_all, SUM(size) AS torrents_size
// 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) . "
"); ");
@ -65,8 +64,7 @@ foreach ($peers_in_last_minutes as $t)
// 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" : '');
} }
@ -74,20 +72,16 @@ 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
@ -111,26 +105,20 @@ echo "\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>';

141
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;
@ -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,114 +300,113 @@ 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

@ -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,13 +63,11 @@ $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
@ -80,52 +75,38 @@ $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,11 +130,12 @@ $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);
} }
@ -163,8 +144,7 @@ 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
} }
@ -175,7 +155,9 @@ function drop_fast_announce ($lp_info)
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,
@ -188,9 +170,6 @@ function msg_die ($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,9 +205,7 @@ 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);
@ -243,12 +220,10 @@ else
$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)');
} }
@ -258,17 +233,13 @@ else
$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,36 +249,29 @@ 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'); 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']) {
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); 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
@ -315,20 +279,15 @@ else
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"); 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']) {
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"); 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,28 +312,25 @@ $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";
@ -402,22 +355,24 @@ 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();
} }
@ -435,15 +390,18 @@ $lp_info = array(
$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));
@ -456,21 +414,16 @@ if (!$output)
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,8 +434,7 @@ 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 . "
@ -504,7 +456,9 @@ if (!$output)
$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,9 +1,13 @@
<?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
@ -12,10 +16,8 @@ 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_init_perc = round($DBS->sql_inittime * 100 / $gen_time);
$sql_total_perc = round($DBS->sql_timetotal * 100 / $gen_time); $sql_total_perc = round($DBS->sql_timetotal * 100 / $gen_time);
@ -42,7 +44,9 @@ function silent_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,25 +303,30 @@ 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');
@ -323,15 +335,14 @@ class sql_db
/** /**
* 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,29 +392,26 @@ 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'));
@ -423,20 +427,19 @@ 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() . "]";
} }
@ -447,15 +450,13 @@ 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();

View file

@ -4,16 +4,16 @@ 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');
} }
@ -21,7 +21,9 @@ $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,

View file

@ -16,12 +16,9 @@ $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));
} }
@ -30,8 +27,7 @@ $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);
@ -51,20 +47,17 @@ $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);
} }
@ -87,8 +80,7 @@ function topic_info ($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'];
} }
@ -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,6 +131,8 @@ $DBS = new DBS([
/** /**
* TODO: @deprecated * TODO: @deprecated
* @param string $db_alias
* @return mixed
*/ */
function DB($db_alias = 'db') function DB($db_alias = 'db')
{ {
@ -139,8 +153,7 @@ 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;
@ -167,7 +180,8 @@ 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()
@ -180,10 +194,8 @@ 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);
} }
} }
@ -199,8 +211,7 @@ function utime ()
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 : '';
@ -211,35 +222,29 @@ function file_write ($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $repla
{ {
$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);
} }
@ -260,12 +265,9 @@ function bb_mkdir ($path, $mode = 0777)
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;
} }
} }
@ -328,8 +330,7 @@ function str_compact ($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);
@ -337,33 +338,21 @@ function make_rand_str ($len = 10)
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);
} }
} }
@ -375,8 +364,7 @@ function hide_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;
@ -419,8 +407,12 @@ function log_request ($file = '', $prepend_str = false, $add_post = true)
$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,19 +425,18 @@ 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
// Tracker init elseif (defined('IN_TRACKER')) {
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)
@ -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));
} }
} }

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,13 +34,10 @@ 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");
} }
@ -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,40 +94,31 @@ 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,

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') {

233
group.php
View file

@ -28,18 +28,18 @@ function generate_user_info(&$row, $date_format, $group_mod, &$from, &$posts, &$
$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;
} }
@ -57,21 +57,17 @@ $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;
@ -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,8 +128,7 @@ 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'];
@ -156,8 +137,7 @@ if (!$group_id)
$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>';
@ -165,12 +145,10 @@ if (!$group_id)
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,20 +161,15 @@ 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 {
else bb_die($lang['NO_GROUPS_EXIST']); bb_die($lang['NO_GROUPS_EXIST']);
} }
} }
else if (isset($_POST['joingroup']) && $_POST['joingroup']) } elseif (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']);
} }
@ -211,20 +184,17 @@ else if (isset($_POST['joingroup']) && $_POST['joingroup'])
$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'));
@ -246,37 +216,28 @@ 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'));
@ -294,25 +255,19 @@ 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
@ -321,29 +276,24 @@ else
"); ");
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');
} }
@ -352,8 +302,7 @@ else
$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']}>");
} }
@ -388,53 +337,37 @@ else
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'];
} }
@ -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']);
} }
@ -538,14 +464,12 @@ else
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(
@ -599,14 +523,12 @@ 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(
@ -624,28 +546,24 @@ 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
@ -658,10 +576,8 @@ 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);
@ -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

@ -19,35 +19,26 @@ $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));
} }
@ -56,16 +47,11 @@ if ($is_moderator)
} }
$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'];
} }
@ -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);

115
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');
} }
@ -58,15 +56,13 @@ $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");
} }
@ -172,25 +167,19 @@ $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) {
{
foreach ($user_ids as $user_id)
{
$moderators[$forum_id][] = '<a href="' . PROFILE_URL . $user_id . '">' . $mod['name_users'][$user_id] . '</a>'; $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'],
@ -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,18 +338,14 @@ 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;
} }
@ -382,16 +353,14 @@ if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled
} }
$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;
} }
@ -399,8 +368,9 @@ if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled
} }
$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,12 +379,9 @@ 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)) {
{
if (file_exists(CRON_ALLOWED))
{
unlink(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

@ -13,8 +13,7 @@ $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';
@ -50,12 +49,23 @@ $require = file_exists($html_dir . $info['src']) ? $html_dir . $info['src'] : $h
</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 {
background: #FFFFFF;
color: #000000;
padding: 1em;
height: 400px;
overflow: auto;
border: 1px inset #000000;
}
#infobox-body p {
margin-top: 1em;
margin-bottom: 1em;
} }
#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">
@ -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,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $user; global $lang, $user;
@ -10,18 +12,15 @@ $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;

View file

@ -1,19 +1,22 @@
<?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'];
} }
@ -27,46 +30,48 @@ $tor = DB()->fetch_row("
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 = $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 .= ($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'] . '?'; $msg .= $lang['PROCEED'] . '?';
@ -78,14 +83,14 @@ switch ($mode)
$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,19 +1,18 @@
<?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');
} }
@ -22,21 +21,15 @@ $topic_id = (int) $this->request['t'];
$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,26 +1,24 @@
<?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]));
} }
} }

View file

@ -1,19 +1,19 @@
<?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");
} }

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':

View file

@ -1,31 +1,29 @@
<?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'];
@ -34,46 +32,43 @@ switch ($field)
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,8 +133,7 @@ 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);

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,21 +1,20 @@
<?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
@ -26,27 +25,21 @@ switch ($mode)
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"; // сам юзер модератор этой группы
} }
@ -54,12 +47,9 @@ switch ($mode)
$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,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata, $datastore; global $lang, $userdata, $datastore;
@ -10,23 +12,21 @@ $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,15 +35,14 @@ 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':
@ -56,18 +55,14 @@ 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>';
} }
} }
@ -80,8 +75,12 @@ switch($mode)
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;

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;
@ -12,8 +14,7 @@ $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();
@ -40,10 +41,8 @@ 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);
} }
} }
@ -57,15 +56,13 @@ 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);
} }

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,59 +12,72 @@ $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);
@ -72,8 +87,12 @@ 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);

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, $datastore; global $userdata, $lang, $datastore;
@ -9,22 +11,19 @@ $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);
} }
@ -37,11 +36,14 @@ switch ($mode)
$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']);
@ -52,15 +54,13 @@ switch ($mode)
// Обновление кеша новостей на главной // Обновление кеша новостей на главной
$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');
} }
@ -73,7 +73,9 @@ switch ($mode)
$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']}'
@ -88,28 +90,25 @@ switch ($mode)
$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>';

View file

@ -1,13 +1,17 @@
<?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
@ -15,7 +19,9 @@ $post = DB()->fetch_row("
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 : '',
@ -25,8 +31,7 @@ $data = array(
$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);
@ -34,8 +39,7 @@ if ($mc_type && $post['poster_id'] != $userdata['user_id'])
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,18 +1,18 @@
<?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
@ -21,42 +21,39 @@ if (isset($this->request['post_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);
@ -66,20 +63,15 @@ switch($this->request['type'])
$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'])));
} }
@ -91,17 +83,14 @@ switch($this->request['type'])
// 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);
} }
@ -111,7 +100,9 @@ switch($this->request['type'])
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,38 +111,28 @@ 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') {
elseif ($this->request['type'] == 'editor')
{
$text = (string)$this->request['text']; $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')) {
{
if ($di->config->get('max_smilies'))
{
$count_smilies = substr_count(bbcode2html($text), '<img class="smile" src="' . $di->config->get('smilies_path')); $count_smilies = substr_count(bbcode2html($text), '<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()->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);
@ -162,23 +143,19 @@ 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'])));
} }
@ -231,21 +208,16 @@ 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']);
} }
@ -256,20 +228,16 @@ switch($this->request['type'])
$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
@ -279,22 +247,18 @@ switch($this->request['type'])
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')));
} }
} }
@ -313,8 +277,7 @@ 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);
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
@ -11,12 +13,10 @@ $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'];
@ -24,7 +24,9 @@ switch ($mode)
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');

View file

@ -1,10 +1,14 @@
<?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');
@ -12,42 +16,34 @@ $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('не заполнен формат создания сообщения');
} }
@ -69,8 +65,7 @@ switch ($mode)
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'];
@ -92,29 +87,22 @@ switch ($mode)
// включение / отключение шаблона в форуме // включение / отключение шаблона в форуме
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;
@ -125,16 +113,14 @@ switch ($mode)
// сохранение изменений // сохранение изменений
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;
@ -146,8 +132,7 @@ 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,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang, $userdata; global $lang, $userdata;
@ -10,17 +12,13 @@ $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)) {
elseif($err = validate_username($username))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>'; $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>';
} }
break; break;
@ -28,12 +26,9 @@ switch($mode)
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)) {
elseif($err = validate_email($email))
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>'; $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $err . '</span>';
} }
break; break;
@ -41,28 +36,17 @@ switch($mode)
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 {
else if ($pass != $pass_confirm) {
{
if ($pass != $pass_confirm)
{
$html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS_ERR'] . '</span>'; $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . $lang['CHOOSE_PASS_ERR'] . '</span>';
} } else {
else if (mb_strlen($pass, 'UTF-8') > 20) {
{
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">' . sprintf($lang['CHOOSE_PASS_ERR_MAX'], 20) . '</span>';
} } elseif (mb_strlen($pass, 'UTF-8') < 5) {
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>'; $html = '<img src="./styles/images/bad.gif"> <span class="leechmed bold">' . sprintf($lang['CHOOSE_PASS_ERR_MIN'], 5) . '</span>';
} } else {
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,14 +1,15 @@
<?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');
} }
@ -26,24 +27,18 @@ $sql = "
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,11 +1,12 @@
<?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'];
@ -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)); $this->ajax_die($lang['ERROR_NO_ATTACHMENT'] . "\n\n" . htmlCHR($file_path));
} } else {
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);
/**
* @param $file_contents
* @return string
*/
function build_tor_filelist($file_contents) 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,61 +45,66 @@ 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');
@ -107,25 +112,20 @@ class torrent
$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,17 +133,13 @@ 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;
@ -153,7 +149,12 @@ class torrent
} }
} }
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,8 +163,7 @@ 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>';
} }
@ -171,18 +171,27 @@ class torrent
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);
} }
} }
/**
* @param $dirname
* @return mixed
*/
function clean_tor_dirname($dirname) function clean_tor_dirname($dirname)
{ {
return str_replace(array('[', ']', '<', '>', "'"), array('&#91;', '&#93;', '&lt;', '&gt;', '&#039;'), $dirname); return str_replace(array('[', ']', '<', '>', "'"), array('&#91;', '&#93;', '&lt;', '&gt;', '&#039;'), $dirname);
} }
if ($bnc_error) $tor_filelist = '<b style="color: #993300;">'.$lang['ERROR_BUILD'].'</b><br /><br />'.$tor_filelist; if ($bnc_error) {
$tor_filelist = '<b style="color: #993300;">' . $lang['ERROR_BUILD'] . '</b><br /><br />' . $tor_filelist;
}
$this->response['html'] = $tor_filelist; $this->response['html'] = $tor_filelist;

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;

View file

@ -1,6 +1,8 @@
<?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

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,6 +13,9 @@ $page_cfg['include_bbcode_js'] = true;
// //
// BBCode templates // BBCode templates
// //
/**
* @return array
*/
function get_bbcode_tpl() function get_bbcode_tpl()
{ {
$bbcode_tpl = array(); $bbcode_tpl = array();
@ -77,6 +82,10 @@ array_deep($bbcode_tpl, 'bbcode_tpl_compact');
return $bbcode_tpl; return $bbcode_tpl;
} }
/**
* @param $text
* @return mixed
*/
function bbcode_tpl_compact($text) function bbcode_tpl_compact($text)
{ {
$text = str_compact($text); $text = str_compact($text);
@ -85,6 +94,10 @@ function bbcode_tpl_compact ($text)
} }
// prepare a posted message for entry into the database // prepare a posted message for entry into the database
/**
* @param $message
* @return mixed|string
*/
function prepare_message($message) function prepare_message($message)
{ {
$message = bbcode::clean_up($message); $message = bbcode::clean_up($message);
@ -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,23 +154,18 @@ 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(
@ -175,8 +180,7 @@ function generate_smilies($mode)
} }
} }
if ($mode == 'window') if ($mode == 'window') {
{
print_page('posting_smilies.tpl', 'simple'); print_page('posting_smilies.tpl', 'simple');
} }
} }
@ -195,38 +199,30 @@ function strip_quotes ($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;
} }
@ -301,24 +287,20 @@ function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $
$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,6 +328,10 @@ function strip_bbcode ($message, $stripquotes = true, $fast_and_dirty = false, $
return $message; return $message;
} }
/**
* @param $text
* @return mixed|string
*/
function extract_search_words($text) function extract_search_words($text)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
@ -383,14 +368,14 @@ 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);
} }
@ -398,12 +383,15 @@ function extract_search_words ($text)
return $text; return $text;
} }
/**
* @param $text
* @return mixed
*/
function replace_synonyms($text) function replace_synonyms($text)
{ {
static $syn_match = null, $syn_replace = null; static $syn_match = null, $syn_replace = null;
if (is_null($syn_match)) 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];
@ -416,6 +404,13 @@ 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;
} }
/**
* @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) function add_search_words($post_id, $post_message, $topic_title = '', $only_return_words = false)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
@ -424,28 +419,27 @@ function add_search_words ($post_id, $post_message, $topic_title = '', $only_ret
$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);
@ -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 = "#
(?<![\"'=]) (?<![\"'=])
@ -794,7 +777,7 @@ 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();
@ -803,12 +786,9 @@ class bbcode
$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,41 +838,46 @@ 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;
} }
} }
/**
* @param $text
* @return string
*/
function bbcode2html($text) 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');
@ -912,38 +895,32 @@ 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>';
@ -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,16 +942,23 @@ class words_rate
} }
} }
/**
* @param $text
* @return int
*/
function get_words_rate($text) 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);
} }
/**
* @param $str
* @return mixed
*/
function hide_passkey($str) function hide_passkey($str)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
@ -984,21 +967,25 @@ function hide_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); return preg_replace("#\?{$di->config->get('passkey_key')}=[a-zA-Z0-9]{" . BT_AUTH_KEY_LENGTH . "}#", "?{$di->config->get('passkey_key')}=passkey", $str);
} }
/**
* @param $postrow
* @param string $mode
* @param int $return_chars
* @return string
*/
function get_parsed_post($postrow, $mode = 'full', $return_chars = 600) 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,
@ -1008,6 +995,9 @@ function get_parsed_post ($postrow, $mode = 'full', $return_chars = 600)
return $message; return $message;
} }
/**
* @param $postrow
*/
function update_post_html($postrow) function update_post_html($postrow)
{ {
DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_id = " . (int)$postrow['post_id'] . " LIMIT 1"); DB()->query("DELETE FROM " . BB_POSTS_HTML . " WHERE post_id = " . (int)$postrow['post_id'] . " LIMIT 1");

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,21 +157,27 @@ 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;
} }
@ -150,8 +187,7 @@ class emailer
// 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;
} }
@ -159,8 +195,7 @@ class emailer
// 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,7 +204,13 @@ 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);
@ -175,10 +232,16 @@ 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);

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,6 +1,8 @@
<?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');
@ -13,14 +15,11 @@ $cron_jobs = DB()->fetch_rowset("
"); ");
// 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;
@ -31,8 +30,6 @@ if ($cron_jobs)
// 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
// //
/**
* @return bool
*/
function cron_get_file_lock() function cron_get_file_lock()
{ {
$lock_obtained = false; $lock_obtained = false;
if (file_exists(CRON_ALLOWED)) if (file_exists(CRON_ALLOWED)) {
{
# bb_log(date('H:i:s - ') . getmypid() .' -x-- FILE-LOCK try'. LOG_LF, CRON_LOG_DIR .'cron_check'); # 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;
} }
/**
* @param $mode
*/
function cron_track_running($mode) function cron_track_running($mode)
{ {
defined('CRON_STARTMARK') or define('CRON_STARTMARK', TRIGGERS_DIR . 'cron_started_at_' . date('Y-m-d_H-i-s') . '_by_pid_' . getmypid()); defined('CRON_STARTMARK') or define('CRON_STARTMARK', TRIGGERS_DIR . 'cron_started_at_' . date('Y-m-d_H-i-s') . '_by_pid_' . getmypid());
if ($mode == 'start') 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');
@ -61,7 +60,6 @@ if (cron_get_file_lock())
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,22 +54,19 @@ 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');
@ -82,8 +78,7 @@ foreach ($cron_jobs as $job)
$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));
} }
@ -116,13 +111,10 @@ 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,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,15 +15,13 @@ 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;
@ -30,12 +30,10 @@ if ($poll_max_days = (int) $di->config->get('poll_max_days'))
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;
@ -46,7 +44,6 @@ if ($poll_max_days = (int) $di->config->get('poll_max_days'))
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,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();
@ -15,10 +17,8 @@ $keeping_dlstat = array(
$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,8 +27,7 @@ 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)");
} }
@ -48,8 +47,7 @@ DB()->query("
"); ");
// 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)");
} }

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();

View file

@ -1,6 +1,8 @@
<?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;

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,6 +1,8 @@
<?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(

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,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();
@ -9,14 +11,12 @@ 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
@ -25,14 +25,12 @@ while (true)
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
@ -40,19 +38,16 @@ while (true)
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,12 +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();
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("

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();

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();
@ -21,8 +23,7 @@ DB()->query("CREATE TABLE ". NEW_BB_BT_LAST_USERSTAT ." LIKE ". BB_BT_LAST_USERS
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,
@ -59,8 +60,7 @@ DB()->query("
"); ");
// 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);
@ -69,8 +69,7 @@ if ($tr_cfg['autoclean'])
} }
// 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
@ -97,8 +96,7 @@ if ($tr_cfg['update_dlstat'])
// 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,

View file

@ -1,12 +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();
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
@ -17,9 +18,7 @@ if ($di->config->get('ocelot.enabled'))
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

View file

@ -1,12 +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();
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;
} }
@ -22,14 +23,12 @@ $sql = "SELECT topic_id
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 . "

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');
@ -24,15 +25,13 @@ $row = DB()->fetch_row("SELECT MIN(topic_id) AS start_id, MAX(topic_id) AS finis
$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,23 +50,18 @@ 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)
@ -79,21 +71,18 @@ while (true)
} }
} }
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 . ",
@ -113,8 +102,7 @@ DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_DLSTATUS_SNAP .", ". OLD_BB_BT_DL
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)
@ -137,8 +125,7 @@ DB()->query("DROP TABLE IF EXISTS ". NEW_BB_BT_DLSTATUS_SNAP .", ". OLD_BB_BT_DL
// //
// 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; // ">="
@ -166,13 +153,11 @@ if ($di->config->get('torhelp_enabled'))
"; ";
$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

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',
@ -30,9 +31,10 @@ 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];

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
DB()->query(" DB()->query("
UPDATE UPDATE

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,23 +12,20 @@ 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;
@ -30,10 +41,12 @@ class datastore_apc extends datastore_common
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;
@ -40,8 +42,7 @@ $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']);
} }
@ -53,42 +54,35 @@ $sql = "
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']);
@ -131,8 +124,7 @@ $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("
@ -150,8 +142,7 @@ 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("

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
@ -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'];
} }
@ -59,8 +60,7 @@ $sql = "
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'];
} }
@ -86,8 +86,7 @@ $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'];
} }
@ -99,8 +98,7 @@ $sql = "
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,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 @@ $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();
@ -21,8 +23,7 @@ $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']);
@ -37,8 +38,7 @@ 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 . ")");
@ -49,8 +49,7 @@ 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 . ")
@ -64,12 +63,10 @@ if ($di->config->get('birthday_check_day') && $di->config->get('birthday_enabled
$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');
@ -36,18 +49,17 @@ class datastore_file extends datastore_common
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')";
@ -60,11 +77,15 @@ class datastore_memcache extends datastore_common
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');
} }

View file

@ -1,19 +1,26 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_redis extends datastore_common class datastore_redis extends datastore_common
{ {
var $cfg = null; public $cfg = null;
var $redis = null; public $redis = null;
var $prefix = null; public $prefix = null;
var $connected = false; public $connected = false;
var $engine = 'Redis'; public $engine = 'Redis';
function datastore_redis ($cfg, $prefix = null) /**
{ * datastore_redis constructor.
if (!$this->is_installed()) * @param $cfg
* @param null $prefix
* @return datastore_redis
*/
public function datastore_redis($cfg, $prefix = null)
{ {
if (!$this->is_installed()) {
die('Error: Redis extension not installed'); die('Error: Redis extension not installed');
} }
@ -23,18 +30,19 @@ class datastore_redis extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function connect () /**
* Подключение
*/
public function connect()
{ {
$this->cur_query = 'connect ' . $this->cfg['host'] . ':' . $this->cfg['port']; $this->cur_query = 'connect ' . $this->cfg['host'] . ':' . $this->cfg['port'];
$this->debug('start'); $this->debug('start');
if ($this->redis->connect($this->cfg['host'],$this->cfg['port'])) if ($this->redis->connect($this->cfg['host'], $this->cfg['port'])) {
{
$this->connected = true; $this->connected = true;
} }
if (!$this->connected && $this->cfg['con_required']) if (!$this->connected && $this->cfg['con_required']) {
{
die('Could not connect to redis server'); die('Could not connect to redis server');
} }
@ -42,9 +50,16 @@ class datastore_redis 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')";
@ -56,11 +71,15 @@ class datastore_redis extends datastore_common
return (bool)$this->redis->set($this->prefix . $title, serialize($var)); return (bool)$this->redis->set($this->prefix . $title, serialize($var));
} }
function clean () /**
{ * Очистка
if (!$this->connected) $this->connect(); */
foreach ($this->known_items as $title => $script_name) 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');
@ -71,17 +90,20 @@ class datastore_redis 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');
@ -92,7 +114,10 @@ class datastore_redis extends datastore_common
} }
} }
function is_installed () /**
* @return bool
*/
public function is_installed()
{ {
return class_exists('Redis'); return class_exists('Redis');
} }

View file

@ -1,13 +1,15 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_sqlite extends datastore_common class datastore_sqlite extends datastore_common
{ {
var $engine = 'SQLite'; public $engine = 'SQLite';
var $db = null; public $db = null;
var $prefix = null; public $prefix = null;
var $cfg = array( public $cfg = array(
'db_file_path' => '/path/to/datastore.db.sqlite', 'db_file_path' => '/path/to/datastore.db.sqlite',
'table_name' => 'datastore', 'table_name' => 'datastore',
'table_schema' => 'CREATE TABLE datastore ( 'table_schema' => 'CREATE TABLE datastore (
@ -20,14 +22,25 @@ class datastore_sqlite extends datastore_common
'log_name' => 'DATASTORE', 'log_name' => 'DATASTORE',
); );
function datastore_sqlite ($cfg, $prefix = null) /**
* datastore_sqlite constructor.
* @param $cfg
* @param null $prefix
* @return datastore_sqlite
*/
public function datastore_sqlite($cfg, $prefix = null)
{ {
$this->cfg = array_merge($this->cfg, $cfg); $this->cfg = array_merge($this->cfg, $cfg);
$this->db = new sqlite_common($this->cfg); $this->db = new sqlite_common($this->cfg);
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store ($item_name, $item_data) /**
* @param $item_name
* @param $item_data
* @return bool
*/
public function store($item_name, $item_data)
{ {
$this->data[$item_name] = $item_data; $this->data[$item_name] = $item_data;
@ -39,14 +52,22 @@ class datastore_sqlite extends datastore_common
return (bool)$result; return (bool)$result;
} }
function clean () /**
* Очистка
*/
public function clean()
{ {
$this->db->query("DELETE FROM " . $this->cfg['table_name']); $this->db->query("DELETE FROM " . $this->cfg['table_name']);
} }
function _fetch_from_store () /**
* Получение из кеша
*/
public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) return; if (!$items = $this->queued_items) {
return;
}
$prefix_len = strlen($this->prefix); $prefix_len = strlen($this->prefix);
$prefix_sql = SQLite3::escapeString($this->prefix); $prefix_sql = SQLite3::escapeString($this->prefix);
@ -57,8 +78,7 @@ class datastore_sqlite extends datastore_common
$rowset = $this->db->fetch_rowset("SELECT ds_title, ds_data FROM " . $this->cfg['table_name'] . " WHERE ds_title IN ('$items_list')"); $rowset = $this->db->fetch_rowset("SELECT ds_title, ds_data FROM " . $this->cfg['table_name'] . " WHERE ds_title IN ('$items_list')");
$this->db->debug('start', "unserialize()"); $this->db->debug('start', "unserialize()");
foreach ($rowset as $row) foreach ($rowset as $row) {
{
$this->data[substr($row['ds_title'], $prefix_len)] = unserialize($row['ds_data']); $this->data[substr($row['ds_title'], $prefix_len)] = unserialize($row['ds_data']);
} }
$this->db->debug('stop'); $this->db->debug('stop');

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