Migration to the new cache subsystem

This commit is contained in:
Yuriy Pikhtarev 2016-05-11 14:32:47 +03:00
commit 69a569eec1
No known key found for this signature in database
GPG key ID: 3A9B5A757B48ECC6
30 changed files with 302 additions and 1219 deletions

View file

@ -9,6 +9,12 @@ require('./pagestart.php');
require(INC_DIR .'functions_group.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
array_deep($_POST, 'trim');
$s = '';
@ -229,7 +235,8 @@ if ($mode)
renumber_order('forum', $cat_id);
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
bb_die($lang['FORUMS_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.php?c='. $cat_id .'">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
@ -325,7 +332,8 @@ if ($mode)
$cat_forums = get_cat_forums();
$fix = fix_orphan_sf();
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
$message = $lang['FORUMS_UPDATED'] . '<br /><br />';
$message .= ($fix) ? "$fix<br /><br />" : '';
@ -355,7 +363,8 @@ if ($mode)
DB()->query("INSERT INTO ". BB_CATEGORIES . $args);
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
bb_die($lang['FORUMS_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
@ -411,7 +420,8 @@ if ($mode)
}
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
bb_die($lang['FORUMS_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
@ -503,7 +513,8 @@ if ($mode)
fix_orphan_sf();
update_user_level('all');
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
bb_die($lang['FORUMS_UPDATED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_FORUMADMIN'], '<a href="admin_forums.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
@ -574,7 +585,8 @@ if ($mode)
$cat_forums = get_cat_forums();
$fix = fix_orphan_sf();
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
$message = $lang['FORUMS_UPDATED'] . '<br /><br />';
$message .= ($fix) ? "$fix<br /><br />" : '';
@ -663,7 +675,8 @@ if ($mode)
renumber_order('forum', $forum_info['cat_id']);
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
$show_main_page = true;
break;
@ -680,7 +693,8 @@ if ($mode)
renumber_order('category');
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
$show_main_page = true;
break;
@ -688,7 +702,8 @@ if ($mode)
case 'forum_sync':
sync('forum', intval($_GET['f']));
$datastore->update('cat_forums');
CACHE('bb_cache')->rm();
// TODO: delete only necessary cache
$cache->flush();
$show_main_page = true;
break;

View file

@ -7,9 +7,16 @@ if (!empty($setmodules))
}
require('./pagestart.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (request_var('submit', '')) {
if (bb_update_config(array('static_sitemap' => request_var('static_sitemap', '')))) {
CACHE('bb_config')->rm();
// TODO: delete only necessary cache
$cache->flush();
}
bb_die('<a href="admin_sitemap.php">' . $lang['GO_BACK'] . '</a>');
}

View file

@ -7,6 +7,12 @@ if (!empty($setmodules))
}
require('./pagestart.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$bb_cfg['use_word_censor'])
{
bb_die('Word censor disabled <br /><br /> ($bb_cfg[\'use_word_censor\'] in config.php)');
@ -91,7 +97,7 @@ if ($mode != '')
bb_die('Could not insert data into words table');
}
CACHE('bb_cache')->rm('censored');
$cache->delete('censored');
$message .= '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>');
bb_die($message);
@ -109,7 +115,7 @@ if ($mode != '')
bb_die('Could not remove data from words table');
}
CACHE('bb_cache')->rm('censored');
$cache->delete('censored');
bb_die($lang['WORD_REMOVED'] . '<br /><br />' . sprintf($lang['CLICK_RETURN_WORDADMIN'], '<a href="admin_words.php">', '</a>') . '<br /><br />' . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], '<a href="index.php?pane=right">', '</a>'));
}

View file

@ -2,25 +2,31 @@
require('./pagestart.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
// Generate relevant output
if (isset($_GET['pane']) && $_GET['pane'] == 'left')
{
if (!$module = CACHE('bb_cache')->get('admin_module' . $user->id))
{
$module = [];
if (!$cache->has('admin_module_' . $user->id)) {
$dir = opendir('.');
$setmodules = 1;
while ($file = readdir($dir))
{
if (preg_match('/^admin_.*?\.php$/', $file))
{
while ($file = readdir($dir)) {
if (preg_match('/^admin_.*?\.php$/', $file)) {
include('./' . $file);
}
}
unset($setmodules);
closedir($dir);
CACHE('bb_cache')->set('admin_module' . $user->id, $module, 600);
$cache->set('admin_module_' . $user->id, $module, 600);
}
$module = $cache->get('admin_module_' . $user->id);
$template->assign_vars(array(
'TPL_ADMIN_NAVIGATE' => true,
'U_FORUM_INDEX' => '../index.php',

View file

@ -4,6 +4,12 @@ define('IN_TRACKER', true);
define('BB_ROOT', './../');
require(BB_ROOT .'common.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (empty($_SERVER['HTTP_USER_AGENT']))
{
header('Location: http://127.0.0.1', true, 301);
@ -142,7 +148,7 @@ $peer_hash = md5(
);
// Get cached peer info from previous announce (last peer info)
$lp_info = CACHE('tr_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'));
@ -195,12 +201,12 @@ $stopped = ($event === 'stopped');
// Stopped event
if ($stopped)
{
CACHE('tr_cache')->rm(PEER_HASH_PREFIX . $peer_hash);
$cache->delete(PEER_HASH_PREFIX . $peer_hash);
if (DBG_LOG) dbg_log(' ', 'stopped');
}
// Get last peer info from DB
if (!CACHE('tr_cache')->used && !$lp_info)
if (!$lp_info)
{
$lp_info = DB()->fetch_row("
SELECT * FROM ". BB_BT_TRACKER ." WHERE peer_hash = '$peer_hash' LIMIT 1
@ -427,12 +433,12 @@ $lp_info = array(
'tor_type' => (int) $tor_type,
);
$lp_info_cached = CACHE('tr_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');
// Get cached output
$output = CACHE('tr_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'));
@ -496,7 +502,7 @@ if (!$output)
'incomplete' => (int) $leechers,
);
$peers_list_cached = CACHE('tr_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');
}

View file

@ -153,38 +153,10 @@ function DB ($db_alias = 'db')
}
/**
* Cache
*/
// Main cache class
require(INC_DIR . 'cache/common.php');
// Main datastore class
require(INC_DIR . 'datastore/common.php');
// Core CACHE class
require(CORE_DIR . 'caches.php');
$CACHES = new CACHES($bb_cfg);
/**
* Datastore
* TODO: @deprecated
*/
function CACHE ($cache_name)
{
global $CACHES;
return $CACHES->get_cache_obj($cache_name);
}
// Common cache classes
require(INC_DIR . 'cache/memcache.php');
require(INC_DIR . 'cache/sqlite.php');
require(INC_DIR . 'cache/redis.php');
require(INC_DIR . 'cache/apc.php');
require(INC_DIR . 'cache/xcache.php');
require(INC_DIR . 'cache/file.php');
/**
* Datastore
*/
// Common datastore classes
require(INC_DIR . 'datastore/common.php');
require(INC_DIR . 'datastore/memcache.php');
require(INC_DIR . 'datastore/sqlite.php');
require(INC_DIR . 'datastore/redis.php');

View file

@ -2,7 +2,13 @@
define('BB_SCRIPT', 'index');
define('BB_ROOT', './');
require(BB_ROOT .'common.php');
require_once __DIR__ . '/common.php';
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$page_cfg['load_tpl_vars'] = array(
'post_icons',
@ -38,7 +44,10 @@ $req_page = 'index_page';
$req_page .= ($viewcat) ? "_c{$viewcat}" : '';
define('REQUESTED_PAGE', $req_page);
caching_output(IS_GUEST, 'send', REQUESTED_PAGE .'_guest_'. $bb_cfg['default_lang']);
if (IS_GUEST && $cache->has(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'))) {
bb_exit($cache->get(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang')));
}
$hide_cat_opt = isset($user->opt_js['h_cat']) ? (string) $user->opt_js['h_cat'] : 0;
$hide_cat_user = array_flip(explode('-', $hide_cat_opt));
@ -124,53 +133,43 @@ $replace_in_parent = array(
);
$cache_name = 'index_sql_' . md5($sql);
if (!$cat_forums = CACHE('bb_cache')->get($cache_name))
{
$cat_forums = array();
foreach (DB()->fetch_rowset($sql) as $row)
{
if (!$cat_id = $row['cat_id'] OR !$forum_id = $row['forum_id'])
{
if (!$cache->has($cache_name)) {
$cat_forums = [];
foreach (DB()->fetch_rowset($sql) as $row) {
if (!$cat_id = $row['cat_id'] OR !$forum_id = $row['forum_id']) {
continue;
}
if ($parent_id = $row['forum_parent'])
{
if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id])
{
if ($parent_id = $row['forum_parent']) {
if (!$parent =& $cat_forums[$cat_id]['f'][$parent_id]) {
$parent = $forums['f'][$parent_id];
$parent['last_post_time'] = 0;
}
if ($row['last_post_time'] > $parent['last_post_time'])
{
foreach ($replace_in_parent as $key)
{
if ($row['last_post_time'] > $parent['last_post_time']) {
foreach ($replace_in_parent as $key) {
$parent[$key] = $row[$key];
}
}
if ($show_subforums && $row['show_on_index'])
{
if ($show_subforums && $row['show_on_index']) {
$parent['last_sf_id'] = $forum_id;
}
else
{
} else {
continue;
}
}
else
{
} else {
$f =& $forums['f'][$forum_id];
$row['forum_desc'] = $f['forum_desc'];
$row['forum_posts'] = $f['forum_posts'];
$row['forum_desc'] = $f['forum_desc'];
$row['forum_posts'] = $f['forum_posts'];
$row['forum_topics'] = $f['forum_topics'];
}
$cat_forums[$cat_id]['f'][$forum_id] = $row;
}
CACHE('bb_cache')->set($cache_name, $cat_forums, 180);
$cache->set($cache_name, $cat_forums, 180);
unset($row, $forums);
$datastore->rm('cat_forums');
}
$cat_forums = $cache->get($cache_name);
// Obtain list of moderators
$moderators = array();
if (!$mod = $datastore->get('moderators'))

View file

@ -436,7 +436,6 @@ INSERT INTO `bb_cron` VALUES ('', '1', 'Accrual seedbonus', 'tr_seed_bonus.php',
INSERT INTO `bb_cron` VALUES ('', '1', 'Make tracker snapshot', 'tr_make_snapshot.php', 'interval', '', '', '10', '', '', '00:10:00', '0', '', '0', '0', '0');
INSERT INTO `bb_cron` VALUES ('', '1', 'Seeder last seen', 'tr_update_seeder_last_seen.php', 'interval', '', '', '255', '', '', '01:00:00', '0', '', '0', '0', '0');
INSERT INTO `bb_cron` VALUES ('', '1', 'Tracker dl-complete count', 'tr_complete_count.php', 'interval', '', '', '255', '', '', '06:00:00', '0', '', '0', '0', '0');
INSERT INTO `bb_cron` VALUES ('', '1', 'Cache garbage collector', 'cache_gc.php', 'interval', '', '', '255', '', '', '00:05:00', '0', '', '0', '0', '0');
INSERT INTO `bb_cron` VALUES ('', '1', 'Sitemap update', 'sitemap.php', 'daily', '', '06:00:00', '30', '', '', '', '0', '', '0', '0', '0');
INSERT INTO `bb_cron` VALUES ('', '1', 'Update forums atom', 'update_forums_atom.php', 'interval', '', '', '255', '', '', '00:15:00', '0', '', '0', '0', '0');

View file

@ -78,3 +78,4 @@ DROP TABLE IF EXISTS `bb_attachments`;
ALTER TABLE `bb_topics` ADD `tracker_id` TINYINT(4) NOT NULL DEFAULT '0' AFTER `topic_moved_id`;
ALTER TABLE `bb_topics` ADD `attach_dl_cnt` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0' AFTER `attach_ext_id`;
DROP TABLE IF EXISTS `bb_bt_tor_dl_stat`;
DELETE FROM `bb_cron` WHERE `cron_script` = 'cache_gc.php';

View file

@ -4,19 +4,19 @@ if (!defined('IN_AJAX')) die(basename(__FILE__));
global $userdata, $lang, $bb_cfg;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$mode = (string) $this->request['mode'];
switch ($mode)
{
case 'clear_cache':
foreach ($bb_cfg['cache']['engines'] as $cache_name => $cache_val)
{
if (!in_array('db_sqlite', $cache_val))
{
CACHE($cache_name)->rm();
}
}
$cache->flush();
$this->response['cache_html'] = '<span class="seed bold">'. $lang['ALL_CACHE_CLEARED'] .'</span>';

View file

@ -19,14 +19,14 @@ $config = [
'tp_release_date' => '**/**/2016',
'tp_release_state' => 'ALPHA',
'services' => [
'cache' => [
'adapter' => \TorrentPier\Cache\FileAdapter::class,
'options' => [
'directory' => __DIR__ . '/../internal_data/cache',
],
],
],
'services' => [
'cache' => [
'adapter' => \TorrentPier\Cache\FileAdapter::class,
'options' => [
'directory' => __DIR__ . '/../internal_data/cache',
],
],
],
// Database
'db' => [

View file

@ -1,65 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_apc extends cache_common
{
var $used = true;
var $engine = 'APC';
var $prefix = null;
function cache_apc ($prefix = null)
{
if (!$this->is_installed())
{
die('Error: APC extension not installed');
}
$this->dbg_enabled = sql_dbg_enabled();
$this->prefix = $prefix;
}
function get ($name, $get_miss_key_callback = '', $ttl = 0)
{
$this->cur_query = "cache->get('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return apc_fetch($this->prefix . $name);
}
function set ($name, $value, $ttl = 0)
{
$this->cur_query = "cache->set('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return apc_store($this->prefix . $name, $value, $ttl);
}
function rm ($name = '')
{
if ($name)
{
$this->cur_query = "cache->rm('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return apc_delete($this->prefix . $name);
}
else
{
return apc_clear_cache();
}
}
function is_installed ()
{
return function_exists('apc_fetch');
}
}

View file

@ -1,103 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_common
{
var $used = false;
/**
* Returns value of variable
*
* @param $name
* @param string $get_miss_key_callback
* @param int $ttl
*
* @return array|bool
*/
function get ($name, $get_miss_key_callback = '', $ttl = 604800)
{
if ($get_miss_key_callback) return $get_miss_key_callback($name);
return is_array($name) ? array() : false;
}
/**
* Store value of variable
*
* @param $name
* @param $value
* @param int $ttl
*
* @return bool
*/
function set ($name, $value, $ttl = 604800)
{
return false;
}
/**
* Remove variable
*
* @param string $name
*
* @return bool
*/
function rm ($name = '')
{
return false;
}
var $num_queries = 0;
var $sql_starttime = 0;
var $sql_inittime = 0;
var $sql_timetotal = 0;
var $cur_query_time = 0;
var $dbg = array();
var $dbg_id = 0;
var $dbg_enabled = false;
var $cur_query = null;
function debug ($mode, $cur_query = null)
{
if (!$this->dbg_enabled) return;
$id =& $this->dbg_id;
$dbg =& $this->dbg[$id];
if ($mode == 'start')
{
$this->sql_starttime = utime();
$dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query);
$dbg['src'] = $this->debug_find_source();
$dbg['file'] = $this->debug_find_source('file');
$dbg['line'] = $this->debug_find_source('line');
$dbg['time'] = '';
}
else if ($mode == 'stop')
{
$this->cur_query_time = utime() - $this->sql_starttime;
$this->sql_timetotal += $this->cur_query_time;
$dbg['time'] = $this->cur_query_time;
$id++;
}
}
function debug_find_source ($mode = '')
{
foreach (debug_backtrace() as $trace)
{
if ($trace['file'] !== __FILE__)
{
switch ($mode)
{
case 'file': return $trace['file'];
case 'line': return $trace['line'];
default: return hide_bb_path($trace['file']) .'('. $trace['line'] .')';
}
}
}
return 'src not found';
}
}

View file

@ -1,136 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_file extends cache_common
{
var $used = true;
var $engine = 'Filecache';
var $dir = null;
var $prefix = null;
function cache_file ($dir, $prefix = null)
{
$this->dir = $dir;
$this->prefix = $prefix;
$this->dbg_enabled = sql_dbg_enabled();
}
function get ($name, $get_miss_key_callback = '', $ttl = 0)
{
$filename = $this->dir . clean_filename($this->prefix . $name) . '.php';
$this->cur_query = "cache->set('$name')";
$this->debug('start');
if (file_exists($filename))
{
require($filename);
}
$this->debug('stop');
$this->cur_query = null;
return (!empty($filecache['value'])) ? $filecache['value'] : false;
}
function set ($name, $value, $ttl = 86400)
{
if (!function_exists('var_export'))
{
return false;
}
$this->cur_query = "cache->set('$name')";
$this->debug('start');
$filename = $this->dir . clean_filename($this->prefix . $name) . '.php';
$expire = TIMENOW + $ttl;
$cache_data = array(
'expire' => $expire,
'value' => $value,
);
$filecache = "<?php\n";
$filecache .= "if (!defined('BB_ROOT')) die(basename(__FILE__));\n";
$filecache .= '$filecache = ' . var_export($cache_data, true) . ";\n";
$filecache .= '?>';
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return (bool) file_write($filecache, $filename, false, true, true);
}
function rm ($name = '')
{
$clear = false;
if ($name)
{
$this->cur_query = "cache->rm('$name')";
$this->debug('start');
$filename = $this->dir . clean_filename($this->prefix . $name) . '.php';
if (file_exists($filename))
{
$clear = (bool) unlink($filename);
}
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
}
else
{
if (is_dir($this->dir))
{
if ($dh = opendir($this->dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file != "." && $file != "..")
{
$filename = $this->dir . $file;
unlink($filename);
$clear = true;
}
}
closedir($dh);
}
}
}
return $clear;
}
function gc ($expire_time = TIMENOW)
{
$clear = false;
if (is_dir($this->dir))
{
if ($dh = opendir($this->dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file != "." && $file != "..")
{
$filename = $this->dir . $file;
require($filename);
if(!empty($filecache['expire']) && ($filecache['expire'] < $expire_time))
{
unlink($filename);
$clear = true;
}
}
}
closedir($dh);
}
}
return $clear;
}
}

View file

@ -1,100 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_memcache extends cache_common
{
var $used = true;
var $engine = 'Memcache';
var $cfg = null;
var $prefix = null;
var $memcache = null;
var $connected = false;
function cache_memcache ($cfg, $prefix = null)
{
if (!$this->is_installed())
{
die('Error: Memcached extension not installed');
}
$this->cfg = $cfg;
$this->prefix = $prefix;
$this->memcache = new Memcache;
$this->dbg_enabled = sql_dbg_enabled();
}
function connect ()
{
$connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect';
$this->cur_query = $connect_type .' '. $this->cfg['host'] .':'. $this->cfg['port'];
$this->debug('start');
if ($this->memcache->$connect_type($this->cfg['host'], $this->cfg['port']))
{
$this->connected = true;
}
if (DBG_LOG) dbg_log(' ', 'CACHE-connect'. ($this->connected ? '' : '-FAIL'));
if (!$this->connected && $this->cfg['con_required'])
{
die('Could not connect to memcached server');
}
$this->debug('stop');
$this->cur_query = null;
}
function get ($name, $get_miss_key_callback = '', $ttl = 0)
{
if (!$this->connected) $this->connect();
$this->cur_query = "cache->get('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false;
}
function set ($name, $value, $ttl = 0)
{
if (!$this->connected) $this->connect();
$this->cur_query = "cache->set('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false;
}
function rm ($name = '')
{
if (!$this->connected) $this->connect();
if ($name)
{
$this->cur_query = "cache->rm('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return ($this->connected) ? $this->memcache->delete($this->prefix . $name, 0) : false;
}
else
{
return ($this->connected) ? $this->memcache->flush() : false;
}
}
function is_installed ()
{
return class_exists('Memcache');
}
}

View file

@ -1,109 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_redis extends cache_common
{
var $used = true;
var $engine = 'Redis';
var $cfg = null;
var $redis = null;
var $prefix = null;
var $connected = false;
function cache_redis ($cfg, $prefix = null)
{
if (!$this->is_installed())
{
die('Error: Redis extension not installed');
}
$this->cfg = $cfg;
$this->prefix = $prefix;
$this->redis = new Redis();
$this->dbg_enabled = sql_dbg_enabled();
}
function connect ()
{
$this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port'];
$this->debug('start');
if ($this->redis->connect($this->cfg['host'], $this->cfg['port']))
{
$this->connected = true;
}
if (!$this->connected && $this->cfg['con_required'])
{
die('Could not connect to redis server');
}
$this->debug('stop');
$this->cur_query = null;
}
function get ($name, $get_miss_key_callback = '', $ttl = 0)
{
if (!$this->connected) $this->connect();
$this->cur_query = "cache->get('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false;
}
function set ($name, $value, $ttl = 0)
{
if (!$this->connected) $this->connect();
$this->cur_query = "cache->set('$name')";
$this->debug('start');
if ($this->redis->set($this->prefix . $name, serialize($value)))
{
if ($ttl > 0)
{
$this->redis->expire($this->prefix . $name, $ttl);
}
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return true;
}
else
{
return false;
}
}
function rm ($name = '')
{
if (!$this->connected) $this->connect();
if ($name)
{
$this->cur_query = "cache->rm('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return ($this->connected) ? $this->redis->del($this->prefix . $name) : false;
}
else
{
return ($this->connected) ? $this->redis->flushdb() : false;
}
}
function is_installed ()
{
return class_exists('Redis');
}
}

View file

@ -1,288 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_sqlite extends cache_common
{
var $used = true;
var $db = null;
var $prefix = null;
var $cfg = array(
'db_file_path' => '/path/to/cache.db.sqlite',
'table_name' => 'cache',
'table_schema' => 'CREATE TABLE cache (
cache_name VARCHAR(255),
cache_expire_time INT,
cache_value TEXT,
PRIMARY KEY (cache_name)
)',
'pconnect' => true,
'con_required' => true,
'log_name' => 'CACHE',
);
function cache_sqlite ($cfg, $prefix = null)
{
$this->cfg = array_merge($this->cfg, $cfg);
$this->db = new sqlite_common($this->cfg);
$this->prefix = $prefix;
}
function get ($name, $get_miss_key_callback = '', $ttl = 604800)
{
if (empty($name))
{
return is_array($name) ? array() : false;
}
$this->db->shard($name);
$cached_items = array();
$this->prefix_len = strlen($this->prefix);
$this->prefix_sql = SQLite3::escapeString($this->prefix);
$name_ary = $name_sql = (array) $name;
array_deep($name_sql, 'SQLite3::escapeString');
// get available items
$rowset = $this->db->fetch_rowset("
SELECT cache_name, cache_value
FROM ". $this->cfg['table_name'] ."
WHERE cache_name IN('$this->prefix_sql". join("','$this->prefix_sql", $name_sql) ."') AND cache_expire_time > ". TIMENOW ."
LIMIT ". count($name) ."
");
$this->db->debug('start', 'unserialize()');
foreach ($rowset as $row)
{
$cached_items[substr($row['cache_name'], $this->prefix_len)] = unserialize($row['cache_value']);
}
$this->db->debug('stop');
// get miss items
if ($get_miss_key_callback AND $miss_key = array_diff($name_ary, array_keys($cached_items)))
{
foreach ($get_miss_key_callback($miss_key) as $k => $v)
{
$this->set($this->prefix . $k, $v, $ttl);
$cached_items[$k] = $v;
}
}
// return
if (is_array($this->prefix . $name))
{
return $cached_items;
}
else
{
return isset($cached_items[$name]) ? $cached_items[$name] : false;
}
}
function set ($name, $value, $ttl = 604800)
{
$this->db->shard($this->prefix . $name);
$name_sql = SQLite3::escapeString($this->prefix . $name);
$expire = TIMENOW + $ttl;
$value_sql = SQLite3::escapeString(serialize($value));
$result = $this->db->query("REPLACE INTO ". $this->cfg['table_name'] ." (cache_name, cache_expire_time, cache_value) VALUES ('$name_sql', $expire, '$value_sql')");
return (bool) $result;
}
function rm ($name = '')
{
if ($name)
{
$this->db->shard($this->prefix . $name);
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'");
}
else
{
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name']);
}
return (bool) $result;
}
function gc ($expire_time = TIMENOW)
{
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time");
return ($result) ? $this->db->changes() : 0;
}
}
class sqlite_common extends cache_common
{
var $cfg = array(
'db_file_path' => 'sqlite.db',
'table_name' => 'table_name',
'table_schema' => 'CREATE TABLE table_name (...)',
'pconnect' => true,
'con_required' => true,
'log_name' => 'SQLite',
'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга)
'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления)
);
var $engine = 'SQLite';
var $dbh = null;
var $connected = false;
var $shard_val = false;
var $table_create_attempts = 0;
function sqlite_common ($cfg)
{
$this->cfg = array_merge($this->cfg, $cfg);
$this->dbg_enabled = sql_dbg_enabled();
}
function connect ()
{
$this->cur_query = ($this->dbg_enabled) ? 'connect to: '. $this->cfg['db_file_path'] : 'connect';
$this->debug('start');
if ($this->dbh = new SQLite3($this->cfg['db_file_path']))
{
$this->connected = true;
}
if (DBG_LOG) dbg_log(' ', $this->cfg['log_name'] .'-connect'. ($this->connected ? '' : '-FAIL'));
if (!$this->connected && $this->cfg['con_required'])
{
trigger_error('SQLite not connected', E_USER_ERROR);
}
$this->debug('stop');
$this->cur_query = null;
}
function create_table ()
{
$this->table_create_attempts++;
return $this->dbh->query($this->cfg['table_schema']);
}
function shard ($name)
{
$type = $this->cfg['shard_type'];
if ($type == 'none') return;
if (is_array($name)) trigger_error('cannot shard: $name is array', E_USER_ERROR);
// define shard_val
if ($type == 'string')
{
$shard_val = substr($name, 0, $this->cfg['shard_val']);
}
else
{
$shard_val = $name % $this->cfg['shard_val'];
}
// все запросы должны быть к одному и тому же шарду
if ($this->shard_val !== false)
{
if ($shard_val != $this->shard_val)
{
trigger_error("shard cannot be reassigned. [{$this->shard_val}, $shard_val, $name]", E_USER_ERROR);
}
else
{
return;
}
}
$this->shard_val = $shard_val;
$this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']);
}
function query ($query)
{
if (!$this->connected) $this->connect();
$this->cur_query = $query;
$this->debug('start');
if (!$result = $this->dbh->query($query))
{
$rowsresult = $this->dbh->query("PRAGMA table_info({$this->cfg['table_name']})");
$rowscount = 0;
while ($row = $rowsresult->fetchArray(SQLITE3_ASSOC))
{
$rowscount++;
}
if (!$this->table_create_attempts && !$rowscount)
{
if ($this->create_table())
{
$result = $this->dbh->query($query);
}
}
if (!$result)
{
$this->trigger_error($this->get_error_msg());
}
}
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return $result;
}
function fetch_row ($query)
{
$result = $this->query($query);
return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false;
}
function fetch_rowset ($query)
{
$result = $this->query($query);
$rowset = array();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$rowset[] = $row;
}
return $rowset;
}
function changes ()
{
return is_resource($this->dbh) ? $this->dbh->changes() : 0;
}
function escape ($str)
{
return SQLite3::escapeString($str);
}
function get_error_msg ()
{
return 'SQLite error #'. ($err_code = $this->dbh->lastErrorCode()) .': '. $this->dbh->lastErrorMsg();
}
function rm ($name = '')
{
if ($name)
{
$this->db->shard($this->prefix . $name);
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_name = '". SQLite3::escapeString($this->prefix . $name) ."'");
}
else
{
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name']);
}
return (bool) $result;
}
function gc ($expire_time = TIMENOW)
{
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time");
return ($result) ? sqlite_changes($this->db->dbh) : 0;
}
function trigger_error ($msg = 'DB Error')
{
if (error_reporting()) trigger_error($msg, E_USER_ERROR);
}
}

View file

@ -1,67 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_xcache extends cache_common
{
var $used = true;
var $engine = 'XCache';
var $prefix = null;
function cache_xcache ($prefix = null)
{
if (!$this->is_installed())
{
die('Error: XCache extension not installed');
}
$this->dbg_enabled = sql_dbg_enabled();
$this->prefix = $prefix;
}
function get ($name, $get_miss_key_callback = '', $ttl = 0)
{
$this->cur_query = "cache->get('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return xcache_get($this->prefix . $name);
}
function set ($name, $value, $ttl = 0)
{
$this->cur_query = "cache->set('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return xcache_set($this->prefix . $name, $value, $ttl);
}
function rm ($name = '')
{
if ($name)
{
$this->cur_query = "cache->rm('$name')";
$this->debug('start');
$this->debug('stop');
$this->cur_query = null;
$this->num_queries++;
return xcache_unset($this->prefix . $name);
}
else
{
xcache_clear_cache(XC_TYPE_PHP, 0);
xcache_clear_cache(XC_TYPE_VAR, 0);
return true;
}
}
function is_installed ()
{
return function_exists('xcache_get');
}
}

View file

@ -1,118 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
class CACHES
{
var $cfg = array(); // конфиг
var $obj = array(); // кеш-объекты
var $ref = array(); // ссылки на $obj (имя_кеша => кеш_объект)
function CACHES ($cfg)
{
$this->cfg = $cfg['cache'];
$this->obj['__stub'] = new cache_common();
}
function get_cache_obj ($cache_name)
{
if (!isset($this->ref[$cache_name]))
{
if (!$engine_cfg =& $this->cfg['engines'][$cache_name])
{
$this->ref[$cache_name] =& $this->obj['__stub'];
}
else
{
$cache_type =& $engine_cfg[0];
$cache_cfg =& $engine_cfg[1];
switch ($cache_type)
{
case 'memcache':
if (!isset($this->obj[$cache_name]))
{
$this->obj[$cache_name] = new cache_memcache($this->cfg['memcache'], $this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
case 'sqlite':
if (!isset($this->obj[$cache_name]))
{
$cache_cfg['pconnect'] = $this->cfg['pconnect'];
$cache_cfg['db_file_path'] = $this->get_db_path($cache_name, $cache_cfg, '.sqlite.db');
$this->obj[$cache_name] = new cache_sqlite($cache_cfg, $this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
case 'db_sqlite':
if (!isset($this->obj[$cache_name]))
{
$cache_cfg['pconnect'] = $this->cfg['pconnect'];
$cache_cfg['db_file_path'] = $this->get_db_path($cache_name, $cache_cfg, '.sqlite.db');
$cache_cfg['table_name'] = $cache_name;
$cache_cfg['table_schema'] = $this->get_table_schema($cache_cfg);
$this->obj[$cache_name] = new sqlite_common($cache_cfg);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
case 'redis':
if (!isset($this->obj[$cache_name]))
{
$this->obj[$cache_name] = new cache_redis($this->cfg['redis'], $this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
case 'apc':
if (!isset($this->obj[$cache_name]))
{
$this->obj[$cache_name] = new cache_apc($this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
case 'xcache':
if (!isset($this->obj[$cache_name]))
{
$this->obj[$cache_name] = new cache_xcache($this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
default: //filecache
if (!isset($this->obj[$cache_name]))
{
$this->obj[$cache_name] = new cache_file($this->cfg['db_dir'] . $cache_name .'/', $this->cfg['prefix']);
}
$this->ref[$cache_name] =& $this->obj[$cache_name];
break;
}
}
}
return $this->ref[$cache_name];
}
function get_db_path ($name, $cfg, $ext)
{
if (!empty($cfg['shard_type']) && $cfg['shard_type'] != 'none')
{
return $this->cfg['db_dir'] . $name .'_*'. $ext;
}
else
{
return $this->cfg['db_dir'] . $name . $ext;
}
}
function get_table_schema ($cfg)
{
return "CREATE TABLE {$cfg['table_name']} ( {$cfg['columns']} )";
}
}

View file

@ -708,7 +708,13 @@ class sql_db
*/
function expect_slow_query ($ignoring_time = 60, $new_priority = 10)
{
if ($old_priority = CACHE('bb_cache')->get('dont_log_slow_query'))
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if ($old_priority = $cache->get('dont_log_slow_query'))
{
if ($old_priority > $new_priority)
{
@ -717,7 +723,8 @@ class sql_db
}
define('IN_FIRST_SLOW_QUERY', true);
CACHE('bb_cache')->set('dont_log_slow_query', $new_priority, $ignoring_time);
$cache->set('dont_log_slow_query', $new_priority, $ignoring_time);
}
/**
@ -860,7 +867,13 @@ class sql_db
*/
function log_slow_query ($log_file = 'sql_slow_bb')
{
if (!defined('IN_FIRST_SLOW_QUERY') && CACHE('bb_cache')->get('dont_log_slow_query'))
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!defined('IN_FIRST_SLOW_QUERY') && $cache->get('dont_log_slow_query'))
{
return;
}

View file

@ -1,14 +0,0 @@
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
global $cron_runtime_log;
foreach ($bb_cfg['cache']['engines'] as $cache_name => $cache_val)
{
if (method_exists(CACHE($cache_name), 'gc'))
{
$changes = CACHE($cache_name)->gc();
$cron_runtime_log = date('Y-m-d H:i:s') ." -- ". str_pad("$cache_name ", 25, '-', STR_PAD_RIGHT) ." del: $changes\n";
}
}

View file

@ -1156,7 +1156,13 @@ function wbr ($text, $max_word_length = HTML_WBR_LENGTH)
function get_bt_userdata ($user_id)
{
if (!$btu = CACHE('bb_cache')->get('btu_' . $user_id))
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$cache->has('btu_' . $user_id))
{
$btu = DB()->fetch_row("
SELECT bt.*, SUM(tr.speed_up) AS speed_up, SUM(tr.speed_down) AS speed_down
@ -1166,8 +1172,11 @@ function get_bt_userdata ($user_id)
GROUP BY bt.user_id
LIMIT 1
");
CACHE('bb_cache')->set('btu_' . $user_id, $btu, 300);
$cache->set('btu_' . $user_id, $btu, 300);
}
$btu = $cache->get('btu_' . $user_id);
return $btu;
}
@ -1217,18 +1226,26 @@ function show_bt_userdata ($user_id)
function bb_get_config ($table, $from_db = false, $update_cache = true)
{
if ($from_db OR !$cfg = CACHE('bb_config')->get("config_{$table}"))
{
$cfg = array();
foreach (DB()->fetch_rowset("SELECT * FROM $table") as $row)
{
$cfg[$row['config_name']] = $row['config_value'];
}
if ($update_cache)
{
CACHE('bb_config')->set("config_{$table}", $cfg);
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$cfg = [];
if (!$cache->has('config_' . $table)) {
if ($from_db) {
foreach (DB()->fetch_rowset("SELECT * FROM $table") as $row) {
$cfg[$row['config_name']] = $row['config_value'];
}
if ($update_cache) {
$cache->set('config_' . $table, $cfg);
}
}
}
$cfg = $cache->get('config_' . $table);
return $cfg;
}
@ -1330,17 +1347,23 @@ function bb_rtrim ($str, $charlist = false)
// Get Userdata, $u can be username or user_id. If $force_name is true, the username will be forced.
function get_userdata ($u, $force_name = false, $allow_guest = false)
{
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$u) return false;
if (intval($u) == GUEST_UID && $allow_guest)
{
if ($u_data = CACHE('bb_cache')->get('guest_userdata'))
if ($u_data = $cache->get('guest_userdata'))
{
return $u_data;
}
}
$u_data = array();
$u_data = [];
$name_search = false;
$exclude_anon_sql = (!$allow_guest) ? "AND user_id != ". GUEST_UID : '';
@ -1368,7 +1391,7 @@ function get_userdata ($u, $force_name = false, $allow_guest = false)
if ($u_data['user_id'] == GUEST_UID)
{
CACHE('bb_cache')->set('guest_userdata', $u_data);
$cache->set('guest_userdata', $u_data);
}
return $u_data;
@ -1684,17 +1707,23 @@ function obtain_word_list (&$orig_word, &$replacement_word)
{
global $bb_cfg;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$bb_cfg['use_word_censor']) return false;
if (!$sql = CACHE('bb_cache')->get('censored'))
{
$sql = DB()->fetch_rowset("SELECT word, replacement FROM ". BB_WORDS);
if(!$sql) $sql = array(array('word' => 1, 'replacement' => 1));
CACHE('bb_cache')->set('censored', $sql, 7200);
if (!$cache->has('censored')) {
$sql = DB()->fetch_rowset("SELECT word, replacement FROM " . BB_WORDS);
if (!$sql) $sql = [['word' => 1, 'replacement' => 1]];
$cache->set('censored', $sql, 7200);
}
foreach($sql as $row)
{
$sql = $cache->get('censored');
foreach ($sql as $row) {
$orig_word[] = '#(?<![\p{Nd}\p{L}_])(' . str_replace('\*', '[\p{Nd}\p{L}_]*?', preg_quote($row['word'], '#')) . ')(?![\p{Nd}\p{L}_])#iu';
$replacement_word[] = $row['replacement'];
}
@ -2075,32 +2104,36 @@ function build_topic_pagination ($url, $replies, $per_page)
//
function get_poll_data_items_js ($topic_id)
{
if (!$topic_id_csv = get_id_csv($topic_id))
{
return is_array($topic_id) ? array() : false;
}
$items = array();
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
if (!$poll_data = CACHE('bb_poll_data')->get("poll_$topic_id"))
{
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$topic_id_csv = get_id_csv($topic_id)) {
return is_array($topic_id) ? [] : false;
}
$items = [];
if (!$cache->has('poll_' . $topic_id)) {
$poll_data = DB()->fetch_rowset("
SELECT topic_id, vote_id, vote_text, vote_result
FROM ". BB_POLL_VOTES ."
FROM " . BB_POLL_VOTES . "
WHERE topic_id IN($topic_id_csv)
ORDER BY topic_id, vote_id
");
CACHE('bb_poll_data')->set("poll_$topic_id", $poll_data);
$cache->set('poll_' . $topic_id, $poll_data);
}
foreach ($poll_data as $row)
{
$opt_text_for_js = htmlCHR($row['vote_text']);
$opt_result_for_js = (int) $row['vote_result'];
$poll_data = $cache->get('poll_' . $topic_id);
foreach ($poll_data as $row) {
$opt_text_for_js = htmlCHR($row['vote_text']);
$opt_result_for_js = (int)$row['vote_result'];
$items[$row['topic_id']][$row['vote_id']] = array($opt_text_for_js, $opt_result_for_js);
}
foreach ($items as $k => $v)
{
foreach ($items as $k => $v) {
$items[$k] = \Zend\Json\Json::encode($v);
}
@ -2168,29 +2201,6 @@ function print_page ($args, $type = '', $mode = '')
}
}
function caching_output ($enabled, $mode, $cache_var_name, $ttl = 300)
{
if (!$enabled || !CACHE('bb_cache')->used)
{
return;
}
if ($mode == 'send')
{
if ($cached_contents = CACHE('bb_cache')->get($cache_var_name))
{
bb_exit($cached_contents);
}
}
else if ($mode == 'store')
{
if ($output = ob_get_contents())
{
CACHE('bb_cache')->set($cache_var_name, $output, $ttl);
}
}
}
function clean_title ($str, $replace_underscore = false)
{
$str = ($replace_underscore) ? str_replace('_', ' ', $str) : $str;

View file

@ -4,7 +4,7 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
function get_sql_log ()
{
global $DBS, $CACHES, $sphinx, $datastore;
global $DBS, $sphinx, $datastore;
$log = '';
@ -13,18 +13,6 @@ function get_sql_log ()
$log .= !empty($db_obj) ? get_sql_log_html($db_obj, "$srv_name [MySQL]") : '';
}
foreach ($CACHES->obj as $cache_name => $cache_obj)
{
if (!empty($cache_obj->db))
{
$log .= get_sql_log_html($cache_obj->db, "cache: $cache_name [{$cache_obj->db->engine}]");
}
elseif (!empty($cache_obj->engine))
{
$log .= get_sql_log_html($cache_obj, "cache: $cache_name [{$cache_obj->engine}]");
}
}
$log .= !empty($sphinx) ? get_sql_log_html($sphinx, '$sphinx') : '';
if (!empty($datastore->db->dbg))

View file

@ -4,6 +4,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
global $lang;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
// Obtain user/online information
$logged_online = $guests_online = 0;
$time_online = TIMENOW - 300;
@ -149,5 +155,5 @@ $online['cnt'] = $online_short['cnt'] = <<<HTML
]
HTML;
CACHE('bb_cache')->set('online_'.$userdata['user_lang'], $online, 60);
CACHE('bb_cache')->set('online_short_'.$userdata['user_lang'], $online_short, 60);
$cache->set('online_' . $userdata['user_lang'], $online, 60);
$cache->set('online_short_' . $userdata['user_lang'], $online_short, 60);

View file

@ -4,6 +4,12 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
global $bb_cfg, $userdata, $template, $DBS, $lang;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!empty($template))
{
$template->assign_vars(array(
@ -83,11 +89,11 @@ echo '
</html>
';
if (defined('REQUESTED_PAGE') && !defined('DISABLE_CACHING_OUTPUT'))
{
if (IS_GUEST === true)
{
caching_output(true, 'store', REQUESTED_PAGE .'_guest_'. $bb_cfg['default_lang']);
if (defined('REQUESTED_PAGE') && !defined('DISABLE_CACHING_OUTPUT')) {
if (IS_GUEST === true) {
if ($output = ob_get_contents()) {
$cache->set(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'), $output, 300);
}
}
}

View file

@ -7,15 +7,18 @@ if (defined('PAGE_HEADER_SENT')) return;
global $page_cfg, $userdata, $user, $bb_cfg, $template, $lang, $images;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$logged_in = (int) !empty($userdata['session_logged_in']);
// Generate logged in/logged out status
if ($logged_in)
{
$u_login_logout = BB_ROOT . LOGIN_URL . "?logout=1";
}
else
{
if ($logged_in) {
$u_login_logout = BB_ROOT . LOGIN_URL . '?logout=1';
} else {
$u_login_logout = BB_ROOT . LOGIN_URL;
}
@ -23,19 +26,19 @@ else
if (defined('SHOW_ONLINE') && SHOW_ONLINE)
{
$online_full = !empty($_REQUEST['online_full']);
$online_list = ($online_full) ? 'online_'.$userdata['user_lang'] : 'online_short_'.$userdata['user_lang'];
$online_list = ($online_full) ? 'online_' . $userdata['user_lang'] : 'online_short_' . $userdata['user_lang'];
${$online_list} = array(
${$online_list} = [
'stat' => '',
'userlist' => '',
'cnt' => '',
);
];
if (defined('IS_GUEST') && !(IS_GUEST || IS_USER))
{
$template->assign_var('SHOW_ONLINE_LIST');
if (!${$online_list} = CACHE('bb_cache')->get($online_list))
if (!${$online_list} = $cache->get($online_list))
{
require(INC_DIR .'online_userlist.php');
}

View file

@ -808,32 +808,56 @@ function ignore_cached_userdata ()
function cache_get_userdata ($id)
{
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (ignore_cached_userdata()) return false;
return CACHE('session_cache')->get($id);
return $cache->get($id);
}
function cache_set_userdata ($userdata, $force = false)
{
global $bb_cfg;
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$userdata || (ignore_cached_userdata() && !$force)) return false;
$id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id'];
return CACHE('session_cache')->set($id, $userdata, $bb_cfg['session_update_intrv']);
return $cache->set($id, $userdata, $di->config->get('session_update_intrv'));
}
function cache_rm_userdata ($userdata)
{
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
if (!$userdata) return false;
$id = ($userdata['user_id'] == GUEST_UID) ? $userdata['session_ip'] : $userdata['session_id'];
return CACHE('session_cache')->rm($id);
return $cache->delete($id);
}
// $user_id - array(id1,id2,..) or (string) id
function cache_rm_user_sessions ($user_id)
{
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$user_id = get_id_csv($user_id);
$rowset = DB()->fetch_rowset("
@ -842,7 +866,7 @@ function cache_rm_user_sessions ($user_id)
foreach ($rowset as $row)
{
CACHE('session_cache')->rm($row['session_id']);
$cache->delete($row['session_id']);
}
}

View file

@ -1,9 +1,15 @@
<?php
define('BB_SCRIPT', 'login');
define('IN_LOGIN', true);
define('BB_ROOT', './');
require(BB_ROOT .'common.php');
define('IN_LOGIN', true);
require_once __DIR__ . '/common.php';
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
array_deep($_POST, 'trim');
@ -63,7 +69,7 @@ $login_password = isset($_POST['login_password']) ? $_POST['login_password'] : '
$need_captcha = false;
if (!$mod_admin_login)
{
$need_captcha = CACHE('bb_login_err')->get('l_err_'. USER_IP);
$need_captcha = $cache->has('l_err_'. USER_IP);
if ($need_captcha < $bb_cfg['invalid_logins']) $need_captcha = false;
}
@ -93,8 +99,8 @@ if (isset($_POST['login']))
if ($user->login($_POST, $mod_admin_login))
{
$redirect_url = (defined('FIRST_LOGON')) ? $bb_cfg['first_logon_redirect_url'] : $redirect_url;
// Обнуление при введении правильно комбинации логин/пароль
CACHE('bb_login_err')->set('l_err_'. USER_IP, 0, 3600);
// Удаление при введении правильной комбинации логин/пароль
$cache->delete('l_err_'. USER_IP);
if ($redirect_url == '/' . LOGIN_URL || $redirect_url == LOGIN_URL) $redirect_url = 'index.php';
redirect($redirect_url);
@ -102,17 +108,13 @@ if (isset($_POST['login']))
$login_errors[] = $lang['ERROR_LOGIN'];
if (!$mod_admin_login)
{
$login_err = CACHE('bb_login_err')->get('l_err_'. USER_IP);
if (!$mod_admin_login) {
$login_err = $cache->get('l_err_' . USER_IP);
if ($login_err > $bb_cfg['invalid_logins']) $need_captcha = true;
if ($login_err > 50)
{
// TODO: блокировка IP
}
CACHE('bb_login_err')->set('l_err_'. USER_IP, ($login_err + 1), 3600);
$cache->set('l_err_' . USER_IP, ($login_err + 1), 3600);
} else {
$need_captcha = false;
}
else $need_captcha = false;
}
}

View file

@ -1,7 +1,14 @@
<?php
define('BB_SCRIPT', 'vote');
require('./common.php');
define('BB_ROOT', './');
require_once __DIR__ . '/common.php';
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$user->session_start(array('req_login' => true));
@ -88,7 +95,7 @@ switch ($mode)
DB()->query("INSERT IGNORE INTO ". BB_POLL_USERS ." (topic_id, user_id, vote_ip, vote_dt) VALUES ($topic_id, {$userdata['user_id']}, '". USER_IP ."', ". TIMENOW .")");
CACHE('bb_poll_data')->rm("poll_$topic_id");
$cache->delete('poll_' . $topic_id);
bb_die($lang['VOTE_CAST']);
break;
@ -150,7 +157,7 @@ switch ($mode)
bb_die($poll->err_msg);
}
$poll->insert_votes_into_db($topic_id);
CACHE('bb_poll_data')->rm("poll_$topic_id");
$cache->delete('poll_' . $topic_id);
bb_die($lang['NEW_POLL_RESULTS']);
break;
@ -232,8 +239,15 @@ class bb_poll
function delete_votes_data ($topic_id)
{
DB()->query("DELETE FROM ". BB_POLL_VOTES ." WHERE topic_id = $topic_id");
DB()->query("DELETE FROM ". BB_POLL_USERS ." WHERE topic_id = $topic_id");
CACHE('bb_poll_data')->rm("poll_$topic_id");
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
DB()->query("DELETE FROM " . BB_POLL_VOTES . " WHERE topic_id = $topic_id");
DB()->query("DELETE FROM " . BB_POLL_USERS . " WHERE topic_id = $topic_id");
$cache->delete('poll_' . $topic_id);
}
}

View file

@ -7,6 +7,9 @@ require(BB_ROOT . 'common.php');
/** @var \TorrentPier\Di $di */
$di = \TorrentPier\Di::getInstance();
/** @var \TorrentPier\Cache\Adapter $cache */
$cache = $di->cache;
$page_cfg['include_bbcode_js'] = true;
$show_last_topic = true;
@ -36,7 +39,10 @@ $req_page = "forum_f{$forum_id}";
$req_page .= ($start) ? "_start{$start}" : '';
define('REQUESTED_PAGE', $req_page);
caching_output(IS_GUEST, 'send', REQUESTED_PAGE .'_guest');
if (IS_GUEST && $cache->has(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang'))) {
bb_exit($cache->get(REQUESTED_PAGE . '_guest_' . $di->config->get('default_lang')));
}
set_die_append_msg();
if (!$forums = $datastore->get('cat_forums'))