Предложи лучше вариант, чем языком чесать...мде... извините пожалуйста, но я очень окуел от данных кодов ! Это просто абзацц ! Вы на дле код гляньте....
Предложи лучше вариант, чем языком чесать... [2]мод в топку:
про код и логику писать не буду, все ужасно.
- Почему не использовать уже имеютщийся каркас torrentpier-а по работе с MySQL? Создаете лишний коннект к БД, дублирование кода, на счет безопасности тоже
- А табличку чистить не надо? это же такими темпами, 90% объема базы, займет табличка с реферерами.
- mysql_close - лучше вешайте на register_shutdown_function()
- Используйте mysql_real_escape_string
- И почему мускуль? Чем вам memcached не угодил? Опять же не целесообразно расходуете ресурсы.
PS.
Вам бы также следовало придерживатся стилистики кода torrentpier-а, раз вы сюда пишете. Ведь код который в архиве можно сказать - не читаем.
<?php
if($bb_cfg['ref_enable'])
{
$engine = array("yandex" => array("yandex.ru", "p", "text", "Яndex.ru",
"http://yandex.ru/", "yandex.png"), "rambler" => array("rambler.ru", "page",
"query", "Рамблер", "http://rambler.ru/", "rambler.png"), "mail" => array("mail.ru",
"sf", "q", "Mail.ru", "http://mail.ru/", "mail.png"), "aport" => array("aport.ru",
"p", "r", "Апорт", "http://aport.ru/", "aport.png"), "live" => array("live.com",
"first", "q", "Live Search", "http://search.live.com/", "live.png"), "google" =>
array("google.ru", "start", "q", "Google", "http://google.ru/", "google.png"),
"webalta" => array("webalta.ru", "page", "q", "WebAlta.ru", "http://webalta.ru/",
"webalta.png"), "yahoo" => array("yahoo.com", "b", "p", "Yahoo!",
"http://yahoo.com/", "yahoo.png"), "nigma" => array("nigma.ru", "startpos", "s",
"Nigma", "http://nigma.ru/", "nigma.png"), "icq" => array("search.icq.com", "sf",
"q", "ICQ Search", "http://search.icq.com/", "icq.png"), "qip" => array("search.qip.ru",
"", "query", "QIP Search", "http://start.qip.ru/", "qip.png"), "bing" => array("bing.com",
"first", "q", "Bing", "http://bing.com/", "bing.png"), );
$http_referer = (isset($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : '';
if ($http_referer) {
if($bb_cfg['sea_facer'] == "yes") {
if(preg_match("/[<](script|iframe)+(.*?)[>]/", html_entity_decode( urldecode( rawurldecode ( $_SERVER['HTTP_REFERER'] . $_SERVER['REQUEST_URI'] ) ) ) . $_SERVER['HTTP_USER_AGENT'] )) {
die ( "Переход заблокирован, перенаправление:<br /><br />Пожалуйста, нажмите <a href=\"{$bb_cfg['server_name']}\">сюда</a>." );
}
}
function referer_encoder ($value) {
$value = str_replace( "<?", "<?", $value );
$value = str_replace( "?>", "?>", $value );
$value = preg_replace( "#<iframe#i", "<iframe", $value );
$value = preg_replace( "#<script#i", "<script", $value );
$value = str_replace( "{", "{", $value );
return $value;
}
# Функция определения домена из ссылки
function clear_host ($url) {
$value = str_replace ('http://', '', $url);
$value = str_replace ('www.', '', $value);
$value = explode ('/', $value);
$value = reset ($value);
return strtolower ($value);
}
function getKeyWord( $q, $word ) {
$referer = urldecode(rawurldecode( $q ));
$parsed_string = parse_url( $referer );
parse_str ( $parsed_string['query'], $parsed_params );
$tmp = $parsed_params[$word];
if (!$tmp) {
preg_match("/{$word}=([^&]*)/i", $referer, $request);
$tmp = $request[1];
}
if($tmp) $tmp = @iconv("utf-8", "windows-1251", $tmp);
return $tmp;
}
# Получаем информацию
$datetime = TIMENOW; # текущее время
$request_uri = @$db->escape( htmlspecialchars( strip_tags( stripslashes( trim( $_SERVER['REQUEST_URI'] ) ) ), ENT_QUOTES ) );
$http_referer = @$db->escape( htmlspecialchars( strip_tags( stripslashes( trim( $http_referer ) ) ), ENT_QUOTES ) ) ;
$user_agent = @$db->escape( htmlspecialchars( strip_tags( stripslashes( trim( $_SERVER['HTTP_USER_AGENT'] ) ) ), ENT_QUOTES ) );
$ip = $db->escape( $_SERVER['REMOTE_ADDR'] );
$homeurl = clear_host ( $_SERVER['HTTP_HOST'] );
$http_referer = str_replace ('www.', '', $http_referer); # вырезаем www.
$host_referer = clear_host ( $http_referer ); # домен реферала
if(stristr($host_referer, 'yandex.')) $host_referer = "yandex";
if(stristr($host_referer, 'rambler.')) $host_referer = "rambler";
if(stristr($host_referer, 'mail.')) $host_referer = "mail";
if(stristr($host_referer, 'aport.')) $host_referer = "aport";
if(stristr($host_referer, '.live.')) $host_referer = "live";
if(stristr($host_referer, 'google.')) $host_referer = "google";
if(stristr($host_referer, 'webalta.')) $host_referer = "webalta";
if(stristr($host_referer, 'yahoo.')) $host_referer = "yahoo";
if(stristr($host_referer, 'nigma.')) $host_referer = "nigma";
if(stristr($host_referer, '.icq.')) $host_referer = "google";
if(stristr($host_referer, '.qip.')) $host_referer = "qip";
if(stristr($host_referer, 'bing.')) $host_referer = "bing";
$request = "";
if (@$engine[$host_referer]['3']) {
@$request = @$db->escape( referer_encoder( htmlspecialchars( strip_tags( stripslashes( trim( getKeyWord($http_referer, $engine[$host_referer]['2'], $engine[$host_referer]['1'] ) ) ) ) , ENT_QUOTES ) ) );
$is_referer = 'engine';
} else $is_referer = 'referer';
$pack_ignor = array();
if($bb_cfg['site_ignor']) $pack_ignor = @explode(", ", $bb_cfg['site_ignor']);
array_push($pack_ignor, $homeurl); # добавляем свой сайт в список игнорируемых
$ip_ignor = array();
if($bb_cfg['ip_ignor']) $ip_ignor = @explode(", ", $bb_cfg['ip_ignor']);
# выполняем, если сайт не в игноре и переменная не пуста
if (!in_array($host_referer, $pack_ignor) && !in_array($ip, $ip_ignor) && trim($http_referer)) {
$position = "";
# смотрим куда именно попали
if (@$subaction == "showfull") $position .= "%news%";
elseif (@$category_id) $position .= "%cat%";
elseif (!empty($nam_e)) $position .= "%posin%";
elseif (empty($nam_e)) $position .= "%main%";
if (@$nam_e) $position .= @$nam_e;
if (@$titl_e) $position .= @$titl_e;
$position = $db->escape($position);
$http_referer = referer_encoder($http_referer);
if ($is_referer == "engine") {
# выполняем проверку на повторение поисковиков
$refexist = $db->fetch_row("SELECT COUNT(*) as count FROM bb_referer WHERE request = '{$request}' AND host = '{$host_referer}'");
if ($refexist['count']) {
$db->query("UPDATE bb_referer SET hits=hits+1, uri='{$request_uri}', position='{$position}', date='{$datetime}', user_ip='{$ip}', user_agent='{$user_agent}' WHERE request = '{$request}' AND host = '{$host_referer}'");
} else {
$db->query("INSERT INTO bb_referer VALUES(null, '{$http_referer}', '{$datetime}', '{$host_referer}', '1', '{$request}', '{$request_uri}', '{$position}', '{$ip}', '{$is_referer}', '{$user_agent}')");
}
} else {
# выполняем проверку на повторение
$refexist = $db->fetch_row("SELECT COUNT(*) as count FROM bb_referer WHERE referer = '{$http_referer}'");
if ($refexist['count']) {
$db->query("UPDATE bb_referer SET hits=hits+1, uri='{$request_uri}', request='{$request}', position='{$position}', date='{$datetime}', user_ip='{$ip}', user_agent='{$user_agent}' WHERE referer='{$http_referer}'");
} else {
$db->query("INSERT INTO bb_referer VALUES (null, '{$http_referer}', '{$datetime}', '{$host_referer}', '1', '{$request}', '{$request_uri}', '{$position}', '{$ip}', '{$is_referer}', '{$user_agent}')");
}
}
}
}
}
?>
// Ref
$bb_cfg['sea_facer'] = "yes";
$bb_cfg['site_ignor'] = "";
$bb_cfg['ip_ignor'] = "";
$bb_cfg['ref_enable'] = true;
$bb_cfg['ref_days_keep'] = 2;
<?php
/*
This file is part of TorrentPier
TorrentPier is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
TorrentPier is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GPL 2.0 should have been included with the program.
If not, see http://www.gnu.org/licenses/
Official SVN repository and contact information can be found at
http://code.google.com/p/torrentpier/
*/
define('IN_PHPBB', true);
define('BB_ROOT', './');
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require(BB_ROOT ."common.$phpEx");
define('REF_COUNT', 50);
// Start session management
$user->session_start();
$link = '';
$query = $db->query("SELECT * FROM bb_referer WHERE type = 'engine' AND request != '' ORDER BY date DESC LIMIT 0,".REF_COUNT."");
while($row = $db->sql_fetchrow($query))
{
$template->assign_block_vars('refrow', array(
'REFERER' => ($row['referer']) ? '<a href="'.$row['referer'].'" target="_blank" />'.str_short($row['referer'], 60).'</a>' : '',
'DATE' => create_date($bb_cfg['default_dateformat'], $row['date'], $bb_cfg['board_timezone']),
'HOST' => '<img src="images/referer/'.$row['host'].'.png" align="absmiddle" alt="'.$row['host'].'" />',
'HITS' => $row['hits'],
'REQUEST' => '<a href="'.$row['uri'].'" />'.$row['request'].'</a>',
'USER_AGENT' => user_browser($row['user_agent']),
'USER_OS' => user_os($row['user_agent']),
));
}
function user_browser($useragent)
{
$arr = array("#.*MSIE (\S*);.*#si" =>
"<img src=images/referer/browser/ie.png align=absmiddle /> Internet Explorer \\1",
"#.*(Opera.*Version|Opera)/(\S*).*#si" =>
"<img src=images/referer/browser/opera.png /> Opera \\2", "#.*Navigator/(\S*).*#si" =>
"Navigator \\1", "#.*Flock/(\S*).*#si" => "Flock \\1", "#.*Firefox/(\S*).*#si" =>
"<img src=images/referer/browser/firefox.png align=absmiddle /> Firefox \\1",
"#.*Chrome/(\S*).*#si" =>
"<img src=images/referer/browser/chrome.png align=absmiddle /> Chrome \\1",
"#.*Version/(\S*).*Safari.*#si" => "Safari \\1", "#.*Safari/(\S*).*#si" =>
"<img src=images/referer/browser/safari.png /> Safari \\1",
"#.*K-Meleon.*#si" => "K-Meleon", "#.*SeaMonkey.*#si" => "SeaMonkey",
"#.*Camino.*#si" => "Camino", "#.*Epiphany.*#si" => "Epiphany",
"#.*America Online Browser.*#si" => "America Online Browser",
"#.*avantbrowser.*#si" => "Avant Browser.");
$result = preg_replace(array_keys($arr), $arr, $useragent);
if (!$result)
$result = "---";
return $result;
}
function user_os($useragent)
{
$arr = array("#.*Windows NT 5.1.*#si" =>
"<img src=images/referer/system/xp.png /> Windows XP",
"#.*Windows NT 5.2.*#si" =>
"<img src=images/referer/system/xp64.png /> Windows XP x64 or Server 2003",
"#.*Windows NT 6.0.*#si" =>
"<img src=images/referer/system/vista.png /> Windows Vista",
"#.*Windows NT 6.1.*#si" =>
"<img src=images/referer/system/win7.png align=absmiddle /> Windows 7",
"#.*Windows NT 5.0.*#si" =>
"<img src=images/referer/system/win2000.png /> Windows 2000",
"#.*(Windows NT 4.0|Windows NT 3.5).*#si" => "Windows NT", "#.*Windows CE.*#si" =>
"Windows CE or Mobile", "#.*Windows Me.*#si" => "Windows ME",
"#.*Windows 98.*#si" => "Windows 98", "#.*Windows 95.*#si" => "Windows 95",
"#.*(Linux|Lynx|Unix).*#si" =>
"<img src=images/referer/system/linux.png /> Linux",
"#.*(Macintosh|PowerPC).*#si" =>
"<img src=images/referer/system/mac.png /> MacOS", "#.*OS/2.*#si" =>
"OS/2", "#.*BeOS.*#si" => "BeOS");
$result = preg_replace(array_keys($arr), $arr, $useragent);
if (!$result)
$result = "---";
return $result;
}
print_page('referer.tpl');
<table width="100%" cellspacing="2" border="0" align="center" cellpadding="2">
<tr>
<td class="nav w100" style="padding-left: 8px;">
<a href="{U_INDEX}">{T_INDEX}</a>
<em>»</em> <a href="referer.php">Переходы</a>
</td>
</tr>
</table>
<table border="0" cellpadding="4" cellspacing="1" width="100%" class="forumline">
<tr>
<th class="thCornerL" align="center">Переход с</th>
<th class="thTop" align="center"> Дата </th>
<th class="thTop" align="center"> Хост </th>
<th class="thTop" align="center"> Хитов </th>
<th class="thCornerR" align="center"> Запрос </th>
<th class="thCornerR" align="center"> Браузер </th>
<th class="thCornerR" align="center"> ОС </th>
</tr>
<!-- BEGIN refrow -->
<tr>
<td class="row1" valign="middle">{refrow.REFERER}</td>
<td class="row1" valign="middle">{refrow.DATE}</td>
<td class="row1 tCenter" valign="middle">{refrow.HOST}</td>
<td class="row1" valign="middle">{refrow.HITS}</td>
<td class="row1" valign="middle">{refrow.REQUEST}</td>
<td class="row1" valign="middle">{refrow.USER_AGENT}</td>
<td class="row1" valign="middle">{refrow.USER_OS}</td>
</tr>
<!-- END refrow -->
<tr>
<td class="catBottom" colspan="7"> </td>
</tr>
</table>
<?php
if (!defined('BB_ROOT')) die(basename(__FILE__));
$ref_days_keep = (int) $bb_cfg['ref_days_keep'];
$db->query("
DELETE FROM bb_referer
WHERE date < ". (TIMENOW - 86400*$ref_days_keep) ."
");
function ref_update()
{
global $db;
$link = '';
$query = $db->query("SELECT * FROM bb_referer WHERE type = 'engine' AND request != '' ORDER BY date DESC LIMIT 0,20");
while($row = $db->sql_fetchrow($query))
{
$link .= '<img style="padding: 1px 0 1px 0" src="images/referer/'.$row['host'].'.png" align="absmiddle" />: <a href="'.$row['uri'].'" title="'.$row['request'].'">'.str_short($row['request'], 25).'</a><br />';
}
$this->response['html'] = $link;
}
CREATE TABLE IF NOT EXISTS `bb_referer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`referer` varchar(255) NOT NULL DEFAULT '',
`date` varchar(20) DEFAULT NULL,
`host` varchar(125) NOT NULL DEFAULT '',
`hits` smallint(6) DEFAULT '0',
`request` text NOT NULL,
`uri` varchar(255) NOT NULL DEFAULT '',
`position` text NOT NULL,
`user_ip` varchar(16) NOT NULL DEFAULT '',
`type` varchar(10) NOT NULL DEFAULT '',
`user_agent` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Notice: Undefined variable: db in /home/admin/public_html/referer.php on line 34 Fatal error: Call to a member function query() on a non-object in /home/admin/public_html/referer.php on line 34