Discuz!官方免费开源建站系统

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索

[已答复] discuz common.inc.php代码分析

[复制链接]
niuniu5201314 发表于 2010-4-14 14:57:06 | 显示全部楼层 |阅读模式
<?php
error_reporting(0);
set_magic_quotes_runtime(0);
$mtime = explode(' ', microtime());
$discuz_starttime = $mtime[1] + $mtime[0];

define('SYS_DEBUG', FALSE);
define('IN_DISCUZ', TRUE);
define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -7));//dirname(__FILE__)魔法常量获取文件绝对路径。从开头截取至倒数第7位(discuz/)
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());//检测系统设置
!defined('CURSCRIPT') && define('CURSCRIPT', '');

if(PHP_VERSION < '4.1.0') {
        $_GET = &$HTTP_GET_VARS;
        $_POST = &$HTTP_POST_VARS;
        $_COOKIE = &$HTTP_COOKIE_VARS;
        $_SERVER = &$HTTP_SERVER_VARS;
        $_ENV = &$HTTP_ENV_VARS;
        $_FILES = &$HTTP_POST_FILES;
}//提高通用性适应不同版本

if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) {
        exit('Request tainting attempted.');
}//因为如果register_globals打开的话, 客户端提交的数据中含有GLOBALS变量名, 就会覆盖服务器上的$GLOBALS变量.
//所以这段代码, 就是判断, 如果提交的数据中有GLOBALS变量名, 就终止程序.

require_once DISCUZ_ROOT.'./include/global.func.php';

//看看浏览者是什么东东,是一个robot那么就直接来一个 403 Forbidden了……
getrobot();//阻止机器人来访
if(defined('NOROBOT') && IS_ROBOT) {
        //需要向客户端发出拒绝访问的HTTP头信息,只需要定义一个NOROBOT和把IS_ROBOT定义成TRUE即可。
        exit(header("HTTP/1.1 403 Forbidden"));
}

//处理过滤全局变量,将其变成变量形式
foreach(array('_COOKIE', '_POST', '_GET') as $_request) {
        foreach($$_request as $_key => $_value) {
                $_key{0} != '_' && $$_key = daddslashes($_value);
        }
}
//如设置自动加反斜线
if (!MAGIC_QUOTES_GPC && $_FILES) {
        $_FILES = daddslashes($_FILES);
}
//初始化一些变量
$charset = $dbs = $dbcharset = $forumfounders = $metakeywords = $extrahead = $seodescription = $mnid = '';
$plugins = $hooks = $admincp = $jsmenu = $forum = $thread = $language = $actioncode = $modactioncode = $lang = array();
$_DCOOKIE = $_DSESSION = $_DCACHE = $_DPLUGIN = $advlist = array();

//引入基本配置
require_once DISCUZ_ROOT.'./config.inc.php';
//对请求的url进行过滤
if($urlxssdefend && !empty($_SERVER['REQUEST_URI'])) {
        $temp = urldecode($_SERVER['REQUEST_URI']);
        if(strpos($temp, '<') !== false || strpos($temp, '"') !== false)
                exit('Request Bad url');
}
//把$_COOKIE中的东西取出来存到$_DCOOKIE这个数组中
$prelength = strlen($cookiepre);
foreach($_COOKIE as $key => $val) {
        if(substr($key, 0, $prelength) == $cookiepre) {
                $_DCOOKIE[(substr($key, $prelength))] = MAGIC_QUOTES_GPC ? $val : daddslashes($val);
        }
}
//安全考虑
unset($prelength, $_request, $_key, $_value);

$inajax = !empty($inajax);
$handlekey = !empty($handlekey) ? htmlspecialchars($handlekey) : '';
$timestamp = time();

if($attackevasive && CURSCRIPT != 'seccode') {
        require_once DISCUZ_ROOT.'./include/security.inc.php';
}
//数据库
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';

//自身的名称$PHP_SELF,自身的文件名字$SCRIPT_FILENAME,论坛的地址$boardurl,得到浏览者的一些信息,比方说ip地址,浏览器类型等等。

