View Full Version : Оптимизация PHP-NUKE
Ни для кого не секрет, что PHP-Nuke является очень ресурсно-потребной системой, и при посещаемости сайта, основанного на php-nuke, свыше 800 уникальных заходов в день, ваш сайт будет перегружать и Базу Данных, и собственно, сам сервер. Следствие чего хостнг-провайдер попросит вас, либо сменить cms, либо перейти на выделенный сервер. И они будут правы, т.к. в среднем (при наборе стандартных модулей и блоков) каждая открываемая страница пользователем производит порядка 80-120 запросов к БД (порой бывает даже 300 запросов), что из ряда вон много. Все это из-за того что php-nuke написана очень просто и использует наиболее легкие методы исполнения работы скрипта, что результат увеличение запросов к БД.
В данной теме мы постараемся максимально снизить нагрузку с БД и php, но не изменить структуру php-nuke. Так же будет по ходу выполнения исправлять допущенные ошибки автором в скриптах.
За основу взята php-nuke версии 7.9 (без каких либо патчей).
Помните, что при изменения кода, заранее запаситесь бекапом файлов вашего сайта и, пожалуй, бекапом базы. Будьте внимательны при изменении кода, тем более, если у вас отличающаяся версия от 7.9, заменять надо не в один в один, а с пониманием и сравнивая строки с вашей версии и добавляя изменения! Особенно обратите внимание на используемую функцию filter() в обработке переменных, она добавлена в 7.9 версии, а, следовательно, ее не будет в версиях ниже, значит, в коде ее у вас не должно быть!
Чтобы узнать, сколько в данный момент у вас выполняет сайт запросов к БД, проследуйте в эту тему форума (http://forum.mynuke.ru/showthread.php?t=44) и произведите изменения указанные там.
Тема для обсуждения (http://forum.mynuke.ru/showthread.php?t=1273)
Начнем мы с оптимизации «ядра» системы. А именно с файла mainfile.php
1. В целях повышения безопасности ограничиваем поступление переменных $admin и $user
Находим:
if(isset($admin))
{
$admin = base64_decode($admin);
$admin = addslashes($admin);
$admin = base64_encode($admin);
}
if(isset($user))
{
$user = base64_decode($user);
$user = addslashes($user);
$user = base64_encode($user);
}
Заменяем на:
// Copyright Soniks http://mynuke.ru
if(isset($_COOKIE['admin']))
{
$admin = base64_decode($_COOKIE['admin']);
$admin = addslashes($admin);
$admin = base64_encode($admin);
}else{
unset($admin);
}
if(isset($_COOKIE['user']))
{
$user = base64_decode($_COOKIE['user']);
$user = addslashes($user);
$user = base64_encode($user);
}else{
unset($user);
}
2. Изменим вызов конфиг файла и подключение к бд, находим:
if (defined('FORUM_ADMIN')) {
require_once("../../../config.php");
require_once("../../../db/db.php");
} elseif (defined('INSIDE_MOD')) {
require_once("../../config.php");
require_once("../../db/db.php");
} else {
require_once("config.php");
require_once("db/db.php");
/* FOLLOWING TWO LINES ARE DEPRECATED BUT ARE HERE FOR OLD MODULES COMPATIBILITY */
/* PLEASE START USING THE NEW SQL ABSTRACTION LAYER. SEE MODULES DOC FOR DETAILS */
require_once("includes/sql_layer.php");
$dbi = sql_connect($dbhost, $dbuname, $dbpass, $dbname);
}
и заменим на:
if (defined('FORUM_ADMIN')) {
define('NUKE_PATH', '../../../');
require_once(NUKE_PATH."config.php");
require_once(NUKE_PATH."db/db.php");
} elseif (defined('INSIDE_MOD')) {
define('NUKE_PATH', '../../');
require_once(NUKE_PATH."config.php");
require_once(NUKE_PATH."db/db.php");
} else {
define('NUKE_PATH', './');
require_once(NUKE_PATH."config.php");
require_once(NUKE_PATH."db/db.php");
/* FOLLOWING TWO LINES ARE DEPRECATED BUT ARE HERE FOR OLD MODULES COMPATIBILITY */
/* PLEASE START USING THE NEW SQL ABSTRACTION LAYER. SEE MODULES DOC FOR DETAILS */
require_once("includes/sql_layer.php");
$dbi = sql_connect($dbhost, $dbuname, $dbpass, $dbname);
}
Обратите здесь внимание на строки:
/* FOLLOWING TWO LINES ARE DEPRECATED BUT ARE HERE FOR OLD MODULES COMPATIBILITY */
/* PLEASE START USING THE NEW SQL ABSTRACTION LAYER. SEE MODULES DOC FOR DETAILS */
require_once("includes/sql_layer.php");
$dbi = sql_connect($dbhost, $dbuname, $dbpass, $dbname);
если вы не используете модули или блоки от старых версий phpnuke, то удалите эти строчки, это позволит снизить нагрузку к БД.
3. Если у вас в mainfile.php нет такой записи, то добавляем ее в начало файла на следующей строчке после <?php :
define('NUKE_FILE', true);
4. Теперь уберем один запрос из системы посредством кэширования статичной информации в файл. Для этого находим:
$result = $db->sql_query("SELECT * FROM ".$prefix."_config");
$row = $db->sql_fetchrow($result);
$sitename = filter($row['sitename'], nohtml);
$nukeurl = filter($row['nukeurl'], nohtml);
$site_logo = filter($row['site_logo'], nohtml);
$slogan = filter($row['slogan'], nohtml);
$startdate = filter($row['startdate'], nohtml);
$adminmail = filter($row['adminmail'], nohtml);
$anonpost = intval($row['anonpost']);
$Default_Theme = filter($row['Default_Theme'], nohtml);
$foot1 = filter($row['foot1']);
$foot2 = filter($row['foot2']);
$foot3 = filteR($row['foot3']);
$commentlimit = intval($row['commentlimit']);
$anonymous = filter($row['anonymous'], nohtml);
$minpass = intval($row['minpass']);
$pollcomm = intval($row['pollcomm']);
$articlecomm = intval($row['articlecomm']);
$broadcast_msg = intval($row['broadcast_msg']);
$my_headlines = intval($row['my_headlines']);
$top = intval($row['top']);
$storyhome = intval($row['storyhome']);
$user_news = intval($row['user_news']);
$oldnum = intval($row['oldnum']);
$ultramode = intval($row['ultramode']);
$banners = intval($row['banners']);
$backend_title = filter($row['backend_title'], nohtml);
$backend_language = filter($row['backend_language'], nohtml);
$language = filter($row['language'], nohtml);
$locale = filter($row['locale'], nohtml);
$multilingual = intval($row['multilingual']);
$useflags = intval($row['useflags']);
$notify = intval($row['notify']);
$notify_email = filter($row['notify_email'], nohtml);
$notify_subject = filter($row['notify_subject'], nohtml);
$notify_message = filter($row['notify_message'], nohtml);
$notify_from = filter($row['notify_from'], nohtml);
$moderate = intval($row['moderate']);
$admingraphic = intval($row['admingraphic']);
$httpref = intval($row['httpref']);
$httprefmax = intval($row['httprefmax']);
$CensorMode = intval($row['CensorMode']);
$CensorReplace = filter($row['CensorReplace'], nohtml);
$copyright = filter($row['copyright']);
$Version_Num = filter($row['Version_Num'], nohtml);
и заменяем на:
// Copyright Soniks http://mynuke.ru
// GET CONFIG VARIABLE
$userinfo = array();
if(file_exists(NUKE_PATH."cache/config")){
include_once(NUKE_PATH."cache/config");
}else{
$result = $db->sql_query("SELECT * FROM ".$prefix."_config LIMIT 1");
$sett ="<?php\n\n";
$sett .="if(!defined('NUKE_FILE'))\n{\n die();\n}\n";
foreach(mysql_fetch_assoc($result) as $key => $value){
$$key = $value;
$sett .="$".$key." = \"".str_replace('"','\"',$value)."\";\n";
}
$sett .="\n?>";
$fp = fopen (NUKE_PATH."cache/config", "wb");
fwrite($fp, $sett);
fclose($fp);
if(!file_exists(NUKE_PATH."cache/.htaccess")){
$sett2 ="deny from all";
$fp2 = fopen (NUKE_PATH."cache/.htaccess", "wb");
fwrite($fp2, $sett2);
fclose($fp2);
}
}
// GET MODULES
$modules_info = array();
$result = $db->sql_query("SELECT title, custom_title, active, view, inmenu, mod_group FROM ".$prefix."_modules");
while (list($title_cnf, $custom_title_cnf, $active_cnf, $view_cnf, $inmenu_cnf, $mod_group_cnf) = $db->sql_fetchrow($result)){
$modules_info[$title_cnf] = array('custom_title' =>$custom_title_cnf, 'active'=>$active_cnf, 'view'=>$view_cnf, 'inmenu'=>$inmenu_cnf, 'mod_group'=>$mod_group_cnf);
}
После этого создаем в главной директории папку с именем cache и назначаем права на запись (775 или 777).
5. Изменим, функции определения админа, пользователя и принадлежности пользователя к группе, находим:
function is_admin($admin) {
global $prefix, $db;
if(!is_array($admin)) {
$admin = base64_decode($admin);
$admin = addslashes($admin);
$admin = explode(":", $admin);
$aid = addslashes($admin[0]);
$pwd = "$admin[1]";
} else {
$aid = addslashes($admin[0]);
$pwd = "$admin[1]";
}
if ($aid != "" AND $pwd != "") {
$aid = substr("$aid", 0,25);
$result = $db->sql_query("SELECT pwd FROM ".$prefix."_authors WHERE aid='$aid'");
$row = $db->sql_fetchrow($result);
$pass = $row['pwd'];
if($pass == $pwd && $pass != "") {
return 1;
}
}
return 0;
}
function is_user($user) {
global $prefix, $db, $user_prefix;
if(!is_array($user)) {
$user = base64_decode($user);
$user = addslashes($user);
$user = explode(":", $user);
$uid = "$user[0]";
$pwd = "$user[2]";
} else {
$uid = "$user[0]";
$pwd = "$user[2]";
}
$uid = addslashes($uid);
$uid = intval($uid);
if ($uid != "" AND $pwd != "") {
$result = $db->sql_query("SELECT user_password FROM ".$user_prefix."_users WHERE user_id='$uid'");
$row = $db->sql_fetchrow($result);
$pass = $row['user_password'];
if($pass == $pwd && $pass != "") {
return 1;
}
}
return 0;
}
function is_group($user, $name) {
global $prefix, $db, $user_prefix;
if(!is_array($user)) {
$user = base64_decode($user);
$user = addslashes($user);
$user = explode(":", $user);
$uid = "$user[0]";
$pwd = "$user[2]";
} else {
$uid = "$user[0]";
$uid = intval($uid);
$pwd = "$user[2]";
}
if ($uid != "" AND $pwd != "") {
$result = $db->sql_query("SELECT user_password FROM ".$user_prefix."_users WHERE user_id='$uid'");
$row = $db->sql_fetchrow($result);
$pass = $row['user_password'];
if($pass == $pwd && $pass != "") {
$result2 = $db->sql_query("SELECT points FROM ".$user_prefix."_users WHERE user_id='$uid'");
$row2 = $db->sql_fetchrow($result2);
$points = intval($row2['points']);
$result3 = $db->sql_query("SELECT mod_group FROM ".$prefix."_modules WHERE title='$name'");
$row3 = $db->sql_fetchrow($result3);
$mod_group = $row3['mod_group'];
$result4 = $db->sql_query("SELECT points FROM ".$prefix."_groups WHERE id='$mod_group'");
$row4 = $db->sql_fetchrow($result4);
$grp = intval($row4['points']);
if (($points >= 0 AND $points >= $grp) OR $mod_group == 0) {
return 1;
}
}
}
return 0;
}
Заменяем на:
// Copyright Soniks http://mynuke.ru
function is_admin($admin) {
global $prefix, $db;
if(defined("ADMIN_SET")) return true;
elseif(defined("NOT_ADMIN_SET")) return false;
else{
if(!is_array($admin)) {
$admin = base64_decode($admin);
$admin = addslashes($admin);
$admin = explode(":", $admin);
$aid = addslashes($admin[0]);
$pwd = "$admin[1]";
} else {
$aid = addslashes($admin[0]);
$pwd = "$admin[1]";
}
if ($aid != "" AND $pwd != "") {
$aid = substr("$aid", 0,25);
$result = $db->sql_query("SELECT pwd FROM ".$prefix."_authors WHERE aid='$aid'");
$row = $db->sql_fetchrow($result);
$pass = $row['pwd'];
if($pass == $pwd && $pass != "") {
define("ADMIN_SET", true);
return true;
}
}
define("NOT_ADMIN_SET", true);
return false;
}
}
// Copyright Soniks http://mynuke.ru
if(!defined("USER_SET") and !defined("NOT_USER_SET") and $user){
if(!is_array($user)) {
$user_main = base64_decode($user);
$user_main = addslashes($user_main);
$user_main = explode(":", $user_main);
$uid_main = "$user_main[0]";
$pwd_main = "$user_main[2]";
} else {
$uid_main = "$user[0]";
$pwd_main = "$user[2]";
}
$uid_main = addslashes($uid_main);
$uid_main = intval($uid_main);
if ($uid_main != "" AND $pwd_main != "") {
$result_main = $db->sql_query("SELECT * FROM ".$user_prefix."_users WHERE user_id='$uid_main' LIMIT 1");
$userinfo = $db->sql_fetchrow($result_main);
$pass_main = $userinfo['user_password'];
if($pass_main == $pwd_main && $pass_main != "") {
define("USER_SET", true);
}else{
define("NOT_USER_SET", true);
}
}else{
define("NOT_USER_SET", true);
}
}elseif(!defined("USER_SET") and !defined("NOT_USER_SET") and !$user){
define("NOT_USER_SET", true);
}
// Copyright Soniks http://mynuke.ru
function is_user($user) {
if(defined("USER_SET")) return true;
if(defined("NOT_USER_SET")) return false;
}
// Copyright Soniks http://mynuke.ru
function is_group($user, $name) {
global $prefix, $db, $userinfo, $group_use;
if (is_user($user) and $group_use==1) {
$result = $db->sql_query("SELECT m.mod_group, g.points FROM ".$prefix."_modules AS m LEFT JOIN ".$prefix."_groups AS g ON(g.id=m.mod_group) WHERE m.title='".addslashes($name)."' LIMIT 1");
$group_info = $db->sql_fetchrow($result);
$points = intval($userinfo['points']);
$mod_group = intval($group_info['mod_group']);
$grp = intval($group_info['points']);
if (($points >= 0 AND $points >= $grp) OR $mod_group == 0) {
return 1;
}
}elseif($group_use==0) return 1;
return 0;
}
Таким образом мы имеем глобальную переменную $userinfo которая содержит в себе всю информацию о пользователе.
6. Изменим функцию подсчета заработанных пользователем балов на сайте, находим:
function update_points($id) {
global $user_prefix, $prefix, $db, $user;
if (is_user($user)) {
if(!is_array($user)) {
$user1 = base64_decode($user);
$user1 = addslashes($user1);
$user1 = explode(":", $user1);
$username = "$user1[1]";
} else {
$username = "$user1[1]";
}
if ($db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_groups")) > '0') {
$id = intval($id);
$result = $db->sql_query("SELECT points FROM ".$prefix."_groups_points WHERE id='$id'");
$row = $db->sql_fetchrow($result);
$rpoints = intval($row['points']);
$db->sql_query("UPDATE ".$user_prefix."_users SET points=points+" . $rpoints . " WHERE username='$username'");
}
}
}
Заменяем ее на:
// Copyright Soniks http://mynuke.ru
function update_points($id_point) {
global $user_prefix, $prefix, $db, $user, $userinfo, $group_use, $groups_points, $admin;
if (is_user($user) and $group_use==1 and !is_admin($admin)) {
if(!is_array($groups_points) or empty($groups_points)){
$result = $db->sql_query("SELECT id, points FROM ".$prefix."_groups_points");
$groups_points = array();
while(list($id, $points) = $db->sql_fetchrow($result)){
$groups_points[$id] = $points;
}
}
$rpoints = intval($groups_points[$id_point]);
if($rpoints != 0) $db->sql_query("UPDATE ".$user_prefix."_users SET points=points+" . $rpoints . " WHERE user_id='".intval($userinfo['user_id'])."'");
}
}
7. Обновим функцию проверки на активность модуля и функции, работающие с блоками, находим:
function is_active($module) {
global $prefix, $db;
$module = trim($module);
$result = $db->sql_query("SELECT active FROM ".$prefix."_modules WHERE title='$module'");
$row = $db->sql_fetchrow($result);
$act = intval($row['active']);
if (!$result OR $act == 0) {
return 0;
} else {
return 1;
}
}
function render_blocks($side, $blockfile, $title, $content, $bid, $url) {
if ($url == "") {
if ($blockfile == "") {
if ($side == "c") {
themecenterbox($title, $content);
} elseif ($side == "d") {
themecenterbox($title, $content);
} else {
themesidebox($title, $content);
}
} else {
if ($side == "c") {
blockfileinc($title, $blockfile, 1);
} elseif ($side == "d") {
blockfileinc($title, $blockfile, 1);
} else {
blockfileinc($title, $blockfile);
}
}
} else {
if ($side == "c" OR $side == "d") {
headlines($bid,1);
} else {
headlines($bid);
}
}
}
function blocks($side) {
global $storynum, $prefix, $multilingual, $currentlang, $db, $admin, $user;
if ($multilingual == 1) {
$querylang = "AND (blanguage='$currentlang' OR blanguage='')";
} else {
$querylang = "";
}
if (strtolower($side[0]) == "l") {
$pos = "l";
} elseif (strtolower($side[0]) == "r") {
$pos = "r";
} elseif (strtolower($side[0]) == "c") {
$pos = "c";
} elseif (strtolower($side[0]) == "d") {
$pos = "d";
}
$side = $pos;
$sql = "SELECT bid, bkey, title, content, url, blockfile, view, expire, action, subscription FROM ".$prefix."_blocks WHERE bposition='$pos' AND active='1' $querylang ORDER BY weight ASC";
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result)) {
$bid = intval($row['bid']);
$title = filter($row['title'], nohtml);
$content = $row['content'];
$url = filter($row['url'], nohtml);
$blockfile = filter($row['blockfile'], nohtml);
$view = intval($row['view']);
$expire = intval($row['expire']);
$action = filter($row['action'], nohtml);
$action = substr("$action", 0,1);
$now = time();
$sub = intval($row['subscription']);
if ($sub == 0 OR ($sub == 1 AND !paid())) {
if ($expire != 0 AND $expire <= $now) {
if ($action == "d") {
$db->sql_query("UPDATE ".$prefix."_blocks SET active='0', expire='0' WHERE bid='$bid'");
return;
} elseif ($action == "r") {
$db->sql_query("DELETE FROM ".$prefix."_blocks WHERE bid='$bid'");
return;
}
}
if ($row == admin) {
adminblock();
} elseif ($row[bkey] == userbox) {
userblock();
} elseif ($row[bkey] == "") {
if ($view == 0) {
render_blocks($side, $blockfile, $title, $content, $bid, $url);
} elseif ($view == 1 AND is_user($user) || is_admin($admin)) {
render_blocks($side, $blockfile, $title, $content, $bid, $url);
} elseif ($view == 2 AND is_admin($admin)) {
render_blocks($side, $blockfile, $title, $content, $bid, $url);
} elseif ($view == 3 AND !is_user($user) || is_admin($admin)) {
render_blocks($side, $blockfile, $title, $content, $bid, $url);
}
}
}
}
}
Заменяем на:
// Copyright Soniks http://mynuke.ru
function is_active($module) {
global $modules_info;
$module = trim($module);
$act = intval($modules_info[$module]['active']);
if ($act == 1) {
return 1;
} else {
return 0;
}
}
// Copyright Soniks http://mynuke.ru
function render_blocks($side, $blockinfo) {
if ($blockinfo['url'] == "") {
if ($blockinfo['blockfile'] == "") {
if ($side == "c") {
themecenterbox($blockinfo['title'], $blockinfo['content']);
} elseif ($side == "d") {
themecenterbox($blockinfo['title'], $blockinfo['content']);
} else {
themesidebox($blockinfo['title'], $blockinfo['content']);
}
} else {
if ($side == "c") {
blockfileinc($blockinfo['title'], $blockinfo['blockfile'], 1);
} elseif ($side == "d") {
blockfileinc($blockinfo['title'], $blockinfo['blockfile'], 1);
} else {
blockfileinc($blockinfo['title'], $blockinfo['blockfile']);
}
}
} else {
if ($side == "c" OR $side == "d") {
headlines($blockinfo,1);
} else {
headlines($blockinfo);
}
}
}
// Copyright Soniks http://mynuke.ru
function blocks($side) {
global $storynum, $prefix, $multilingual, $currentlang, $db, $admin, $user, $block_info;
if(!is_array($block_info) or empty($block_info)){
$block_info = array();
if ($multilingual == 1) {
$querylang = "AND (blanguage='$currentlang' OR blanguage='')";
} else {
$querylang = "";
}
$result = $db->sql_query("SELECT bid, bkey, title, content, url, bposition, weight, blockfile, view, expire, action, subscription, refresh, time FROM ".$prefix."_blocks WHERE active='1' $querylang ORDER BY bposition, weight ASC");
while($row = $db->sql_fetchrow($result)) {
$bid = intval($row['bid']);
$bkey = filter($row['bkey'], nohtml);
$title = filter($row['title'], nohtml);
$content = $row['content'];
$url = filter($row['url'], nohtml);
$blockfile = filter($row['blockfile'], nohtml);
$view = intval($row['view']);
$expire = intval($row['expire']);
$action = filter($row['action'], nohtml);
$action = substr("$action", 0,1);
$sub = intval($row['subscription']);
$refresh = intval($row['refresh']);
$time = intval($row['time']);
$block_info[$row['bposition']][] = array('bid'=>$bid, 'bkey'=>$bkey, 'title'=>$title, 'content'=>$content, 'url'=>$url, 'blockfile'=>$blockfile, 'view'=>$view, 'expire'=>$expire, 'action'=>$action, 'subscription'=>$sub, 'refresh'=>$refresh, 'time'=>$time);
}
}
if (strtolower($side[0]) == "l") {
$pos = "l";
} elseif (strtolower($side[0]) == "r") {
$pos = "r";
} elseif (strtolower($side[0]) == "c") {
$pos = "c";
} elseif (strtolower($side[0]) == "d") {
$pos = "d";
}
$side = $pos;
if($block_info[$side]){
foreach($block_info[$side] as $value) {
$bid = $value['bid'];
$bkey = $value['bkey'];
$view = $value['view'];
$expire = $value['expire'];
$action = $value['action'];
$now = time();
$sub = $value['subscription'];
if ($sub == 0 OR ($sub == 1 AND !paid())) {
if ($expire != 0 AND $expire <= $now) {
if ($action == "d") {
$db->sql_query("UPDATE ".$prefix."_blocks SET active='0', expire='0' WHERE bid='$bid'");
return;
} elseif ($action == "r") {
$db->sql_query("DELETE FROM ".$prefix."_blocks WHERE bid='$bid'");
return;
}
}
if ($bkey == "admin") {
adminblock($value);
} elseif ($bkey == "userbox") {
userblock();
} elseif ($bkey == "") {
if ($view == 0) {
render_blocks($side, $value);
} elseif ($view == 1 AND is_user($user) || is_admin($admin)) {
render_blocks($side, $value);
} elseif ($view == 2 AND is_admin($admin)) {
render_blocks($side, $value);
} elseif ($view == 3 AND !is_user($user) || is_admin($admin)) {
render_blocks($side, $value);
}
}
}
}
}
}
[b]8. Облегчим функцию, отвечающая за сессии, находим:
function online() {
global $user, $cookie, $prefix, $db;
cookiedecode($user);
$ip = $_SERVER["REMOTE_ADDR"];
$uname = $cookie[1];
if (!isset($uname)) {
$uname = "$ip";
$guest = 1;
}
$past = time()-300;
$db->sql_query("DELETE FROM ".$prefix."_session WHERE time < '$past'");
$result = $db->sql_query("SELECT time FROM ".$prefix."_session WHERE uname='$uname'");
$ctime = time();
if ($uname!="") {
$uname = substr("$uname", 0,25);
if ($row = $db->sql_fetchrow($result)) {
$db->sql_query("UPDATE ".$prefix."_session SET uname='$uname', time='$ctime', host_addr='$ip', guest='$guest' WHERE uname='$uname'");
} else {
$db->sql_query("INSERT INTO ".$prefix."_session (uname, time, host_addr, guest) VALUES ('$uname', '$ctime', '$ip', '$guest')");
}
}
}
Заменяем на:
// Copyright Soniks http://mynuke.ru
function online() {
global $user, $prefix, $db, $userinfo;
$ip = $_SERVER["REMOTE_ADDR"];
$guest = 0;
$uname = $userinfo['username'];
if (!$uname) {
$uname = "$ip";
$guest = 1;
}
$past = time()-300;
$db->sql_query("DELETE FROM ".$prefix."_session WHERE time < '$past' OR uname='".addslashes($uname)."'");
$ctime = time();
if ($uname!="") {
$uname = substr("$uname", 0,25);
$db->sql_query("INSERT INTO ".$prefix."_session (uname, time, host_addr, guest) VALUES ('$uname', '$ctime', '$ip', '$guest')");
}
}
Так же выполняем SQL-запрос в phpMyAdmin:
DROP TABLE IF EXISTS `nuke_session`;
CREATE TABLE `nuke_session` (
`uname` varchar(25) NOT NULL default '',
`time` varchar(14) NOT NULL default '',
`host_addr` varchar(48) NOT NULL default '',
`guest` int(1) NOT NULL default '0',
KEY `time` (`time`),
KEY `guest` (`guest`)
) TYPE=HEAP;
не забываем в запросе заменить префиксы nuke_ на свои!
9. Облегчим функции, отвечающие за Ultramode (вывод заголовков новостей), информацию о пользователе по cookie и информация о пользователе из БД, находим:
function ultramode() {
global $prefix, $db;
$ultra = "ultramode.txt";
$file = fopen("$ultra", "w");
fwrite($file, "General purpose self-explanatory file with news headlines\n");
$result = $db->sql_query("SELECT sid, aid, title, time, comments, topic FROM ".$prefix."_stories ORDER BY time DESC LIMIT 0,10");
while ($row = $db->sql_fetchrow($result)) {
$rsid = intval($row['sid']);
$raid = filter($row['aid'], nohtml);
$rtitle = filter($row['title'], nohtml);
$rtime = $row['time'];
$rcomments = intval($row['comments']);
$rtopic = intval($row['topic']);
$row2 = $db->sql_fetchrow($db->sql_query("select topictext, topicimage from ".$prefix."_topics where topicid='$rtopic'"));
$topictext = filter($row2['topictext'], nohtml);
$topicimage = filter($row2['topicimage'], nohtml);
$content = "%%\n$rtitle\n/modules.php?name=News&file=article&sid=$rsid\n$rtime\n$raid\n$topictext\n$rcomments\n$topicimage\n";
fwrite($file, $content);
}
fclose($file);
}
function cookiedecode($user) {
global $cookie, $prefix, $db, $user_prefix;
$user = base64_decode($user);
$user = addslashes($user);
// $user = htmlentities($user, ENT_QUOTES);
$cookie = explode(":", $user);
$result = $db->sql_query("SELECT user_password FROM ".$user_prefix."_users WHERE username='$cookie[1]'");
$row = $db->sql_fetchrow($result);
$pass = $row['user_password'];
if ($cookie[2] == $pass && $pass != "") {
return $cookie;
} else {
unset($user);
unset($cookie);
}
}
function getusrinfo($user) {
global $userinfo, $user_prefix, $db;
$user2 = base64_decode($user);
$user2 = addslashes($user2);
$user3 = explode(":", $user2);
$result = $db->sql_query("SELECT * FROM ".$user_prefix."_users WHERE username='$user3[1]' AND user_password='$user3[2]'");
if ($db->sql_numrows($result) == 1) {
$userinfo = $db->sql_fetchrow($result);
}
return $userinfo;
}
Заменяем на:
// Copyright Soniks http://mynuke.ru
function ultramode() {
global $prefix, $db;
$ultra = "ultramode.txt";
$file = fopen("$ultra", "w");
fwrite($file, "General purpose self-explanatory file with news headlines\n");
$result = $db->sql_query("SELECT s.sid, s.aid, s.title, s.time, s.comments, t.topictext, t.topicimage FROM ".$prefix."_stories AS s LEFT JOIN ".$prefix."_topics AS t ON(t.topicid=s.topic) ORDER BY s.time DESC LIMIT 0,10");
while ($row = $db->sql_fetchrow($result)) {
$rsid = intval($row['sid']);
$raid = filter($row['aid'], nohtml);
$rtitle = filter($row['title'], nohtml);
$rtime = $row['time'];
$rcomments = intval($row['comments']);
$topictext = filter($row['topictext'], nohtml);
$topicimage = filter($row['topicimage'], nohtml);
$content = "%%\n$rtitle\n/modules.php?name=News&file=article&sid=$rsid\n$rtime\n$raid\n$topictext\n$rcomments\n$topicimage\n";
fwrite($file, $content);
}
fclose($file);
}
//Copyright Soniks http://mynuke.ru
function cookiedecode($user) {
global $cookie;
if(is_user($user)){
$user = base64_decode($user);
$user = addslashes($user);
$cookie = explode(":", $user);
return $cookie;
} else {
unset($user);
unset($cookie);
}
}
//Copyright Soniks http://mynuke.ru
function getusrinfo($user) {
global $userinfo;
return $userinfo;
}
10. Немного изменим блок администратора, но по-прежнему он будет производить 7 запросов к БД, такова цена информативности, тем более что это будет только для администратора и поэтому не столь значимо, находим:
function adminblock() {
global $admin, $prefix, $db, $admin_file;
if (is_admin($admin)) {
$result = $db->sql_query("SELECT title, content FROM ".$prefix."_blocks WHERE bkey='admin'");
while ($row = $db->sql_fetchrow($result)) {
$row[content] = filter($row[content]);
$row[title] = filter($row[title], nohtml);
$content = "<font class=\"content\">$row[content]</font>";
themesidebox($row[title], $row[content]);
}
$title = ""._WAITINGCONT."";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_queue"));
$content = "<font class=\"content\">";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=submissions\">"._SUBMISSIONS."</a>: $num<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_reviews_add"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=reviews\">"._WREVIEWS."</a>: $num<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_newlink"));
$brokenl = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_modrequest WHERE brokenlink='1'"));
$modreql = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_modrequest WHERE brokenlink='0'"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=Links\">"._WLINKS."</a>: $num<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=LinksListModRequests\">"._MODREQLINKS."</a>: $modreql<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=LinksListBrokenLinks\">"._BROKENLINKS."</a>: $brokenl<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_newdownload"));
$brokend = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_modrequest WHERE brokendownload='1'"));
$modreqd = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_modrequest WHERE brokendownload='0'"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=downloads\">"._UDOWNLOADS."</a>: $num<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=DownloadsListModRequests\">"._MODREQDOWN."</a>: $modreqd<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=DownloadsListBrokenDownloads\">"._BROKENDOWN."</a>: $brokend<br></font>";
themesidebox($title, $content);
}
}
Заменяем на:
//Copyright Soniks http://mynuke.ru
function adminblock($blockinfo) {
global $admin, $prefix, $db, $admin_file;
if (is_admin($admin)) {
$content = str_replace("admin.php",$admin_file.".php", $blockinfo['content']);
$content = "<font class=\"content\">$content</font>";
themesidebox($blockinfo['title'], $content);
$title = ""._WAITINGCONT."";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_queue"));
$content = "<font class=\"content\">";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=submissions\">"._SUBMISSIONS."</a>: $num<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_reviews_add"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=reviews\">"._WREVIEWS."</a>: $num<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_newlink"));
$brokenl = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_modrequest WHERE brokenlink='1'"));
$modreql = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_links_modrequest WHERE brokenlink='0'"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=Links\">"._WLINKS."</a>: $num<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=LinksListModRequests\">"._MODREQLINKS."</a>: $modreql<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=LinksListBrokenLinks\">"._BROKENLINKS."</a>: $brokenl<br>";
$num = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_newdownload"));
$brokend = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_modrequest WHERE brokendownload='1'"));
$modreqd = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_downloads_modrequest WHERE brokendownload='0'"));
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=downloads\">"._UDOWNLOADS."</a>: $num<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=DownloadsListModRequests\">"._MODREQDOWN."</a>: $modreqd<br>";
$content .= "<strong><big>·</big></strong> <a href=\"".$admin_file.".php?op=DownloadsListBrokenDownloads\">"._BROKENDOWN."</a>: $brokend<br></font>";
themesidebox($title, $content);
}
}
11. Упрощаем функцию вывода RSS в блоке и автоматического добавления запрограммированных новостей, находим:
function headlines($bid, $cenbox=0) {
global $prefix, $db;
$bid = intval($bid);
$result = $db->sql_query("SELECT title, content, url, refresh, time FROM ".$prefix."_blocks WHERE bid='$bid'");
$row = $db->sql_fetchrow($result);
$title = filter($row['title'], nohtml);
$content = filter($row['content']);
$url = filter($row['url'], nohtml);
$refresh = intval($row['refresh']);
$otime = $row['time'];
$past = time()-$refresh;
if ($otime < $past) {
$btime = time();
$rdf = parse_url($url);
$fp = fsockopen($rdf['host'], 80, $errno, $errstr, 15);
if (!$fp) {
$content = "";
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='$bid'");
$cont = 0;
if ($cenbox == 0) {
themesidebox($title, $content);
} else {
themecenterbox($title, $content);
}
return;
}
if ($fp) {
if ($rdf['query'] != '')
$rdf['query'] = "?" . $rdf['query'];
fputs($fp, "GET " . $rdf['path'] . $rdf['query'] . " HTTP/1.0\r\n");
fputs($fp, "HOST: " . $rdf['host'] . "\r\n\r\n");
$string = "";
while(!feof($fp)) {
$pagetext = fgets($fp,300);
$string .= chop($pagetext);
}
fputs($fp,"Connection: close\r\n\r\n");
fclose($fp);
$items = explode("</item>",$string);
$content = "<font class=\"content\">";
for ($i=0;$i<10;$i++) {
$link = ereg_replace(".*<link>","",$items[$i]);
$link = ereg_replace("</link>.*","",$link);
$title2 = ereg_replace(".*<title>","",$items[$i]);
$title2 = ereg_replace("</title>.*","",$title2);
$title2 = stripslashes($title2);
if ($items[$i] == "" AND $cont != 1) {
$content = "";
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='$bid'");
$cont = 0;
if ($cenbox == 0) {
themesidebox($title, $content);
} else {
themecenterbox($title, $content);
}
return;
} else {
if (strcmp($link,$title2) AND $items[$i] != "") {
$cont = 1;
$content .= "<strong><big>·</big></strong><a href=\"$link\" target=\"new\">$title2</a><br>\n";
}
}
}
}
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='$bid'");
}
$siteurl = ereg_replace("http://","",$url);
$siteurl = explode("/",$siteurl);
if (($cont == 1) OR ($content != "")) {
$content .= "<br><a href=\"http://$siteurl[0]\" target=\"blank\"><b>"._HREADMORE."</b></a></font>";
} elseif (($cont == 0) OR ($content == "")) {
$content = "<font class=\"content\">"._RSSPROBLEM."</font>";
}
if ($cenbox == 0) {
themesidebox($title, $content);
} else {
themecenterbox($title, $content);
}
}
function automated_news() {
global $prefix, $multilingual, $currentlang, $db;
if ($multilingual == 1) {
$querylang = "WHERE (alanguage='$currentlang' OR alanguage='')"; /* the OR is needed to display stories who are posted to ALL languages */
} else {
$querylang = "";
}
$today = getdate();
$day = $today[mday];
if ($day < 10) {
$day = "0$day";
}
$month = $today[mon];
if ($month < 10) {
$month = "0$month";
}
$year = $today[year];
$hour = $today[hours];
$min = $today[minutes];
$sec = "00";
$result = $db->sql_query("SELECT anid, time FROM ".$prefix."_autonews $querylang");
while ($row = $db->sql_fetchrow($result)) {
$anid = $row['anid'];
$time = $row['time'];
ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $date);
if (($date[1] <= $year) AND ($date[2] <= $month) AND ($date[3] <= $day)) {
if (($date[4] < $hour) AND ($date[5] >= $min) OR ($date[4] <= $hour) AND ($date[5] <= $min)) {
$result2 = $db->sql_query("SELECT * FROM ".$prefix."_autonews WHERE anid='$anid'");
while ($row2 = $db->sql_fetchrow($result2)) {
$num = $db->sql_numrows($db->sql_query("SELECT sid FROM ".$prefix."_stories WHERE title='$row2[title]'"));
if ($num == 0) {
$title = $row2['title'];
$hometext = filter($row2['hometext']);
$bodytext = filter($row2['bodytext']);
$notes = filter($row2['notes']);
$catid2 = intval($row2['catid']);
$aid2 = filter($row2['aid'], nohtml);
$time2 = $row2['time'];
$topic2 = intval($row2['topic']);
$informant2 = filter($row2['informant'], nohtml);
$ihome2 = intval($row2['ihome']);
$alanguage2 = $row2['alanguage'];
$acomm2 = intval($row2['acomm']);
$associated2 = $row2['associated'];
// Prepare and filter variables to be saved
$hometext = filter($hometext, "", 1);
$bodytext = filter($bodytext, "", 1);
$notes = filter($notes, "", 1);
$aid2 = filter($aid2, nohtml, 1);
$informant2 = filter($informant2, nohtml, 1);
$db->sql_query("DELETE FROM ".$prefix."_autonews WHERE anid='$anid'");
$db->sql_query("INSERT INTO ".$prefix."_stories VALUES (NULL, '$catid2', '$aid2', '$title', '$time2', '$hometext', '$bodytext', '0', '0', '$topic2', '$informant2', '$notes', '$ihome2', '$alanguage2', '$acomm2', '0', '0', '0', '0', '0', '$associated2')");
}
}
}
}
}
}
Заменяем на:
//Copyright Soniks http://mynuke.ru
function headlines($blockinfo, $cenbox=0) {
global $prefix, $db;
$content = $blockinfo['content'];
$otime = $blockinfo['time'];
$past = time()-$blockinfo['refresh'];
if ($otime < $past) {
$btime = time();
$rdf = parse_url($blockinfo['url']);
$fp = fsockopen($rdf['host'], 80, $errno, $errstr, 15);
if (!$fp) {
$content = "";
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='".$blockinfo['bid']."'");
$cont = 0;
if ($cenbox == 0) {
themesidebox($blockinfo['title'], $content);
} else {
themecenterbox($blockinfo['title'], $content);
}
return;
}
if ($fp) {
if ($rdf['query'] != '')
$rdf['query'] = "?" . $rdf['query'];
fputs($fp, "GET " . $rdf['path'] . $rdf['query'] . " HTTP/1.0\r\n");
fputs($fp, "HOST: " . $rdf['host'] . "\r\n\r\n");
$string = "";
while(!feof($fp)) {
$pagetext = fgets($fp,300);
$string .= chop($pagetext);
}
fputs($fp,"Connection: close\r\n\r\n");
fclose($fp);
$items = explode("</item>",$string);
$content = "<font class=\"content\">";
for ($i=0;$i<10;$i++) {
$link = ereg_replace(".*<link>","",$items[$i]);
$link = ereg_replace("</link>.*","",$link);
$title2 = ereg_replace(".*<title>","",$items[$i]);
$title2 = ereg_replace("</title>.*","",$title2);
$title2 = stripslashes($title2);
if ($items[$i] == "" AND $cont != 1) {
$content = "";
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='".$blockinfo['bid']."'");
$cont = 0;
if ($cenbox == 0) {
themesidebox($blockinfo['title'], $content);
} else {
themecenterbox($blockinfo['title'], $content);
}
return;
} else {
if (strcmp($link,$title2) AND $items[$i] != "") {
$cont = 1;
$content .= "<strong><big>·</big></strong><a href=\"$link\" target=\"new\">$title2</a><br>\n";
}
}
}
}
$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='".$blockinfo['bid']."'");
}
$siteurl = ereg_replace("http://","",$blockinfo['url']);
$siteurl = explode("/",$siteurl);
if (($cont == 1) OR ($content != "")) {
$content .= "<br><a href=\"http://$siteurl[0]\" target=\"blank\"><b>"._HREADMORE."</b></a></font>";
} elseif (($cont == 0) OR ($content == "")) {
$content = "<font class=\"content\">"._RSSPROBLEM."</font>";
}
if ($cenbox == 0) {
themesidebox($blockinfo['title'], $content);
} else {
themecenterbox($blockinfo['title'], $content);
}
}
//Copyright Soniks http://mynuke.ru
function automated_news() {
global $prefix, $multilingual, $currentlang, $db;
if ($multilingual == 1) {
$querylang = "WHERE (alanguage='$currentlang' OR alanguage='')"; /* the OR is needed to display stories who are posted to ALL languages */
} else {
$querylang = "";
}
$today = getdate();
$day = $today[mday];
if ($day < 10) {
$day = "0$day";
}
$month = $today[mon];
if ($month < 10) {
$month = "0$month";
}
$year = $today[year];
$hour = $today[hours];
$min = $today[minutes];
$sec = "00";
$result = $db->sql_query("SELECT * FROM ".$prefix."_autonews $querylang");
while ($row = $db->sql_fetchrow($result)) {
$anid = $row['anid'];
$time = $row['time'];
ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $date);
if (($date[1] <= $year) AND ($date[2] <= $month) AND ($date[3] <= $day)) {
if (($date[4] < $hour) AND ($date[5] >= $min) OR ($date[4] <= $hour) AND ($date[5] <= $min)) {
$num = $db->sql_numrows($db->sql_query("SELECT sid FROM ".$prefix."_stories WHERE title='".$row['title']."' AND hometext='".$row['hometext']."'"));
if ($num == 0) {
$title = $row['title'];
$hometext = filter($row['hometext']);
$bodytext = filter($row['bodytext']);
$notes = filter($row['notes']);
$catid2 = intval($row['catid']);
$aid2 = filter($row['aid'], nohtml);
$time2 = $row['time'];
$topic2 = intval($row['topic']);
$informant2 = filter($row['informant'], nohtml);
$ihome2 = intval($row['ihome']);
$alanguage2 = $row['alanguage'];
$acomm2 = intval($row['acomm']);
$associated2 = $row['associated'];
// Prepare and filter variables to be saved
$hometext = filter($hometext, "", 1);
$bodytext = filter($bodytext, "", 1);
$notes = filter($notes, "", 1);
$aid2 = filter($aid2, nohtml, 1);
$informant2 = filter($informant2, nohtml, 1);
$db->sql_query("DELETE FROM ".$prefix."_autonews WHERE anid='$anid'");
$db->sql_query("INSERT INTO ".$prefix."_stories VALUES (NULL, '$catid2', '$aid2', '$title', '$time2', '$hometext', '$bodytext', '0', '0', '$topic2', '$informant2', '$notes', '$ihome2', '$alanguage2', '$acomm2', '0', '0', '0', '0', '0', '$associated2')");
}
}
}
}
}
12. Облегчим блок пользователя, находим:
function userblock() {
global $user, $cookie, $db, $user_prefix;
if((is_user($user)) AND ($cookie[8])) {
$sql = "SELECT ublock FROM ".$user_prefix."_users WHERE user_id='$cookie[0]'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$title = ""._MENUFOR." $cookie[1]";
themesidebox($title, $row[ublock]);
}
}
заменяем на:
//Copyright Soniks http://mynuke.ru
function userblock() {
global $user, $userinfo;
if(is_user($user) and $userinfo['ublockon']==1) {
$title = ""._MENUFOR." ".$userinfo['username'];
themesidebox($title, $userinfo['ublock']);
}
}
13. От ниже следующую функцию getTopics() мы избавимся, когда будем оптимизировать модуль новостей.
14. Чуток упростим функцию массовых сообщений от пользователей, находим:
function public_message() {
global $prefix, $user_prefix, $db, $user, $admin, $p_msg, $cookie, $broadcast_msg;
if ($broadcast_msg == 1) {
if (is_user($user)) {
cookiedecode($user);
$result = $db->sql_query("SELECT broadcast FROM ".$user_prefix."_users WHERE username='$cookie[1]'");
$row = $db->sql_fetchrow($result);
$upref = intval($row['broadcast']);
Заменяем на:
//Copyright Soniks http://mynuke.ru
function public_message() {
global $prefix, $db, $user, $admin, $p_msg, $userinfo, $broadcast_msg;
if ($broadcast_msg == 1) {
if (is_user($user)) {
$upref = intval($userinfo['broadcast']);
15. Обновим функцию определения текущей темы оформления, находим:
function get_theme() {
global $user, $cookie, $Default_Theme;
if(is_user($user)) {
$user2 = base64_decode($user);
$user2 = addslashes($user2);
$t_cookie = explode(":", $user2);
if($t_cookie[9]=="") $t_cookie[9]=$Default_Theme;
if(isset($theme)) $t_cookie[9]=$theme;
if(!$tfile=@opendir("themes/$t_cookie[9]")) {
$ThemeSel = $Default_Theme;
} else {
$ThemeSel = $t_cookie[9];
}
} else {
$ThemeSel = $Default_Theme;
}
return($ThemeSel);
}
Заменяем на:
//Copyright Soniks http://mynuke.ru
function get_theme() {
global $user, $userinfo, $Default_Theme;
if(is_user($user)) {
if($userinfo['theme']=="") $userinfo['theme']=$Default_Theme;
if(isset($theme)) $userinfo['theme']=$theme;
if(!$tfile=@opendir("themes/".$userinfo['theme']."")) {
$ThemeSel = $Default_Theme;
} else {
$ThemeSel = $userinfo['theme'];
}
} else {
$ThemeSel = $Default_Theme;
}
return($ThemeSel);
}
16. Уберем пару запросов в функции подсчета дней до окончании подписки пользователя (мало кто этим пользуется, но все-таки), находим:
function paid() {
global $db, $user, $cookie, $adminmail, $sitename, $nukeurl, $subscription_url, $user_prefix, $prefix;
if (is_user($user)) {
if ($subscription_url != "") {
$renew = ""._SUBRENEW." $subscription_url";
} else {
$renew = "";
}
cookiedecode($user);
$sql = "SELECT * FROM ".$prefix."_subscriptions WHERE userid='$cookie[0]'";
$result = $db->sql_query($sql);
$numrows = $db->sql_numrows($result);
$row = $db->sql_fetchrow($result);
if ($numrows == 0) {
return 0;
} elseif ($numrows != 0) {
$time = time();
if ($row[subscription_expire] <= $time) {
$db->sql_query("DELETE FROM ".$prefix."_subscriptions WHERE userid='$cookie[0]' AND id='$row[id]'");
$from = "$sitename <$adminmail>";
$subject = "$sitename: "._SUBEXPIRED."";
$body = ""._HELLO." $cookie[1]:\n\n"._SUBSCRIPTIONAT." $sitename "._HASEXPIRED."\n$renew\n\n"._HOPESERVED."\n\n$sitename "._TEAM."\n$nukeurl";
$row = $db->sql_fetchrow($db->sql_query("SELECT user_email FROM ".$user_prefix."_users WHERE id='$cookie[0]' AND nickname='$cookie[1]' AND password='$cookie[2]'"));
$mailheaders = "Content-Type: text/plain; charset="._CHARSET."\n";
$mailheaders .= "From: $sitename <$adminmail>\n";
mail($row[user_email], $subject, $body, $mailheaders);
}
return 1;
}
} else {
return 0;
}
}
Заменяем ее на:
//Copyright Soniks http://mynuke.ru
function paid() {
global $db, $user, $userinfo, $adminmail, $sitename, $nukeurl, $subscription_url, $user_prefix, $prefix;
if (is_user($user)) {
if ($subscription_url != "") {
$renew = ""._SUBRENEW." $subscription_url";
} else {
$renew = "";
}
$sql = "SELECT * FROM ".$prefix."_subscriptions WHERE userid='".$userinfo['user_id']."'";
$result = $db->sql_query($sql);
$numrows = $db->sql_numrows($result);
$row = $db->sql_fetchrow($result);
if ($numrows == 0) {
return 0;
} elseif ($numrows != 0) {
$time = time();
if ($row[subscription_expire] <= $time) {
$db->sql_query("DELETE FROM ".$prefix."_subscriptions WHERE userid='".$userinfo['user_id']."' AND id='".$row['id']."'");
$from = "$sitename <$adminmail>";
$subject = "$sitename: "._SUBEXPIRED."";
$body = ""._HELLO." ".$userinfo['username'].":\n\n"._SUBSCRIPTIONAT." $sitename "._HASEXPIRED."\n$renew\n\n"._HOPESERVED."\n\n$sitename "._TEAM."\n$nukeurl";
$mailheaders = "Content-Type: text/plain; charset="._CHARSET."\n";
$mailheaders .= "From: $sitename <$adminmail>\n";
mail($userinfo['user_email'], $subject, $body, $mailheaders);
}
return 1;
}
} else {
return 0;
}
}
17. И последнее изменение в этом файле, обновим функцию банерной системы (данная система появилась в версии 7.9, сл-но у версий ниже данное делать не нужно), находим:
function ads($position) {
global $prefix, $db, $admin, $sitename, $adminmail, $nukeurl;
$position = intval($position);
if (paid()) {
return;
}
$numrows = $db->sql_numrows($db->sql_query("SELECT * FROM ".$prefix."_banner WHERE position='$position' AND active='1'"));
/* Get a random banner if exist any. */
if ($numrows > 1) {
$numrows = $numrows-1;
mt_srand((double)microtime()*1000000);
$bannum = mt_rand(0, $numrows);
} else {
$bannum = 0;
}
$sql = "SELECT bid, impmade, imageurl, clickurl, alttext FROM ".$prefix."_banner WHERE position='$position' AND active='1' LIMIT $bannum,1";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$bid = $row[bid];
$imageurl = filter($row[imageurl], nohtml);
$clickurl = filter($row[clickurl], nohtml);
$alttext = filter($row[alttext], nohtml);
$db->sql_query("UPDATE ".$prefix."_banner SET impmade=impmade+1 WHERE bid='$bid'");
if($numrows > 0) {
$sql2 = "SELECT cid, imptotal, impmade, clicks, date, ad_class, ad_code, ad_width, ad_height FROM ".$prefix."_banner WHERE bid='$bid'";
$result2 = $db->sql_query($sql2);
$row2 = $db->sql_fetchrow($result2);
$cid = $row2[cid];
$imptotal = $row2[imptotal];
$imptotal = intval($imptotal);
$impmade = $row2[impmade];
$impmade = intval($impmade);
$clicks = $row2[clicks];
$clicks = intval($clicks);
$date = $row2[date];
$ad_class = filter($row2[ad_class], nohtml);
$ad_code = $row2[ad_code];
$ad_width = intval($row['ad_width']);
$ad_height = intval($row['ad_height']);
/* Check if this impression is the last one and print the banner */
if (($imptotal <= $impmade) AND ($imptotal != 0)) {
$db->sql_query("UPDATE ".$prefix."_banner SET active='0' WHERE bid='$bid'");
$sql3 = "SELECT name, contact, email FROM ".$prefix."_banner_clients WHERE cid='$cid'";
$result3 = $db->sql_query($sql3);
$row3 = $db->sql_fetchrow($result3);
$c_name = filter($row3[name], nohtml);
$c_contact = filter($row3[contact], nohtml);
$c_email = filter($row3[email], nohtml);
Заменяем на:
//Copyright Soniks http://mynuke.ru
function ads($position) {
global $prefix, $db, $admin, $sitename, $adminmail, $nukeurl, $adsinfo;
$position = intval($position);
if(!is_array($adsinfo) or !$adsinfo){
$adsinfo = array();
$rows = $db->sql_query("SELECT * FROM ".$prefix."_banner WHERE active='1' ORDER BY position");
while($ads_result = $db->sql_fetchrow($rows)){
$adsinfo[$ads_result['position']][$ads_result['bid']] = $ads_result;
}
}
if(!empty($adsinfo[$position])){
$bid = array_rand($adsinfo[$position]);
$now_ads = $adsinfo[$position][$bid];
if(!is_admin($admin)) $db->sql_query("UPDATE ".$prefix."_banner SET impmade=impmade+1 WHERE bid='$bid'");
$imageurl = filter($now_ads['imageurl'], nohtml);
$clickurl = filter($now_ads['clickurl'], nohtml);
$alttext = filter($now_ads['alttext'], nohtml);
$cid = $now_ads['cid'];
$imptotal = intval($now_ads['imptotal']);
$impmade = intval($now_ads['impmade']);
$clicks = intval($now_ads['clicks']);
$date = $now_ads['date'];
$ad_class = filter($now_ads['ad_class'], nohtml);
$ad_code = $now_ads['ad_code'];
$ad_width = intval($now_ads['ad_width']);
$ad_height = intval($now_ads['ad_height']);
/* Check if this impression is the last one and print the banner */
if (($imptotal <= $impmade) AND ($imptotal != 0)) {
$db->sql_query("UPDATE ".$prefix."_banner SET active='0' WHERE bid='$bid'");
$result = $db->sql_query("SELECT name, contact, email FROM ".$prefix."_banner_clients WHERE cid='$cid'");
$row = $db->sql_fetchrow($result);
$c_name = filter($row['name'], nohtml);
$c_contact = filter($row['contact'], nohtml);
$c_email = filter($row['email'], nohtml);
Теперь внесем небольшое изменение в админ файлы настроек системы и модулей.
Открываем файл /admin/modules/settings.php
Находим:
Header("Location: ".$admin_file.".php?op=Configure");
И выше добавляем:
//Copyright Soniks http://mynuke.ru
$result = $db->sql_query("SELECT * FROM ".$prefix."_config LIMIT 1");
$sett ="<?php\n\n";
$sett .="if(!defined('NUKE_FILE'))\n{\n die();\n}\n";
foreach(mysql_fetch_assoc($result) as $key => $value){
$$key = $value;
$sett .="$".$key." = \"".str_replace('"','\"',$value)."\";\n";
}
$sett .="\n?>";
if($sett !=""){
$fp = fopen (NUKE_PATH."cache/config", "wb");
fwrite($fp, $sett);
fclose($fp);
}
if(!file_exists(NUKE_PATH."cache/.htaccess")){
$sett2 ="deny from all";
$fp2 = fopen (NUKE_PATH."cache/.htaccess", "wb");
fwrite($fp2, $sett2);
fclose($fp2);
}
Открываем файл /admin/modules/modules.php
Находим:
$res = $db->sql_query("update " . $prefix . "_main set main_module='$title'");
$res2 = $db->sql_query("update " . $prefix . "_modules set active='$active', view='$view' where mid='$mid'");
Ниже добавляем:
//Copyright Soniks http://mynuke.ru
$sett ="<?php\n\n";
$sett .="if(!defined('NUKE_FILE'))\n{\n die();\n}\n";
$sett .= '$main_module = "'.$title.'";';
$sett .="\n?>";
$fp = fopen (NUKE_PATH."cache/main", "wb");
fwrite($fp, $sett);
fclose($fp);
if(!file_exists(NUKE_PATH."cache/.htaccess")){
$sett2 ="deny from all";
$fp2 = fopen (NUKE_PATH."cache/.htaccess", "wb");
fwrite($fp2, $sett2);
fclose($fp2);
}
Вносим новую переменную в конфиг, окрываем config.php
Находим:
$subscription_url = "";
и ниже добавляем:
$group_use = 1; // использование групп: 1-да | 0-нет
Если вы пользуетесь группами для пользователей в php-nuke (не в форуме), то ставим 1, а если вам не нужны заработанные балы пользователей на сайте и сами группы, то ставим 0 - это уменьшит количество запросов на сайте.
Откорректируем modules.php, находим:
$result = $db->sql_query("SELECT active, view FROM ".$prefix."_modules WHERE title='$name'");
$row = $db->sql_fetchrow($result);
$mod_active = intval($row['active']);
$view = intval($row['view']);
Заменяем на:
$mod_active = intval($modules_info[$name]['active']);
$view = intval($modules_info[$name]['view']);
Находим:
$result2 = $db->sql_query("SELECT mod_group FROM ".$prefix."_modules WHERE title='$name'");
$row2 = $db->sql_fetchrow($result2);
if ($row2[mod_group] != 0) {
$result3 = $db->sql_query("SELECT name FROM ".$prefix."_groups WHERE id='$row2[mod_group]'");
$row3 = $db->sql_fetchrow($result3);
echo ""._ADDITIONALYGRP.": <b>$row3[name]</b><br><br>";
}
Заменяем на:
if ($modules_info[$name]['mod_group'] != 0) {
$result = $db->sql_query("SELECT name FROM ".$prefix."_groups WHERE id='".$modules_info[$name]['mod_group']."'");
$row = $db->sql_fetchrow($result);
echo ""._ADDITIONALYGRP.": <b>".$row['name']."</b><br><br>";
}
Откорректируем index.php, находим:
$row = $db->sql_fetchrow($db->sql_query("SELECT main_module from ".$prefix."_main"));
$name = $row['main_module'];
Заменяем на:
// GET MAIN MODULE
if(file_exists("./cache/main")){
include_once("./cache/main");
}else{
$row = $db->sql_fetchrow($db->sql_query("SELECT main_module from ".$prefix."_main"));
$name = $row['main_module'];
$sett ="<?php\n\n";
$sett .="if(!defined('NUKE_FILE'))\n{\n die();\n}\n";
$sett .= '$main_module = "'.$row['main_module'].'";';
$sett .="\n?>";
$fp = fopen ("./cache/main", "wb");
fwrite($fp, $sett);
fclose($fp);
if(!file_exists("./cache/.htaccess")){
$sett2 ="deny from all";
$fp2 = fopen ("./cache/.htaccess", "wb");
fwrite($fp2, $sett2);
fclose($fp2);
}
}
$name = $main_module;
Упростим немного систему бана, открываем includes/ipban.php
Находим:
$numrow = $db->sql_numrows($db->sql_query("SELECT id FROM ".$prefix."_banned_ip WHERE ip_address='$ip'"));
if ($numrow != 0) {
echo "<br><br><center><img src='images/admin/ipban.gif'><br><br><b>You has been banned by the administrator</b></center>";
die();
}
$ip_class = explode(".", $ip);
$ip = "$ip_class[0].$ip_class[1].$ip_class[2].*";
$row = $db->sql_fetchrow($db->sql_query("SELECT ip_address FROM ".$prefix."_banned_ip WHERE ip_address='$ip'"));
$ip_class_banned = explode(".", $row[ip_address]);
if ($ip_class_banned[3] == "*") {
if ($ip_class[0] == $ip_class_banned[0] && $ip_class[1] == $ip_class_banned[1] && $ip_class[2] == $ip_class_banned[2]) {
echo "<br><br><center><img src='images/admin/ipban.gif'><br><br><b>You has been banned by the administrator</b></center>";
die();
}
}
Заменяем на:
$ip_class = explode(".", $ip);
$ip2 = "$ip_class[0].$ip_class[1].$ip_class[2].*";
//ADD
$numrow = $db->sql_numrows($db->sql_query("SELECT id FROM ".$prefix."_banned_ip WHERE ip_address='$ip' OR ip_address='$ip2'"));
if ($numrow != 0) {
echo "<br><br><center><img src='images/admin/ipban.gif'><br><br><b>You has been banned by the administrator</b></center>";
die();
}
И последнее изменение в ядре системы, но очень весомое.
Открываем header.php
Если вы используете сторонние системы безопасности php-nuke или же вам не нужна система бана пользователей, то удаляем строчку:
include("includes/ipban.php");
Настоятельно рекомендую избавиться от стандартной статистики посещаемости, она ну уж слишком много запросов делает к БД, да и обычные счетчики типа http://top.mail.ru/ куда информативнее.
Если решились, то находим и удаляем строчку:
include("includes/counter.php");
Так же надо убрать теперь не нужные нам таблицы, для этого выполним SQL-запрос:
DROP TABLE `nuke_counter`, `nuke_stats_date`, `nuke_stats_hour`, `nuke_stats_month`, `nuke_stats_year`;
*не забываем заменить префикс nuke_ на свой
Так же удаляем теперь не нужные нам файлы:
includes/counter.php и папку modules/Statistics/
В результате проведенных выше изменений над ядром системы количество запросов снизилось до ~8, это с учетом всех включенных возможностей php-nuke.
Оптимизируем блок: Навигация
Открываем blocks/block-Modules.php
И заменяем весь текст, который находиться в том файле на:
<?php
if (eregi("block-Modules.php", $_SERVER['PHP_SELF'])) {
Header("Location: index.php");
die();
}
global $prefix, $db, $admin, $main_module, $modules_info;
//Copyright Soniks http://mynuke.ru
if(!isset($main_module)){
if(file_exists("./cache/main")){
include_once("./cache/main");
}else{
$row = $db->sql_fetchrow($db->sql_query("SELECT main_module from ".$prefix."_main"));
$name = $row['main_module'];
$sett ="<?php\n\n";
$sett .="if(!defined('NUKE_FILE'))\n{\n die();\n}\n";
$sett .= '$main_module = "'.$row['main_module'].'";';
$sett .="\n?>";
$fp = fopen ("./cache/main", "wb");
fwrite($fp, $sett);
fclose($fp);
if(!file_exists("./cache/.htaccess")){
$sett2 ="deny from all";
$fp2 = fopen ("./cache/.htaccess", "wb");
fwrite($fp2, $sett2);
fclose($fp2);
}
}
}
/* If you're Admin you and only you can see Inactive modules and test it */
/* If the module doesn't exist, it will be removed from the database automaticaly */
/* If you copied a new module is the /modules/ directory, it will be added to the database */
if(is_admin($admin)){
$handle=opendir('modules');
$modlist = array();
while ($file = readdir($handle)) {
if ( (!ereg("[.]",$file)) )
$modlist[$file]= "$file";
}
closedir($handle);
foreach ($modules_info as $title=>$modules_itm) {
if($modlist[$title]) unset($modlist[$title]);
else {
$db->sql_query("DELETE FROM ".$prefix."_modules WHERE title='$title'");
unset($modules_info[$title]);
}
}
if(!empty($modlist)){
foreach($modlist as $modlist_name){
$db->sql_query("INSERT INTO ".$prefix."_modules (mid, title, custom_title, active, view, inmenu, mod_group) VALUES (NULL, '".addslashes($modlist_name)."', '".ereg_replace("_", " ", addslashes($modlist_name))."', '0', '0', '1', '0')");
$modules_info[addslashes($modlist_name)] = array('custom_title' =>ereg_replace("_", " ", addslashes($modlist_name)), 'active'=>0, 'view'=>0, 'inmenu'=>1, 'mod_group'=>0);
}
}
asort($modules_info);
$content_admin = "<br><center><b>"._INVISIBLEMODULES."</b><br>";
$content_admin .= "<font class=\"tiny\">"._ACTIVEBUTNOTSEE."</font></center><br>";
$a = 0;
$dummy = 0;
foreach ($modules_info as $mn_title=>$modules_itms) {
if($modules_itms['active'] ==1 and $modules_itms['inmenu']=0 and $m_title != $main_module){
if ($modules_itms['custom_title'] !="")
$mn_title2 = $modules_itms['custom_title'];
else
$mn_title2 = ereg_replace("_", " ", $mn_title);
if ($mn_title2 != "") {
$content_admin .= "<strong><big>·</big></strong> <a href=\"modules.php?name=$mn_title\">$mn_title2</a><br>\n";
$dummy = 1;
} else {
$a = 1;
}
}
}
if ($a == 1 AND $dummy != 1)
$content_admin .= "<strong><big>·</big></strong> <i>"._NONE."</i><br>\n";
$content_admin .= "<br><center><b>"._NOACTIVEMODULES."</b><br>";
$content_admin .= "<font class=\"tiny\">"._FORADMINTESTS."</font></center><br>";
foreach ($modules_info as $mn_title=>$modules_itms) {
if($modules_itms['active'] ==0 ){
if ($modules_itms['custom_title'] !="")
$mn_title2 = $modules_itms['custom_title'];
else
$mn_title2 = ereg_replace("_", " ", $mn_title);
if ($mn_title2 != "") {
$content_admin .= "<strong><big>·</big></strong> <a href=\"modules.php?name=$mn_title\">$mn_title2</a><br>\n";
$dummy = 1;
} else {
$a = 1;
}
}
}
if ($a == 1 AND $dummy != 1)
$content_admin .= "<strong><big>·</big></strong> <i>"._NONE."</i><br>\n";
}
/* Now we make the Modules block with the correspondent links */
asort($modules_info);
$content .= "<strong><big>·</big></strong> <a href=\"index.php\">"._HOME."</a><br>\n";
foreach ($modules_info as $m_title=>$modules_itms) {
if($modules_itms['active'] ==1 and $modules_itms['inmenu']=1 and $m_title != $main_module and ((is_admin($admin) and $modules_itms['view'] == 2) or $modules_itms['view'] != 2)){
$m_title2 = ereg_replace("_", " ", $m_title);
if ($modules_itms['custom_title'] !="")
$m_title2 = $modules_itms['custom_title'];
else
$m_title2 = ereg_replace("_", " ", $m_title);
$content .= "<strong><big>·</big></strong> <a href=\"modules.php?name=$m_title\">$m_title2</a><br>\n";
}
}
$content .= $content_admin;
?>
В результате чего, данный блок под пользователем не совершает ни одного запроса.
Оптимизируем модуль Новостей
Открываем modules/News/index.php
Находим:
$querylang = "AND (alanguage='$currentlang' OR alanguage='')";
Заменяем на:
$querylang = "AND (s.alanguage='$currentlang' OR s.alanguage='')";
Находим:
$qdb = "WHERE (ihome='0' OR catid='0')";
Заменяем на:
$qdb = "WHERE (s.ihome='0' OR s.catid='0')";
Находим:
$qdb = "WHERE topic='$new_topic'";
Заменяем на:
$qdb = "WHERE s.topic='$new_topic'";
Находим:
$result = $db->sql_query("SELECT sid, catid, aid, title, time, hometext, bodytext, comments, counter, topic, informant, notes, acomm, score, ratings FROM ".$prefix."_stories $qdb $querylang ORDER BY sid DESC limit $storynum");
Заменяем на:
$result = $db->sql_query("SELECT s.*, t.*, c.title as title1 FROM ".$prefix."_stories AS s LEFT JOIN ".$prefix."_topics AS t ON(t.topicid=s.topic) LEFT JOIN ".$prefix."_stories_cat AS c ON( c.catid=s.catid and s.catid>0) $qdb $querylang ORDER BY s.sid DESC limit $storynum");
Находим:
if ($catid > 0) {
$row2 = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_stories_cat WHERE catid='$catid'"));
$cattitle = stripslashes(check_html($row2['title'], "nohtml"));
}
Заменяем на:
$cattitle = stripslashes(check_html($row['title1'], "nohtml"));
Находим:
getTopics($s_sid);
Заменяем на:
$topicid = intval($row['topicid']);
$topicname = filter($row['topicname'], nohtml);
$topicimage = filter($row['topicimage'], nohtml);
$topictext = filter($row['topictext'], nohtml);
Находим:
$row3 = $db->sql_fetchrow($db->sql_query("SELECT title FROM ".$prefix."_stories_cat WHERE catid='$catid'"));
$title1 = filter($row3['title'], nohtml);
$title = "<a href=\"modules.php?name=News&file=categories&op=newindex&catid=$catid\"><font class=\"storycat\">$title1</font></a>: $title";
Заменяем на:
$title = "<a href=\"modules.php?name=News&file=categories&op=newindex&catid=$catid\"><font class=\"storycat\">$cattitle</font></a>: $title";
Находим:
global $sitename, $user, $cookie, $module_name;
Заменяем на:
global $sitename, $user, $cookie, $module_name, $db, $prefix;
И того на главной странице модуля новостей имеем один или 2 запроса в зависимости просматриваете ли вы все новости или же отдельный топик новостей.
Еще добавлю:
Если не используете возможность запрограммировать публикацию статьи на будущее, то закомментируйте или удалите строку:
automated_news();
Оптимизируем модуль Новостей
Открываем modules/News/article.php
Находим:
require_once("mainfile.php");
Выше добавляем:
$show_related = 1; // 1 - Показывать блок "Связанные ссылки" | 0 - не показывать
$show_ratings = 1; // 1 - Показывать блок "Рейтинг статьи " | 0 - не показывать
$show_option = 1; // 1 - Показывать блок "Опции " | 0 - не показывать (Админ все равно будет видить этот блок)
То, что мы сейчас добавили, является настраиваемой частью скрипта, вы можете выключить не нужные вам блоки.
Находим:
$sid = $_GET['sid'];
Заменяем на:
$sid = intval($_GET['sid']);
Находим:
$result = $db->sql_query("select catid, aid, time, title, hometext, bodytext, topic, informant, notes, acomm, haspoll, pollID, score, ratings FROM ".$prefix."_stories where sid='$sid'");
Заменяем на:
$result = $db->sql_query("SELECT s.*, t.*, c.title as title1 FROM ".$prefix."_stories AS s LEFT JOIN ".$prefix."_topics AS t ON(t.topicid=s.topic) LEFT JOIN ".$prefix."_stories_cat AS c ON( c.catid=s.catid and s.catid>0) WHERE s.sid='$sid'");
Находим:
getTopics($sid);
Заменяем на:
$topicid = intval($row['topicid']);
$topicname = filter($row['topicname'], nohtml);
$topicimage = filter($row['topicimage'], nohtml);
$topictext = filter($row['topictext'], nohtml);
Находим:
if ($catid != 0) {
$row2 = $db->sql_fetchrow($db->sql_query("select title from ".$prefix."_stories_cat where catid='$catid'"));
$title1 = filter($row2['title'], nohtml);
Заменяем на:
if($title1 = filter($row['title1'], nohtml)){
Это мы оптимизировали вывод самих новостей, а теперь займемся выводом блоков, которые выводятся с права от новости.
Находим:
$row3 = $db->sql_fetchrow($db->sql_query("SELECT pollTitle, voters FROM ".$prefix."_poll_desc WHERE pollID='$pollID'"));
Заменяем на:
$row3 = $db->sql_fetchrow($db->sql_query("SELECT d.pollTitle, d.voters, COUNT(c.tid) AS ctid FROM ".$prefix."_poll_desc AS d LEFT JOIN ".$prefix."_pollcomments AS c ON(c.pollID='$pollID') WHERE d.pollID='$pollID' GROUP BY d.pollTitle"));
Находим:
for($i = 1; $i <= 12; $i++) {
$result4 = $db->sql_query("SELECT pollID, optionText, optionCount, voteID FROM ".$prefix."_poll_data WHERE (pollID='$pollID') AND (voteID='$i')");
$row4 = $db->sql_fetchrow($result4);
$numrows = $db->sql_numrows($result4);
if($numrows != 0) {
$optionText = $row4['optionText'];
if($optionText != "") {
$boxContent .= "<tr><td valign=\"top\"><input type=\"radio\" name=\"voteID\" value=\"".$i."\"></td><td width=\"100%\"><font class=\"content\">$optionText</font></td></tr>\n";
}
}
}
Заменяем на:
$result4 = $db->sql_query("SELECT pollID, optionText, optionCount, voteID FROM ".$prefix."_poll_data WHERE pollID='$pollID' ORDER BY voteID ");
$numrows = $db->sql_numrows($result4);
if($numrows != 0) {
while($row4 = $db->sql_fetchrow($result4)){
$optionText = $row4['optionText'];
if($optionText != "") {
$boxContent .= "<tr><td valign=\"top\"><input type=\"radio\" name=\"voteID\" value=\"".$row4['voteID']."\"></td><td width=\"100%\"><font class=\"content\">$optionText</font></td></tr>\n";
}
}
}
Находим и удаляем:
for($i = 0; $i < 12; $i++) {
$row5 = $db->sql_fetchrow($db->sql_query("SELECT optionCount FROM ".$prefix."_poll_data WHERE (pollID='$pollID') AND (voteID='$i')"));
$optionCount = $row5['optionCount'];
$sum = (int)$sum+$optionCount;
}
Находим:
if ($pollcomm) {
$result6 = $db->sql_query("select * from ".$prefix."_pollcomments where pollID='$pollID'");
$numcom = $db->sql_numrows($result6);
$boxContent .= "<br>"._VOTES.": <b>$sum</b><br>"._PCOMMENTS." <b>$numcom</b>\n\n";
} else {
$boxContent .= "<br>"._VOTES." <b>$sum</b>\n\n";
}
Заменяем на:
if ($pollcomm) {
$boxContent .= "<br>"._VOTES.": <b>$voters</b><br>"._PCOMMENTS." <b>".$row3['ctid']."</b>\n\n";
} else {
$boxContent .= "<br>"._VOTES." <b>$voters</b>\n\n";
}
Находим:
$row7 = $db->sql_fetchrow($db->sql_query("select title, content, active, bposition from ".$prefix."_blocks where blockfile='block-Login.php' $querylang"));
Выше добавляем (изменено):
global $block_info;
$show_login = false;
if($block_info){
if($block_info['r']){
foreach($block_info['r'] as $value){
if($value['blockfile'] =='block-Login.php'){
$show_login = true;
break;
}
}
}
}else{
Находим:
if (($active == 1) AND ($position == "r") AND (!is_user($user))) {
loginbox();
}
Заменяем на:
if (($active == 1) AND ($position == "r")) $show_login = true;
}
if(!is_user($user) and $show_login) loginbox();
Находим:
$boxtitle = ""._RELATED."";
Выше добавляем:
if($show_related==1){
Находим:
$boxstuff .= "<a href=\"modules.php?name=$module_name&file=article&sid=$topstory\">$ttitle</a></font></center><br>\n";
themesidebox($boxtitle, $boxstuff);
Ниже добавляем:
}
Находим:
if ($ratings != 0) {
Выше добавляем:
if($show_ratings==1){
Находим:
$ratecontent .= "<center><input type=\"submit\" value=\""._CASTMYVOTE."\"></center></form>";
themesidebox($ratetitle, $ratecontent);
Ниже добавляем:
}
Находим:
$optiontitle = ""._OPTIONS."";
Выше добавляем:
if($show_option==1 or is_admin($admin)){
Находим (изменено):
echo "</td></tr></table>\n";
Выше добавляем:
}
В результате, при прочтение полной версии новости, модуль делает 2 запроса без блоков и 6 с блоками (2-опрос, 2-ссылки). Это без вывода ассоциаций и комментариев (ими займемся позже).
На сегодня хватит :smile:
Предыдущий пост был подправлен!
Оптимизируем модуль Новостей
Открываем modules/News/associates.php
Находим и удаляем:
require_once("mainfile.php");
$module_name = basename(dirname(__FILE__));
get_lang($module_name);
$sid = intval($sid);
$arow = $db->sql_fetchrow($db->sql_query("SELECT associated FROM ".$prefix."_stories WHERE sid='$sid'"));
Находим:
if ($arow[associated] != "") {
OpenTable();
echo "<center><b>"._ASSOTOPIC."</b><br><br>";
$asso_t = explode("-",$arow[associated]);
for ($i=0; $i<sizeof($asso_t); $i++) {
if ($asso_t[$i] != "") {
$atop = $db->sql_fetchrow($db->sql_query("SELECT topicimage, topictext from ".$prefix."_topics WHERE topicid='$asso_t[$i]'"));
$atop[topictext] = filter($atop[topictext], nohtml);
echo "<a href=\"modules.php?name=$module_name&new_topic=$asso_t[$i]\"><img src=\"$tipath$atop[topicimage]\" border=\"0\" hspace=\"10\" alt=\"$atop[topictext]\" title=\"$atop[topictext]\"></a>";
}
}
Заменяем на:
global $tipath, $row;
if ($row['associated'] != "") {
OpenTable();
echo "<center><b>"._ASSOTOPIC."</b><br><br>";
if(substr($row['associated'], -1)=="-") $row['associated'] = substr($row['associated'], 0, -1);
$asso_t = explode("-",$row['associated']);
$asso_t = implode(",", $asso_t);
$aresult = $db->sql_query("SELECT topicid, topicimage, topictext FROM ".$prefix."_topics WHERE topicid IN($asso_t)");
while($atop = $db->sql_fetchrow($aresult)){
$atop['topictext'] = filter($atop['topictext'], nohtml);
echo "<a href=\"modules.php?name=$module_name&new_topic=".$atop['topicid']."\"><img src=\"".$tipath.$atop['topicimage']."\" border=\"0\" hspace=\"10\" alt=\"".$atop['topictext']."\" title=\"".$atop['topictext']."\"></a>";
}
Оптимизируем модуль Новостей
Открываем modules/News/categories.php
Находим:
$result = $db->sql_query("SELECT sid, aid, title, time, hometext, bodytext, comments, counter, topic, informant, notes, acomm, score, ratings FROM ".$prefix."_stories where catid='$catid' $querylang ORDER BY sid DESC limit $storynum");
Заменяем на:
$result = $db->sql_query("SELECT s.*, t.*, c.title as title1 FROM ".$prefix."_stories AS s LEFT JOIN ".$prefix."_topics AS t ON(t.topicid=s.topic) LEFT JOIN ".$prefix."_stories_cat AS c ON(c.catid=s.catid) WHERE s.catid='$catid' $querylang ORDER BY s.sid DESC LIMIT $storynum");
Находим:
getTopics($s_sid);
Заменяем на:
$topicid = intval($row['topicid']);
$topicname = filter($row['topicname'], nohtml);
$topicimage = filter($row['topicimage'], nohtml);
$topictext = filter($row['topictext'], nohtml);
Находим:
$row2 = $db->sql_fetchrow($db->sql_query("select title from ".$prefix."_stories_cat where catid='$catid'"));
$title1 = filter($row2['title'], "nohtml");
Заменяем на:
$title1 = filter($row['title1'], "nohtml");
Открываем modules/News/print.php
Находим:
$row = $db->sql_fetchrow($db->sql_query("SELECT title, time, hometext, bodytext, topic, notes FROM ".$prefix."_stories WHERE sid='$sid'"));
Заменяем на:
$row = $db->sql_fetchrow($db->sql_query("SELECT s.*, t.topictext FROM ".$prefix."_stories AS s LEFT JOIN ".$prefix."_topics AS t ON(t.topicid=s.topic) WHERE s.sid='$sid'"));
Находим:
$row2 = $db->sql_fetchrow($db->sql_query("SELECT topictext FROM ".$prefix."_topics WHERE topicid='$topic'"));
$topictext = filter($row2['topictext'], nohtml);
Заменяем на:
$topictext = filter($row['topictext'], nohtml);
MyNuke.ru