Reformat by php-cs-fixer.

This commit is contained in:
Yuriy Pikhtarev 2016-09-29 00:35:37 +03:00
commit 21f9ef22fc
No known key found for this signature in database
GPG key ID: 3A9B5A757B48ECC6
135 changed files with 2141 additions and 1301 deletions

View file

@ -32,7 +32,9 @@ if (!$result = DB()->sql_query($sql)) {
$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' || $config_name == 'seed_bonus_release' || $config_name == 'bonus_upload' || $config_name == 'bonus_upload_price') $new[$config_name] = serialize(str_replace(',', '.', $new[$config_name])); if ($config_name == 'seed_bonus_points' || $config_name == 'seed_bonus_release' || $config_name == 'bonus_upload' || $config_name == 'bonus_upload_price') {
$new[$config_name] = serialize(str_replace(',', '.', $new[$config_name]));
}
bb_update_config(array($config_name => $new[$config_name])); bb_update_config(array($config_name => $new[$config_name]));
} }
} }
@ -78,7 +80,9 @@ switch ($mode) {
$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]) continue; if (!$row || !$seed_release[$i]) {
continue;
}
$template->assign_block_vars('seed_bonus', array( $template->assign_block_vars('seed_bonus', array(
'RELEASE' => $seed_release[$i], 'RELEASE' => $seed_release[$i],
@ -92,7 +96,9 @@ switch ($mode) {
$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]) continue; if (!$row || !$price_row[$i]) {
continue;
}
$template->assign_block_vars('bonus_upload', array( $template->assign_block_vars('bonus_upload', array(
'UP' => $row, 'UP' => $row,

View file

@ -1,7 +1,9 @@
<?php <?php
if (!empty($setmodules)) { if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['TP']['TRACKER_CONFIG'] = basename(__FILE__); if (IS_SUPER_ADMIN) {
$module['TP']['TRACKER_CONFIG'] = basename(__FILE__);
}
return; return;
} }
require('./pagestart.php'); require('./pagestart.php');
@ -9,7 +11,9 @@ 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');

View file

@ -1,7 +1,9 @@
<?php <?php
if (!empty($setmodules)) { if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['TP']['CRON'] = basename(__FILE__) . '?mode=list'; if (IS_SUPER_ADMIN) {
$module['TP']['CRON'] = basename(__FILE__) . '?mode=list';
}
return; return;
} }
@ -16,9 +18,13 @@ if ($mode == 'run' && !$job_id) {
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');
@ -176,18 +182,20 @@ 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);
} else if ($cron_action == 'delete' && $jobs) { } elseif ($cron_action == 'delete' && $jobs) {
delete_jobs($jobs); delete_jobs($jobs);
} else if (($cron_action == 'disable' || $cron_action == 'enable') && $jobs) { } elseif (($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');
} else if (validate_cron_post($_POST) == 1) { } elseif (validate_cron_post($_POST) == 1) {
if ($_POST['mode'] == 'edit') { if ($_POST['mode'] == 'edit') {
update_cron_job($_POST); update_cron_job($_POST);
} else if ($_POST['mode'] == 'add') { } elseif ($_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 {

View file

@ -42,7 +42,6 @@ if (isset($_POST['add_name'])) {
$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);
} }
// //

View file

@ -116,7 +116,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.php" . '">', "</a>")); bb_die($lang['FORUM_AUTH_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMAUTH'], '<a href="' . "admin_forumauth.php" . '">', "</a>"));
} // End of submit } // End of submit
// //
@ -133,7 +132,6 @@ if (empty($forum_id)) {
'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'];

View file

@ -146,7 +146,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
// //

View file

@ -38,7 +38,7 @@ $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 = '';
@ -110,11 +110,11 @@ if ($mode) {
if ($parent = get_forum_data($forum_parent)) { if ($parent = get_forum_data($forum_parent)) {
$cat_id = $parent['cat_id']; $cat_id = $parent['cat_id'];
} }
} else if (isset($_REQUEST['c'])) { } elseif (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"';
@ -264,10 +264,10 @@ if ($mode) {
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');
} }
} else if ($cat_id != $old_cat_id) { } elseif ($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;
} else if ($forum_data['forum_parent']) { } elseif ($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;
} }
@ -563,29 +563,29 @@ 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;
} else if ($move_down_forum_id = get_prev_root_forum_id($forums, $forum_order)) { } elseif ($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
else if ($move > 0 && $next_forum) { elseif ($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;
} else if ($move_up_forum_id = get_next_root_forum_id($forums, $forum_order)) { } elseif ($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;
@ -602,7 +602,7 @@ if ($mode) {
forum_order = forum_order + $move forum_order = forum_order + $move
WHERE forum_id = $forum_id WHERE forum_id = $forum_id
"); ");
} else if ($move_down_forum_id) { } elseif ($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
@ -734,7 +734,6 @@ if (!$mode || $show_main_page) {
$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']),
@ -759,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
@ -898,10 +896,9 @@ function renumber_order($mode, $cat = 0)
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) function get_cat_forums($cat_id = false)
{ {
$forums = array(); $forums = array();
$where_sql = ''; $where_sql = '';
@ -959,7 +956,7 @@ function get_prev_root_forum_id($forums, $curr_forum_order)
$i = $i - 10; $i = $i - 10;
} }
return FALSE; return false;
} }
function get_next_root_forum_id($forums, $curr_forum_order) function get_next_root_forum_id($forums, $curr_forum_order)
@ -974,7 +971,7 @@ function get_next_root_forum_id($forums, $curr_forum_order)
$i = $i + 10; $i = $i + 10;
} }
return FALSE; return false;
} }
function get_orphan_sf() function get_orphan_sf()
@ -999,7 +996,7 @@ function get_orphan_sf()
return implode(',', $bad_sf_ary); return implode(',', $bad_sf_ary);
} }
function fix_orphan_sf($orphan_sf_sql = '', $show_mess = FALSE) function fix_orphan_sf($orphan_sf_sql = '', $show_mess = false)
{ {
global $lang; global $lang;
@ -1067,7 +1064,7 @@ function get_forum_data($forum_id)
} }
} }
return FALSE; return false;
} }
function get_max_forum_order($cat_id) function get_max_forum_order($cat_id)

View file

@ -26,7 +26,7 @@ if (!empty($_POST['edit']) || !empty($_POST['new'])) {
); );
$mode = 'editgroup'; $mode = 'editgroup';
$template->assign_block_vars('group_edit', array()); $template->assign_block_vars('group_edit', array());
} else if (!empty($_POST['new'])) { } elseif (!empty($_POST['new'])) {
$group_info = array( $group_info = array(
'group_name' => '', 'group_name' => '',
'group_description' => '', 'group_description' => '',
@ -62,7 +62,7 @@ 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,
)); ));
} else if (!empty($_POST['group_update'])) { } elseif (!empty($_POST['group_update'])) {
if (!empty($_POST['group_delete'])) { if (!empty($_POST['group_delete'])) {
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']);
@ -84,7 +84,7 @@ if (!empty($_POST['edit']) || !empty($_POST['new'])) {
if ($group_name === '') { if ($group_name === '') {
bb_die($lang['NO_GROUP_NAME']); bb_die($lang['NO_GROUP_NAME']);
} else if ($group_moderator === '') { } elseif ($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);
@ -128,7 +128,7 @@ if (!empty($_POST['edit']) || !empty($_POST['new'])) {
$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 if ($mode == 'newgroup') { } elseif ($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);

View file

@ -18,9 +18,15 @@ $group_id = (int)request_var(POST_GROUPS_URL, 0);
$errors = $user_id_sql = array(); $errors = $user_id_sql = array();
if (isset($_POST['submit'])) { if (isset($_POST['submit'])) {
if (!$subject) $errors[] = $lang['EMPTY_SUBJECT']; if (!$subject) {
if (!$message) $errors[] = $lang['EMPTY_MESSAGE']; $errors[] = $lang['EMPTY_SUBJECT'];
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");

View file

@ -76,7 +76,7 @@ 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']) : '';

View file

@ -1,12 +1,16 @@
<?php <?php
if (!empty($setmodules)) { if (!empty($setmodules)) {
if (IS_SUPER_ADMIN) $module['GENERAL']['REBUILD_SEARCH_INDEX'] = basename(__FILE__); if (IS_SUPER_ADMIN) {
$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');
@ -199,8 +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 // refresh } else {
{ // 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
@ -247,8 +252,9 @@ if ($mode == 'submit' || $mode == 'refresh') {
$template->assign_vars(array( $template->assign_vars(array(
'CANCEL_BUTTON' => true, 'CANCEL_BUTTON' => true,
)); ));
} else // end of processing } else {
{ // 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'];
@ -329,8 +335,8 @@ if ($mode == 'submit' || $mode == 'refresh') {
'S_REBUILD_SEARCH_ACTION' => $form_action, 'S_REBUILD_SEARCH_ACTION' => $form_action,
)); ));
} else // show the input page } else {
{ // 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;
@ -362,8 +368,9 @@ if ($mode == 'submit' || $mode == 'refresh') {
$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 // when finished } else {
{ // 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"';

View file

@ -28,7 +28,7 @@ while ($file = readdir($dir)) {
if ($img_size[0] && $img_size[1]) { if ($img_size[0] && $img_size[1]) {
$smiley_images[] = $file; $smiley_images[] = $file;
} else if (preg_match('/.pak$/i', $file)) { } elseif (preg_match('/.pak$/i', $file)) {
$smiley_paks[] = $file; $smiley_paks[] = $file;
} }
} }
@ -123,7 +123,7 @@ if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) {
'S_HIDDEN_FIELDS' => $hidden_vars, 'S_HIDDEN_FIELDS' => $hidden_vars,
)); ));
} }
} else if (isset($_POST['export_pack']) || isset($_GET['export_pack'])) { } elseif (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') {
@ -150,7 +150,7 @@ if (isset($_GET['import_pack']) || isset($_POST['import_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>'));
} else if (isset($_POST['add']) || isset($_GET['add'])) { } elseif (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>';
@ -166,7 +166,7 @@ if (isset($_GET['import_pack']) || isset($_POST['import_pack'])) {
'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')
)); ));
} else if ($mode != '') { } elseif ($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'];

View file

@ -80,7 +80,7 @@ if ($submit && $mode == 'user') {
bb_die($message); bb_die($message);
} // Make admin a user (if already admin) } // Make admin a user (if already admin)
else if ($_POST['userlevel'] === 'user') { elseif ($_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");
@ -127,7 +127,7 @@ 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']);
} }
@ -282,7 +282,7 @@ 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,
)); ));
} else if ($mode == 'group' && $group_id) { } elseif ($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)) {

View file

@ -73,7 +73,7 @@ if (isset($_POST['submit'])) {
} }
$ip_1_counter++; $ip_1_counter++;
} }
} else if (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i]))) { } elseif (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++) {
@ -81,7 +81,7 @@ if (isset($_POST['submit'])) {
$ip_list[] = encode_ip($ip[$j]); $ip_list[] = encode_ip($ip[$j]);
} }
} }
} else if (preg_match('/^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$/', trim($ip_list_temp[$i]))) { } elseif (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])));
} }
} }
@ -265,7 +265,7 @@ if (isset($_POST['submit'])) {
$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++;
} else if (!empty($banlist[$i]['ban_email'])) { } elseif (!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++;

View file

@ -136,17 +136,23 @@ if (!isset($_REQUEST['dosearch'])) {
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':
@ -154,55 +160,75 @@ if (!isset($_REQUEST['dosearch'])) {
$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:
@ -231,7 +257,9 @@ if (!isset($_REQUEST['dosearch'])) {
$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;
@ -250,7 +278,9 @@ if (!isset($_REQUEST['dosearch'])) {
$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;
@ -287,7 +317,9 @@ if (!isset($_REQUEST['dosearch'])) {
$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])) {
bb_die($lang['SEARCH_INVALID_IP']);
}
for ($i = $start_range[3]; $i <= $end_range[3]; $i++) { 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);
} }
@ -318,7 +350,9 @@ if (!isset($_REQUEST['dosearch'])) {
$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;
@ -333,7 +367,7 @@ if (!isset($_REQUEST['dosearch'])) {
$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'];
@ -347,9 +381,11 @@ if (!isset($_REQUEST['dosearch'])) {
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) $no_result_search = false; if ($no_result_search == true) {
$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'];
} }
@ -362,9 +398,11 @@ if (!isset($_REQUEST['dosearch'])) {
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) $no_result_search = false; if ($no_result_search == true) {
$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'];
} }
@ -572,7 +610,9 @@ if (!isset($_REQUEST['dosearch'])) {
$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));

View file