$PHP_SELF = dhtmlspecialchars($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
$BASESCRIPT = basename($PHP_SELF);//获取文件名
list($BASEFILENAME) = explode('.', $BASESCRIPT);
$boardurl = htmlspecialchars('http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api|archiver|wap)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/');
//获得ip
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
}
//ip是不是点分段
preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
unset($onlineipmatches);
//缓存开启
$cachelost = (@include DISCUZ_ROOT.'./forumdata/cache/cache_settings.php') ? '' : 'settings';
@extract($_DCACHE['settings']);
if($gzipcompress && function_exists('ob_gzhandler') && !in_array(CURSCRIPT, array('attachment', 'wap')) && !$inajax) {
        ob_start('ob_gzhandler');
} else {
        $gzipcompress = 0;
        ob_start();//检查gzip是不是打开了,打开就用ob_gzhandler,没有就用ob_start。
}
//平衡负载用的
if(!empty($loadctrl) && substr(PHP_OS, 0, 3) != 'WIN') {
        if($fp = @fopen('/proc/loadavg', 'r')) {
                list($loadaverage) = explode(' ', fread($fp, 6));
                fclose($fp);
                if($loadaverage > $loadctrl) {
                        header("HTTP/1.0 503 Service Unavailable");
                        include DISCUZ_ROOT.'./include/serverbusy.htm';
                        exit();
                }
        }
}
//生成缓存
if(in_array(CURSCRIPT, array('index', 'forumdisplay', 'viewthread', 'post', 'topicadmin', 'register', 'archiver', 'username'))) {
        $cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/cache_'.CURSCRIPT.'.php') ? '' : ' '.CURSCRIPT;
}
//连接数据库,详情在db_mysql.inc.php中
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
$dbuser = $dbpw = $pconnect = $sdb = NULL;
 楼主| niuniu5201314 发表于 2010-4-14 14:57:24 | 显示全部楼层
////处理SID
$sid = daddslashes(($transsidstatus || CURSCRIPT == 'wap') && (isset($_GET['sid']) || isset($_POST['sid'])) ?
        (isset($_GET['sid']) ? $_GET['sid'] : $_POST['sid']) :
        (isset($_DCOOKIE['sid']) ? $_DCOOKIE['sid'] : ''));

CURSCRIPT == 'attachment' && isset($_GET['sid']) && $sid = addslashes(authcode($_GET['sid'], 'DECODE', $_DCACHE['settings']['authkey']));

//加密key
$discuz_auth_key = md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']);
//解密cookie
list($discuz_pw, $discuz_secques, $discuz_uid) = empty($_DCOOKIE['auth']) ? array('', '', 0) : daddslashes(explode("\t", authcode($_DCOOKIE['auth'], 'DECODE')), 1);
//初始用户变量
$prompt = $sessionexists = $seccode = 0;
$membertablefields = 'm.uid AS discuz_uid, m.username AS discuz_user, m.password AS discuz_pw, m.secques AS discuz_secques,
        m.adminid, m.groupid, m.groupexpiry, m.extgroupids, m.email, m.timeoffset, m.tpp, m.ppp, m.posts, m.digestposts,
        m.oltime, m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5,
        m.extcredits6, m.extcredits7, m.extcredits8, m.timeformat, m.dateformat, m.pmsound, m.sigstatus, m.invisible,
        m.lastvisit, m.lastactivity, m.lastpost, m.prompt, m.accessmasks, m.editormode, m.customshow, m.customaddfeed';