@ -21,7 +21,7 @@ $mode = htmlspecialchars($mode);
if (isset($_POST['add'])) { if (isset($_POST['add'])) {
$mode = 'add'; $mode = 'add';
} else if (isset($_POST['save'])) { } elseif (isset($_POST['save'])) {
$mode = 'save'; $mode = 'save';
} }
@ -54,7 +54,7 @@ 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,
)); ));
} else if ($mode == 'save') { } elseif ($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', ''));
@ -82,7 +82,7 @@ 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);
} else if ($mode == 'delete') { } elseif ($mode == 'delete') {
$word_id = intval(request_var('id', 0)); $word_id = intval(request_var('id', 0));
if ($word_id) { if ($word_id) {

View file

@ -189,10 +189,10 @@ if (isset($_GET['pane']) && $_GET['pane'] == 'left') {
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';

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,9 +20,7 @@ $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
@ -28,7 +28,6 @@ foreach ($sql as $i => $query) {
} }
echo '</table>'; echo '</table>';
echo '<div align="center"><pre>'; echo '<div align="center"><pre>';
if ($l = sys('la')) { if ($l = sys('la')) {

View file

@ -9,7 +9,9 @@ $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 = array(30, 15, 5, 1);
$peers_in_last_sec_limit = 300; $peers_in_last_sec_limit = 300;
@ -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
@ -81,13 +81,7 @@ function commify_ob($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,12 +105,9 @@ 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')) {
@ -128,7 +119,6 @@ if ($l = sys('la')) {
} }
echo 'gen time: <b>' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . "</b> sec\n"; echo 'gen time: <b>' . sprintf('%.3f', (array_sum(explode(' ', microtime())) - TIMESTART)) . "</b> sec\n";
echo '</pre></div>'; echo '</pre></div>';
echo '</body></html>'; echo '</body></html>';

View file

@ -18,7 +18,7 @@ $di = \TorrentPier\Di::getInstance();
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']);
} else if (file_exists(BB_DISABLED)) { } elseif (file_exists(BB_DISABLED)) {
$ajax->ajax_die($lang['BOARD_DISABLE_CRON']); $ajax->ajax_die($lang['BOARD_DISABLE_CRON']);
} }
} }
@ -73,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'],
@ -103,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');
@ -117,7 +117,7 @@ class ajax_common
/** /**
* Perform action * Perform action
*/ */
function exec() public function exec()
{ {
global $lang; global $lang;
@ -189,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;
@ -200,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'];
@ -209,7 +209,7 @@ class ajax_common
/** /**
* Send data * Send data
*/ */
function send() public function send()
{ {
$this->response['action'] = $this->action; $this->response['action'] = $this->action;
@ -228,7 +228,7 @@ class ajax_common
* *
* @return string * @return string
*/ */
function ob_handler($contents) public function ob_handler($contents)
{ {
if (DBG_USER) { if (DBG_USER) {
if ($contents) { if ($contents) {
@ -251,7 +251,7 @@ class ajax_common
/** /**
* Admin session * Admin session
*/ */
function check_admin_session() public function check_admin_session()
{ {
global $user; global $user;
@ -273,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();
@ -284,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;
@ -298,7 +300,7 @@ 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;
@ -309,102 +311,102 @@ class ajax_common
} }
} }
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

@ -17,7 +17,9 @@ if (empty($_SERVER['HTTP_USER_AGENT'])) {
// Ignore 'completed' event // Ignore 'completed' event
if (isset($_GET['event']) && $_GET['event'] === 'completed') { if (isset($_GET['event']) && $_GET['event'] === 'completed') {
if (DBG_LOG) dbg_log(' ', '!die-event-completed'); if (DBG_LOG) {
dbg_log(' ', '!die-event-completed');
}
dummy_exit(mt_rand(600, 1200)); dummy_exit(mt_rand(600, 1200));
} }
@ -128,7 +130,9 @@ $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')) {
@ -151,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,
@ -177,7 +183,9 @@ $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
@ -186,7 +194,9 @@ if (!$lp_info) {
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) {
@ -315,7 +325,9 @@ if ($tr_cfg['gold_silver_enabled'] && $down_add) {
} }
// 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;
@ -346,7 +358,9 @@ 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) {
@ -355,7 +369,9 @@ if (!$lp_info || !$peer_info_updated) {
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
@ -377,12 +393,16 @@ $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
@ -439,7 +459,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
@ -40,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();
@ -52,33 +58,33 @@ 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
*/ */
function sql_db($cfg_values) public function sql_db($cfg_values)
{ {
global $DBS; global $DBS;
@ -94,7 +100,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();
@ -117,7 +123,7 @@ 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');
@ -149,7 +155,7 @@ 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');
@ -168,7 +174,7 @@ class sql_db
/** /**
* Base query method * Base query method
*/ */
function sql_query($query) public function sql_query($query)
{ {
if (!is_resource($this->link)) { if (!is_resource($this->link)) {
$this->init(); $this->init();
@ -192,7 +198,7 @@ class sql_db
/** /**
* Execute query WRAPPER (with error handling) * Execute query WRAPPER (with error handling)
*/ */
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();
@ -204,7 +210,7 @@ class sql_db
/** /**
* Return number of rows * Return number of rows
*/ */
function num_rows($result = false) public function num_rows($result = false)
{ {
$num_rows = false; $num_rows = false;
@ -218,7 +224,7 @@ 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;
} }
@ -226,7 +232,7 @@ class sql_db
/** /**
* Fetch current row * Fetch current row
*/ */
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;
} }
@ -234,7 +240,7 @@ class sql_db
/** /**
* Alias of sql_fetchrow() * Alias of sql_fetchrow()
*/ */
function fetch_next($result) public function fetch_next($result)
{ {
return $this->sql_fetchrow($result); return $this->sql_fetchrow($result);
} }
@ -242,7 +248,7 @@ class sql_db
/** /**
* Fetch row WRAPPER (with error handling) * Fetch row WRAPPER (with error handling)
*/ */
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();
@ -254,7 +260,7 @@ class sql_db
/** /**
* Fetch all rows * Fetch all rows
*/ */
function sql_fetchrowset($result) public function sql_fetchrowset($result)
{ {
$rowset = array(); $rowset = array();
@ -268,7 +274,7 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
*/ */
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();
@ -280,7 +286,7 @@ class sql_db
/** /**
* Escape string used in sql query * Escape string used in sql query
*/ */
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();
@ -308,7 +314,7 @@ 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' => '',
@ -328,7 +334,7 @@ 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);
@ -336,13 +342,15 @@ class sql_db
$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();
@ -364,9 +372,11 @@ class sql_db
/** /**
* Store debug info * Store debug info
*/ */
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) {
@ -396,10 +406,12 @@ class sql_db
/** /**
* Trigger error * Trigger error
*/ */
function trigger_error($msg = '') public function trigger_error($msg = '')
{ {
if (error_reporting()) { if (error_reporting()) {
if (!$msg) $msg = 'DB Error'; if (!$msg) {
$msg = 'DB Error';
}
if (DBG_TRACKER === true) { if (DBG_TRACKER === true) {
$err = $this->sql_error(); $err = $this->sql_error();
@ -415,7 +427,7 @@ 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();
@ -433,10 +445,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,7 +4,9 @@ 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'])) {
@ -19,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

@ -49,7 +49,9 @@ $message = sprintf($lang['CALLSEED_TEXT'], make_url(TOPIC_URL . $topic_id), $t_d
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);

View file

@ -1,17 +1,29 @@
<?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');
@ -329,16 +341,16 @@ function array_deep(&$var, $fn, $one_dimensional = false, $array_only = false)
if (is_array($v)) { if (is_array($v)) {
if ($one_dimensional) { if ($one_dimensional) {
unset($var[$k]); unset($var[$k]);
} else if ($array_only) { } elseif ($array_only) {
$var[$k] = $fn($v); $var[$k] = $fn($v);
} else { } else {
array_deep($var[$k], $fn); array_deep($var[$k], $fn);
} }
} else if (!$array_only) { } elseif (!$array_only) {
$var[$k] = $fn($v); $var[$k] = $fn($v);
} }
} }
} else if (!$array_only) { } elseif (!$array_only) {
$var = $fn($var); $var = $fn($var);
} }
} }
@ -393,8 +405,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'])) {
@ -407,7 +423,9 @@ 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);
} }
@ -416,7 +434,7 @@ function log_request($file = '', $prepend_str = false, $add_post = true)
if (!defined('IN_TRACKER')) { if (!defined('IN_TRACKER')) {
require(INC_DIR . 'init_bb.php'); require(INC_DIR . 'init_bb.php');
} // Tracker init } // Tracker init
else if (defined('IN_TRACKER')) { elseif (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)

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

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

View file

@ -31,11 +31,15 @@ function generate_user_info(&$row, $date_format, $group_mod, &$from, &$posts, &$
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;
} }
@ -100,15 +104,15 @@ if (!$group_id) {
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';
} else if ($row['membership'] == $member) { } elseif ($row['membership'] == $member) {
$type = 'MEMBER'; $type = 'MEMBER';
} else if ($row['membership'] == $pending) { } elseif ($row['membership'] == $pending) {
$type = 'PENDING'; $type = 'PENDING';
} else if ($row['group_type'] == GROUP_OPEN) { } elseif ($row['group_type'] == GROUP_OPEN) {
$type = 'OPEN'; $type = 'OPEN';
} else if ($row['group_type'] == GROUP_CLOSED) { } elseif ($row['group_type'] == GROUP_CLOSED) {
$type = 'CLOSED'; $type = 'CLOSED';
} else if ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) { } elseif ($row['group_type'] == GROUP_HIDDEN && IS_ADMIN) {
$type = 'HIDDEN'; $type = 'HIDDEN';
} else { } else {
continue; continue;
@ -160,9 +164,11 @@ if (!$group_id) {
} else { } else {
if (IS_ADMIN) { if (IS_ADMIN) {
redirect('admin/admin_groups.php'); redirect('admin/admin_groups.php');
} else bb_die($lang['NO_GROUPS_EXIST']); } else {
bb_die($lang['NO_GROUPS_EXIST']);
} }
} 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']);
} }
@ -210,7 +216,7 @@ if (!$group_id) {
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']);
} else if (!empty($_POST['unsub']) || !empty($_POST['unsubpending'])) { } elseif (!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);
@ -270,7 +276,7 @@ if (!$group_id) {
"); ");
update_user_level($sql_in); update_user_level($sql_in);
} else if (!empty($_POST['deny']) || !empty($_POST['remove'])) { } elseif (!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)
@ -342,14 +348,14 @@ if (!$group_id) {
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 . '" />';
} else if ($is_group_member || $is_group_pending_member) { } elseif ($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 . '" />';
} else if (IS_GUEST) { } elseif (IS_GUEST) {
$group_details = $lang['LOGIN_TO_JOIN']; $group_details = $lang['LOGIN_TO_JOIN'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} else { } else {
@ -358,10 +364,10 @@ if (!$group_id) {
$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 . '" />';
} else if ($group_info['group_type'] == GROUP_CLOSED) { } elseif ($group_info['group_type'] == GROUP_CLOSED) {
$group_details = $lang['THIS_CLOSED_GROUP']; $group_details = $lang['THIS_CLOSED_GROUP'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} else if ($group_info['group_type'] == GROUP_HIDDEN) { } elseif ($group_info['group_type'] == GROUP_HIDDEN) {
$group_details = $lang['THIS_HIDDEN_GROUP']; $group_details = $lang['THIS_HIDDEN_GROUP'];
$s_hidden_fields = ''; $s_hidden_fields = '';
} }

View file

@ -353,7 +353,9 @@ 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']);
@ -366,7 +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,
@ -387,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

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

View file

@ -1,13 +1,17 @@
<?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'];
@ -26,16 +30,24 @@ $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) {
@ -49,7 +61,9 @@ switch ($mode) {
// Права на изменение статуса // Права на изменение статуса
if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) { if ($tor['tor_status'] == TOR_CLOSED_CPHOLD) {
if (!IS_ADMIN) $this->verify_mod_rights($tor['forum_id']); if (!IS_ADMIN) {
$this->verify_mod_rights($tor['forum_id']);
}
DB()->query("UPDATE " . BB_TOPICS . " SET topic_status = " . TOPIC_UNLOCKED . " WHERE topic_id = {$topic_id} LIMIT 1"); DB()->query("UPDATE " . BB_TOPICS . " SET topic_status = " . TOPIC_UNLOCKED . " WHERE topic_id = {$topic_id} LIMIT 1");
} else { } else {
$this->verify_mod_rights($tor['forum_id']); $this->verify_mod_rights($tor['forum_id']);
@ -74,7 +88,9 @@ switch ($mode) {
$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']);
@ -83,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,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $lang; global $lang;
@ -46,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,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $bf, $lang; global $bf, $lang;

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $datastore, $lang; global $datastore, $lang;

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;

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;
@ -39,18 +41,26 @@ switch ($field) {
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')) {
$this->ajax_die($lang['MODULE_OFF']);
}
if (!isset($lang['GENDER_SELECT'][$value])) { if (!isset($lang['GENDER_SELECT'][$value])) {
$this->ajax_die($lang['ERROR']); $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'])) {
@ -107,7 +117,9 @@ 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']);

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;
@ -18,4 +20,6 @@ if ($req_uid == $userdata['user_id'] || IS_ADMIN) {
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,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;

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;
@ -22,7 +24,9 @@ switch ($mode) {
$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':
@ -36,7 +40,9 @@ switch ($mode) {
$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':
@ -69,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;

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;
@ -13,22 +15,32 @@ $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');
@ -36,26 +48,36 @@ switch ($mode) {
$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);
@ -65,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;
@ -34,8 +36,12 @@ 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']);
@ -67,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']}'
@ -96,9 +104,11 @@ switch ($mode) {
} }
} }
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 : '',

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;
@ -19,7 +21,9 @@ 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']) {
@ -32,7 +36,9 @@ if (isset($this->request['post_id'])) {
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);
} }
@ -94,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);
@ -135,7 +143,9 @@ 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']);

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;
@ -22,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');
@ -140,8 +144,9 @@ switch ($mode) {
// возможный дубль названия шаблона // возможный дубль названия шаблона
if ($sql_error) { if ($sql_error) {
if ($sql_error['code'] == 1062) // Duplicate entry if ($sql_error['code'] == 1062) {
{ // 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;

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('IN_AJAX')) die(basename(__FILE__)); if (!defined('IN_AJAX')) {
die(basename(__FILE__));
}
global $user, $lang; global $user, $lang;

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;
@ -41,18 +43,18 @@ function build_tor_filelist($file_contents)
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) public function torrent($decoded_file_contents)
{ {
$this->tor_decoded = $decoded_file_contents; $this->tor_decoded = $decoded_file_contents;
} }
function get_filelist() public function get_filelist()
{ {
$this->build_filelist_array(); $this->build_filelist_array();
@ -68,7 +70,7 @@ class torrent
} }
} }
function build_filelist_array() public function build_filelist_array()
{ {
$info = $this->tor_decoded['info']; $info = $this->tor_decoded['info'];
@ -129,7 +131,7 @@ class torrent
} }
} }
function build_file_item($name, $length) public function build_file_item($name, $length)
{ {
global $images, $lang; global $images, $lang;
@ -146,7 +148,7 @@ class torrent
return "$name <i>$length</i> $magnet_name $magnet_ext"; return "$name <i>$length</i> $magnet_name $magnet_ext";
} }
function build_filelist_html() public function build_filelist_html()
{ {
global $html; global $html;
return $html->array2html($this->files_ary); return $html->array2html($this->files_ary);
@ -158,6 +160,8 @@ 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

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// //
// $Id: sphinxapi.php 2055 2009-11-06 23:09:58Z shodan $ // $Id: sphinxapi.php 2055 2009-11-06 23:09:58Z shodan $
@ -128,13 +130,15 @@ function sphPackI64($v)
} }
// x32, int // x32, int
if (is_int($v)) if (is_int($v)) {
return pack("NN", $v < 0 ? -1 : 0, $v); return pack("NN", $v < 0 ? -1 : 0, $v);
}
// x32, bcmath // x32, bcmath
if (function_exists("bcmul")) { if (function_exists("bcmul")) {
if (bccomp($v, 0) == -1) if (bccomp($v, 0) == -1) {
$v = bcadd("18446744073709551616", $v); $v = bcadd("18446744073709551616", $v);
}
$h = bcdiv($v, "4294967296", 0); $h = bcdiv($v, "4294967296", 0);
$l = bcmod($v, "4294967296"); $l = bcmod($v, "4294967296");
return pack("NN", (float)$h, (float)$l); // conversion to float is intentional; int would lose 31st bit return pack("NN", (float)$h, (float)$l); // conversion to float is intentional; int would lose 31st bit
@ -151,9 +155,9 @@ function sphPackI64($v)
$h = $hi * 2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328 $h = $hi * 2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328
if ($v < 0) { if ($v < 0) {
if ($l == 0) if ($l == 0) {
$h = 4294967296.0 - $h; $h = 4294967296.0 - $h;
else { } else {
$h = 4294967295.0 - $h; $h = 4294967295.0 - $h;
$l = 4294967296.0 - $l; $l = 4294967296.0 - $l;
} }
@ -171,8 +175,9 @@ function sphPackU64($v)
assert($v >= 0); assert($v >= 0);
// x64, int // x64, int
if (is_int($v)) if (is_int($v)) {
return pack("NN", $v >> 32, $v & 0xFFFFFFFF); return pack("NN", $v >> 32, $v & 0xFFFFFFFF);
}
// x64, bcmath // x64, bcmath
if (function_exists("bcmul")) { if (function_exists("bcmul")) {
@ -194,8 +199,9 @@ function sphPackU64($v)
} }
// x32, int // x32, int
if (is_int($v)) if (is_int($v)) {
return pack("NN", 0, $v); return pack("NN", 0, $v);
}
// x32, bcmath // x32, bcmath
if (function_exists("bcmul")) { if (function_exists("bcmul")) {
@ -220,19 +226,25 @@ function sphPackU64($v)
// unpack 64-bit unsigned // unpack 64-bit unsigned
function sphUnpackU64($v) function sphUnpackU64($v)
{ {
list ($hi, $lo) = array_values(unpack("N*N*", $v)); list($hi, $lo) = array_values(unpack("N*N*", $v));
if (PHP_INT_SIZE >= 8) { if (PHP_INT_SIZE >= 8) {
if ($hi < 0) $hi += (1 << 32); // because php 5.2.2 to 5.2.5 is totally fucked up again if ($hi < 0) {
if ($lo < 0) $lo += (1 << 32); $hi += (1 << 32);
} // because php 5.2.2 to 5.2.5 is totally fucked up again
if ($lo < 0) {
$lo += (1 << 32);
}
// x64, int // x64, int
if ($hi <= 2147483647) if ($hi <= 2147483647) {
return ($hi << 32) + $lo; return ($hi << 32) + $lo;
}
// x64, bcmath // x64, bcmath
if (function_exists("bcmul")) if (function_exists("bcmul")) {
return bcadd($lo, bcmul($hi, "4294967296")); return bcadd($lo, bcmul($hi, "4294967296"));
}
// x64, no-bcmath // x64, no-bcmath
$C = 100000; $C = 100000;
@ -243,15 +255,17 @@ function sphUnpackU64($v)
$l = $l % $C; $l = $l % $C;
} }
if ($h == 0) if ($h == 0) {
return $l; return $l;
}
return sprintf("%d%05d", $h, $l); return sprintf("%d%05d", $h, $l);
} }
// x32, int // x32, int
if ($hi == 0) { if ($hi == 0) {
if ($lo > 0) if ($lo > 0) {
return $lo; return $lo;
}
return sprintf("%u", $lo); return sprintf("%u", $lo);
} }
@ -259,8 +273,9 @@ function sphUnpackU64($v)
$lo = sprintf("%u", $lo); $lo = sprintf("%u", $lo);
// x32, bcmath // x32, bcmath
if (function_exists("bcmul")) if (function_exists("bcmul")) {
return bcadd($lo, bcmul($hi, "4294967296")); return bcadd($lo, bcmul($hi, "4294967296"));
}
// x32, no-bcmath // x32, no-bcmath
$hi = (float)$hi; $hi = (float)$hi;
@ -275,33 +290,40 @@ function sphUnpackU64($v)
$h = sprintf("%.0f", $h); $h = sprintf("%.0f", $h);
$l = sprintf("%07.0f", $l); $l = sprintf("%07.0f", $l);
if ($h == "0") if ($h == "0") {
return sprintf("%.0f", (float)$l); return sprintf("%.0f", (float)$l);
}
return $h . $l; return $h . $l;
} }
// unpack 64-bit signed // unpack 64-bit signed
function sphUnpackI64($v) function sphUnpackI64($v)
{ {
list ($hi, $lo) = array_values(unpack("N*N*", $v)); list($hi, $lo) = array_values(unpack("N*N*", $v));
// x64 // x64
if (PHP_INT_SIZE >= 8) { if (PHP_INT_SIZE >= 8) {
if ($hi < 0) $hi += (1 << 32); // because php 5.2.2 to 5.2.5 is totally fucked up again if ($hi < 0) {
if ($lo < 0) $lo += (1 << 32); $hi += (1 << 32);
} // because php 5.2.2 to 5.2.5 is totally fucked up again
if ($lo < 0) {
$lo += (1 << 32);
}
return ($hi << 32) + $lo; return ($hi << 32) + $lo;
} }
// x32, int // x32, int
if ($hi == 0) { if ($hi == 0) {
if ($lo > 0) if ($lo > 0) {
return $lo; return $lo;
}
return sprintf("%u", $lo); return sprintf("%u", $lo);
} // x32, int } // x32, int
elseif ($hi == -1) { elseif ($hi == -1) {
if ($lo < 0) if ($lo < 0) {
return $lo; return $lo;
}
return sprintf("%.0f", $lo - 4294967296.0); return sprintf("%.0f", $lo - 4294967296.0);
} }
@ -318,8 +340,9 @@ function sphUnpackI64($v)
$lo = sprintf("%u", $lo); $lo = sprintf("%u", $lo);
// x32, bcmath // x32, bcmath
if (function_exists("bcmul")) if (function_exists("bcmul")) {
return $neg . bcadd(bcadd($lo, bcmul($hi, "4294967296")), $c); return $neg . bcadd(bcadd($lo, bcmul($hi, "4294967296")), $c);
}
// x32, no-bcmath // x32, no-bcmath
$hi = (float)$hi; $hi = (float)$hi;
@ -338,8 +361,9 @@ function sphUnpackI64($v)
$h = sprintf("%.0f", $h); $h = sprintf("%.0f", $h);
$l = sprintf("%07.0f", $l); $l = sprintf("%07.0f", $l);
if ($h == "0") if ($h == "0") {
return $neg . sprintf("%.0f", (float)$l); return $neg . sprintf("%.0f", (float)$l);
}
return $neg . $h . $l; return $neg . $h . $l;
} }
@ -348,7 +372,9 @@ function sphFixUint($value)
{ {
if (PHP_INT_SIZE >= 8) { if (PHP_INT_SIZE >= 8) {
// x64 route, workaround broken unpack() in 5.2.2+ // x64 route, workaround broken unpack() in 5.2.2+
if ($value < 0) $value += (1 << 32); if ($value < 0) {
$value += (1 << 32);
}
return $value; return $value;
} else { } else {
// x32 route, workaround php signed/unsigned braindamage // x32 route, workaround php signed/unsigned braindamage
@ -360,51 +386,51 @@ function sphFixUint($value)
/// sphinx searchd client class /// sphinx searchd client class
class SphinxClient extends cache_common class SphinxClient extends cache_common
{ {
var $_host; ///< searchd host (default is "localhost") public $_host; ///< searchd host (default is "localhost")
var $_port; ///< searchd port (default is 9312) public $_port; ///< searchd port (default is 9312)
var $_offset; ///< how many records to seek from result-set start (default is 0) public $_offset; ///< how many records to seek from result-set start (default is 0)
var $_limit; ///< how many records to return from result-set starting at offset (default is 20) public $_limit; ///< how many records to return from result-set starting at offset (default is 20)
var $_mode; ///< query matching mode (default is SPH_MATCH_ALL) public $_mode; ///< query matching mode (default is SPH_MATCH_ALL)
var $_weights; ///< per-field weights (default is 1 for all fields) public $_weights; ///< per-field weights (default is 1 for all fields)
var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) public $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
var $_sortby; ///< attribute to sort by (defualt is "") public $_sortby; ///< attribute to sort by (defualt is "")
var $_min_id; ///< min ID to match (default is 0, which means no limit) public $_min_id; ///< min ID to match (default is 0, which means no limit)
var $_max_id; ///< max ID to match (default is 0, which means no limit) public $_max_id; ///< max ID to match (default is 0, which means no limit)
var $_filters; ///< search filters public $_filters; ///< search filters
var $_groupby; ///< group-by attribute name public $_groupby; ///< group-by attribute name
var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) public $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) public $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
var $_groupdistinct;///< group-by count-distinct attribute public $_groupdistinct;///< group-by count-distinct attribute
var $_maxmatches; ///< max matches to retrieve public $_maxmatches; ///< max matches to retrieve
var $_cutoff; ///< cutoff to stop searching at (default is 0) public $_cutoff; ///< cutoff to stop searching at (default is 0)
var $_retrycount; ///< distributed retries count public $_retrycount; ///< distributed retries count
var $_retrydelay; ///< distributed retries delay public $_retrydelay; ///< distributed retries delay
var $_anchor; ///< geographical anchor point public $_anchor; ///< geographical anchor point
var $_indexweights; ///< per-index weights public $_indexweights; ///< per-index weights
var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) public $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) public $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
var $_fieldweights; ///< per-field-name weights public $_fieldweights; ///< per-field-name weights
var $_overrides; ///< per-query attribute values overrides public $_overrides; ///< per-query attribute values overrides
var $_select; ///< select-list (attributes or expressions, with optional aliases) public $_select; ///< select-list (attributes or expressions, with optional aliases)
var $_error; ///< last error message public $_error; ///< last error message
var $_warning; ///< last warning message public $_warning; ///< last warning message
var $_connerror; ///< connection error vs remote error flag public $_connerror; ///< connection error vs remote error flag
var $_reqs; ///< requests array for multi-query public $_reqs; ///< requests array for multi-query
var $_mbenc; ///< stored mbstring encoding public $_mbenc; ///< stored mbstring encoding
var $_arrayresult; ///< whether $result["matches"] should be a hash or an array public $_arrayresult; ///< whether $result["matches"] should be a hash or an array
var $_timeout; ///< connect timeout public $_timeout; ///< connect timeout
var $bb_queries = array(); public $bb_queries = array();
var $bb_indexes = array(); public $bb_indexes = array();
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// common stuff // common stuff
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
/// create a new client object and fill defaults /// create a new client object and fill defaults
function SphinxClient() public function SphinxClient()
{ {
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
@ -450,32 +476,33 @@ class SphinxClient extends cache_common
$this->_timeout = 0; $this->_timeout = 0;
} }
function __destruct() public function __destruct()
{ {
if ($this->_socket !== false) if ($this->_socket !== false) {
fclose($this->_socket); fclose($this->_socket);
} }
}
/// get last error message (string) /// get last error message (string)
function GetLastError() public function GetLastError()
{ {
return $this->_error; return $this->_error;
} }
/// get last warning message (string) /// get last warning message (string)
function GetLastWarning() public function GetLastWarning()
{ {
return $this->_warning; return $this->_warning;
} }
/// get last error flag (to tell network connection errors from searchd errors or broken responses) /// get last error flag (to tell network connection errors from searchd errors or broken responses)
function IsConnectError() public function IsConnectError()
{ {
return $this->_connerror; return $this->_connerror;
} }
/// set searchd host name (string) and port (integer) /// set searchd host name (string) and port (integer)
function SetServer($host, $port = 0) public function SetServer($host, $port = 0)
{ {
assert(is_string($host)); assert(is_string($host));
if ($host[0] == '/') { if ($host[0] == '/') {
@ -491,18 +518,17 @@ class SphinxClient extends cache_common
$this->_host = $host; $this->_host = $host;
$this->_port = $port; $this->_port = $port;
$this->_path = ''; $this->_path = '';
} }
/// set server connection timeout (0 to remove) /// set server connection timeout (0 to remove)
function SetConnectTimeout($timeout) public function SetConnectTimeout($timeout)
{ {
assert(is_numeric($timeout)); assert(is_numeric($timeout));
$this->_timeout = $timeout; $this->_timeout = $timeout;
} }
function _Send($handle, $data, $length) public function _Send($handle, $data, $length)
{ {
if (feof($handle) || fwrite($handle, $data, $length) !== $length) { if (feof($handle) || fwrite($handle, $data, $length) !== $length) {
$this->_error = 'connection unexpectedly closed (timed out?)'; $this->_error = 'connection unexpectedly closed (timed out?)';
@ -515,7 +541,7 @@ class SphinxClient extends cache_common
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
/// enter mbstring workaround mode /// enter mbstring workaround mode
function _MBPush() public function _MBPush()
{ {
$this->_mbenc = ""; $this->_mbenc = "";
if (ini_get("mbstring.func_overload") & 2) { if (ini_get("mbstring.func_overload") & 2) {
@ -525,14 +551,15 @@ class SphinxClient extends cache_common
} }
/// leave mbstring workaround mode /// leave mbstring workaround mode
function _MBPop() public function _MBPop()
{ {
if ($this->_mbenc) if ($this->_mbenc) {
mb_internal_encoding($this->_mbenc); mb_internal_encoding($this->_mbenc);
} }
}
/// connect to searchd server /// connect to searchd server
function _Connect() public function _Connect()
{ {
$this->cur_query = "connect to: {$this->_host}"; $this->cur_query = "connect to: {$this->_host}";
$this->debug('start'); $this->debug('start');
@ -540,8 +567,9 @@ class SphinxClient extends cache_common
if ($this->_socket !== false) { if ($this->_socket !== false) {
// we are in persistent connection mode, so we have a socket // we are in persistent connection mode, so we have a socket
// however, need to check whether it's still alive // however, need to check whether it's still alive
if (!feof($this->_socket)) if (!feof($this->_socket)) {
return $this->_socket; return $this->_socket;
}
// force reopen // force reopen
$this->_socket = false; $this->_socket = false;
@ -559,16 +587,18 @@ class SphinxClient extends cache_common
$port = $this->_port; $port = $this->_port;
} }
if ($this->_timeout <= 0) if ($this->_timeout <= 0) {
$fp = fsockopen($host, $port, $errno, $errstr); $fp = fsockopen($host, $port, $errno, $errstr);
else } else {
$fp = fsockopen($host, $port, $errno, $errstr, $this->_timeout); $fp = fsockopen($host, $port, $errno, $errstr, $this->_timeout);
}
if (!$fp) { if (!$fp) {
if ($this->_path) if ($this->_path) {
$location = $this->_path; $location = $this->_path;
else } else {
$location = "{$this->_host}:{$this->_port}"; $location = "{$this->_host}:{$this->_port}";
}
$errstr = trim($errstr); $errstr = trim($errstr);
$this->_error = "connection to $location failed (errno=$errno, msg=$errstr)"; $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)";
@ -600,14 +630,14 @@ class SphinxClient extends cache_common
} }
/// get and check response packet from searchd server /// get and check response packet from searchd server
function _GetResponse($fp, $client_ver) public function _GetResponse($fp, $client_ver)
{ {
$response = ""; $response = "";
$len = 0; $len = 0;
$header = fread($fp, 8); $header = fread($fp, 8);
if (strlen($header) == 8) { if (strlen($header) == 8) {
list ($status, $ver, $len) = array_values(unpack("n2a/Nb", $header)); list($status, $ver, $len) = array_values(unpack("n2a/Nb", $header));
$left = $len; $left = $len;
while ($left > 0 && !feof($fp)) { while ($left > 0 && !feof($fp)) {
$chunk = fread($fp, $left); $chunk = fread($fp, $left);
@ -617,8 +647,9 @@ class SphinxClient extends cache_common
} }
} }
} }
if ($this->_socket === false) if ($this->_socket === false) {
fclose($fp); fclose($fp);
}
// check response // check response
$read = strlen($response); $read = strlen($response);
@ -663,7 +694,7 @@ class SphinxClient extends cache_common
/// set offset and count into result set, /// set offset and count into result set,
/// and optionally set max-matches and cutoff limits /// and optionally set max-matches and cutoff limits
function SetLimits($offset, $limit, $max = 0, $cutoff = 0) public function SetLimits($offset, $limit, $max = 0, $cutoff = 0)
{ {
assert(is_int($offset)); assert(is_int($offset));
assert(is_int($limit)); assert(is_int($limit));
@ -672,15 +703,17 @@ class SphinxClient extends cache_common
assert($max >= 0); assert($max >= 0);
$this->_offset = $offset; $this->_offset = $offset;
$this->_limit = $limit; $this->_limit = $limit;
if ($max > 0) if ($max > 0) {
$this->_maxmatches = $max; $this->_maxmatches = $max;
if ($cutoff > 0) }
if ($cutoff > 0) {
$this->_cutoff = $cutoff; $this->_cutoff = $cutoff;
} }
}
/// set maximum query time, in milliseconds, per-index /// set maximum query time, in milliseconds, per-index
/// integer, 0 means "do not limit" /// integer, 0 means "do not limit"
function SetMaxQueryTime($max) public function SetMaxQueryTime($max)
{ {
assert(is_int($max)); assert(is_int($max));
assert($max >= 0); assert($max >= 0);
@ -688,7 +721,7 @@ class SphinxClient extends cache_common
} }
/// set matching mode /// set matching mode
function SetMatchMode($mode) public function SetMatchMode($mode)
{ {
assert($mode == SPH_MATCH_ALL assert($mode == SPH_MATCH_ALL
|| $mode == SPH_MATCH_ANY || $mode == SPH_MATCH_ANY
@ -701,7 +734,7 @@ class SphinxClient extends cache_common
} }
/// set ranking mode /// set ranking mode
function SetRankingMode($ranker) public function SetRankingMode($ranker)
{ {
assert($ranker == SPH_RANK_PROXIMITY_BM25 assert($ranker == SPH_RANK_PROXIMITY_BM25
|| $ranker == SPH_RANK_BM25 || $ranker == SPH_RANK_BM25
@ -712,7 +745,7 @@ class SphinxClient extends cache_common
} }
/// set matches sorting mode /// set matches sorting mode
function SetSortMode($mode, $sortby = "") public function SetSortMode($mode, $sortby = "")
{ {
assert( assert(
$mode == SPH_SORT_RELEVANCE || $mode == SPH_SORT_RELEVANCE ||
@ -730,17 +763,18 @@ class SphinxClient extends cache_common
/// bind per-field weights by order /// bind per-field weights by order
/// DEPRECATED; use SetFieldWeights() instead /// DEPRECATED; use SetFieldWeights() instead
function SetWeights($weights) public function SetWeights($weights)
{ {
assert(is_array($weights)); assert(is_array($weights));
foreach ($weights as $weight) foreach ($weights as $weight) {
assert(is_int($weight)); assert(is_int($weight));
}
$this->_weights = $weights; $this->_weights = $weights;
} }
/// bind per-field weights by name /// bind per-field weights by name
function SetFieldWeights($weights) public function SetFieldWeights($weights)
{ {
assert(is_array($weights)); assert(is_array($weights));
foreach ($weights as $name => $weight) { foreach ($weights as $name => $weight) {
@ -751,7 +785,7 @@ class SphinxClient extends cache_common
} }
/// bind per-index weights by name /// bind per-index weights by name
function SetIndexWeights($weights) public function SetIndexWeights($weights)
{ {
assert(is_array($weights)); assert(is_array($weights));
foreach ($weights as $index => $weight) { foreach ($weights as $index => $weight) {
@ -763,7 +797,7 @@ class SphinxClient extends cache_common
/// set IDs range to match /// set IDs range to match
/// only match records if document ID is beetwen $min and $max (inclusive) /// only match records if document ID is beetwen $min and $max (inclusive)
function SetIDRange($min, $max) public function SetIDRange($min, $max)
{ {
assert(is_numeric($min)); assert(is_numeric($min));
assert(is_numeric($max)); assert(is_numeric($max));
@ -774,15 +808,16 @@ class SphinxClient extends cache_common
/// set values set filter /// set values set filter
/// only match records where $attribute value is in given set /// only match records where $attribute value is in given set
function SetFilter($attribute, $values, $exclude = false) public function SetFilter($attribute, $values, $exclude = false)
{ {
assert(is_string($attribute)); assert(is_string($attribute));
assert(is_array($values)); assert(is_array($values));
assert(count($values)); assert(count($values));
if (is_array($values) && count($values)) { if (is_array($values) && count($values)) {
foreach ($values as $value) foreach ($values as $value) {
assert(is_numeric($value)); assert(is_numeric($value));
}
$this->_filters[] = array("type" => SPH_FILTER_VALUES, "attr" => $attribute, "exclude" => $exclude, "values" => $values); $this->_filters[] = array("type" => SPH_FILTER_VALUES, "attr" => $attribute, "exclude" => $exclude, "values" => $values);
} }
@ -790,7 +825,7 @@ class SphinxClient extends cache_common
/// set range filter /// set range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive) /// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterRange($attribute, $min, $max, $exclude = false) public function SetFilterRange($attribute, $min, $max, $exclude = false)
{ {
assert(is_string($attribute)); assert(is_string($attribute));
assert(is_numeric($min)); assert(is_numeric($min));
@ -802,7 +837,7 @@ class SphinxClient extends cache_common
/// set float range filter /// set float range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive) /// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterFloatRange($attribute, $min, $max, $exclude = false) public function SetFilterFloatRange($attribute, $min, $max, $exclude = false)
{ {
assert(is_string($attribute)); assert(is_string($attribute));
assert(is_float($min)); assert(is_float($min));
@ -815,7 +850,7 @@ class SphinxClient extends cache_common
/// setup anchor point for geosphere distance calculations /// setup anchor point for geosphere distance calculations
/// required to use @geodist in filters and sorting /// required to use @geodist in filters and sorting
/// latitude and longitude must be in radians /// latitude and longitude must be in radians
function SetGeoAnchor($attrlat, $attrlong, $lat, $long) public function SetGeoAnchor($attrlat, $attrlong, $lat, $long)
{ {
assert(is_string($attrlat)); assert(is_string($attrlat));
assert(is_string($attrlong)); assert(is_string($attrlong));
@ -826,7 +861,7 @@ class SphinxClient extends cache_common
} }
/// set grouping attribute and function /// set grouping attribute and function
function SetGroupBy($attribute, $func, $groupsort = "@group desc") public function SetGroupBy($attribute, $func, $groupsort = "@group desc")
{ {
assert(is_string($attribute)); assert(is_string($attribute));
assert(is_string($groupsort)); assert(is_string($groupsort));
@ -843,14 +878,14 @@ class SphinxClient extends cache_common
} }
/// set count-distinct attribute for group-by queries /// set count-distinct attribute for group-by queries
function SetGroupDistinct($attribute) public function SetGroupDistinct($attribute)
{ {
assert(is_string($attribute)); assert(is_string($attribute));
$this->_groupdistinct = $attribute; $this->_groupdistinct = $attribute;
} }
/// set distributed retries count and delay /// set distributed retries count and delay
function SetRetries($count, $delay = 0) public function SetRetries($count, $delay = 0)
{ {
assert(is_int($count) && $count >= 0); assert(is_int($count) && $count >= 0);
assert(is_int($delay) && $delay >= 0); assert(is_int($delay) && $delay >= 0);
@ -860,7 +895,7 @@ class SphinxClient extends cache_common
/// set result set format (hash or array; hash by default) /// set result set format (hash or array; hash by default)
/// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
function SetArrayResult($arrayresult) public function SetArrayResult($arrayresult)
{ {
assert(is_bool($arrayresult)); assert(is_bool($arrayresult));
$this->_arrayresult = $arrayresult; $this->_arrayresult = $arrayresult;
@ -869,7 +904,7 @@ class SphinxClient extends cache_common
/// set attribute values override /// set attribute values override
/// there can be only one override per attribute /// there can be only one override per attribute
/// $values must be a hash that maps document IDs to attribute values /// $values must be a hash that maps document IDs to attribute values
function SetOverride($attrname, $attrtype, $values) public function SetOverride($attrname, $attrtype, $values)
{ {
assert(is_string($attrname)); assert(is_string($attrname));
assert(in_array($attrtype, array(SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT))); assert(in_array($attrtype, array(SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT)));
@ -879,7 +914,7 @@ class SphinxClient extends cache_common
} }
/// set select-list (attributes or expressions), SQL-like syntax /// set select-list (attributes or expressions), SQL-like syntax
function SetSelect($select) public function SetSelect($select)
{ {
assert(is_string($select)); assert(is_string($select));
$this->_select = $select; $this->_select = $select;
@ -888,14 +923,14 @@ class SphinxClient extends cache_common
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
/// clear all filters (for multi-queries) /// clear all filters (for multi-queries)
function ResetFilters() public function ResetFilters()
{ {
$this->_filters = array(); $this->_filters = array();
$this->_anchor = array(); $this->_anchor = array();
} }
/// clear groupby settings (for multi-queries) /// clear groupby settings (for multi-queries)
function ResetGroupBy() public function ResetGroupBy()
{ {
$this->_groupby = ""; $this->_groupby = "";
$this->_groupfunc = SPH_GROUPBY_DAY; $this->_groupfunc = SPH_GROUPBY_DAY;
@ -904,7 +939,7 @@ class SphinxClient extends cache_common
} }
/// clear all attribute value overrides (for multi-queries) /// clear all attribute value overrides (for multi-queries)
function ResetOverrides() public function ResetOverrides()
{ {
$this->_overrides = array(); $this->_overrides = array();
} }
@ -913,7 +948,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, run given search query through given indexes, /// connect to searchd server, run given search query through given indexes,
/// and return the search results /// and return the search results
function Query($query, $index = "*", $comment = "") public function Query($query, $index = "*", $comment = "")
{ {
assert(empty($this->_reqs)); assert(empty($this->_reqs));
@ -923,19 +958,21 @@ class SphinxClient extends cache_common
$this->bb_queries = array(); $this->bb_queries = array();
$this->bb_indexes = array(); $this->bb_indexes = array();
if (!is_array($results)) if (!is_array($results)) {
return false; // probably network error; error message should be already filled return false;
} // probably network error; error message should be already filled
$this->_error = $results[0]["error"]; $this->_error = $results[0]["error"];
$this->_warning = $results[0]["warning"]; $this->_warning = $results[0]["warning"];
if ($results[0]["status"] == SEARCHD_ERROR) if ($results[0]["status"] == SEARCHD_ERROR) {
return false; return false;
else } else {
return $results[0]; return $results[0];
} }
}
/// helper to pack floats in network byte order /// helper to pack floats in network byte order
function _PackFloat($f) public function _PackFloat($f)
{ {
$t1 = pack("f", $f); // machine order $t1 = pack("f", $f); // machine order
list(, $t2) = unpack("L*", $t1); // int in machine order list(, $t2) = unpack("L*", $t1); // int in machine order
@ -944,7 +981,7 @@ class SphinxClient extends cache_common
/// add query to multi-query batch /// add query to multi-query batch
/// returns index into results array from RunQueries() call /// returns index into results array from RunQueries() call
function AddQuery($query, $index = "*", $comment = "") public function AddQuery($query, $index = "*", $comment = "")
{ {
// mbstring workaround // mbstring workaround
$this->_MBPush(); $this->_MBPush();
@ -954,8 +991,9 @@ class SphinxClient extends cache_common
$req .= pack("N", strlen($this->_sortby)) . $this->_sortby; $req .= pack("N", strlen($this->_sortby)) . $this->_sortby;
$req .= pack("N", strlen($query)) . $query; // query itself $req .= pack("N", strlen($query)) . $query; // query itself
$req .= pack("N", count($this->_weights)); // weights $req .= pack("N", count($this->_weights)); // weights
foreach ($this->_weights as $weight) foreach ($this->_weights as $weight) {
$req .= pack("N", (int)$weight); $req .= pack("N", (int)$weight);
}
$req .= pack("N", strlen($index)) . $index; // indexes $req .= pack("N", strlen($index)) . $index; // indexes
$req .= pack("N", 1); // id64 range marker $req .= pack("N", 1); // id64 range marker
$req .= sphPackU64($this->_min_id) . sphPackU64($this->_max_id); // id64 range $req .= sphPackU64($this->_min_id) . sphPackU64($this->_max_id); // id64 range
@ -968,8 +1006,9 @@ class SphinxClient extends cache_common
switch ($filter["type"]) { switch ($filter["type"]) {
case SPH_FILTER_VALUES: case SPH_FILTER_VALUES:
$req .= pack("N", count($filter["values"])); $req .= pack("N", count($filter["values"]));
foreach ($filter["values"] as $value) foreach ($filter["values"] as $value) {
$req .= sphPackI64($value); $req .= sphPackI64($value);
}
break; break;
case SPH_FILTER_RANGE: case SPH_FILTER_RANGE:
@ -1006,16 +1045,18 @@ class SphinxClient extends cache_common
// per-index weights // per-index weights
$req .= pack("N", count($this->_indexweights)); $req .= pack("N", count($this->_indexweights));
foreach ($this->_indexweights as $idx => $weight) foreach ($this->_indexweights as $idx => $weight) {
$req .= pack("N", strlen($idx)) . $idx . pack("N", $weight); $req .= pack("N", strlen($idx)) . $idx . pack("N", $weight);
}
// max query time // max query time
$req .= pack("N", $this->_maxquerytime); $req .= pack("N", $this->_maxquerytime);
// per-field weights // per-field weights
$req .= pack("N", count($this->_fieldweights)); $req .= pack("N", count($this->_fieldweights));
foreach ($this->_fieldweights as $field => $weight) foreach ($this->_fieldweights as $field => $weight) {
$req .= pack("N", strlen($field)) . $field . pack("N", $weight); $req .= pack("N", strlen($field)) . $field . pack("N", $weight);
}
// comment // comment
$req .= pack("N", strlen($comment)) . $comment; $req .= pack("N", strlen($comment)) . $comment;
@ -1058,7 +1099,7 @@ class SphinxClient extends cache_common
} }
/// connect to searchd, run queries batch, and return an array of result sets /// connect to searchd, run queries batch, and return an array of result sets
function RunQueries() public function RunQueries()
{ {
if (empty($this->_reqs)) { if (empty($this->_reqs)) {
$this->_error = "no queries defined, issue AddQuery() first"; $this->_error = "no queries defined, issue AddQuery() first";
@ -1101,7 +1142,7 @@ class SphinxClient extends cache_common
} }
/// parse and return search query (or queries) response /// parse and return search query (or queries) response
function _ParseSearchResponse($response, $nreqs) public function _ParseSearchResponse($response, $nreqs)
{ {
$p = 0; // current position $p = 0; // current position
$max = strlen($response); // max position for checks, to protect against broken responses $max = strlen($response); // max position for checks, to protect against broken responses
@ -1181,7 +1222,7 @@ class SphinxClient extends cache_common
list(, $weight) = unpack("N*", substr($response, $p, 4)); list(, $weight) = unpack("N*", substr($response, $p, 4));
$p += 4; $p += 4;
} else { } else {
list ($doc, $weight) = array_values(unpack("N*N*", list($doc, $weight) = array_values(unpack("N*N*",
substr($response, $p, 8))); substr($response, $p, 8)));
$p += 8; $p += 8;
$doc = sphFixUint($doc); $doc = sphFixUint($doc);
@ -1189,10 +1230,11 @@ class SphinxClient extends cache_common
$weight = sprintf("%u", $weight); $weight = sprintf("%u", $weight);
// create match entry // create match entry
if ($this->_arrayresult) if ($this->_arrayresult) {
$result["matches"][$idx] = array("id" => $doc, "weight" => $weight); $result["matches"][$idx] = array("id" => $doc, "weight" => $weight);
else } else {
$result["matches"][$doc]["weight"] = $weight; $result["matches"][$doc]["weight"] = $weight;
}
// parse and create attributes // parse and create attributes
$attrvals = array(); $attrvals = array();
@ -1229,13 +1271,14 @@ class SphinxClient extends cache_common
} }
} }
if ($this->_arrayresult) if ($this->_arrayresult) {
$result["matches"][$idx]["attrs"] = $attrvals; $result["matches"][$idx]["attrs"] = $attrvals;
else } else {
$result["matches"][$doc]["attrs"] = $attrvals; $result["matches"][$doc]["attrs"] = $attrvals;
} }
}
list ($total, $total_found, $msecs, $words) = list($total, $total_found, $msecs, $words) =
array_values(unpack("N*N*N*N*", substr($response, $p, 16))); array_values(unpack("N*N*N*N*", substr($response, $p, 16)));
$result["total"] = sprintf("%u", $total); $result["total"] = sprintf("%u", $total);
$result["total_found"] = sprintf("%u", $total_found); $result["total_found"] = sprintf("%u", $total_found);
@ -1247,7 +1290,7 @@ class SphinxClient extends cache_common
$p += 4; $p += 4;
$word = substr($response, $p, $len); $word = substr($response, $p, $len);
$p += $len; $p += $len;
list ($docs, $hits) = array_values(unpack("N*N*", substr($response, $p, 8))); list($docs, $hits) = array_values(unpack("N*N*", substr($response, $p, 8)));
$p += 8; $p += 8;
$result["words"][$word] = array( $result["words"][$word] = array(
"docs" => sprintf("%u", $docs), "docs" => sprintf("%u", $docs),
@ -1268,7 +1311,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, and generate exceprts (snippets) /// connect to searchd server, and generate exceprts (snippets)
/// of given documents for given query. returns false on failure, /// of given documents for given query. returns false on failure,
/// an array of snippets on success /// an array of snippets on success
function BuildExcerpts($docs, $index, $words, $opts = array()) public function BuildExcerpts($docs, $index, $words, $opts = array())
{ {
assert(is_array($docs)); assert(is_array($docs));
assert(is_string($index)); assert(is_string($index));
@ -1286,15 +1329,33 @@ class SphinxClient extends cache_common
// fixup options // fixup options
///////////////// /////////////////
if (!isset($opts["before_match"])) $opts["before_match"] = "<b>"; if (!isset($opts["before_match"])) {
if (!isset($opts["after_match"])) $opts["after_match"] = "</b>"; $opts["before_match"] = "<b>";
if (!isset($opts["chunk_separator"])) $opts["chunk_separator"] = " ... "; }
if (!isset($opts["limit"])) $opts["limit"] = 256; if (!isset($opts["after_match"])) {
if (!isset($opts["around"])) $opts["around"] = 5; $opts["after_match"] = "</b>";
if (!isset($opts["exact_phrase"])) $opts["exact_phrase"] = false; }
if (!isset($opts["single_passage"])) $opts["single_passage"] = false; if (!isset($opts["chunk_separator"])) {
if (!isset($opts["use_boundaries"])) $opts["use_boundaries"] = false; $opts["chunk_separator"] = " ... ";
if (!isset($opts["weight_order"])) $opts["weight_order"] = false; }
if (!isset($opts["limit"])) {
$opts["limit"] = 256;
}
if (!isset($opts["around"])) {
$opts["around"] = 5;
}
if (!isset($opts["exact_phrase"])) {
$opts["exact_phrase"] = false;
}
if (!isset($opts["single_passage"])) {
$opts["single_passage"] = false;
}
if (!isset($opts["use_boundaries"])) {
$opts["use_boundaries"] = false;
}
if (!isset($opts["weight_order"])) {
$opts["weight_order"] = false;
}
///////////////// /////////////////
// build request // build request
@ -1302,10 +1363,18 @@ class SphinxClient extends cache_common
// v.1.0 req // v.1.0 req
$flags = 1; // remove spaces $flags = 1; // remove spaces
if ($opts["exact_phrase"]) $flags |= 2; if ($opts["exact_phrase"]) {
if ($opts["single_passage"]) $flags |= 4; $flags |= 2;
if ($opts["use_boundaries"]) $flags |= 8; }
if ($opts["weight_order"]) $flags |= 16; if ($opts["single_passage"]) {
$flags |= 4;
}
if ($opts["use_boundaries"]) {
$flags |= 8;
}
if ($opts["weight_order"]) {
$flags |= 16;
}
$req = pack("NN", 0, $flags); // mode=0, flags=$flags $req = pack("NN", 0, $flags); // mode=0, flags=$flags
$req .= pack("N", strlen($index)) . $index; // req index $req .= pack("N", strlen($index)) . $index; // req index
$req .= pack("N", strlen($words)) . $words; // req words $req .= pack("N", strlen($words)) . $words; // req words
@ -1369,7 +1438,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, and generate keyword list for a given query /// connect to searchd server, and generate keyword list for a given query
/// returns false on failure, /// returns false on failure,
/// an array of words on success /// an array of words on success
function BuildKeywords($query, $index, $hits) public function BuildKeywords($query, $index, $hits)
{ {
assert(is_string($query)); assert(is_string($query));
assert(is_string($index)); assert(is_string($index));
@ -1444,7 +1513,7 @@ class SphinxClient extends cache_common
return $res; return $res;
} }
function EscapeString($string) public function EscapeString($string)
{ {
$from = array('\\', '(', ')', '|', '-', '!', '@', '~', '"', '&', '/', '^', '$', '='); $from = array('\\', '(', ')', '|', '-', '!', '@', '~', '"', '&', '/', '^', '$', '=');
$to = array('\\\\', '\(', '\)', '\|', '\-', '\!', '\@', '\~', '\"', '\&', '\/', '\^', '\$', '\='); $to = array('\\\\', '\(', '\)', '\|', '\-', '\!', '\@', '\~', '\"', '\&', '\/', '\^', '\$', '\=');
@ -1458,15 +1527,16 @@ class SphinxClient extends cache_common
/// batch update given attributes in given rows in given indexes /// batch update given attributes in given rows in given indexes
/// returns amount of updated documents (0 or more) on success, or -1 on failure /// returns amount of updated documents (0 or more) on success, or -1 on failure
function UpdateAttributes($index, $attrs, $values, $mva = false) public function UpdateAttributes($index, $attrs, $values, $mva = false)
{ {
// verify everything // verify everything
assert(is_string($index)); assert(is_string($index));
assert(is_bool($mva)); assert(is_bool($mva));
assert(is_array($attrs)); assert(is_array($attrs));
foreach ($attrs as $attr) foreach ($attrs as $attr) {
assert(is_string($attr)); assert(is_string($attr));
}
assert(is_array($values)); assert(is_array($values));
foreach ($values as $id => $entry) { foreach ($values as $id => $entry) {
@ -1476,12 +1546,14 @@ class SphinxClient extends cache_common
foreach ($entry as $v) { foreach ($entry as $v) {
if ($mva) { if ($mva) {
assert(is_array($v)); assert(is_array($v));
foreach ($v as $vv) foreach ($v as $vv) {
assert(is_int($vv)); assert(is_int($vv));
} else }
} else {
assert(is_int($v)); assert(is_int($v));
} }
} }
}
// build request // build request
$req = pack("N", strlen($index)) . $index; $req = pack("N", strlen($index)) . $index;
@ -1497,23 +1569,28 @@ class SphinxClient extends cache_common
$req .= sphPackU64($id); $req .= sphPackU64($id);
foreach ($entry as $v) { foreach ($entry as $v) {
$req .= pack("N", $mva ? count($v) : $v); $req .= pack("N", $mva ? count($v) : $v);
if ($mva) if ($mva) {
foreach ($v as $vv) foreach ($v as $vv) {
$req .= pack("N", $vv); $req .= pack("N", $vv);
} }
} }
}
}
// connect, send query, get response // connect, send query, get response
if (!($fp = $this->_Connect())) if (!($fp = $this->_Connect())) {
return -1; return -1;
}
$len = strlen($req); $len = strlen($req);
$req = pack("nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len) . $req; // add header $req = pack("nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len) . $req; // add header
if (!$this->_Send($fp, $req, $len + 8)) if (!$this->_Send($fp, $req, $len + 8)) {
return -1; return -1;
}
if (!($response = $this->_GetResponse($fp, VER_COMMAND_UPDATE))) if (!($response = $this->_GetResponse($fp, VER_COMMAND_UPDATE))) {
return -1; return -1;
}
// parse response // parse response
list(, $updated) = unpack("N*", substr($response, 0, 4)); list(, $updated) = unpack("N*", substr($response, 0, 4));
@ -1524,25 +1601,27 @@ class SphinxClient extends cache_common
// persistent connections // persistent connections
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
function Open() public function Open()
{ {
if ($this->_socket !== false) { if ($this->_socket !== false) {
$this->_error = 'already connected'; $this->_error = 'already connected';
return false; return false;
} }
if (!$fp = $this->_Connect()) if (!$fp = $this->_Connect()) {
return false; return false;
}
// command, command version = 0, body length = 4, body = 1 // command, command version = 0, body length = 4, body = 1
$req = pack("nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1); $req = pack("nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1);
if (!$this->_Send($fp, $req, 12)) if (!$this->_Send($fp, $req, 12)) {
return false; return false;
}
$this->_socket = $fp; $this->_socket = $fp;
return true; return true;
} }
function Close() public function Close()
{ {
if ($this->_socket === false) { if ($this->_socket === false) {
$this->_error = 'not connected'; $this->_error = 'not connected';
@ -1559,7 +1638,7 @@ class SphinxClient extends cache_common
// status // status
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
function Status() public function Status()
{ {
$this->_MBPush(); $this->_MBPush();
if (!($fp = $this->_Connect())) { if (!($fp = $this->_Connect())) {
@ -1577,17 +1656,18 @@ class SphinxClient extends cache_common
$res = substr($response, 4); // just ignore length, error handling, etc $res = substr($response, 4); // just ignore length, error handling, etc
$p = 0; $p = 0;
list ($rows, $cols) = array_values(unpack("N*N*", substr($response, $p, 8))); list($rows, $cols) = array_values(unpack("N*N*", substr($response, $p, 8)));
$p += 8; $p += 8;
$res = array(); $res = array();
for ($i = 0; $i < $rows; $i++) for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) { for ($j = 0; $j < $cols; $j++) {
list(, $len) = unpack("N*", substr($response, $p, 4)); list(, $len) = unpack("N*", substr($response, $p, 4));
$p += 4; $p += 4;
$res[$i][] = substr($response, $p, $len); $res[$i][] = substr($response, $p, $len);
$p += $len; $p += $len;
} }
}
$this->_MBPop(); $this->_MBPop();
return $res; return $res;

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',
@ -220,7 +222,7 @@ function strip_quotes($text)
$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
@ -244,7 +246,7 @@ function strip_quotes($text)
// 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"]);
} }
} }
@ -349,12 +351,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) $text_out[] = $word; if (mb_strlen($word) > $min_word_len && mb_strlen($word) <= $max_word_len) {
$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);
} }
@ -399,11 +403,11 @@ function add_search_words($post_id, $post_message, $topic_title = '', $only_retu
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,
@ -421,7 +425,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',
@ -431,17 +435,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();
@ -451,7 +455,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/?&%;][^\[\]]*)?';
@ -517,7 +521,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();
@ -570,7 +574,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);
@ -646,7 +650,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);
@ -663,7 +667,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();
@ -671,7 +675,9 @@ 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')) { 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>"; $link = "<a href=\"$url\" class=\"postLink\">$url_name</a>";
@ -689,7 +695,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);
@ -705,7 +711,7 @@ class bbcode
* *
* @return string * @return string
*/ */
function make_clickable($text) public function make_clickable($text)
{ {
$url_regexp = "# $url_regexp = "#
(?<![\"'=]) (?<![\"'=])
@ -739,7 +745,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();
@ -764,7 +770,7 @@ class bbcode
* *
* @return mixed * @return mixed
*/ */
function smilies_pass($text) public function smilies_pass($text)
{ {
global $datastore; global $datastore;
@ -786,7 +792,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);
@ -800,7 +806,7 @@ 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;
@ -825,14 +831,14 @@ function bbcode2html($text)
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');
@ -850,7 +856,7 @@ 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();

View file

@ -1,17 +1,19 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
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*/) 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();
@ -22,7 +24,7 @@ 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();
@ -35,7 +37,7 @@ 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 = '';
@ -43,44 +45,44 @@ class emailer
} }
// Sets an email address to send to // Sets an email address to send to
function email_address($address) public function email_address($address)
{ {
$this->addresses['to'] = trim($address); $this->addresses['to'] = trim($address);
} }
function cc($address) public function cc($address)
{ {
$this->addresses['cc'][] = trim($address); $this->addresses['cc'][] = trim($address);
} }
function bcc($address) public function bcc($address)
{ {
$this->addresses['bcc'][] = trim($address); $this->addresses['bcc'][] = trim($address);
} }
function replyto($address) public function replyto($address)
{ {
$this->reply_to = trim($address); $this->reply_to = trim($address);
} }
function from($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 = '') 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) public function extra_headers($headers)
{ {
$this->extra_headers .= trim($headers) . "\n"; $this->extra_headers .= trim($headers) . "\n";
} }
function use_template($template_file, $template_lang = '') public function use_template($template_file, $template_lang = '')
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -118,13 +120,13 @@ class emailer
} }
// assign variables // assign variables
function assign_vars($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') public function send($email_format = 'text')
{ {
global $userdata; global $userdata;
@ -206,7 +208,7 @@ class emailer
return true; return true;
} }
function encode($str) public function encode($str)
{ {
if ($this->encoding == '') { if ($this->encoding == '') {
return $str; return $str;

View file

@ -1,22 +1,24 @@
<?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() public function sitemap()
{ {
$this->home = make_url(); $this->home = make_url();
} }
function build_map() 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();
@ -27,7 +29,7 @@ class sitemap
return $map; return $map;
} }
function build_index($count) 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";
@ -41,7 +43,7 @@ class sitemap
return $map; return $map;
} }
function build_stat() 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();
@ -51,7 +53,7 @@ class sitemap
return $map; return $map;
} }
function build_map_topic($n) 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);
@ -60,7 +62,7 @@ class sitemap
return $map; return $map;
} }
function get_forum() public function get_forum()
{ {
global $datastore; global $datastore;
@ -79,15 +81,18 @@ 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) public function get_topic($page = false)
{ {
global $datastore; global $datastore;
@ -99,7 +104,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 {
@ -118,15 +125,18 @@ 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() public function get_static()
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -151,7 +161,7 @@ class sitemap
return $xml; return $xml;
} }
function get_xml($loc, $lm) 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";
@ -162,7 +172,7 @@ class sitemap
return $xml; return $xml;
} }
function send_url($url, $map) public function send_url($url, $map)
{ {
$data = false; $data = false;
$file = $url . urlencode($map); $file = $url . urlencode($map);
@ -185,11 +195,13 @@ 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,20 +1,22 @@
<?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) public function DBS($cfg)
{ {
$this->cfg = $cfg['db']; $this->cfg = $cfg['db'];
$this->alias = $cfg['db_alias']; $this->alias = $cfg['db_alias'];
@ -25,7 +27,7 @@ class DBS
} }
// получение/инициализация класса для сервера $srv_name // получение/инициализация класса для сервера $srv_name
function get_db_obj($srv_name_or_alias = 'db1') 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);
@ -37,11 +39,11 @@ class DBS
} }
// определение имени сервера // определение имени сервера
function get_srv_name($name) public function get_srv_name($name)
{ {
if (isset($this->alias[$name])) { if (isset($this->alias[$name])) {
$srv_name = $this->alias[$name]; $srv_name = $this->alias[$name];
} else if (isset($this->cfg[$name])) { } elseif (isset($this->cfg[$name])) {
$srv_name = $name; $srv_name = $name;
} else { } else {
$srv_name = 'db1'; $srv_name = 'db1';

View file

@ -1,44 +1,46 @@
<?php <?php
if (!defined('SQL_DEBUG')) die(basename(__FILE__)); if (!defined('SQL_DEBUG')) {
die(basename(__FILE__));
}
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 $inited = false; public $inited = false;
var $locked = false; public $locked = false;
var $locks = array(); public $locks = array();
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 $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 $do_explain = false; public $do_explain = false;
var $explain_hold = ''; public $explain_hold = '';
var $explain_out = ''; public $explain_out = '';
var $shutdown = array(); public $shutdown = array();
var $DBS = array(); public $DBS = array();
/** /**
* Constructor * Constructor
*/ */
function sql_db($cfg_values) public function sql_db($cfg_values)
{ {
global $DBS; global $DBS;
@ -58,7 +60,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();
@ -82,7 +84,7 @@ class sql_db
/** /**
* Open connection * Open connection
*/ */
function connect() public function connect()
{ {
$this->cur_query = ($this->dbg_enabled) ? ($this->cfg['persist'] ? 'p' : '') . "connect to: {$this->cfg['dbhost']}" : 'connect'; $this->cur_query = ($this->dbg_enabled) ? ($this->cfg['persist'] ? 'p' : '') . "connect to: {$this->cfg['dbhost']}" : 'connect';
$this->debug('start'); $this->debug('start');
@ -107,7 +109,7 @@ class sql_db
/** /**
* Select database * Select database
*/ */
function select_db() public function select_db()
{ {
$this->cur_query = ($this->dbg_enabled) ? "select db: {$this->cfg['dbname']}" : 'select db'; $this->cur_query = ($this->dbg_enabled) ? "select db: {$this->cfg['dbname']}" : 'select db';
$this->debug('start'); $this->debug('start');
@ -126,7 +128,7 @@ class sql_db
/** /**
* Base query method * Base query method
*/ */
function sql_query($query) public function sql_query($query)
{ {
if (!is_resource($this->link)) { if (!is_resource($this->link)) {
$this->init(); $this->init();
@ -158,7 +160,7 @@ class sql_db
/** /**
* Execute query WRAPPER (with error handling) * Execute query WRAPPER (with error handling)
*/ */
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();
@ -170,11 +172,11 @@ class sql_db
/** /**
* Return number of rows * Return number of rows
*/ */
function num_rows($result = false) public function num_rows($result = false)
{ {
$num_rows = false; $num_rows = false;
if ($result OR $result = $this->result) { if ($result or $result = $this->result) {
$num_rows = is_resource($result) ? mysql_num_rows($result) : false; $num_rows = is_resource($result) ? mysql_num_rows($result) : false;
} }
@ -184,7 +186,7 @@ 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;
} }
@ -192,7 +194,7 @@ class sql_db
/** /**
* Fetch current field * Fetch current field
*/ */
function sql_fetchfield($field, $rownum = -1, $query_id = 0) public function sql_fetchfield($field, $rownum = -1, $query_id = 0)
{ {
if (!$query_id) { if (!$query_id) {
$query_id = $this->query_result; $query_id = $this->query_result;
@ -208,7 +210,7 @@ class sql_db
} else { } else {
if ($this->rowset[$query_id]) { if ($this->rowset[$query_id]) {
$result = $this->rowset[$query_id][0][$field]; $result = $this->rowset[$query_id][0][$field];
} else if ($this->row[$query_id]) { } elseif ($this->row[$query_id]) {
$result = $this->row[$query_id][$field]; $result = $this->row[$query_id][$field];
} }
} }
@ -222,7 +224,7 @@ class sql_db
/** /**
* Fetch current row * Fetch current row
*/ */
function sql_fetchrow($result, $field_name = '') public function sql_fetchrow($result, $field_name = '')
{ {
$row = mysql_fetch_assoc($result); $row = mysql_fetch_assoc($result);
@ -236,7 +238,7 @@ class sql_db
/** /**
* Alias of sql_fetchrow() * Alias of sql_fetchrow()
*/ */
function fetch_next($result) public function fetch_next($result)
{ {
return $this->sql_fetchrow($result); return $this->sql_fetchrow($result);
} }
@ -244,7 +246,7 @@ class sql_db
/** /**
* Fetch row WRAPPER (with error handling) * Fetch row WRAPPER (with error handling)
*/ */
function fetch_row($query, $field_name = '') public function fetch_row($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) { if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
@ -256,7 +258,7 @@ class sql_db
/** /**
* Fetch all rows * Fetch all rows
*/ */
function sql_fetchrowset($result, $field_name = '') public function sql_fetchrowset($result, $field_name = '')
{ {
$rowset = array(); $rowset = array();
@ -270,7 +272,7 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
*/ */
function fetch_rowset($query, $field_name = '') public function fetch_rowset($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) { if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
@ -282,7 +284,7 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
*/ */
function fetch_all($query, $field_name = '') public function fetch_all($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) { if (!$result = $this->sql_query($query)) {
$this->trigger_error(); $this->trigger_error();
@ -294,7 +296,7 @@ class sql_db
/** /**
* Get last inserted id after insert statement * Get last inserted id after insert statement
*/ */
function sql_nextid() public function sql_nextid()
{ {
return mysql_insert_id($this->link); return mysql_insert_id($this->link);
} }
@ -302,9 +304,9 @@ class sql_db
/** /**
* Free sql result * Free sql result
*/ */
function sql_freeresult($result = false) public function sql_freeresult($result = false)
{ {
if ($result OR $result = $this->result) { if ($result or $result = $this->result) {
$return_value = is_resource($result) ? mysql_free_result($result) : false; $return_value = is_resource($result) ? mysql_free_result($result) : false;
} }
@ -314,10 +316,14 @@ class sql_db
/** /**
* Escape data used in sql query * Escape data used in sql query
*/ */
function escape($v, $check_type = false, $dont_escape = false) public function escape($v, $check_type = false, $dont_escape = false)
{ {
if ($dont_escape) return $v; if ($dont_escape) {
if (!$check_type) return $this->escape_string($v); return $v;
}
if (!$check_type) {
return $this->escape_string($v);
}
switch (true) { switch (true) {
case is_string($v): case is_string($v):
@ -338,7 +344,7 @@ class sql_db
/** /**
* Escape string * Escape string
*/ */
function escape_string($str) public function escape_string($str)
{ {
if (!is_resource($this->link)) { if (!is_resource($this->link)) {
$this->init(); $this->init();
@ -352,7 +358,7 @@ class sql_db
* *
* Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT * Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT
*/ */
function build_array($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true) public function build_array($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true)
{ {
$fields = $values = $ary = $query = array(); $fields = $values = $ary = $query = array();
$dont_escape = $data_already_escaped; $dont_escape = $data_already_escaped;
@ -370,7 +376,7 @@ class sql_db
$fields = join(', ', $fields); $fields = join(', ', $fields);
$values = join(', ', $values); $values = join(', ', $values);
$query = "($fields)\nVALUES\n($values)"; $query = "($fields)\nVALUES\n($values)";
} else if ($query_type == 'INSERT_SELECT') { } elseif ($query_type == 'INSERT_SELECT') {
foreach ($input_ary as $field => $val) { foreach ($input_ary as $field => $val) {
$fields[] = $field; $fields[] = $field;
$values[] = $this->escape($val, $check_type, $dont_escape); $values[] = $this->escape($val, $check_type, $dont_escape);
@ -378,7 +384,7 @@ class sql_db
$fields = join(', ', $fields); $fields = join(', ', $fields);
$values = join(', ', $values); $values = join(', ', $values);
$query = "($fields)\nSELECT\n$values"; $query = "($fields)\nSELECT\n$values";
} else if ($query_type == 'MULTI_INSERT') { } elseif ($query_type == 'MULTI_INSERT') {
foreach ($input_ary as $id => $sql_ary) { foreach ($input_ary as $id => $sql_ary) {
foreach ($sql_ary as $field => $val) { foreach ($sql_ary as $field => $val) {
$values[] = $this->escape($val, $check_type, $dont_escape); $values[] = $this->escape($val, $check_type, $dont_escape);
@ -389,7 +395,7 @@ class sql_db
$fields = join(', ', array_keys($input_ary[0])); $fields = join(', ', array_keys($input_ary[0]));
$values = join(",\n", $ary); $values = join(",\n", $ary);
$query = "($fields)\nVALUES\n$values"; $query = "($fields)\nVALUES\n$values";
} else if ($query_type == 'SELECT' || $query_type == 'UPDATE') { } elseif ($query_type == 'SELECT' || $query_type == 'UPDATE') {
foreach ($input_ary as $field => $val) { foreach ($input_ary as $field => $val) {
$ary[] = "$field = " . $this->escape($val, $check_type, $dont_escape); $ary[] = "$field = " . $this->escape($val, $check_type, $dont_escape);
} }
@ -404,7 +410,7 @@ class sql_db
return "\n" . $query . "\n"; return "\n" . $query . "\n";
} }
function get_empty_sql_array() public function get_empty_sql_array()
{ {
return array( return array(
'SELECT' => array(), 'SELECT' => array(),
@ -420,7 +426,7 @@ class sql_db
); );
} }
function build_sql($sql_ary) public function build_sql($sql_ary)
{ {
$sql = ''; $sql = '';
array_deep($sql_ary, 'array_unique', false, true); array_deep($sql_ary, 'array_unique', false, true);
@ -463,7 +469,7 @@ class sql_db
/** /**
* Return sql error array * Return sql error array
*/ */
function sql_error() public function sql_error()
{ {
if (is_resource($this->link)) { if (is_resource($this->link)) {
return array('code' => mysql_errno($this->link), 'message' => mysql_error($this->link)); return array('code' => mysql_errno($this->link), 'message' => mysql_error($this->link));
@ -475,7 +481,7 @@ class sql_db
/** /**
* Close sql connection * Close sql connection
*/ */
function close() public function close()
{ {
if (is_resource($this->link)) { if (is_resource($this->link)) {
$this->unlock(); $this->unlock();
@ -497,7 +503,7 @@ class sql_db
/** /**
* Add shutdown query * Add shutdown query
*/ */
function add_shutdown_query($sql) public function add_shutdown_query($sql)
{ {
$this->shutdown['__sql'][] = $sql; $this->shutdown['__sql'][] = $sql;
} }
@ -505,9 +511,11 @@ class sql_db
/** /**
* Exec shutdown queries * Exec shutdown queries
*/ */
function exec_shutdown_queries() public function exec_shutdown_queries()
{ {
if (empty($this->shutdown)) return; if (empty($this->shutdown)) {
return;
}
if (!empty($this->shutdown['post_html'])) { if (!empty($this->shutdown['post_html'])) {
$post_html_sql = $this->build_array('MULTI_INSERT', $this->shutdown['post_html']); $post_html_sql = $this->build_array('MULTI_INSERT', $this->shutdown['post_html']);
@ -524,10 +532,10 @@ class sql_db
/** /**
* Lock tables * Lock tables
*/ */
function lock($tables, $lock_type = 'WRITE') public function lock($tables, $lock_type = 'WRITE')
{ {
if ($this->cfg['persist']) { if ($this->cfg['persist']) {
# return true; # return true;
} }
$tables_sql = array(); $tables_sql = array();
@ -545,7 +553,7 @@ class sql_db
/** /**
* Unlock tables * Unlock tables
*/ */
function unlock() public function unlock()
{ {
if ($this->locked && $this->sql_query("UNLOCK TABLES")) { if ($this->locked && $this->sql_query("UNLOCK TABLES")) {
$this->locked = false; $this->locked = false;
@ -557,7 +565,7 @@ class sql_db
/** /**
* Obtain user level lock * Obtain user level lock
*/ */
function get_lock($name, $timeout = 0) public function get_lock($name, $timeout = 0)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$timeout = (int)$timeout; $timeout = (int)$timeout;
@ -573,7 +581,7 @@ class sql_db
/** /**
* Obtain user level lock status * Obtain user level lock status
*/ */
function release_lock($name) public function release_lock($name)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result"); $row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result");
@ -588,7 +596,7 @@ class sql_db
/** /**
* Release user level lock * Release user level lock
*/ */
function is_free_lock($name) public function is_free_lock($name)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result"); $row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result");
@ -598,7 +606,7 @@ class sql_db
/** /**
* Make per db unique lock name * Make per db unique lock name
*/ */
function get_lock_name($name) public function get_lock_name($name)
{ {
if (!$this->selected_db) { if (!$this->selected_db) {
$this->init(); $this->init();
@ -610,7 +618,7 @@ class sql_db
/** /**
* Get info about last query * Get info about last query
*/ */
function query_info() public function query_info()
{ {
$info = array(); $info = array();
@ -618,9 +626,9 @@ class sql_db
$info[] = "$num rows"; $info[] = "$num rows";
} }
if (is_resource($this->link) AND $ext = mysql_info($this->link)) { if (is_resource($this->link) and $ext = mysql_info($this->link)) {
$info[] = "$ext"; $info[] = "$ext";
} else if (!$num && ($aff = $this->affected_rows($this->result) AND $aff != -1)) { } elseif (!$num && ($aff = $this->affected_rows($this->result) and $aff != -1)) {
$info[] = "$aff rows"; $info[] = "$aff rows";
} }
@ -630,7 +638,7 @@ class sql_db
/** /**
* Get server version * Get server version
*/ */
function server_version() public function server_version()
{ {
preg_match('#^(\d+\.\d+\.\d+).*#', mysql_get_server_info(), $m); preg_match('#^(\d+\.\d+\.\d+).*#', mysql_get_server_info(), $m);
return $m[1]; return $m[1];
@ -640,7 +648,7 @@ class sql_db
* Set slow query marker for xx seconds * Set slow query marker for xx seconds
* This will disable counting other queries as "slow" during this time * This will disable counting other queries as "slow" during this time
*/ */
function expect_slow_query($ignoring_time = 60, $new_priority = 10) public function expect_slow_query($ignoring_time = 60, $new_priority = 10)
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -662,9 +670,11 @@ class sql_db
/** /**
* Store debug info * Store debug info
*/ */
function debug($mode) public function debug($mode)
{ {
if (!SQL_DEBUG) return; if (!SQL_DEBUG) {
return;
}
$id =& $this->dbg_id; $id =& $this->dbg_id;
$dbg =& $this->dbg[$id]; $dbg =& $this->dbg[$id];
@ -685,7 +695,7 @@ class sql_db
if ($this->do_explain) { if ($this->do_explain) {
$this->explain('start'); $this->explain('start');
} }
} else if ($mode == 'stop') { } elseif ($mode == 'stop') {
if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) {
$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;
@ -715,7 +725,7 @@ class sql_db
/** /**
* Trigger error * Trigger error
*/ */
function trigger_error($msg = 'DB Error') public function trigger_error($msg = 'DB Error')
{ {
if (error_reporting()) { if (error_reporting()) {
if (DBG_LOG === true) { if (DBG_LOG === true) {
@ -732,7 +742,7 @@ class sql_db
/** /**
* Find caller source * Find caller source
*/ */
function debug_find_source($mode = '') public function debug_find_source($mode = '')
{ {
foreach (debug_backtrace() as $trace) { foreach (debug_backtrace() as $trace) {
if (!empty($trace['file']) && $trace['file'] !== __FILE__) { if (!empty($trace['file']) && $trace['file'] !== __FILE__) {
@ -752,7 +762,7 @@ class sql_db
/** /**
* Prepare for logging * Prepare for logging
*/ */
function log_next_query($queries_count = 1, $log_file = 'sql_queries') public function log_next_query($queries_count = 1, $log_file = 'sql_queries')
{ {
$this->DBS['log_file'] = $log_file; $this->DBS['log_file'] = $log_file;
$this->DBS['log_counter'] = $queries_count; $this->DBS['log_counter'] = $queries_count;
@ -761,7 +771,7 @@ class sql_db
/** /**
* Log query * Log query
*/ */
function log_query($log_file = 'sql_queries') public function log_query($log_file = 'sql_queries')
{ {
$q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time); $q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time);
$msg = array(); $msg = array();
@ -782,7 +792,7 @@ class sql_db
/** /**
* Log slow query * Log slow query
*/ */
function log_slow_query($log_file = 'sql_slow_bb') public function log_slow_query($log_file = 'sql_slow_bb')
{ {
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -799,9 +809,11 @@ class sql_db
/** /**
* Log error * Log error
*/ */
function log_error() public function log_error()
{ {
if (!SQL_LOG_ERRORS) return; if (!SQL_LOG_ERRORS) {
return;
}
$msg = array(); $msg = array();
$err = $this->sql_error(); $err = $this->sql_error();
@ -825,7 +837,7 @@ class sql_db
/** /**
* Explain queries (based on code from phpBB3) * Explain queries (based on code from phpBB3)
*/ */
function explain($mode, $html_table = '', $row = '') public function explain($mode, $html_table = '', $row = '')
{ {
$query = str_compact($this->cur_query); $query = str_compact($this->cur_query);
// remove comments // remove comments
@ -836,7 +848,7 @@ class sql_db
$this->explain_hold = ''; $this->explain_hold = '';
if (preg_match('#UPDATE ([a-z0-9_]+).*?WHERE(.*)/#', $query, $m)) { if (preg_match('#UPDATE ([a-z0-9_]+).*?WHERE(.*)/#', $query, $m)) {
$query = "SELECT * FROM $m[1] WHERE $m[2]"; $query = "SELECT * FROM $m[1] WHERE $m[2]";
} else if (preg_match('#DELETE FROM ([a-z0-9_]+).*?WHERE(.*)#s', $query, $m)) { } elseif (preg_match('#DELETE FROM ([a-z0-9_]+).*?WHERE(.*)#s', $query, $m)) {
$query = "SELECT * FROM $m[1] WHERE $m[2]"; $query = "SELECT * FROM $m[1] WHERE $m[2]";
} }
@ -855,7 +867,9 @@ class sql_db
break; break;
case 'stop': case 'stop':
if (!$this->explain_hold) break; if (!$this->explain_hold) {
break;
}
$id = $this->dbg_id - 1; $id = $this->dbg_id - 1;
$htid = 'expl-' . intval($this->link) . '-' . $id; $htid = 'expl-' . intval($this->link) . '-' . $id;

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

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// //
// Functions // Functions
@ -10,7 +12,7 @@ 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)) {

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

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__));
}
/** @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__));
}
/** @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,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__));
}
/** @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__));
}
/** @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__));
}
/** @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__));
}
require(CLASS_DIR . 'sitemap.php'); require(CLASS_DIR . 'sitemap.php');

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__));
}
/** @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__));
}
/** @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__));
}
/** @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__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
@ -30,7 +32,9 @@ if ($di->config->get('seed_bonus_enabled') && $di->config->get('seed_bonus_point
$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]) continue; if (!$points || !$seed_release[$i]) {
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();
@ -11,14 +13,18 @@ $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) update_forum_feed(0, $forums_data); if (filemtime($di->config->get('atom.path') . '/f/0.atom') <= $timecheck) {
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,13 +1,15 @@
<?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) public function datastore_apc($prefix = null)
{ {
if (!$this->is_installed()) { if (!$this->is_installed()) {
die('Error: APC extension not installed'); die('Error: APC extension not installed');
@ -16,7 +18,7 @@ class datastore_apc extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store($title, $var) public function store($title, $var)
{ {
$this->data[$title] = $var; $this->data[$title] = $var;
@ -29,7 +31,7 @@ class datastore_apc extends datastore_common
return (bool)apc_store($this->prefix . $title, $var); return (bool)apc_store($this->prefix . $title, $var);
} }
function clean() public function clean()
{ {
foreach ($this->known_items as $title => $script_name) { foreach ($this->known_items as $title => $script_name) {
$this->cur_query = "cache->rm('$title')"; $this->cur_query = "cache->rm('$title')";
@ -42,7 +44,7 @@ class datastore_apc extends datastore_common
} }
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) { if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');
@ -60,7 +62,7 @@ class datastore_apc extends datastore_common
} }
} }
function is_installed() 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;

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

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
$ranks = array(); $ranks = array();

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__));
}
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();

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,14 +41,14 @@ 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) {
// игнор уже поставленного в очередь либо уже извлеченного // игнор уже поставленного в очередь либо уже извлеченного
@ -56,7 +58,7 @@ class datastore_common
} }
} }
function &get($title) public function &get($title)
{ {
if (!isset($this->data[$title])) { if (!isset($this->data[$title])) {
$this->enqueue($title); $this->enqueue($title);
@ -65,18 +67,18 @@ class datastore_common
return $this->data[$title]; return $this->data[$title];
} }
function store($item_name, $item_data) public function store($item_name, $item_data)
{ {
} }
function rm($items) public function rm($items)
{ {
foreach ((array)$items as $item) { foreach ((array)$items as $item) {
unset($this->data[$item]); unset($this->data[$item]);
} }
} }
function update($items) public function update($items)
{ {
if ($items == 'all') { if ($items == 'all') {
$items = array_keys(array_unique($this->known_items)); $items = array_keys(array_unique($this->known_items));
@ -86,7 +88,7 @@ class datastore_common
} }
} }
function _fetch() public function _fetch()
{ {
$this->_fetch_from_store(); $this->_fetch_from_store();
@ -99,11 +101,11 @@ class datastore_common
$this->queued_items = array(); $this->queued_items = array();
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
} }
function _build_item($title) public function _build_item($title)
{ {
if (!empty($this->known_items[$title])) { if (!empty($this->known_items[$title])) {
require(INC_DIR . $this->ds_dir . $this->known_items[$title]); require(INC_DIR . $this->ds_dir . $this->known_items[$title]);
@ -112,20 +114,22 @@ class datastore_common
} }
} }
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) 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];
@ -138,7 +142,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'] = '';
} else if ($mode == 'stop') { } elseif ($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;
@ -146,7 +150,7 @@ class datastore_common
} }
} }
function debug_find_source($mode = '') public function debug_find_source($mode = '')
{ {
foreach (debug_backtrace() as $trace) { foreach (debug_backtrace() as $trace) {
if ($trace['file'] !== __FILE__) { if ($trace['file'] !== __FILE__) {

View file

@ -1,21 +1,23 @@
<?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) 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) public function store($title, $var)
{ {
$this->cur_query = "cache->set('$title')"; $this->cur_query = "cache->set('$title')";
$this->debug('start'); $this->debug('start');
@ -36,7 +38,7 @@ 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;
@ -54,7 +56,7 @@ class datastore_file extends datastore_common
} }
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) { if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');

View file

@ -1,16 +1,18 @@
<?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) public function datastore_memcache($cfg, $prefix = null)
{ {
if (!$this->is_installed()) { if (!$this->is_installed()) {
die('Error: Memcached extension not installed'); die('Error: Memcached extension not installed');
@ -22,7 +24,7 @@ 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';
@ -33,7 +35,9 @@ class datastore_memcache extends datastore_common
$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');
@ -43,9 +47,11 @@ class datastore_memcache extends datastore_common
$this->cur_query = null; $this->cur_query = null;
} }
function store($title, $var) public function store($title, $var)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) {
$this->connect();
}
$this->data[$title] = $var; $this->data[$title] = $var;
$this->cur_query = "cache->set('$title')"; $this->cur_query = "cache->set('$title')";
@ -57,9 +63,11 @@ 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() public function clean()
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) {
$this->connect();
}
foreach ($this->known_items as $title => $script_name) { 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');
@ -71,14 +79,16 @@ class datastore_memcache extends datastore_common
} }
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) { 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) {
$this->connect();
}
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');
@ -90,7 +100,7 @@ class datastore_memcache extends datastore_common
} }
} }
function is_installed() public function is_installed()
{ {
return class_exists('Memcache'); return class_exists('Memcache');
} }

View file

@ -1,16 +1,18 @@
<?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) public function datastore_redis($cfg, $prefix = null)
{ {
if (!$this->is_installed()) { if (!$this->is_installed()) {
die('Error: Redis extension not installed'); die('Error: Redis extension not installed');
@ -22,7 +24,7 @@ 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');
@ -39,9 +41,11 @@ class datastore_redis extends datastore_common
$this->cur_query = null; $this->cur_query = null;
} }
function store($title, $var) 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')";
@ -53,9 +57,11 @@ 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() public function clean()
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) {
$this->connect();
}
foreach ($this->known_items as $title => $script_name) { 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');
@ -67,14 +73,16 @@ class datastore_redis extends datastore_common
} }
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) { 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) {
$this->connect();
}
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');
@ -86,7 +94,7 @@ class datastore_redis extends datastore_common
} }
} }
function is_installed() 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,14 @@ class datastore_sqlite extends datastore_common
'log_name' => 'DATASTORE', 'log_name' => 'DATASTORE',
); );
function datastore_sqlite($cfg, $prefix = null) 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) public function store($item_name, $item_data)
{ {
$this->data[$item_name] = $item_data; $this->data[$item_name] = $item_data;
@ -39,14 +41,16 @@ 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);

View file

@ -1,13 +1,15 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
class datastore_xcache extends datastore_common class datastore_xcache extends datastore_common
{ {
var $prefix = null; public $prefix = null;
var $engine = 'XCache'; public $engine = 'XCache';
function datastore_xcache($prefix = null) public function datastore_xcache($prefix = null)
{ {
if (!$this->is_installed()) { if (!$this->is_installed()) {
die('Error: XCache extension not installed'); die('Error: XCache extension not installed');
@ -17,7 +19,7 @@ class datastore_xcache extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store($title, $var) public function store($title, $var)
{ {
$this->data[$title] = $var; $this->data[$title] = $var;
@ -30,7 +32,7 @@ class datastore_xcache extends datastore_common
return (bool)xcache_set($this->prefix . $title, $var); return (bool)xcache_set($this->prefix . $title, $var);
} }
function clean() public function clean()
{ {
foreach ($this->known_items as $title => $script_name) { foreach ($this->known_items as $title => $script_name) {
$this->cur_query = "cache->rm('$title')"; $this->cur_query = "cache->rm('$title')";
@ -43,7 +45,7 @@ class datastore_xcache extends datastore_common
} }
} }
function _fetch_from_store() public function _fetch_from_store()
{ {
if (!$items = $this->queued_items) { if (!$items = $this->queued_items) {
$src = $this->_debug_find_caller('enqueue'); $src = $this->_debug_find_caller('enqueue');
@ -61,7 +63,7 @@ class datastore_xcache extends datastore_common
} }
} }
function is_installed() public function is_installed()
{ {
return function_exists('xcache_get'); return function_exists('xcache_get');
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
function get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div) function get_path_from_id($id, $ext_id, $base_path, $first_div, $sec_div)
{ {
@ -69,7 +71,9 @@ function set_tracks($cookie_name, &$tracking_ary, $tracks = null, $val = TIMENOW
{ {
global $tracking_topics, $tracking_forums, $user; global $tracking_topics, $tracking_forums, $user;
if (IS_GUEST) return; if (IS_GUEST) {
return;
}
$prev_tracking_ary = $tracking_ary; $prev_tracking_ary = $tracking_ary;
@ -261,7 +265,7 @@ function auth($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_
// //
if ($type == AUTH_ALL) { if ($type == AUTH_ALL) {
$auth_fields = array_keys($bf['forum_perm']); $auth_fields = array_keys($bf['forum_perm']);
} else if ($auth_type = array_search($type, $bf['forum_perm'])) { } elseif ($auth_type = array_search($type, $bf['forum_perm'])) {
$auth_fields = array($auth_type); $auth_fields = array($auth_type);
} }
@ -282,10 +286,10 @@ function auth($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_
if ($forum_id == AUTH_LIST_ALL) { if ($forum_id == AUTH_LIST_ALL) {
$f_access = $forums['f']; $f_access = $forums['f'];
} else if (isset($forums['f'][$forum_id])) { } elseif (isset($forums['f'][$forum_id])) {
$f_access[$forum_id] = $forums['f'][$forum_id]; $f_access[$forum_id] = $forums['f'][$forum_id];
} }
} else if (isset($f_access['forum_id'])) { } elseif (isset($f_access['forum_id'])) {
// Change passed $f_access format for later using in foreach() // Change passed $f_access format for later using in foreach()
$f_access = array($f_access['forum_id'] => $f_access); $f_access = array($f_access['forum_id'] => $f_access);
} }
@ -313,7 +317,7 @@ function auth($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_
$u_access[$row['forum_id']] = $row['forum_perm']; $u_access[$row['forum_id']] = $row['forum_perm'];
} }
} // USER mode } // USER mode
else if (!empty($ug_data['user_id'])) { elseif (!empty($ug_data['user_id'])) {
$is_guest = empty($ug_data['session_logged_in']); $is_guest = empty($ug_data['session_logged_in']);
$is_admin = (!$is_guest && $ug_data['user_level'] == ADMIN); $is_admin = (!$is_guest && $ug_data['user_level'] == ADMIN);
@ -406,26 +410,30 @@ function auth($type, $forum_id, $ug_data, $f_access = array(), $group_perm = UG_
function auth_check($bf_ary, $bf_key, $perm_ary, $perm_key, $is_admin = false) function auth_check($bf_ary, $bf_key, $perm_ary, $perm_key, $is_admin = false)
{ {
if ($is_admin) return true; if ($is_admin) {
if (!isset($perm_ary[$perm_key])) return false; return true;
}
if (!isset($perm_ary[$perm_key])) {
return false;
}
return bf($perm_ary[$perm_key], $bf_ary, $bf_key); return bf($perm_ary[$perm_key], $bf_ary, $bf_key);
} }
class Date_Delta class Date_Delta
{ {
var $auto_granularity = array( public $auto_granularity = array(
60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute 60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute
10800 => 'minutes', // 3 hours 10800 => 'minutes', // 3 hours
259200 => 'hours', // 3 days 259200 => 'hours', // 3 days
31363200 => 'mday', // 12 months 31363200 => 'mday', // 12 months
311040000 => 'mon', // 10 years 311040000 => 'mon', // 10 years
); );
var $intervals = array(); public $intervals = array();
var $format = ''; public $format = '';
// Creates new object. // Creates new object.
function Date_Delta() public function Date_Delta()
{ {
global $lang; global $lang;
@ -434,7 +442,7 @@ class Date_Delta
} }
// Makes the spellable phrase. // Makes the spellable phrase.
function spellDelta($first, $last, $from = 'auto') public function spellDelta($first, $last, $from = 'auto')
{ {
if ($last < $first) { if ($last < $first) {
$old_first = $first; $old_first = $first;
@ -455,7 +463,9 @@ class Date_Delta
// Solve data delta. // Solve data delta.
$delta = $this->getDelta($first, $last); $delta = $this->getDelta($first, $last);
if (!$delta) return false; if (!$delta) {
return false;
}
// Make spellable phrase. // Make spellable phrase.
$parts = array(); $parts = array();
@ -472,15 +482,19 @@ class Date_Delta
continue; continue;
} }
$parts[] = declension($n, $this->intervals[$k], $this->format); $parts[] = declension($n, $this->intervals[$k], $this->format);
if ($k == $from) break; if ($k == $from) {
break;
}
} }
return join(' ', $parts); return join(' ', $parts);
} }
// returns the associative array with date deltas. // returns the associative array with date deltas.
function getDelta($first, $last) public function getDelta($first, $last)
{ {
if ($last < $first) return false; if ($last < $first) {
return false;
}
// Solve H:M:S part. // Solve H:M:S part.
$hms = ($last - $first) % (3600 * 24); $hms = ($last - $first) % (3600 * 24);
@ -520,10 +534,12 @@ class Date_Delta
} }
// Returns the length (in days) of the specified month. // Returns the length (in days) of the specified month.
function monthLength($year, $mon) public function monthLength($year, $mon)
{ {
$l = 28; $l = 28;
while (checkdate($mon, $l + 1, $year)) $l++; while (checkdate($mon, $l + 1, $year)) {
$l++;
}
return $l; return $l;
} }
} }
@ -561,15 +577,17 @@ function get_select($select, $selected = null, $return_as = 'html', $first_opt =
class html_common class html_common
{ {
var $options = ''; public $options = '';
var $attr = array(); public $attr = array();
var $cur_attr = null; public $cur_attr = null;
var $max_length = HTML_SELECT_MAX_LENGTH; public $max_length = HTML_SELECT_MAX_LENGTH;
var $selected = array(); public $selected = array();
function build_select($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') public function build_select($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '')
{ {
if (empty($params)) return ''; if (empty($params)) {
return '';
}
$this->options = ''; $this->options = '';
$this->selected = array_flip((array)$selected); $this->selected = array_flip((array)$selected);
@ -593,7 +611,7 @@ class html_common
return "\n<select $select_params>\n" . $this->options . "</select>\n"; return "\n<select $select_params>\n" . $this->options . "</select>\n";
} }
function _build_select_rec($params) public function _build_select_rec($params)
{ {
foreach ($params as $opt_name => $opt_val) { foreach ($params as $opt_name => $opt_val) {
$opt_name = rtrim($opt_name); $opt_name = rtrim($opt_name);
@ -623,14 +641,14 @@ class html_common
} }
} }
function array2html($array, $ul = 'ul', $li = 'li') public function array2html($array, $ul = 'ul', $li = 'li')
{ {
$this->out = ''; $this->out = '';
$this->_array2html_rec($array, $ul, $li); $this->_array2html_rec($array, $ul, $li);
return "<$ul class=\"tree-root\">{$this->out}</$ul>"; return "<$ul class=\"tree-root\">{$this->out}</$ul>";
} }
function _array2html_rec($array, $ul, $li) public function _array2html_rec($array, $ul, $li)
{ {
foreach ($array as $k => $v) { foreach ($array as $k => $v) {
if (is_array($v)) { if (is_array($v)) {
@ -644,7 +662,7 @@ class html_common
} }
// all arguments should be already htmlspecialchar()d (if needed) // all arguments should be already htmlspecialchar()d (if needed)
function build_checkbox($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1) public function build_checkbox($name, $title, $checked = false, $disabled = false, $class = null, $id = null, $value = 1)
{ {
$name = ' name="' . $name . '" '; $name = ' name="' . $name . '" ';
$value = ' value="' . $value . '" '; $value = ' value="' . $value . '" ';
@ -671,8 +689,12 @@ function build_checkbox($name, $title, $checked = false, $disabled = false, $cla
function replace_quote($str, $double = true, $single = true) function replace_quote($str, $double = true, $single = true)
{ {
if ($double) $str = str_replace('"', '&quot;', $str); if ($double) {
if ($single) $str = str_replace("'", '&#039;', $str); $str = str_replace('"', '&quot;', $str);
}
if ($single) {
$str = str_replace("'", '&#039;', $str);
}
return $str; return $str;
} }
@ -754,7 +776,7 @@ function url_arg($url, $arg, $value, $amp = '&amp;')
$new = is_null($value) ? '' : $m[1] . urlencode($value); $new = is_null($value) ? '' : $m[1] . urlencode($value);
$url = str_replace($cur, $new, $url); $url = str_replace($cur, $new, $url);
} // добавляем параметр } // добавляем параметр
else if (!is_null($value)) { elseif (!is_null($value)) {
$div = (strpos($url, '?') !== false) ? $amp : '?'; $div = (strpos($url, '?') !== false) ? $amp : '?';
$url = $url . $div . $arg . '=' . urlencode($value); $url = $url . $div . $arg . '=' . urlencode($value);
} }
@ -848,9 +870,9 @@ function checkbox_get_val(&$key, &$val, $default = 1, $on = 1, $off = 0)
if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) { if (isset($_REQUEST[$key]) && is_string($_REQUEST[$key])) {
$val = (int)$_REQUEST[$key]; $val = (int)$_REQUEST[$key];
} else if (!isset($_REQUEST[$key]) && isset($_REQUEST['prev_' . $key])) { } elseif (!isset($_REQUEST[$key]) && isset($_REQUEST['prev_' . $key])) {
$val = $off; $val = $off;
} else if (isset($previous_settings[$key]) && (!IS_GUEST || !empty($search_id))) { } elseif (isset($previous_settings[$key]) && (!IS_GUEST || !empty($search_id))) {
$val = ($previous_settings[$key]) ? $on : $off; $val = ($previous_settings[$key]) ? $on : $off;
} else { } else {
$val = $default; $val = $default;
@ -865,7 +887,7 @@ function select_get_val($key, &$val, $options_ary, $default, $num = true)
if (isset($options_ary[$_REQUEST[$key]])) { if (isset($options_ary[$_REQUEST[$key]])) {
$val = ($num) ? intval($_REQUEST[$key]) : $_REQUEST[$key]; $val = ($num) ? intval($_REQUEST[$key]) : $_REQUEST[$key];
} }
} else if (isset($previous_settings[$key])) { } elseif (isset($previous_settings[$key])) {
$val = $previous_settings[$key]; $val = $previous_settings[$key];
} else { } else {
$val = $default; $val = $default;
@ -995,7 +1017,9 @@ function get_username($user_id)
function get_user_id($username) function get_user_id($username)
{ {
if (empty($username)) return false; if (empty($username)) {
return false;
}
$row = DB()->fetch_row("SELECT user_id FROM " . BB_USERS . " WHERE username = '" . DB()->escape($username) . "' LIMIT 1"); $row = DB()->fetch_row("SELECT user_id FROM " . BB_USERS . " WHERE username = '" . DB()->escape($username) . "' LIMIT 1");
return $row['user_id']; return $row['user_id'];
} }
@ -1214,7 +1238,9 @@ function get_userdata($u, $force_name = false, $allow_guest = false)
/** @var \TorrentPier\Cache\Adapter $cache */ /** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache; $cache = $di->cache;
if (!$u) return false; if (!$u) {
return false;
}
if (intval($u) == GUEST_UID && $allow_guest) { if (intval($u) == GUEST_UID && $allow_guest) {
if ($u_data = $cache->get('guest_userdata')) { if ($u_data = $cache->get('guest_userdata')) {
@ -1285,15 +1311,21 @@ function get_forum_select($mode = 'guest', $name = POST_FORUM_URL, $selected = n
foreach ($forums['f'] as $fid => $f) { foreach ($forums['f'] as $fid => $f) {
switch ($mode) { switch ($mode) {
case 'guest': case 'guest':
if ($f['auth_view'] != AUTH_ALL) continue 2; if ($f['auth_view'] != AUTH_ALL) {
continue 2;
}
break; break;
case 'user': case 'user':
if ($f['auth_view'] != AUTH_ALL && $f['auth_view'] != AUTH_REG) continue 2; if ($f['auth_view'] != AUTH_ALL && $f['auth_view'] != AUTH_REG) {
continue 2;
}
break; break;
case 'not_auth_forums': case 'not_auth_forums':
if (isset($not_auth_forums_fary[$f['forum_id']])) continue 2; if (isset($not_auth_forums_fary[$f['forum_id']])) {
continue 2;
}
break; break;
case 'admin': case 'admin':
@ -1335,7 +1367,9 @@ function setup_style()
if (!IS_GUEST && !empty($userdata['tpl_name'])) { if (!IS_GUEST && !empty($userdata['tpl_name'])) {
foreach ($di->config->get('templates') as $folder => $name) { foreach ($di->config->get('templates') as $folder => $name) {
if ($userdata['tpl_name'] == $folder) $tpl_dir_name = basename($userdata['tpl_name']); if ($userdata['tpl_name'] == $folder) {
$tpl_dir_name = basename($userdata['tpl_name']);
}
} }
} }
@ -1366,8 +1400,12 @@ function bb_date($gmepoch, $format = false, $friendly_date = true)
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!$format) $format = $di->config->get('default_dateformat'); if (!$format) {
if (empty($lang)) require_once($di->config->get('default_lang_dir') . 'main.php'); $format = $di->config->get('default_dateformat');
}
if (empty($lang)) {
require_once($di->config->get('default_lang_dir') . 'main.php');
}
if (empty($userdata['session_logged_in'])) { if (empty($userdata['session_logged_in'])) {
$tz = $di->config->get('board_timezone'); $tz = $di->config->get('board_timezone');
@ -1394,14 +1432,16 @@ function bb_date($gmepoch, $format = false, $friendly_date = true)
$date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz));
} elseif ($today == 1 && $month != 1) { } elseif ($today == 1 && $month != 1) {
$yesterday = date('t', mktime(0, 0, 0, ($month - 1), 1, $year)); $yesterday = date('t', mktime(0, 0, 0, ($month - 1), 1, $year));
if ($date_today == $yesterday && $date_month == ($month - 1) && $date_year == $year) if ($date_today == $yesterday && $date_month == ($month - 1) && $date_year == $year) {
$date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz));
}
} elseif ($today == 1 && $month == 1) { } elseif ($today == 1 && $month == 1) {
$yesterday = date('t', mktime(0, 0, 0, 12, 1, ($year - 1))); $yesterday = date('t', mktime(0, 0, 0, 12, 1, ($year - 1)));
if ($date_today == $yesterday && $date_month == 12 && $date_year == ($year - 1)) if ($date_today == $yesterday && $date_month == 12 && $date_year == ($year - 1)) {
$date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz)); $date = 'yesterday' . gmdate($time_format, $gmepoch + (3600 * $tz));
} }
} }
}
return ($di->config->get('translate_dates')) ? strtr(strtoupper($date), $lang['DATETIME']) : $date; return ($di->config->get('translate_dates')) ? strtr(strtoupper($date), $lang['DATETIME']) : $date;
} }
@ -1411,7 +1451,9 @@ function birthday_age($date)
/** @var \TorrentPier\Di $di */ /** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance(); $di = \TorrentPier\Di::getInstance();
if (!$date) return false; if (!$date) {
return false;
}
$tz = TIMENOW + (3600 * $di->config->get('board_timezone')); $tz = TIMENOW + (3600 * $di->config->get('board_timezone'));
@ -1422,7 +1464,7 @@ function birthday_age($date)
// Pagination routine, generates // Pagination routine, generates
// page number sequence // page number sequence
// //
function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE) function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = true)
{ {
global $lang, $template; global $lang, $template;
@ -1504,7 +1546,6 @@ function generate_pagination($base_url, $num_items, $per_page, $start_item, $add
if ($on_page < $total_pages) { if ($on_page < $total_pages) {
$page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "&amp;start=" . ($on_page * $per_page) . '">' . $lang['NEXT_PAGE'] . '</a>'; $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "&amp;start=" . ($on_page * $per_page) . '">' . $lang['NEXT_PAGE'] . '</a>';
} }
} }
$pagination = ($page_string) ? '<a class="menu-root" href="#pg-jump">' . $lang['GOTO_PAGE'] . '</a> :&nbsp;&nbsp;' . $page_string : ''; $pagination = ($page_string) ? '<a class="menu-root" href="#pg-jump">' . $lang['GOTO_PAGE'] . '</a> :&nbsp;&nbsp;' . $page_string : '';
@ -1533,11 +1574,15 @@ function obtain_word_list(&$orig_word, &$replacement_word)
/** @var \TorrentPier\Cache\Adapter $cache */ /** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache; $cache = $di->cache;
if (!$di->config->get('use_word_censor')) return false; if (!$di->config->get('use_word_censor')) {
return false;
}
if (!$cache->has('censored')) { if (!$cache->has('censored')) {
$sql = DB()->fetch_rowset("SELECT word, replacement FROM " . BB_WORDS); $sql = DB()->fetch_rowset("SELECT word, replacement FROM " . BB_WORDS);
if (!$sql) $sql = [['word' => 1, 'replacement' => 1]]; if (!$sql) {
$sql = [['word' => 1, 'replacement' => 1]];
}
$cache->set('censored', $sql, 7200); $cache->set('censored', $sql, 7200);
} }
@ -1753,7 +1798,7 @@ function cat_exists($cat_id)
// //
class log_action class log_action
{ {
var $log_type = [ public $log_type = [
# LOG_TYPE_NAME LOG_TYPE_ID # LOG_TYPE_NAME LOG_TYPE_ID
'mod_topic_delete' => 1, 'mod_topic_delete' => 1,
'mod_topic_move' => 2, 'mod_topic_move' => 2,
@ -1772,10 +1817,10 @@ class log_action
'adm_ban_email' => 15, 'adm_ban_email' => 15,
'adm_ban_name' => 16, 'adm_ban_name' => 16,
]; ];
var $log_type_select = []; public $log_type_select = [];
var $log_disabled = false; public $log_disabled = false;
function init() public function init()
{ {
global $lang; global $lang;
@ -1784,12 +1829,16 @@ class log_action
} }
} }
function mod($type_name, $args = array()) public function mod($type_name, $args = array())
{ {
global $userdata; global $userdata;
if (empty($this->log_type)) $this->init(); if (empty($this->log_type)) {
if ($this->log_disabled) return; $this->init();
}
if ($this->log_disabled) {
return;
}
$forum_id =& $args['forum_id']; $forum_id =& $args['forum_id'];
$forum_id_new =& $args['forum_id_new']; $forum_id_new =& $args['forum_id_new'];
@ -1825,7 +1874,7 @@ class log_action
DB()->query("INSERT INTO " . BB_LOG . " $sql_args"); DB()->query("INSERT INTO " . BB_LOG . " $sql_args");
} }
function admin($type_name, $args = array()) public function admin($type_name, $args = array())
{ {
$this->mod($type_name, $args); $this->mod($type_name, $args);
} }
@ -1850,13 +1899,13 @@ function get_topic_icon($topic, $is_unread = null)
if ($topic['topic_type'] == POST_ANNOUNCE) { if ($topic['topic_type'] == POST_ANNOUNCE) {
$folder = $images['folder_announce']; $folder = $images['folder_announce'];
$folder_new = $images['folder_announce_new']; $folder_new = $images['folder_announce_new'];
} else if ($topic['topic_type'] == POST_STICKY) { } elseif ($topic['topic_type'] == POST_STICKY) {
$folder = $images['folder_sticky']; $folder = $images['folder_sticky'];
$folder_new = $images['folder_sticky_new']; $folder_new = $images['folder_sticky_new'];
} else if ($topic['topic_status'] == TOPIC_LOCKED) { } elseif ($topic['topic_status'] == TOPIC_LOCKED) {
$folder = $images['folder_locked']; $folder = $images['folder_locked'];
$folder_new = $images['folder_locked_new']; $folder_new = $images['folder_locked_new'];
} else if (isset($topic['tracker_status'])) { } elseif (isset($topic['tracker_status'])) {
$folder = ($t_hot) ? $images['folder_dl_hot'] : $images['folder_dl']; $folder = ($t_hot) ? $images['folder_dl_hot'] : $images['folder_dl'];
$folder_new = ($t_hot) ? $images['folder_dl_hot_new'] : $images['folder_dl_new']; $folder_new = ($t_hot) ? $images['folder_dl_hot_new'] : $images['folder_dl_new'];
} }
@ -1882,7 +1931,7 @@ function build_topic_pagination($url, $replies, $per_page)
$pg .= ' .. '; $pg .= ' .. ';
$page = $total_pages - 2; $page = $total_pages - 2;
$j += ($total_pages - 3) * $per_page; $j += ($total_pages - 3) * $per_page;
} else if ($page < $total_pages) { } elseif ($page < $total_pages) {
$pg .= ', '; $pg .= ', ';
} }
} }
@ -1979,7 +2028,7 @@ function print_page($args, $type = '', $mode = '')
$tpl = (is_array($args) && !empty($args['tpl'])) ? $args['tpl'] : $args; $tpl = (is_array($args) && !empty($args['tpl'])) ? $args['tpl'] : $args;
$tpl = ($type === 'admin') ? ADMIN_TPL_DIR . $tpl : $tpl; $tpl = ($type === 'admin') ? ADMIN_TPL_DIR . $tpl : $tpl;
$gen_simple_header = (is_array($args) && !empty($args['simple']) OR $type === 'simple') ? true : $gen_simple_header; $gen_simple_header = (is_array($args) && !empty($args['simple']) or $type === 'simple') ? true : $gen_simple_header;
if ($mode !== 'no_header') { if ($mode !== 'no_header') {
require(PAGE_HEADER); require(PAGE_HEADER);
@ -2044,7 +2093,9 @@ function init_sphinx()
global $sphinx; global $sphinx;
if (!isset($sphinx)) { if (!isset($sphinx)) {
if (!class_exists('SphinxClient')) require(INC_DIR . 'api/sphinx.php'); if (!class_exists('SphinxClient')) {
require(INC_DIR . 'api/sphinx.php');
}
$sphinx = new SphinxClient(); $sphinx = new SphinxClient();
$sphinx->SetConnectTimeout(5); $sphinx->SetConnectTimeout(5);
@ -2092,7 +2143,7 @@ function get_title_match_topics($search)
if (!empty($result['matches'])) { if (!empty($result['matches'])) {
$where_ids = array_keys($result['matches']); $where_ids = array_keys($result['matches']);
} }
} else if ($error = $sphinx->GetLastError()) { } elseif ($error = $sphinx->GetLastError()) {
if (strpos($error, 'errno=110')) { if (strpos($error, 'errno=110')) {
bb_die($lang['SEARCH_ERROR']); bb_die($lang['SEARCH_ERROR']);
} }
@ -2236,10 +2287,16 @@ function profile_url($data)
$title = $ranks[$user_rank]['rank_title']; $title = $ranks[$user_rank]['rank_title'];
$style = $ranks[$user_rank]['rank_style']; $style = $ranks[$user_rank]['rank_style'];
} }
if (empty($title)) $title = $lang['USER']; if (empty($title)) {
if (empty($style)) $style = 'colorUser'; $title = $lang['USER'];
}
if (empty($style)) {
$style = 'colorUser';
}
if (!$di->config->get('color_nick')) $style = ''; if (!$di->config->get('color_nick')) {
$style = '';
}
$username = !empty($data['username']) ? $data['username'] : $lang['GUEST']; $username = !empty($data['username']) ? $data['username'] : $lang['GUEST'];
$user_id = (!empty($data['user_id']) && $username != $lang['GUEST']) ? $data['user_id'] : GUEST_UID; $user_id = (!empty($data['user_id']) && $username != $lang['GUEST']) ? $data['user_id'] : GUEST_UID;
@ -2269,7 +2326,7 @@ function get_avatar($user_id, $ext_id, $allow_avatar = true, $size = true, $heig
if ($user_id == BOT_UID && $di->config->get('avatars.bot_avatar')) { if ($user_id == BOT_UID && $di->config->get('avatars.bot_avatar')) {
$user_avatar = '<img src="' . make_url($di->config->get('avatars.upload_path') . $di->config->get('avatars.bot_avatar')) . '" alt="' . $user_id . '" ' . $height . ' ' . $width . ' />'; $user_avatar = '<img src="' . make_url($di->config->get('avatars.upload_path') . $di->config->get('avatars.bot_avatar')) . '" alt="' . $user_id . '" ' . $height . ' ' . $width . ' />';
} else if ($allow_avatar && $ext_id) { } elseif ($allow_avatar && $ext_id) {
if (file_exists(get_avatar_path($user_id, $ext_id))) { if (file_exists(get_avatar_path($user_id, $ext_id))) {
$user_avatar = '<img src="' . make_url(get_avatar_path($user_id, $ext_id)) . '" alt="' . $user_id . '" ' . $height . ' ' . $width . ' />'; $user_avatar = '<img src="' . make_url(get_avatar_path($user_id, $ext_id)) . '" alt="' . $user_id . '" ' . $height . ' ' . $width . ' />';
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
function sync_all_forums() function sync_all_forums()
{ {
@ -524,9 +526,13 @@ function post_delete($mode_or_post_id, $user_id = null, $exclude_first = true)
// Get required params // Get required params
if ($del_user_posts) { if ($del_user_posts) {
if (!$user_csv = get_id_csv($user_id)) return false; if (!$user_csv = get_id_csv($user_id)) {
return false;
}
} else { } else {
if (!$post_csv = get_id_csv($mode_or_post_id)) return false; if (!$post_csv = get_id_csv($mode_or_post_id)) {
return false;
}
// фильтр заглавных сообщений в теме // фильтр заглавных сообщений в теме
if ($exclude_first) { if ($exclude_first) {
@ -622,7 +628,7 @@ function post_delete($mode_or_post_id, $user_id = null, $exclude_first = true)
$log_action->admin('mod_post_delete', array( $log_action->admin('mod_post_delete', array(
'log_msg' => 'user: ' . get_usernames_for_log($user_id) . "<br />posts: $deleted_posts_count", 'log_msg' => 'user: ' . get_usernames_for_log($user_id) . "<br />posts: $deleted_posts_count",
)); ));
} else if (!defined('IN_CRON')) { } elseif (!defined('IN_CRON')) {
foreach ($log_topics as $row) { foreach ($log_topics as $row) {
$log_action->mod('mod_post_delete', array( $log_action->mod('mod_post_delete', array(
'forum_id' => $row['forum_id'], 'forum_id' => $row['forum_id'],

View file

@ -88,7 +88,9 @@ function insert_cron_job($cron_arr)
if ($_POST['cron_script'] == $row['cron_script']) { if ($_POST['cron_script'] == $row['cron_script']) {
$langmode = $lang['SCRIPT_DUPLICATE']; $langmode = $lang['SCRIPT_DUPLICATE'];
} else $langmode = $lang['TITLE_DUPLICATE']; } else {
$langmode = $lang['TITLE_DUPLICATE'];
}
$message = $langmode . "<br /><br />" . sprintf($lang['CLICK_RETURN_JOBS_ADDED'], "<a href=\"javascript:history.back(-1)\">", "</a>") . "<br /><br />" . sprintf($lang['CLICK_RETURN_JOBS'], "<a href=\"admin_cron.php?mode=list\">", "</a>") . "<br /><br />" . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], "<a href=\"index.php?pane=right\">", "</a>"); $message = $langmode . "<br /><br />" . sprintf($lang['CLICK_RETURN_JOBS_ADDED'], "<a href=\"javascript:history.back(-1)\">", "</a>") . "<br /><br />" . sprintf($lang['CLICK_RETURN_JOBS'], "<a href=\"admin_cron.php?mode=list\">", "</a>") . "<br /><br />" . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], "<a href=\"index.php?pane=right\">", "</a>");

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
function update_table_bool($table_name, $key, $field_name, $field_def_val) function update_table_bool($table_name, $key, $field_name, $field_def_val)
{ {
@ -72,7 +74,6 @@ function set_tpl_vars_lang($default_cfg)
'L_' . strtoupper($config_name) . '_EXPL' => isset($lang[$config_name . '_expl']) ? $lang[$config_name . '_expl'] : '', 'L_' . strtoupper($config_name) . '_EXPL' => isset($lang[$config_name . '_expl']) ? $lang[$config_name . '_expl'] : '',
'L_' . strtoupper($config_name) . '_HEAD' => isset($lang[$config_name . '_head']) ? $lang[$config_name . '_head'] : '', 'L_' . strtoupper($config_name) . '_HEAD' => isset($lang[$config_name . '_head']) ? $lang[$config_name . '_head'] : '',
)); ));
} }
} }
@ -82,9 +83,9 @@ function update_config_table($table_name, $default_cfg, $cfg, $type)
if (isset($_POST[$config_name]) && $_POST[$config_name] != $cfg[$config_name]) { if (isset($_POST[$config_name]) && $_POST[$config_name] != $cfg[$config_name]) {
if ($type == 'str') { if ($type == 'str') {
$config_value = $_POST[$config_name]; $config_value = $_POST[$config_name];
} else if ($type == 'bool') { } elseif ($type == 'bool') {
$config_value = ($_POST[$config_name]) ? 1 : 0; $config_value = ($_POST[$config_name]) ? 1 : 0;
} else if ($type == 'num') { } elseif ($type == 'num') {
$config_value = abs(intval($_POST[$config_name])); $config_value = abs(intval($_POST[$config_name]));
} else { } else {
return; return;

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// Максимум записей = 50 // Максимум записей = 50
// [Обновлено] - если дата изменения первого поста топика не старее недели (?) или в топике новые сообщения не старее недели (?) // [Обновлено] - если дата изменения первого поста топика не старее недели (?) или в топике новые сообщения не старее недели (?)
@ -12,7 +14,9 @@ function update_forum_feed($forum_id, $forum_data)
$file_path = $di->config->get('atom.path') . '/f/' . $forum_id . '.atom'; $file_path = $di->config->get('atom.path') . '/f/' . $forum_id . '.atom';
$select_tor_sql = $join_tor_sql = ''; $select_tor_sql = $join_tor_sql = '';
if ($forum_id == 0) $forum_data['atom_forum_name'] = 'Общая по всем разделам'; if ($forum_id == 0) {
$forum_data['atom_forum_name'] = 'Общая по всем разделам';
}
if ($forum_id > 0 && $forum_data['atom_tr_allowed']) { if ($forum_id > 0 && $forum_data['atom_tr_allowed']) {
$select_tor_sql = ', tor.size AS tor_size, tor.tor_status'; $select_tor_sql = ', tor.size AS tor_size, tor.tor_status';
$join_tor_sql = "LEFT JOIN " . BB_BT_TORRENTS . " tor ON(t.topic_id = tor.topic_id)"; $join_tor_sql = "LEFT JOIN " . BB_BT_TORRENTS . " tor ON(t.topic_id = tor.topic_id)";
@ -33,7 +37,7 @@ function update_forum_feed($forum_id, $forum_data)
ORDER BY t.topic_last_post_time DESC ORDER BY t.topic_last_post_time DESC
LIMIT 100 LIMIT 100
"; ";
} else if ($forum_id > 0) { } elseif ($forum_id > 0) {
$sql = " $sql = "
SELECT SELECT
t.topic_id, t.topic_title, t.topic_status, t.topic_id, t.topic_title, t.topic_status,
@ -55,10 +59,14 @@ function update_forum_feed($forum_id, $forum_data)
$topics = array(); $topics = array();
foreach ($topics_tmp as $topic) { foreach ($topics_tmp as $topic) {
if (isset($topic['topic_status'])) { if (isset($topic['topic_status'])) {
if ($topic['topic_status'] == TOPIC_MOVED) continue; if ($topic['topic_status'] == TOPIC_MOVED) {
continue;
}
} }
if (isset($topic['tor_status'])) { if (isset($topic['tor_status'])) {
if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; if ($di->config->get('tor_frozen.' . $topic['tor_status'])) {
continue;
}
} }
$topics[] = $topic; $topics[] = $topic;
} }
@ -66,8 +74,11 @@ function update_forum_feed($forum_id, $forum_data)
unlink($file_path); unlink($file_path);
return false; return false;
} }
if (create_atom($file_path, 'f', $forum_id, htmlCHR($forum_data['atom_forum_name']), $topics)) return true; if (create_atom($file_path, 'f', $forum_id, htmlCHR($forum_data['atom_forum_name']), $topics)) {
else return false; return true;
} else {
return false;
}
} }
function update_user_feed($user_id, $username) function update_user_feed($user_id, $username)
@ -96,10 +107,14 @@ function update_user_feed($user_id, $username)
$topics = array(); $topics = array();
foreach ($topics_tmp as $topic) { foreach ($topics_tmp as $topic) {
if (isset($topic['topic_status'])) { if (isset($topic['topic_status'])) {
if ($topic['topic_status'] == TOPIC_MOVED) continue; if ($topic['topic_status'] == TOPIC_MOVED) {
continue;
}
} }
if (isset($topic['tor_status'])) { if (isset($topic['tor_status'])) {
if ($di->config->get('tor_frozen.' . $topic['tor_status'])) continue; if ($di->config->get('tor_frozen.' . $topic['tor_status'])) {
continue;
}
} }
$topics[] = $topic; $topics[] = $topic;
} }
@ -107,8 +122,11 @@ function update_user_feed($user_id, $username)
unlink($file_path); unlink($file_path);
return false; return false;
} }
if (create_atom($file_path, 'u', $user_id, wbr($username), $topics)) return true; if (create_atom($file_path, 'u', $user_id, wbr($username), $topics)) {
else return false; return true;
} else {
return false;
}
} }
function create_atom($file_path, $mode, $id, $title, $topics) function create_atom($file_path, $mode, $id, $title, $topics)
@ -118,11 +136,15 @@ function create_atom($file_path, $mode, $id, $title, $topics)
$dir = dirname($file_path); $dir = dirname($file_path);
if (!file_exists($dir)) { if (!file_exists($dir)) {
if (!bb_mkdir($dir)) return false; if (!bb_mkdir($dir)) {
return false;
}
} }
foreach ($topics as $topic) { foreach ($topics as $topic) {
$last_time = $topic['topic_last_post_time']; $last_time = $topic['topic_last_post_time'];
if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; if ($topic['topic_last_post_edit_time']) {
$last_time = $topic['topic_last_post_edit_time'];
}
$date = bb_date($last_time, 'Y-m-d', 0); $date = bb_date($last_time, 'Y-m-d', 0);
$time = bb_date($last_time, 'H:i:s', 0); $time = bb_date($last_time, 'H:i:s', 0);
break; break;
@ -150,12 +172,16 @@ function create_atom($file_path, $mode, $id, $title, $topics)
$topic_title = wbr($topic_title); $topic_title = wbr($topic_title);
$author_name = ($topic['first_username']) ? wbr($topic['first_username']) : 'Гость'; $author_name = ($topic['first_username']) ? wbr($topic['first_username']) : 'Гость';
$last_time = $topic['topic_last_post_time']; $last_time = $topic['topic_last_post_time'];
if ($topic['topic_last_post_edit_time']) $last_time = $topic['topic_last_post_edit_time']; if ($topic['topic_last_post_edit_time']) {
$last_time = $topic['topic_last_post_edit_time'];
}
$date = bb_date($last_time, 'Y-m-d', 0); $date = bb_date($last_time, 'Y-m-d', 0);
$time = bb_date($last_time, 'H:i:s', 0); $time = bb_date($last_time, 'H:i:s', 0);
$updated = ''; $updated = '';
$checktime = TIMENOW - 604800; // неделя (week) $checktime = TIMENOW - 604800; // неделя (week)
if ($topic['topic_first_post_edit_time'] && $topic['topic_first_post_edit_time'] > $checktime) $updated = '[Обновлено] '; if ($topic['topic_first_post_edit_time'] && $topic['topic_first_post_edit_time'] > $checktime) {
$updated = '[Обновлено] ';
}
$atom .= "<entry>\n"; $atom .= "<entry>\n";
$atom .= " <title type=\"html\"><![CDATA[$updated$topic_title$tor_size]]></title>\n"; $atom .= " <title type=\"html\"><![CDATA[$updated$topic_title$tor_size]]></title>\n";
$atom .= " <author>\n"; $atom .= " <author>\n";

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
function get_sql_log() function get_sql_log()
{ {
@ -16,7 +18,7 @@ function get_sql_log()
if (!empty($datastore->db->dbg)) { if (!empty($datastore->db->dbg)) {
$log .= get_sql_log_html($datastore->db, 'cache: datastore [' . $datastore->engine . ']'); $log .= get_sql_log_html($datastore->db, 'cache: datastore [' . $datastore->engine . ']');
} else if (!empty($datastore->dbg)) { } elseif (!empty($datastore->dbg)) {
$log .= get_sql_log_html($datastore, 'cache: datastore [' . $datastore->engine . ']'); $log .= get_sql_log_html($datastore, 'cache: datastore [' . $datastore->engine . ']');
} }

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
function update_user_level($user_id) function update_user_level($user_id)
{ {
@ -157,7 +159,9 @@ function delete_permissions($group_id = null, $user_id = null, $cat_id = null)
function store_permissions($group_id, $auth_ary) function store_permissions($group_id, $auth_ary)
{ {
if (empty($auth_ary) || !is_array($auth_ary)) return; if (empty($auth_ary) || !is_array($auth_ary)) {
return;
}
$values = array(); $values = array();

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// //
// Prepare a message for posting // Prepare a message for posting
@ -30,14 +32,13 @@ function prepare_post(&$mode, &$post_data, &$error_msg, &$username, &$subject, &
// Check subject // Check subject
if (!empty($subject)) { if (!empty($subject)) {
$subject = str_replace('&amp;', '&', $subject); $subject = str_replace('&amp;', '&', $subject);
} else if ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) { } elseif ($mode == 'newtopic' || ($mode == 'editpost' && $post_data['first_post'])) {
$error_msg .= (!empty($error_msg)) ? '<br />' . $lang['EMPTY_SUBJECT'] : $lang['EMPTY_SUBJECT']; $error_msg .= (!empty($error_msg)) ? '<br />' . $lang['EMPTY_SUBJECT'] : $lang['EMPTY_SUBJECT'];
} }
// Check message // Check message
if (!empty($message)) { if (!empty($message)) {
} elseif ($mode != 'delete') {
} else if ($mode != 'delete') {
$error_msg .= (!empty($error_msg)) ? '<br />' . $lang['EMPTY_MESSAGE'] : $lang['EMPTY_MESSAGE']; $error_msg .= (!empty($error_msg)) ? '<br />' . $lang['EMPTY_MESSAGE'] : $lang['EMPTY_MESSAGE'];
} }
@ -232,7 +233,7 @@ function update_post_stats($mode, $post_data, $forum_id, $topic_id, $post_id, $u
$forum_update_sql .= ($row['last_post_id']) ? ', forum_last_post_id = ' . $row['last_post_id'] : ', forum_last_post_id = 0'; $forum_update_sql .= ($row['last_post_id']) ? ', forum_last_post_id = ' . $row['last_post_id'] : ', forum_last_post_id = 0';
} }
} }
} else if ($post_data['first_post']) { } elseif ($post_data['first_post']) {
$sql = "SELECT MIN(post_id) AS first_post_id FROM " . BB_POSTS . " WHERE topic_id = $topic_id"; $sql = "SELECT MIN(post_id) AS first_post_id FROM " . BB_POSTS . " WHERE topic_id = $topic_id";
if (!($result = DB()->sql_query($sql))) { if (!($result = DB()->sql_query($sql))) {
bb_die('Error in deleting post #3'); bb_die('Error in deleting post #3');
@ -363,7 +364,7 @@ function user_notification($mode, &$post_data, &$topic_title, &$forum_id, &$topi
if (!$notify_user && !empty($topic_watch)) { if (!$notify_user && !empty($topic_watch)) {
DB()->query("DELETE FROM " . BB_TOPICS_WATCH . " WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}"); DB()->query("DELETE FROM " . BB_TOPICS_WATCH . " WHERE topic_id = $topic_id AND user_id = {$userdata['user_id']}");
} else if ($notify_user && empty($topic_watch)) { } elseif ($notify_user && empty($topic_watch)) {
DB()->query(" DB()->query("
INSERT INTO " . BB_TOPICS_WATCH . " (user_id, topic_id, notify_status) INSERT INTO " . BB_TOPICS_WATCH . " (user_id, topic_id, notify_status)
VALUES (" . $userdata['user_id'] . ", $topic_id, " . TOPIC_WATCH_NOTIFIED . ") VALUES (" . $userdata['user_id'] . ", $topic_id, " . TOPIC_WATCH_NOTIFIED . ")
@ -376,14 +377,18 @@ function insert_post($mode, $topic_id, $forum_id = '', $old_forum_id = '', $new_
{ {
global $userdata, $lang; global $userdata, $lang;
if (!$topic_id) return; if (!$topic_id) {
return;
}
$post_username = $post_subject = $post_text = $poster_ip = ''; $post_username = $post_subject = $post_text = $poster_ip = '';
$post_time = $current_time = TIMENOW; $post_time = $current_time = TIMENOW;
if ($mode == 'after_move') { if ($mode == 'after_move') {
if (!$forum_id || !$old_forum_id) return; if (!$forum_id || !$old_forum_id) {
return;
}
$sql = "SELECT forum_id, forum_name $sql = "SELECT forum_id, forum_name
FROM " . BB_FORUMS . " FROM " . BB_FORUMS . "
@ -393,18 +398,20 @@ function insert_post($mode, $topic_id, $forum_id = '', $old_forum_id = '', $new_
foreach (DB()->fetch_rowset($sql) as $row) { foreach (DB()->fetch_rowset($sql) as $row) {
$forum_names[$row['forum_id']] = htmlCHR($row['forum_name']); $forum_names[$row['forum_id']] = htmlCHR($row['forum_name']);
} }
if (!$forum_names) return; if (!$forum_names) {
return;
}
$post_text = sprintf($lang['BOT_TOPIC_MOVED_FROM_TO'], '[url=' . make_url(FORUM_URL . $old_forum_id) . ']' . $forum_names[$old_forum_id] . '[/url]', '[url=' . make_url(FORUM_URL . $forum_id) . ']' . $forum_names[$forum_id] . '[/url]', profile_url($userdata)); $post_text = sprintf($lang['BOT_TOPIC_MOVED_FROM_TO'], '[url=' . make_url(FORUM_URL . $old_forum_id) . ']' . $forum_names[$old_forum_id] . '[/url]', '[url=' . make_url(FORUM_URL . $forum_id) . ']' . $forum_names[$forum_id] . '[/url]', profile_url($userdata));
$poster_id = BOT_UID; $poster_id = BOT_UID;
$poster_ip = '7f000001'; $poster_ip = '7f000001';
} else if ($mode == 'after_split_to_old') { } elseif ($mode == 'after_split_to_old') {
$post_text = sprintf($lang['BOT_MESS_SPLITS'], '[url=' . make_url(TOPIC_URL . $new_topic_id) . ']' . htmlCHR($new_topic_title) . '[/url]', profile_url($userdata)); $post_text = sprintf($lang['BOT_MESS_SPLITS'], '[url=' . make_url(TOPIC_URL . $new_topic_id) . ']' . htmlCHR($new_topic_title) . '[/url]', profile_url($userdata));
$poster_id = BOT_UID; $poster_id = BOT_UID;
$poster_ip = '7f000001'; $poster_ip = '7f000001';
} else if ($mode == 'after_split_to_new') { } elseif ($mode == 'after_split_to_new') {
$sql = "SELECT t.topic_title, p.post_time $sql = "SELECT t.topic_title, p.post_time
FROM " . BB_TOPICS . " t, " . BB_POSTS . " p FROM " . BB_TOPICS . " t, " . BB_POSTS . " p
WHERE t.topic_id = $old_topic_id WHERE t.topic_id = $old_topic_id

View file

@ -1,6 +1,8 @@
<?php <?php
if (!defined('BB_ROOT')) die(basename(__FILE__)); if (!defined('BB_ROOT')) {
die(basename(__FILE__));
}
// Languages // Languages
function language_select($default_lang, $select_name = 'language') function language_select($default_lang, $select_name = 'language')
@ -12,7 +14,9 @@ function language_select($default_lang, $select_name = 'language')
$x = 0; $x = 0;
foreach ($di->config->get('lang') as $key => $data) { foreach ($di->config->get('lang') as $key => $data) {
$selected = ''; $selected = '';
if ($key == $default_lang) $selected = ' selected="selected"'; if ($key == $default_lang) {
$selected = ' selected="selected"';
}
$lang_select .= '<option value="' . $key . '"' . $selected . '>' . $data['name'] . '</option>'; $lang_select .= '<option value="' . $key . '"' . $selected . '>' . $data['name'] . '</option>';
$x++; $x++;
} }
@ -49,7 +53,9 @@ function templates_select($default_style, $select_name = 'tpl_name')
$x = 0; $x = 0;
foreach ($di->config->get('templates') as $folder => $name) { foreach ($di->config->get('templates') as $folder => $name) {
$selected = ''; $selected = '';
if ($folder == $default_style) $selected = ' selected="selected"'; if ($folder == $default_style) {
$selected = ' selected="selected"';
}
$templates_select .= '<option value="' . $folder . '"' . $selected . '>' . $name . '</option>'; $templates_select .= '<option value="' . $folder . '"' . $selected . '>' . $name . '</option>';
$x++; $x++;
} }

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