if($sid) {//对用户进行权限管理,如是登陆用户进一步完善信息,如是游客,清除本地cookie
        if($discuz_uid) {//如果用户存在查询SESSION表中的SESSION
                $query = $db->query("SELECT s.sid, s.styleid, s.groupid='6' AS ipbanned, s.pageviews AS spageviews, s.lastolupdate, s.seccode, $membertablefields
                        FROM {$tablepre}sessions s, {$tablepre}members m
                        WHERE m.uid=s.uid AND s.sid='$sid' AND CONCAT_WS('.',s.ip1,s.ip2,s.ip3,s.ip4)='$onlineip' AND m.uid='$discuz_uid'
                        AND m.password='$discuz_pw' AND m.secques='$discuz_secques'");
        } else {//查询当前游客存在SESSION表中的SESSION
                $query = $db->query("SELECT sid, uid AS sessionuid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
                        FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'");
        }
        if($_DSESSION = $db->fetch_array($query)) {//当前用户SESSION存在
                $sessionexists = 1;
                if(!empty($_DSESSION['sessionuid'])) {//判断是否为游客 完善登陆用户SESSION
                        $_DSESSION = array_merge($_DSESSION, $db->fetch_first("SELECT $membertablefields
                                FROM {$tablepre}members m WHERE uid='$_DSESSION[sessionuid]'"));
                }
        } else {//游客
                         //清除游客本地的COOKIE
                if($_DSESSION = $db->fetch_first("SELECT sid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
                        FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'")) {
                        clearcookies();
                        $sessionexists = 1;
                }
        }
}
//SESSION不存在
if(!$sessionexists) {
        if($discuz_uid) {//登陆用户 获取信息
                if(!($_DSESSION = $db->fetch_first("SELECT $membertablefields, m.styleid
                        FROM {$tablepre}members m WHERE m.uid='$discuz_uid' AND m.password='$discuz_pw' AND m.secques='$discuz_secques'"))) {
                        clearcookies();
                }
        }
//判断当前用户IP是否受限
        if(ipbanned($onlineip)) $_DSESSION['ipbanned'] = 1;

        $_DSESSION['sid'] = random(6);
        $_DSESSION['seccode'] = random(6, 1);
}
//获取日期时间格式
$_DSESSION['dateformat'] = empty($_DSESSION['dateformat']) || empty($_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1])? $_DCACHE['settings']['dateformat'] : $_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1];
$_DSESSION['timeformat'] = empty($_DSESSION['timeformat']) ? $_DCACHE['settings']['timeformat'] : ($_DSESSION['timeformat'] == 1 ? 'h:i A' : 'H:i');
$_DSESSION['timeoffset'] = isset($_DSESSION['timeoffset']) && $_DSESSION['timeoffset'] != 9999 ? $_DSESSION['timeoffset'] : $_DCACHE['settings']['timeoffset'];

$membertablefields = '';
@extract($_DSESSION);

$newpm = $prompt & 1;
$doingtask = $prompt & 2 ? 1 : 0;

//上次访问 当前时间,格式为用户定义的格式(游客为默认设置)
$lastvisit = empty($lastvisit) ? $timestamp - 86400 : $lastvisit;
$timenow = array('time' => gmdate("$dateformat $timeformat", $timestamp + 3600 * $timeoffset),
        'offset' => ($timeoffset >= 0 ? ($timeoffset == 0 ? '' : '+'.$timeoffset) : $timeoffset));

if(PHP_VERSION > '5.1') {
        @date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
}

$accessadd1 = $accessadd2 = $modadd1 = $modadd2 = $metadescription = '';
//判断是否为登陆用户
//游客扩展信息设为默认

if(empty($discuz_uid) || empty($discuz_user)) {//用户处理,游客
        $discuz_user = $extgroupids = '';
        $discuz_uid = $adminid = $posts = $digestposts = $pageviews = $oltime = $invisible
                = $credits = $extcredits1 = $extcredits2 = $extcredits3 = $extcredits4
                = $extcredits5 = $extcredits6 = $extcredits7 = $extcredits8 = 0;
        $groupid = empty($groupid) || $groupid != 6 ? 7 : 6;

} else {//已登录处理,判断管理员
        $discuz_userss = $discuz_user;
        $discuz_user = addslashes($discuz_user);

        if($accessmasks) {
                $accessadd1 = ', a.allowview, a.allowpost, a.allowreply, a.allowgetattach, a.allowpostattach';
                $accessadd2 = "LEFT JOIN {$tablepre}access a ON a.uid='$discuz_uid' AND a.fid=f.fid";
        }

        if($adminid == 3) {
                $modadd1 = ', m.uid AS ismoderator';
                $modadd2 = "LEFT JOIN {$tablepre}moderators m ON m.uid='$discuz_uid' AND m.fid=f.fid";
        }
}

if($errorreport == 2 || ($errorreport == 1 && $adminid > 0)) {
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
}
//定义论坛哈希值
define('FORMHASH', formhash());

//包含统计页面
$statstatus && !$inajax && require_once DISCUZ_ROOT.'./include/counter.inc.php';
$extra = isset($extra) && @preg_match("/^[&=;a-z0-9]+$/i", $extra) ? $extra : '';
$rsshead = $navtitle = $navigation = '';
//判断组,载入用户组缓存
$_DSESSION['groupid'] = $groupid = empty($ipbanned) ? (empty($groupid) ? 7 : intval($groupid)) : 6;
if(!@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.$groupid.'.php') {
        $grouptype = $db->result_first("SELECT type FROM {$tablepre}usergroups WHERE groupid='$groupid'");
        if(!empty($grouptype)) {
                $cachelost .= ' usergroup_'.$groupid;
        } else {
                $grouptype = 'member';
        }
}
回复

使用道具 举报

 楼主| niuniu5201314 发表于 2010-4-14 14:57:42 | 显示全部楼层
//用户组初始化
if($discuz_uid && $_DSESSION) {//登陆用户
        if(!empty($groupexpiry) && $groupexpiry < $timestamp && !in_array(CURSCRIPT, array('wap', 'member'))) {
                dheader("Location: {$boardurl}member.php?action=groupexpiry");
        } elseif($grouptype && $groupid != getgroupid($discuz_uid, array
                (
                'type' => $grouptype,
                'creditshigher' => $groupcreditshigher,
                'creditslower' => $groupcreditslower
                ), $_DSESSION)) {
                @extract($_DSESSION);
                $cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.intval($groupid).'.php') ? '' : ' usergroup_'.$groupid;
        }
}

$tpp = intval(empty($_DSESSION['tpp']) ? $topicperpage : $_DSESSION['tpp']);
$ppp = intval(empty($_DSESSION['ppp']) ? $postperpage : $_DSESSION['ppp']);
//管理权限初始化
if(!in_array($adminid, array(1, 2, 3))) {
        $alloweditpost = $alloweditpoll = $allowstickthread = $allowmodpost = $allowdelpost = $allowmassprune
                = $allowrefund = $allowcensorword = $allowviewip = $allowbanip = $allowedituser = $allowmoduser
                = $allowbanuser = $allowpostannounce = $allowviewlog = $disablepostctrl = 0;
} elseif(isset($radminid) && $adminid != $radminid && $adminid != $groupid) {
        $cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/admingroup_'.intval($adminid).'.php') ? '' : ' admingroup_'.$groupid;
}
//页面信息初始化
$page = isset($page) ? max(1, intval($page)) : 1;
$tid = isset($tid) && is_numeric($tid) ? $tid : 0;
$fid = isset($fid) && is_numeric($fid) ? $fid : 0;
$typeid = isset($typeid) ? intval($typeid) : 0;

$modthreadkey = isset($modthreadkey) && $modthreadkey == modthreadkey($tid) ? $modthreadkey : '';
$auditstatuson = $modthreadkey ? true : false;

if(!empty($tid) || !empty($fid)) {
        if(empty($tid)) {
                $forum = $db->fetch_first("SELECT f.fid, f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
                        FROM {$tablepre}forums f
                        LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
                        WHERE f.fid='$fid'");
        } else {
                $forum = $db->fetch_first("SELECT t.tid, t.closed,".(defined('SQL_ADD_THREAD') ? SQL_ADD_THREAD : '')." f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
                        FROM {$tablepre}threads t
                        INNER JOIN {$tablepre}forums f ON f.fid=t.fid
                        LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
                        WHERE t.tid='$tid'".($auditstatuson ? '' : " AND t.displayorder>='0'")." LIMIT 1");
                $tid = $forum['tid'];
        }

        if($forum) {
                $fid = $forum['fid'];
                $forum['ismoderator'] = !empty($forum['ismoderator']) || $adminid == 1 || $adminid == 2 ? 1 : 0;
                foreach(array('postcredits', 'replycredits', 'threadtypes', 'threadsorts', 'digestcredits', 'postattachcredits', 'getattachcredits') as $key) {
                        $forum[$key] = !empty($forum[$key]) ? unserialize($forum[$key]) : array();
                }
        } else {
                $fid = 0;
        }
}
//页面样式初始化
                $styleid = intval(!empty($_GET['styleid']) ? $_GET['styleid'] :
                (!empty($_POST['styleid']) ? $_POST['styleid'] :
                (!empty($_DSESSION['styleid']) ? $_DSESSION['styleid'] :
                $_DCACHE['settings']['styleid'])));

$styleid = intval(isset($styles[$styleid]) ? $styleid : $_DCACHE['settings']['styleid']);

if(@!include DISCUZ_ROOT.'./forumdata/cache/style_'.intval(!empty($forum['styleid']) ? $forum['styleid'] : $styleid).'.php') {
        $cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/style_'.($styleid = $_DCACHE['settings']['styleid']).'.php') ? '' : ' style_'.$styleid;
}
//缓存处理
if($cachelost) {
        require_once DISCUZ_ROOT.'./include/cache.func.php';
        updatecache();
        exit('Cache List: '.$cachelost.'<br />Caches successfully created, please refresh.');
}
//========================================================================================================================
if(CURSCRIPT != 'wap') {
        if($nocacheheaders) {
                @dheader("Expires: 0");
                @dheader("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE);
                @dheader("Pragma: no-cache");
        }
        if($headercharset) {
                @dheader('Content-Type: text/html; charset='.$charset);
        }
        if(empty($_DCOOKIE['sid']) || $sid != $_DCOOKIE['sid']) {
                dsetcookie('sid', $sid, 604800, 1, true);
        }
}

$_DCOOKIE['loginuser'] = !empty($_DCOOKIE['loginuser']) ? substr(htmlspecialchars($_DCOOKIE['loginuser']), 0, 15) : '';

if(!empty($insenz['cronnextrun']) && $insenz['cronnextrun'] <= $timestamp) {
        require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
        insenz_runcron();
} elseif($cronnextrun && $cronnextrun <= $timestamp) {
        require_once DISCUZ_ROOT.'./include/cron.func.php';
        runcron();
} elseif(isset($insenz['statsnextrun']) && $insenz['statsnextrun'] <= $timestamp) {
        require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
        insenz_onlinestats();
}
//插件初始化
if(isset($plugins['include']) && is_array($plugins['include'])) {
        foreach($plugins['include'] as $include) {
                if(!$include['adminid'] || ($include['adminid'] && $include['adminid'] >= $adminid)) {
                        @include_once DISCUZ_ROOT.'./plugins/'.$include['script'].'.inc.php';
                }
        }
}

if((!empty($_DCACHE['advs']) || $globaladvs) && !defined('IN_ADMINCP')) {
        require_once DISCUZ_ROOT.'./include/advertisements.inc.php';
}
//是否允许访问
if(isset($allowvisit) && $allowvisit == 0 && !(CURSCRIPT == 'member' && ($action == 'groupexpiry' || $action == 'activate'))) {
        showmessage('user_banned', NULL, 'HALTED');
} elseif(!(in_array(CURSCRIPT, array('logging', 'wap', 'seccode', 'ajax')) || $adminid == 1)) {
        if($bbclosed) {
                clearcookies();
                $closedreason = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable='closedreason'");
                showmessage($closedreason ? $closedreason : 'board_closed', NULL, 'NOPERM');
        }
        periodscheck('visitbanperiods');
}

if((!empty($fromuid) || !empty($fromuser)) && ($creditspolicy['promotion_visit'] || $creditspolicy['promotion_register'])) {
        require_once DISCUZ_ROOT.'/include/promotion.inc.php';
}

if($uc['addfeed']) {
        $customaddfeed = $customaddfeed == '-1' ? 0 : ($customaddfeed == 0 ? $uc['addfeed'] : intval($customaddfeed));
} else {
        $customaddfeed = 0;
}

$rssauth = $rssstatus && $discuz_uid ? rawurlencode(authcode("$discuz_uid\t".($fid ? $fid : '')."\t".substr(md5($discuz_pw.$discuz_secques), 0, 8), 'ENCODE', md5($_DCACHE['settings']['authkey']))) : '0';
$transferstatus = $transferstatus && $allowtransfer;
$feedpostnum = $feedpostnum && $uchomeurl ? intval($feedpostnum) : 0;

?>
回复

使用道具 举报

js_xiaoleme 发表于 2010-4-28 10:41:17 | 显示全部楼层
好详细呀   加油谢谢喽
回复

使用道具 举报

yhf0414 发表于 2010-5-4 14:27:59 | 显示全部楼层
谢谢了!对我有用的,嘿嘿
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|Discuz! 官方站 ( 皖ICP备16010102号 )star

GMT+8, 2024-11-16 23:47 , Processed in 0.041969 second(s), 4 queries , Gzip On, Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表