First commit

This commit is contained in:
2025-06-18 10:24:27 +08:00
commit ebc39cd5dd
3873 changed files with 412712 additions and 0 deletions

View File

@@ -0,0 +1,312 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_admincp.php 31471 2012-08-31 07:33:26Z zhengqingpeng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_admincp
{
var $core = null;
var $script = null;
var $userlogin = false;
var $adminsession = array();
var $adminuser = array();
var $perms = null;
var $panel = 1;
var $isfounder = false;
var $cpsetting = array();
var $cpaccess = 0;
var $sessionlife = 1800;
var $sessionlimit = 0;
public static function &instance() {
static $object;
if(empty($object)) {
$object = new discuz_admincp();
}
return $object;
}
function __construct() {
;
}
function init() {
if(empty($this->core) || !is_object($this->core)) {
exit('No Discuz core found');
}
$this->cpsetting = $this->core->config['admincp'];
$this->adminuser = & $this->core->var['member'];
$this->core->var['setting']['jspath'] = 'static/js/';
$this->isfounder = $this->checkfounder($this->adminuser);
$this->sessionlimit = TIMESTAMP - $this->sessionlife;
$this->check_cpaccess();
$this->writecplog();
}
function writecplog() {
global $_G;
$extralog = implodearray(array('GET' => $_GET, 'POST' => $_POST), array('formhash', 'submit', 'addsubmit', 'admin_password', 'sid', 'action'));
writelog('cplog', implode("\t", clearlogstring(array($_G['timestamp'], $_G['username'], $_G['adminid'], $_G['clientip'], getgpc('action'), $extralog))));
}
function check_cpaccess() {
global $_G;
$session = array();
if(!$this->adminuser['uid']) {
$this->cpaccess = getglobal('config/admincp/mustlogin') ? -5 : 0;
} else {
if(!$this->isfounder) {
$session = C::t('common_admincp_member')->fetch($this->adminuser['uid']);
if($session) {
$session = array_merge($session, C::t('common_admincp_session')->fetch_session($this->adminuser['uid'], $this->panel));
}
} else {
$session = C::t('common_admincp_session')->fetch_session($this->adminuser['uid'], $this->panel);
}
if(empty($session)) {
$this->cpaccess = $this->isfounder ? 1 : -2;
} elseif($_G['setting']['adminipaccess'] && !ipaccess($_G['clientip'], $_G['setting']['adminipaccess'])) {
$this->do_user_login();
} elseif ($session && empty($session['uid'])) {
$this->cpaccess = 1;
} elseif ($session['dateline'] < $this->sessionlimit) {
$this->cpaccess = 1;
} elseif ($this->cpsetting['checkip'] && ($session['ip'] != $this->core->var['clientip'])) {
$this->cpaccess = 1;
$_G['admincp_checkip_noaccess'] = 1;
} elseif ($session['errorcount'] >= 0 && $session['errorcount'] <= 3) {
$this->cpaccess = 2;
} elseif ($session['errorcount'] == -1) {
$this->cpaccess = 3;
} else {
$this->cpaccess = -1;
}
}
if($this->cpaccess == 2 || $this->cpaccess == 3) {
if(!empty($session['customperm'])) {
$session['customperm'] = dunserialize($session['customperm']);
}
}
$this->adminsession = $session;
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['admin_password'])) {
if($this->cpaccess == 2) {
$this->check_admin_login();
} elseif($this->cpaccess == 0) {
$this->check_user_login();
}
}
if($this->cpaccess == 1) {
C::t('common_admincp_session')->delete_session($this->adminuser['uid'], $this->panel, $this->sessionlife);
C::t('common_admincp_session')->insert(array(
'uid' => $this->adminuser['uid'],
'adminid' => $this->adminuser['adminid'],
'panel' => $this->panel,
'ip' => $this->core->var['clientip'],
'dateline' => TIMESTAMP,
'errorcount' => 0,
));
} elseif ($this->cpaccess == 3) {
$this->load_admin_perms();
C::t('common_admincp_session')->update_session($this->adminuser['uid'], $this->panel, array('dateline' => TIMESTAMP, 'ip' => $this->core->var['clientip'], 'errorcount' => -1));
}
if($this->cpaccess != 3) {
$this->do_user_login();
}
}
function check_admin_login() {
global $_G;
if((empty($_POST['admin_questionid']) || empty($_POST['admin_answer'])) && ($_G['config']['admincp']['forcesecques'] || $_G['group']['forcesecques'])) {
$this->do_user_login();
}
loaducenter();
$ucresult = uc_user_login($this->adminuser['uid'], $_POST['admin_password'], 1, 1, $_POST['admin_questionid'], $_POST['admin_answer'], $this->core->var['clientip']);
if($ucresult[0] > 0) {
C::t('common_admincp_session')->update_session($this->adminuser['uid'], $this->panel, array('dateline' => TIMESTAMP, 'ip' => $this->core->var['clientip'], 'errorcount' => -1));
dheader('Location: '.ADMINSCRIPT.'?'.cpurl('url', array('sid')));
} else {
$errorcount = $this->adminsession['errorcount'] + 1;
C::t('common_admincp_session')->update_session($this->adminuser['uid'], $this->panel, array('dateline' => TIMESTAMP, 'ip' => $this->core->var['clientip'], 'errorcount' => $errorcount));
}
}
function check_user_login() {
global $_G;
$admin_username = isset($_POST['admin_username']) ? trim($_POST['admin_username']) : '';
if($admin_username != '') {
require_once libfile('function/member');
if(logincheck($_POST['admin_username'])) {
if((empty($_POST['admin_questionid']) || empty($_POST['admin_answer'])) && ($_G['config']['admincp']['forcesecques'] || $_G['group']['forcesecques'])) {
$this->do_user_login();
}
$result = userlogin($_POST['admin_username'], $_POST['admin_password'], $_POST['admin_questionid'], $_POST['admin_answer'], 'username', $this->core->var['clientip']);
if($result['status'] == 1) {
$cpgroupid = C::t('common_admincp_member')->fetch($result['member']['uid']);
$cpgroupid = $cpgroupid['uid'];
if($cpgroupid || $this->checkfounder($result['member'])) {
C::t('common_admincp_session')->insert(array(
'uid' =>$result['member']['uid'],
'adminid' =>$result['member']['adminid'],
'panel' =>$this->panel,
'dateline' => TIMESTAMP,
'ip' => $this->core->var['clientip'],
'errorcount' => -1), false, true);
setloginstatus($result['member'], 0);
dheader('Location: '.ADMINSCRIPT.'?'.cpurl('url', array('sid')));
} else {
$this->cpaccess = -2;
}
} else {
loginfailed($_POST['admin_username']);
}
} else {
$this->cpaccess = -4;
}
}
}
function allow($action, $operation, $do) {
if($this->perms === null) {
$this->load_admin_perms();
}
if(isset($this->perms['all'])) {
return $this->perms['all'];
}
if(!empty($_POST) && !array_key_exists('_allowpost', $this->perms) && $action.'_'.$operation != 'misc_custommenu') {
return false;
}
$this->perms['misc_custommenu'] = 1;
$key = $action;
if(isset($this->perms[$key])) {
return $this->perms[$key];
}
$key = $action.'_'.$operation;
if(isset($this->perms[$key])) {
return $this->perms[$key];
}
$key = $action.'_'.$operation.'_'.$do;
if(isset($this->perms[$key])) {
return $this->perms[$key];
}
return false;
}
function load_admin_perms() {
$this->perms = array();
if(!$this->isfounder) {
if($this->adminsession['cpgroupid']) {
foreach(C::t('common_admincp_perm')->fetch_all_by_cpgroupid($this->adminsession['cpgroupid']) as $perm) {
if(empty($this->adminsession['customperm'])) {
$this->perms[$perm['perm']] = true;
} elseif(!in_array($perm['perm'], (array)$this->adminsession['customperm'])) {
$this->perms[$perm['perm']] = true;
}
}
} else {
$this->perms['all'] = true;
}
} else {
$this->perms['all'] = true;
}
}
function checkfounder($user) {
$founders = str_replace(' ', '', $this->cpsetting['founder']);
if(!$user['uid'] || $user['groupid'] != 1 || $user['adminid'] != 1) {
return false;
} elseif(empty($founders)) {
return true;
} elseif(strexists(",$founders,", ",{$user['uid']},")) {
return true;
} elseif(!is_numeric($user['username']) && strexists(",$founders,", ",{$user['username']},")) {
return true;
} else {
return FALSE;
}
}
function do_user_login() {
require $this->admincpfile('login');
}
function do_admin_logout() {
C::t('common_admincp_session')->delete_session($this->adminuser['uid'], $this->panel, $this->sessionlife);
}
function admincpfile($action) {
return DISCUZ_ROOT.'./source/admincp/admincp_'.$action.'.php';
}
function show_admincp_main() {
$this->do_request('main');
}
function show_no_access() {
cpheader();
cpmsg('action_noaccess', '', 'error');
cpfooter();
}
function do_request($action) {
global $_G;
$lang = lang('admincp');
$title = 'cplog_'.getgpc('action').(getgpc('operation') ? '_'.getgpc('operation') : '');
$operation = getgpc('operation');
$do = getgpc('do');
$sid = $_G['sid'];
$isfounder = $this->isfounder;
if($action == 'main' || $this->allow($action, $operation, $do)) {
require DISCUZ_ROOT.'./source/admincp/admincp_'.$action.'.php';
} else {
cpheader();
cpmsg('action_noaccess', '', 'error');
}
}
}

View File

@@ -0,0 +1,905 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_application.php 36342 2017-01-09 01:15:30Z nemohou $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_application extends discuz_base{
var $mem = null;
var $session = null;
var $config = array();
var $var = array();
var $cachelist = array();
var $init_db = true;
var $init_setting = true;
var $init_user = true;
var $init_session = true;
var $init_cron = true;
var $init_misc = true;
var $init_mobile = true;
var $initated = false;
var $superglobal = array(
'GLOBALS' => 1,
'_GET' => 1,
'_POST' => 1,
'_REQUEST' => 1,
'_COOKIE' => 1,
'_SERVER' => 1,
'_ENV' => 1,
'_FILES' => 1,
);
static function &instance() {
static $object;
if(empty($object)) {
$object = new self();
}
return $object;
}
public function __construct() {
$this->_init_cnf();
$this->_init_env();
$this->_init_config();
$this->_init_input();
$this->_init_output();
}
public function init() {
if(!$this->initated) {
$this->_init_db();
$this->_init_setting();
$this->_init_user();
$this->_init_session();
$this->_init_mobile();
$this->_init_cron();
$this->_init_misc();
}
$this->initated = true;
}
private function _init_env() {
error_reporting(E_ERROR);
define('ICONV_ENABLE', function_exists('iconv'));
define('MB_ENABLE', function_exists('mb_convert_encoding'));
define('EXT_OBGZIP', function_exists('ob_gzhandler'));
define('TIMESTAMP', time());
$this->timezone_set();
if(!defined('DISCUZ_CORE_FUNCTION') && !@include(DISCUZ_ROOT.'./source/function/function_core.php')) {
exit('function_core.php is missing');
}
if(function_exists('ini_get')) {
$memorylimit = @ini_get('memory_limit');
if($memorylimit && return_bytes($memorylimit) < 33554432 && function_exists('ini_set')) {
ini_set('memory_limit', '128m');
}
}
define('IS_ROBOT', checkrobot());
foreach ($GLOBALS as $key => $value) {
if (!isset($this->superglobal[$key])) {
$GLOBALS[$key] = null; unset($GLOBALS[$key]);
}
}
if(!defined('APPTYPEID')) {
define('APPTYPEID', 0);
}
if(!defined('CURSCRIPT')) {
define('CURSCRIPT', null);
}
global $_G;
$_G = array(
'uid' => 0,
'username' => '',
'adminid' => 0,
'groupid' => 1,
'sid' => '',
'formhash' => '',
'connectguest' => 0,
'timestamp' => TIMESTAMP,
'starttime' => microtime(true),
'clientip' => $this->_get_client_ip(),
'remoteport' => $_SERVER['REMOTE_PORT'],
'referer' => '',
'charset' => '',
'gzipcompress' => '',
'authkey' => '',
'timenow' => array(),
'widthauto' => 0,
'disabledwidthauto' => 0,
'PHP_SELF' => '',
'siteurl' => '',
'siteroot' => '',
'siteport' => '',
'pluginrunlist' => !defined('PLUGINRUNLIST') ? array() : explode(',', PLUGINRUNLIST),
'config' => & $this->config,
'setting' => array(),
'member' => array(),
'group' => array(),
'cookie' => array(),
'style' => array(),
'cache' => array(),
'session' => array(),
'lang' => array(),
'fid' => 0,
'tid' => 0,
'forum' => array(),
'thread' => array(),
'rssauth' => '',
'home' => array(),
'space' => array(),
'block' => array(),
'article' => array(),
'action' => array(
'action' => APPTYPEID,
'fid' => 0,
'tid' => 0,
),
'mobile' => '',
'notice_structure' => array(
'mypost' => array('post','rate','pcomment','activity','reward','goods','at'),
'interactive' => array('poke','friend','wall','comment','click','sharenotice'),
'system' => array('system','credit','group','verify','magic','task','show','group','pusearticle','mod_member','blog','article'),
'manage' => array('mod_member','report','pmreport'),
'app' => array(),
),
'mobiletpl' => array('1' => 'touch', '2' => 'touch', '3' => 'touch', 'yes' => 'touch'),
);
$_G['PHP_SELF'] = dhtmlspecialchars($this->_get_script_url());
$_G['basescript'] = CURSCRIPT;
$_G['basefilename'] = basename($_G['PHP_SELF']);
$sitepath = substr($_G['PHP_SELF'], 0, strrpos($_G['PHP_SELF'], '/'));
if(defined('IN_API')) {
$sitepath = preg_replace("/\/api\/?.*?$/i", '', $sitepath);
} elseif(defined('IN_ARCHIVER')) {
$sitepath = preg_replace("/\/archiver/i", '', $sitepath);
}
if(defined('IN_NEWMOBILE')) {
$sitepath = preg_replace("/\/m/i", '', $sitepath);
}
$_G['isHTTPS'] = $this->_is_https();
$_G['scheme'] = 'http'.($_G['isHTTPS'] ? 's' : '');
$_G['siteurl'] = dhtmlspecialchars($_G['scheme'].'://'.$_SERVER['HTTP_HOST'].$sitepath.'/');
$url = parse_url($_G['siteurl']);
$_G['siteroot'] = isset($url['path']) ? $url['path'] : '';
$_G['siteport'] = empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' || $_SERVER['SERVER_PORT'] == '443' ? '' : ':'.$_SERVER['SERVER_PORT'];
if(defined('SUB_DIR')) {
$_G['siteurl'] = str_replace(SUB_DIR, '/', $_G['siteurl']);
$_G['siteroot'] = str_replace(SUB_DIR, '/', $_G['siteroot']);
}
$this->var = & $_G;
}
private function _get_script_url() {
if(!isset($this->var['PHP_SELF'])){
$scriptName = basename($_SERVER['SCRIPT_FILENAME']);
if(basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
$this->var['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
} else if(basename($_SERVER['PHP_SELF']) === $scriptName) {
$this->var['PHP_SELF'] = $_SERVER['PHP_SELF'];
} else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
$this->var['PHP_SELF'] = $_SERVER['ORIG_SCRIPT_NAME'];
} else if(($pos = strpos($_SERVER['PHP_SELF'],'/'.$scriptName)) !== false) {
$this->var['PHP_SELF'] = substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
} else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT']) === 0) {
$this->var['PHP_SELF'] = str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
$this->var['PHP_SELF'][0] != '/' && $this->var['PHP_SELF'] = '/'.$this->var['PHP_SELF'];
} else {
system_error('request_tainting');
}
}
return $this->var['PHP_SELF'];
}
private function _init_input() {
if (isset($_GET['GLOBALS']) ||isset($_POST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
system_error('request_tainting');
}
$prelength = strlen($this->config['cookie']['cookiepre']);
foreach($_COOKIE as $key => $val) {
if(substr($key, 0, $prelength) == $this->config['cookie']['cookiepre']) {
$this->var['cookie'][substr($key, $prelength)] = $val;
}
}
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST)) {
$_GET = array_merge($_GET, $_POST);
}
if(isset($_GET['page'])) {
$_GET['page'] = rawurlencode($_GET['page']);
}
if(!(!empty($_GET['handlekey']) && preg_match('/^\w+$/', $_GET['handlekey']))) {
unset($_GET['handlekey']);
}
if(!empty($this->var['config']['input']['compatible']) && !defined('DISCUZ_DEPRECATED')) {
foreach($_GET as $k => $v) {
$this->var['gp_'.$k] = daddslashes($v);
}
}
$this->var['mod'] = empty($_GET['mod']) ? '' : dhtmlspecialchars($_GET['mod']);
$this->var['inajax'] = empty($_GET['inajax']) ? 0 : (empty($this->var['config']['output']['ajaxvalidate']) ? 1 : ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || $_SERVER['REQUEST_METHOD'] == 'POST' ? 1 : 0));
$this->var['page'] = empty($_GET['page']) ? 1 : max(1, intval($_GET['page']));
$this->var['sid'] = $this->var['cookie']['sid'] = isset($this->var['cookie']['sid']) ? dhtmlspecialchars($this->var['cookie']['sid']) : '';
if(empty($this->var['cookie']['saltkey'])) {
$this->var['cookie']['saltkey'] = random(8);
dsetcookie('saltkey', $this->var['cookie']['saltkey'], 86400 * 30, 1, 1);
}
$this->var['authkey'] = md5($this->var['config']['security']['authkey'].$this->var['cookie']['saltkey']);
}
private function _init_cnf() {
$_config = array();
@include DISCUZ_ROOT.'./config/config_global.php';
if(empty($_config)) {
if(!file_exists(DISCUZ_ROOT.'./data/install.lock')) {
header('location: install/');
exit;
} else {
system_error('config_notfound');
}
}
$this->config = & $_config;
}
private function _init_config() {
if(empty($this->var['config']['security']['authkey'])) {
$this->var['config']['security']['authkey'] = md5($this->var['config']['cookie']['cookiepre'].$this->var['config']['db'][1]['dbname']);
}
if(empty($this->var['config']['debug']) || !file_exists(libfile('function/debug'))) {
define('DISCUZ_DEBUG', false);
error_reporting(0);
} elseif($this->var['config']['debug'] === 1 || $this->var['config']['debug'] === 2 || !empty($_REQUEST['debug']) && $_REQUEST['debug'] === $this->var['config']['debug']) {
define('DISCUZ_DEBUG', true);
error_reporting(E_ERROR);
if($this->var['config']['debug'] === 2) {
error_reporting(E_ALL);
}
} else {
define('DISCUZ_DEBUG', false);
error_reporting(0);
}
if(!empty($this->var['config']['deprecated'])) {
define('DISCUZ_DEPRECATED', $this->var['config']['deprecated']);
}
define('STATICURL', !empty($this->var['config']['output']['staticurl']) ? $this->var['config']['output']['staticurl'] : 'static/');
$this->var['staticurl'] = STATICURL;
if(substr($this->var['config']['cookie']['cookiepath'], 0, 1) != '/') {
$this->var['config']['cookie']['cookiepath'] = '/'.$this->var['config']['cookie']['cookiepath'];
}
$this->var['config']['cookie']['cookiepre'] = $this->var['config']['cookie']['cookiepre'].substr(md5($this->var['config']['cookie']['cookiepath'].'|'.$this->var['config']['cookie']['cookiedomain']), 0, 4).'_';
}
private function _init_output() {
if($this->config['security']['attackevasive'] && (!defined('CURSCRIPT') || !in_array($this->var['mod'], array('seccode', 'secqaa', 'swfupload')) && !defined('DISABLEDEFENSE'))) {
require_once libfile('misc/security', 'include');
}
if(!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) {
$this->config['output']['gzip'] = false;
}
$allowgzip = $this->config['output']['gzip'] && empty($this->var['inajax']) && $this->var['mod'] != 'attachment' && EXT_OBGZIP;
setglobal('gzipcompress', $allowgzip);
if(!ob_start($allowgzip ? 'ob_gzhandler' : null)) {
ob_start();
}
setglobal('charset', $this->config['output']['charset']);
define('CHARSET', $this->config['output']['charset']);
if($this->config['output']['forceheader']) {
@header('Content-Type: text/html; charset='.CHARSET);
}
if($this->var['isHTTPS'] && isset($this->config['output']['upgradeinsecure']) && $this->config['output']['upgradeinsecure']) {
@header('Content-Security-Policy: upgrade-insecure-requests');
}
}
public function reject_robot() {
if(IS_ROBOT) {
exit(header("HTTP/1.1 403 Forbidden"));
}
}
private function _xss_check() {
static $check = array('"', '>', '<', '\'', '(', ')', 'CONTENT-TRANSFER-ENCODING');
if(isset($_GET['formhash']) && $_GET['formhash'] !== formhash()) {
if(defined('CURMODULE') && constant('CURMODULE') == 'logging' && isset($_GET['action']) && $_GET['action'] == 'logout') {
header("HTTP/1.1 302 Found");
header("Location: index.php");
exit();
} else {
system_error('request_tainting');
}
}
if($_SERVER['REQUEST_METHOD'] == 'GET' ) {
$temp = $_SERVER['REQUEST_URI'];
} elseif(empty ($_GET['formhash'])) {
$temp = $_SERVER['REQUEST_URI'].http_build_query($_POST);
} else {
$temp = '';
}
if(!empty($temp)) {
$temp = strtoupper(urldecode(urldecode($temp)));
foreach ($check as $str) {
if(strpos($temp, $str) !== false) {
system_error('request_tainting');
}
}
}
return true;
}
private function _is_https() {
if(isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
return true;
}
if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
return true;
}
if(isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && strtolower($_SERVER['HTTP_X_CLIENT_SCHEME']) == 'https') {
return true;
}
if(isset($_SERVER['HTTP_FROM_HTTPS']) && strtolower($_SERVER['HTTP_FROM_HTTPS']) != 'off') {
return true;
}
if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
private function _get_client_ip() {
$ip = $_SERVER['REMOTE_ADDR'];
if (!array_key_exists('security', $this->config) || !$this->config['security']['onlyremoteaddr']) {
if (array_key_exists('ipgetter', $this->config) && !empty($this->config['ipgetter']['setting'])) {
$s = empty($this->config['ipgetter'][$this->config['ipgetter']['setting']]) ? array() : $this->config['ipgetter'][$this->config['ipgetter']['setting']];
$c = 'ip_getter_'.$this->config['ipgetter']['setting'];
$r = $c::get($s);
$ip = ip::validate_ip($r) ? $r : $ip;
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && ip::validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ",") > 0) {
$exp = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = ip::validate_ip(trim($exp[0])) ? $exp[0] : $ip;
} else {
$ip = ip::validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $ip;
}
}
}
return $ip;
}
private function _init_db() {
if($this->init_db) {
$driver = 'db_driver_mysqli';
if(getglobal('config/db/slave')) {
$driver = 'db_driver_mysqli_slave';
}
DB::init($driver, $this->config['db']);
}
}
private function _init_session() {
$sessionclose = !empty($this->var['setting']['sessionclose']);
$this->session = $sessionclose ? new discuz_session_close() : new discuz_session();
if($this->init_session) {
$this->session->init($this->var['cookie']['sid'], $this->var['clientip'], $this->var['uid']);
$this->var['sid'] = $this->session->sid;
$this->var['session'] = $this->session->var;
if(isset($this->var['sid']) && $this->var['sid'] !== $this->var['cookie']['sid']) {
dsetcookie('sid', $this->var['sid'], 86400);
}
if(ip::checkbanned($this->var['clientip'])) {
$this->session->set('groupid', 6);
}
if($this->session->get('groupid') == 6) {
$this->var['member']['groupid'] = 6;
if(!defined('IN_MOBILE_API')) {
sysmessage('user_banned');
} else {
mobile_core::result(array('error' => 'user_banned'));
}
}
if($this->var['uid'] && !$sessionclose && ($this->session->isnew || ($this->session->get('lastactivity') + 600) < TIMESTAMP)) {
$this->session->set('lastactivity', TIMESTAMP);
if($this->session->isnew) {
if($this->var['member']['lastip'] && $this->var['member']['lastvisit']) {
dsetcookie('lip', $this->var['member']['lastip'].','.$this->var['member']['lastvisit']);
}
C::t('common_member_status')->update($this->var['uid'], array('lastip' => $this->var['clientip'], 'port' => $this->var['remoteport'], 'lastvisit' => TIMESTAMP));
}
}
}
}
private function _init_user() {
if($this->init_user) {
if($auth = getglobal('auth', 'cookie')) {
$auth = daddslashes(explode("\t", authcode($auth, 'DECODE')));
}
list($discuz_pw, $discuz_uid) = empty($auth) || count($auth) < 2 ? array('', '') : $auth;
if($discuz_uid) {
$user = getuserbyuid($discuz_uid, 1);
}
if(!empty($user) && $user['password'] == $discuz_pw) {
if(isset($user['_inarchive'])) {
C::t('common_member_archive')->move_to_master($discuz_uid);
}
$this->var['member'] = $user;
} else {
$user = array();
$this->_init_guest();
}
if($user && $user['groupexpiry'] > 0 && $user['groupexpiry'] < TIMESTAMP) {
$memberfieldforum = C::t('common_member_field_forum')->fetch($discuz_uid);
$groupterms = dunserialize($memberfieldforum['groupterms']);
if(!empty($groupterms['main'])) {
if($groupterms['main']['groupid']) {
$user['groupid'] = $groupterms['main']['groupid'];
} else {
$groupnew = C::t('common_usergroup')->fetch_by_credits($user['credits']);
$user['groupid'] = $groupnew['groupid'];
}
$user['adminid'] = $groupterms['main']['adminid'];
C::t("common_member")->update($user['uid'], array('groupexpiry'=> 0, 'groupid' => $user['groupid'], 'adminid' => $user['adminid']));
unset($groupterms['main'], $groupterms['ext'][$this->var['member']['groupid']]);
$this->var['member'] = $user;
C::t('common_member_field_forum')->update($discuz_uid, array('groupterms' => serialize($groupterms)));
} elseif((getgpc('mod') != 'spacecp' || CURSCRIPT != 'home') && CURSCRIPT != 'member') {
dheader('location: home.php?mod=spacecp&ac=usergroup&do=expiry');
}
}
if($user && $user['freeze'] && (getgpc('mod') != 'spacecp' && getgpc('mod') != 'misc' || CURSCRIPT != 'home') && CURSCRIPT != 'member' && CURSCRIPT != 'misc') {
dheader('location: home.php?mod=spacecp&ac=profile&op=password');
}
$this->cachelist[] = 'usergroup_'.$this->var['member']['groupid'];
if($user && $user['adminid'] > 0 && $user['groupid'] != $user['adminid']) {
$this->cachelist[] = 'admingroup_'.$this->var['member']['adminid'];
}
} else {
$this->_init_guest();
}
setglobal('groupid', getglobal('groupid', 'member'));
!empty($this->cachelist) && loadcache($this->cachelist);
if($this->var['member'] && $this->var['group']['radminid'] == 0 && $this->var['member']['adminid'] > 0 && $this->var['member']['groupid'] != $this->var['member']['adminid'] && !empty($this->var['cache']['admingroup_'.$this->var['member']['adminid']])) {
$this->var['group'] = array_merge($this->var['group'], $this->var['cache']['admingroup_'.$this->var['member']['adminid']]);
}
if(!empty($this->var['group']['allowmakehtml']) && isset($_GET['_makehtml'])) {
$this->var['makehtml'] = 1;
$this->_init_guest();
loadcache(array('usergroup_7'));
$this->var['group'] = $this->var['cache']['usergroup_7'];
unset($this->var['inajax']);
}
if(empty($this->var['cookie']['lastvisit'])) {
$this->var['member']['lastvisit'] = TIMESTAMP - 3600;
dsetcookie('lastvisit', TIMESTAMP - 3600, 86400 * 30);
} else {
$this->var['member']['lastvisit'] = $this->var['cookie']['lastvisit'];
}
setglobal('uid', getglobal('uid', 'member'));
setglobal('username', getglobal('username', 'member'));
setglobal('adminid', getglobal('adminid', 'member'));
setglobal('groupid', getglobal('groupid', 'member'));
if(!empty($this->var['member']['newprompt'])) {
$this->var['member']['newprompt_num'] = C::t('common_member_newprompt')->fetch($this->var['member']['uid']);
$this->var['member']['newprompt_num'] = dunserialize($this->var['member']['newprompt_num']['data']);
$this->var['member']['category_num'] = helper_notification::get_categorynum($this->var['member']['newprompt_num']);
}
}
private function _init_guest() {
$username = '';
$groupid = 7;
if(!empty($this->var['cookie']['con_auth_hash']) && ($openid = authcode($this->var['cookie']['con_auth_hash']))) {
$this->var['connectguest'] = 1;
$username = 'QQ_'.substr($openid, -6);
$this->var['setting']['cacheindexlife'] = 0;
$this->var['setting']['cachethreadlife'] = 0;
$groupid = $this->var['setting']['connect']['guest_groupid'] ? $this->var['setting']['connect']['guest_groupid'] : $this->var['setting']['newusergroupid'];
}
setglobal('member', array( 'uid' => 0, 'username' => $username, 'adminid' => 0, 'groupid' => $groupid, 'credits' => 0, 'timeoffset' => 9999));
}
private function _init_cron() {
$ext = empty($this->config['remote']['on']) || empty($this->config['remote']['cron']) || APPTYPEID == 200;
if($this->init_cron && $this->init_setting && $ext) {
if($this->var['cache']['cronnextrun'] <= TIMESTAMP) {
discuz_cron::run();
}
}
}
private function _init_misc() {
if($this->config['security']['urlxssdefend'] && !defined('DISABLEXSSCHECK')) {
$this->_xss_check();
}
if(!$this->init_misc) {
return false;
}
lang('core');
if($this->init_setting && $this->init_user) {
if(!isset($this->var['member']['timeoffset']) || $this->var['member']['timeoffset'] == 9999 || $this->var['member']['timeoffset'] === '') {
$this->var['member']['timeoffset'] = $this->var['setting']['timeoffset'];
}
}
$timeoffset = $this->init_setting ? $this->var['member']['timeoffset'] : $this->var['setting']['timeoffset'];
$this->var['timenow'] = array(
'time' => dgmdate(TIMESTAMP),
'offset' => $timeoffset >= 0 ? ($timeoffset == 0 ? '' : '+'.$timeoffset) : $timeoffset
);
$this->timezone_set($timeoffset);
$this->var['formhash'] = formhash();
define('FORMHASH', $this->var['formhash']);
if($this->init_user) {
$allowvisitflag = in_array(CURSCRIPT, array('member')) || defined('ALLOWGUEST') && ALLOWGUEST;
if($this->var['group'] && isset($this->var['group']['allowvisit']) && !$this->var['group']['allowvisit']) {
if($this->var['uid'] && !$allowvisitflag) {
if(!defined('IN_MOBILE_API')) {
($this->var['member']['groupexpiry'] > 0) ? showmessage('user_banned_has_expiry', '', array('expiry' => dgmdate($this->var['member']['groupexpiry'], 'Y-m-d H:i:s'))) : showmessage('user_banned');
} else {
($this->var['member']['groupexpiry'] > 0) ? mobile_core::result(array('error' => 'user_banned_has_expiry')) : mobile_core::result(array('error' => 'user_banned'));
}
} elseif((!defined('ALLOWGUEST') || !ALLOWGUEST) && !in_array(CURSCRIPT, array('member', 'api'))) {
if(defined('IN_ARCHIVER')) {
dheader('location: ../member.php?mod=logging&action=login&referer='.rawurlencode($this->var['siteurl']."archiver/".$this->var['basefilename'].($_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '')));
} else if(!defined('IN_MOBILE_API')) {
dheader('location: member.php?mod=logging&action=login&referer='.rawurlencode($this->var['siteurl'].$this->var['basefilename'].($_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '')));
} else {
mobile_core::result(array('error' => 'to_login'));
}
}
}
if(isset($this->var['member']['status']) && $this->var['member']['status'] == -1 && !$allowvisitflag) {
if(!defined('IN_MOBILE_API')) {
showmessage('user_banned');
} else {
mobile_core::result(array('error' => 'user_banned'));
}
}
}
if($this->var['setting']['ipaccess'] && !ipaccess($this->var['clientip'], $this->var['setting']['ipaccess'])) {
if(!defined('IN_MOBILE_API')) {
showmessage('user_banned');
} else {
mobile_core::result(array('error' => 'user_banned'));
}
}
if($this->var['setting']['bbclosed']) {
if($this->var['uid'] && ($this->var['group']['allowvisit'] == 2 || $this->var['groupid'] == 1)) {
} elseif(in_array(CURSCRIPT, array('admin', 'member', 'api')) || defined('ALLOWGUEST') && ALLOWGUEST) {
} else {
$closedreason = C::t('common_setting')->fetch_setting('closedreason');
$closedreason = str_replace(':', '&#58;', $closedreason);
if(!defined('IN_MOBILE_API')) {
showmessage($closedreason ? $closedreason : 'board_closed', NULL, array('adminemail' => $this->var['setting']['adminemail']), array('login' => 1));
} else {
mobile_core::result(array('error' => $closedreason ? $closedreason : 'board_closed'));
}
}
}
if(CURSCRIPT != 'admin' && !(in_array($this->var['mod'], array('logging', 'seccode')))) {
periodscheck('visitbanperiods');
}
if(defined('IN_MOBILE')) {
$this->var['tpp'] = $this->var['setting']['mobile']['forum']['topicperpage'] ? intval($this->var['setting']['mobile']['forum']['topicperpage']) : ($this->var['setting']['topicperpage'] ? intval($this->var['setting']['topicperpage']) : 20);
$this->var['ppp'] = $this->var['setting']['mobile']['forum']['postperpage'] ? intval($this->var['setting']['mobile']['forum']['postperpage']) : ($this->var['setting']['postperpage'] ? intval($this->var['setting']['postperpage']) : 10);
} else {
$this->var['tpp'] = $this->var['setting']['topicperpage'] ? intval($this->var['setting']['topicperpage']) : 20;
$this->var['ppp'] = $this->var['setting']['postperpage'] ? intval($this->var['setting']['postperpage']) : 10;
}
if($this->var['setting']['nocacheheaders']) {
@header("Expires: -1");
@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
@header("Pragma: no-cache");
}
if($this->session->isnew && $this->var['uid']) {
updatecreditbyaction('daylogin', $this->var['uid']);
include_once libfile('function/stat');
updatestat('login', 1);
if(defined('IN_MOBILE')) {
updatestat('mobilelogin', 1);
}
if($this->var['setting']['connect']['allow'] && $this->var['member']['conisbind']) {
updatestat('connectlogin', 1);
}
}
if(isset($this->var['member']['conisbind']) && $this->var['member']['conisbind'] && $this->var['setting'] && $this->var['setting']['connect']['newbiespan'] !== '') {
$this->var['setting']['newbiespan'] = $this->var['setting']['connect']['newbiespan'];
}
$lastact = TIMESTAMP."\t".dhtmlspecialchars(basename($this->var['PHP_SELF']))."\t".dhtmlspecialchars($this->var['mod']);
dsetcookie('lastact', $lastact, 86400);
setglobal('currenturl_encode', base64_encode($this->var['scheme'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']));
if((!empty($_GET['fromuid']) || !empty($_GET['fromuser'])) && ($this->var['setting']['creditspolicy']['promotion_visit'] || $this->var['setting']['creditspolicy']['promotion_register'])) {
require_once libfile('misc/promotion', 'include');
}
$this->var['seokeywords'] = !empty($this->var['setting']['seokeywords'][CURSCRIPT]) ? $this->var['setting']['seokeywords'][CURSCRIPT] : '';
$this->var['seodescription'] = !empty($this->var['setting']['seodescription'][CURSCRIPT]) ? $this->var['setting']['seodescription'][CURSCRIPT] : '';
}
private function _init_setting() {
if($this->init_setting) {
if(empty($this->var['setting'])) {
$this->cachelist[] = 'setting';
}
if(empty($this->var['style'])) {
$this->cachelist[] = 'style_default';
}
if(!isset($this->var['cache']['cronnextrun'])) {
$this->cachelist[] = 'cronnextrun';
}
}
!empty($this->cachelist) && loadcache($this->cachelist);
if(!is_array($this->var['setting']) && !is_a($this->var['setting'], 'memory_setting_array')) {
$this->var['setting'] = array();
}
}
public function _init_style() {
if(defined('IN_MOBILE')) {
$mobile = max(1, intval(IN_MOBILE));
if($mobile && $this->var['setting']['styleid'.$mobile]) {
$styleid = $this->var['setting']['styleid'.$mobile];
}
} else {
$styleid = !empty($this->var['cookie']['styleid']) ? $this->var['cookie']['styleid'] : 0;
if(intval(!empty($this->var['forum']['styleid']))) {
$this->var['cache']['style_default']['styleid'] = $styleid = $this->var['forum']['styleid'];
} elseif(intval(!empty($this->var['category']['styleid']))) {
$this->var['cache']['style_default']['styleid'] = $styleid = $this->var['category']['styleid'];
}
}
if(defined('IN_NEWMOBILE') && $this->var['setting']['mobile']['allowmnew'] && $this->var['setting']['styleid2']) {
$styleid = $this->var['setting']['styleid2'];
}
$styleid = intval($styleid);
if($styleid && $styleid != $this->var['setting']['styleid']) {
loadcache('style_'.$styleid);
if($this->var['cache']['style_'.$styleid]) {
$this->var['style'] = $this->var['cache']['style_'.$styleid];
}
}
define('IMGDIR', $this->var['style']['imgdir']);
define('STYLEID', $this->var['style']['styleid']);
define('VERHASH', $this->var['style']['verhash']);
define('TPLDIR', $this->var['style']['tpldir']);
define('TEMPLATEID', $this->var['style']['templateid']);
}
private function _init_mobile() {
if(!$this->init_mobile) {
if(!defined('HOOKTYPE')) {
define('HOOKTYPE', 'hookscript');
}
return false;
}
if(!$this->var['setting'] || !$this->var['setting']['mobile']['allowmobile'] || !is_array($this->var['setting']['mobile'])) {
$nomobile = true;
$unallowmobile = true;
}
if(getgpc('forcemobile')) {
dsetcookie('dismobilemessage', '1', 3600);
}
$mobile = getgpc('mobile');
if(!getgpc('mobile') && getgpc('showmobile')) {
$mobile = getgpc('showmobile');
}
$mobileflag = isset($this->var['mobiletpl'][$mobile]);
if($mobile === 'no') {
dsetcookie('mobile', 'no', 3600);
$nomobile = true;
} elseif(isset($this->var['cookie']['mobile']) && $this->var['cookie']['mobile'] == 'no' && $mobileflag) {
checkmobile();
dsetcookie('mobile', '');
} elseif(isset($this->var['cookie']['mobile']) && $this->var['cookie']['mobile'] == 'no') {
$nomobile = true;
} elseif(!($mobile_ = checkmobile())) {
$nomobile = true;
}
if(!$mobile || $mobile == 'yes') {
$mobile = isset($mobile_) ? $mobile_ : 2;
}
if(!$this->var['mobile'] && empty($unallowmobile) && $mobileflag) {
if(getgpc('showmobile')) {
dheader("Location:misc.php?mod=mobile");
}
parse_str($_SERVER['QUERY_STRING'], $query);
$query['mobile'] = 'no';
unset($query['simpletype']);
$query_sting_tmp = http_build_query($query);
$redirect = ($this->var['setting']['domain']['app']['forum'] ? $this->var['scheme'].'://'.$this->var['setting']['domain']['app']['forum'].'/' : $this->var['siteurl']).$this->var['basefilename'].'?'.$query_sting_tmp;
dheader('Location: '.$redirect);
}
if($nomobile || (!$this->var['setting']['mobile']['mobileforward'] && !$mobileflag)) {
if(!defined('HOOKTYPE')) {
define('HOOKTYPE', 'hookscript');
}
if(!empty($this->var['setting']['domain']['app']['mobile']) && $_SERVER['HTTP_HOST'] == $this->var['setting']['domain']['app']['mobile'] && !empty($this->var['setting']['domain']['app']['default'])) {
dheader('Location:'.$this->var['scheme'].'://'.$this->var['setting']['domain']['app']['default'].$_SERVER['REQUEST_URI']);
return false;
} else {
return false;
}
}
if($mobile !== '2' && $mobile !== '3' && empty($this->var['setting']['mobile']['legacy'])) {
$mobile = '2';
}
define('IN_MOBILE', isset($this->var['mobiletpl'][$mobile]) ? $mobile : '2');
if(!defined('HOOKTYPE')) {
define('HOOKTYPE', 'hookscriptmobile');
}
setglobal('gzipcompress', 0);
$arr = array();
foreach(array_keys($this->var['mobiletpl']) as $mobiletype) {
$arr[] = '&mobile='.$mobiletype;
$arr[] = 'mobile='.$mobiletype;
}
parse_str($_SERVER['QUERY_STRING'], $query);
$query['mobile'] = 'no';
unset($query['simpletype']);
$query_sting_tmp = http_build_query($query);
$this->var['setting']['mobile']['nomobileurl'] = ($this->var['setting']['domain']['app']['forum'] ? $this->var['scheme'].'://'.$this->var['setting']['domain']['app']['forum'].'/' : $this->var['siteurl']).$this->var['basefilename'].'?'.$query_sting_tmp;
$this->var['setting']['lazyload'] = 0;
if('utf-8' != CHARSET) {
if(strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
foreach($_POST AS $pk => $pv) {
if(!is_numeric($pv)) {
$_GET[$pk] = $_POST[$pk] = $this->mobile_iconv_recurrence($pv);
if(!empty($this->var['config']['input']['compatible'])) {
$this->var['gp_'.$pk] = daddslashes($_GET[$pk]);
}
}
}
}
}
if(!$this->var['setting']['mobile']['mobilesimpletype']) {
$this->var['setting']['imagemaxwidth'] = 224;
}
$this->var['setting']['regstatus'] = $this->var['setting']['mobile']['mobileregister'] ? $this->var['setting']['regstatus'] : 0 ;
$this->var['setting']['avatarmethod'] = 0;
ob_start();
}
public function timezone_set($timeoffset = 0) {
if(function_exists('date_default_timezone_set')) {
@date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
}
}
public function mobile_iconv_recurrence($value) {
if(is_array($value)) {
foreach($value AS $key => $val) {
$value[$key] = $this->mobile_iconv_recurrence($val);
}
} else {
$value = diconv($value, 'utf-8', CHARSET);
}
return $value;
}
}
?>

View File

@@ -0,0 +1,66 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_base.php 30321 2012-05-22 09:09:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
abstract class discuz_base
{
private $_e;
private $_m;
public function __construct() {
}
public function __set($name, $value) {
$setter='set'.$name;
if(method_exists($this,$setter)) {
return $this->$setter($value);
} elseif($this->canGetProperty($name)) {
throw new Exception('The property "'.get_class($this).'->'.$name.'" is readonly');
} else {
throw new Exception('The property "'.get_class($this).'->'.$name.'" is not defined');
}
}
public function __get($name) {
$getter='get'.$name;
if(method_exists($this,$getter)) {
return $this->$getter();
} else {
throw new Exception('The property "'.get_class($this).'->'.$name.'" is not defined');
}
}
public function __call($name,$parameters) {
throw new Exception('Class "'.get_class($this).'" does not have a method named "'.$name.'".');
}
public function canGetProperty($name)
{
return method_exists($this,'get'.$name);
}
public function canSetProperty($name)
{
return method_exists($this,'set'.$name);
}
public function __toString() {
return get_class($this);
}
public function __invoke() {
return get_class($this);
}
}
?>

View File

@@ -0,0 +1,20 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_block.php 27449 2012-02-01 05:32:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_block
{
public function cookparameter($parameter) {
return daddslashes($parameter);
}
}
?>

View File

@@ -0,0 +1,111 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_censor.php 31079 2012-07-13 07:03:10Z liulanbo $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
define('DISCUZ_CENSOR_SUCCEED', 0);
define('DISCUZ_CENSOR_BANNED', 1);
define('DISCUZ_CENSOR_MODERATED', 2);
define('DISCUZ_CENSOR_REPLACED', 3);
class discuz_censor {
var $table = 'common_word';
var $censor_words = array();
var $bbcodes_display;
var $result;
var $words_found = array();
var $highlight;
public function __construct() {
global $_G;
loadcache(array('censor', 'bbcodes_display'));
$this->censor_words = !empty($_G['cache']['censor']) ? $_G['cache']['censor'] : array();
$this->bbcodes_display = $_G['cache']['bbcodes_display'][$_G['groupid']];
}
public static function & instance() {
static $instance;
if(!$instance) {
$instance = new self();
}
return $instance;
}
function highlight($message, $badwords_regex) {
$color = $this->highlight;
if(empty($color)) {
return $message;
}
$message = preg_replace($badwords_regex, '<span style="color: '.$color.';">\\1</span>', $message);
return $message;
}
function check(&$message, $modword = NULL) {
$limitnum = 500;
$this->words_found = array();
$bbcodes = 'b|i|color|size|font|align|list|indent|email|hide|quote|code|free|table|tr|td|img|swf|attach|payto|float'.($this->bbcodes_display ? '|'.implode('|', array_keys($this->bbcodes_display)) : '');
if(is_array($this->censor_words['banned']) && !empty($this->censor_words['banned'])) {
foreach($this->censor_words['banned'] as $banned_words) {
if(preg_match_all($banned_words, @preg_replace(array("/\[($bbcodes)=?(.*)\]/iU", "/\[\/($bbcodes)\]/i"), array('${2}', ''), $message), $matches)) {
$this->words_found = $matches[0];
$this->result = DISCUZ_CENSOR_BANNED;
$this->words_found = array_unique($this->words_found);
$message = $this->highlight($message, $banned_words);
return DISCUZ_CENSOR_BANNED;
}
}
}
if(is_array($this->censor_words['mod']) && !empty($this->censor_words['mod'])) {
if($modword !== NULL) {
$message = preg_replace($this->censor_words['mod'], $modword, $message);
}
foreach($this->censor_words['mod'] as $mod_words) {
if(preg_match_all($mod_words, @preg_replace(array("/\[($bbcodes)=?(.*)\]/iU", "/\[\/($bbcodes)\]/i"), array('${2}', ''), $message), $matches)) {
$this->words_found = $matches[0];
$this->result = DISCUZ_CENSOR_MODERATED;
$message = $this->highlight($message, $mod_words);
$this->words_found = array_unique($this->words_found);
return DISCUZ_CENSOR_MODERATED;
}
}
}
if(!empty($this->censor_words['filter'])) {
$i = 0;
while($find_words = array_slice($this->censor_words['filter']['find'], $i, $limitnum)) {
if(empty($find_words)) break;
$replace_words = array_slice($this->censor_words['filter']['replace'], $i, $limitnum);
$i += $limitnum;
$message = preg_replace($find_words, $replace_words, $message);
}
$this->result = DISCUZ_CENSOR_REPLACED;
return DISCUZ_CENSOR_REPLACED;
}
$this->result = DISCUZ_CENSOR_SUCCEED;
return DISCUZ_CENSOR_SUCCEED;
}
function modbanned() {
return $this->result == DISCUZ_CENSOR_BANNED;
}
function modmoderated() {
return $this->result == DISCUZ_CENSOR_MODERATED;
}
function modreplaced() {
return $this->result == DISCUZ_CENSOR_REPLACED;
}
function modsucceed() {
return $this->result == DISCUZ_CENSOR_SUCCEED;
}
}

View File

@@ -0,0 +1,154 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_container.php 32457 2013-01-21 05:19:57Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_container extends discuz_base
{
protected $_obj;
protected $_objs = array();
public function __construct($obj = null) {
if(isset($obj)) {
if(is_object($obj)) {
$this->_obj = $obj;
} else if(is_string($obj)) {
try {
if(func_num_args()) {
$p = func_get_args();
unset($p[0]);
$ref = new ReflectionClass($obj);
$this->_obj = $ref->newInstanceArgs($p);
unset($ref);
} else {
$this->_obj = new $obj;
}
} catch (Exception $e) {
throw new Exception('Class "'.$obj.'" does not exists.');
}
}
}
parent::__construct();
}
public function getobj() {
return $this->_obj;
}
public function setobj($value) {
$this->_obj = $value;
}
public function __call($name, $p) {
if(method_exists($this->_obj, $name)) {
if(isset($this->_obj->methods[$name][0])) {
$this->_call($name, $p, 0);
}
switch (count($p)) {
case 0: $this->_obj->data = $this->_obj->{$name}();break;
case 1: $this->_obj->data = $this->_obj->{$name}($p[0]);break;
case 2: $this->_obj->data = $this->_obj->{$name}($p[0], $p[1]);break;
case 3: $this->_obj->data = $this->_obj->{$name}($p[0], $p[1], $p[2]);break;
case 4: $this->_obj->data = $this->_obj->{$name}($p[0], $p[1], $p[2], $p[3]);break;
case 5: $this->_obj->data = $this->_obj->{$name}($p[0], $p[1], $p[2], $p[3], $p[4]);break;
default: $this->_obj->data = call_user_func_array(array($this->_obj, $name), $p);break;
}
if(isset($this->_obj->methods[$name][1])) {
$this->_call($name, $p, 1);
}
return $this->_obj->data;
} else {
throw new Exception('Class "'.get_class($this->_obj).'" does not have a method named "'.$name.'".');
}
}
protected function _call($name, $p, $type) {
$ret = null;
if(isset($this->_obj->methods[$name][$type])) {
foreach($this->_obj->methods[$name][$type] as $extend) {
if(is_array($extend) && isset($extend['class'])) {
$obj = $this->_getobj($extend['class'], $this->_obj);
switch (count($p)) {
case 0: $ret = $obj->{$extend['method']}();break;
case 1: $ret = $obj->{$extend['method']}($p[0]);break;
case 2: $ret = $obj->{$extend['method']}($p[0], $p[1]);break;
case 3: $ret = $obj->{$extend['method']}($p[0], $p[1], $p[2]);break;
case 4: $ret = $obj->{$extend['method']}($p[0], $p[1], $p[2], $p[3]);break;
case 5: $ret = $obj->{$extend['method']}($p[0], $p[1], $p[2], $p[3], $p[4]);break;
default: $ret = call_user_func_array(array($obj, $extend['method']), $p);break;
}
} elseif(is_callable($extend, true)) {
if(is_array($extend)) {
list($obj, $method) = $extend;
if(method_exists($obj, $method)) {
if(is_object($obj)) {
$obj->obj = $this->_obj;
switch (count($p)) {
case 0: $ret = $obj->{$method}();break;
case 1: $ret = $obj->{$method}($p[0]);break;
case 2: $ret = $obj->{$method}($p[0], $p[1]);break;
case 3: $ret = $obj->{$method}($p[0], $p[1], $p[2]);break;
case 4: $ret = $obj->{$method}($p[0], $p[1], $p[2], $p[3]);break;
case 5: $ret = $obj->{$method}($p[0], $p[1], $p[2], $p[3], $p[4]);break;
default: $ret = call_user_func_array(array($obj, $method), $p);break;
}
} else {
$p[] = $this;
$ret = call_user_func_array($extend, $p);
}
}/* else {
throw new Exception('Class "'.get_class($extend[0]).'" does not have a method named "'.$extend[1].'".');
}*/
} else {
$p[] = $this->_obj;
$ret = call_user_func_array($extend, $p);
}
}
}
}
return $ret;
}
protected function _getobj($class, $obj) {
if(!isset($this->_objs[$class])) {
$this->_objs[$class] = new $class($obj);
if(method_exists($this->_objs[$class], 'init_base_var')) {
$this->_objs[$class]->init_base_var();
}
}
return $this->_objs[$class];
}
public function __get($name) {
if(isset($this->_obj) && property_exists($this->_obj, $name) === true) {
return $this->_obj->$name;
} else {
return parent::__get($name);
}
}
public function __set($name, $value) {
if(isset($this->_obj) && property_exists($this->_obj, $name) === true) {
return $this->_obj->$name = $value;
} else {
return parent::__set($name, $value);
}
}
public function __isset($name) {
return isset($this->_obj->$name);
}
}
?>

View File

@@ -0,0 +1,18 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_core.php 27449 2012-02-01 05:32:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_core extends discuz_application {
}
?>

View File

@@ -0,0 +1,175 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_cron.php 30314 2012-05-22 03:12:44Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_cron
{
public static function run($cronid = 0) {
global $_G;
$cron = $cronid ? C::t('common_cron')->fetch($cronid) : C::t('common_cron')->fetch_nextrun(TIMESTAMP);
$processname ='DZ_CRON_'.(empty($cron) ? 'CHECKER' : $cron['cronid']);
if($cronid && !empty($cron)) {
discuz_process::unlock($processname);
}
if(discuz_process::islocked($processname, 600)) {
return false;
}
if($cron) {
$cron['filename'] = str_replace(array('..', '/', '\\'), '', $cron['filename']);
$efile = explode(':', $cron['filename']);
if(count($efile) > 1) {
$cronfile = in_array($efile[0], $_G['setting']['plugins']['available']) ? DISCUZ_ROOT.'./source/plugin/'.$efile[0].'/cron/'.$efile[1] : '';
} else {
$cronfile = DISCUZ_ROOT.'./source/include/cron/'.$cron['filename'];
}
if($cronfile) {
$cron['minute'] = explode("\t", $cron['minute']);
self::setnextime($cron);
@set_time_limit(1000);
@ignore_user_abort(TRUE);
if(!@include $cronfile) {
return false;
}
}else{
$data = array('available' => '0');
C::t('common_cron')->update($cron['cronid'], $data);
}
}
self::nextcron();
discuz_process::unlock($processname);
return true;
}
private static function nextcron() {
$cron = C::t('common_cron')->fetch_nextcron();
if($cron && isset($cron['nextrun'])) {
savecache('cronnextrun', $cron['nextrun']);
} else {
savecache('cronnextrun', TIMESTAMP + 86400 * 365);
}
return true;
}
private static function setnextime($cron) {
if(empty($cron)) return FALSE;
list($yearnow, $monthnow, $daynow, $weekdaynow, $hournow, $minutenow) = explode('-', gmdate('Y-m-d-w-H-i', TIMESTAMP + getglobal('setting/timeoffset') * 3600));
if($cron['weekday'] == -1) {
if($cron['day'] == -1) {
$firstday = $daynow;
$secondday = $daynow + 1;
} else {
$firstday = $cron['day'];
$secondday = $cron['day'] + gmdate('t', TIMESTAMP + getglobal('setting/timeoffset') * 3600);
}
} else {
$firstday = $daynow + ($cron['weekday'] - $weekdaynow);
$secondday = $firstday + 7;
}
if($firstday < $daynow) {
$firstday = $secondday;
}
if($firstday == $daynow) {
$todaytime = self::todaynextrun($cron);
if($todaytime['hour'] == -1 && $todaytime['minute'] == -1) {
$cron['day'] = $secondday;
$nexttime = self::todaynextrun($cron, 0, -1);
$cron['hour'] = $nexttime['hour'];
$cron['minute'] = $nexttime['minute'];
} else {
$cron['day'] = $firstday;
$cron['hour'] = $todaytime['hour'];
$cron['minute'] = $todaytime['minute'];
}
} else {
$cron['day'] = $firstday;
$nexttime = self::todaynextrun($cron, 0, -1);
$cron['hour'] = $nexttime['hour'];
$cron['minute'] = $nexttime['minute'];
}
$nextrun = @gmmktime($cron['hour'], $cron['minute'] > 0 ? $cron['minute'] : 0, 0, $monthnow, $cron['day'], $yearnow) - getglobal('setting/timeoffset') * 3600;
$data = array('lastrun' => TIMESTAMP, 'nextrun' => $nextrun);
if(!($nextrun > TIMESTAMP)) {
$data['available'] = '0';
}
C::t('common_cron')->update($cron['cronid'], $data);
return true;
}
private static function todaynextrun($cron, $hour = -2, $minute = -2) {
$hour = $hour == -2 ? gmdate('H', TIMESTAMP + getglobal('setting/timeoffset') * 3600) : $hour;
$minute = $minute == -2 ? gmdate('i', TIMESTAMP + getglobal('setting/timeoffset') * 3600) : $minute;
$nexttime = array();
if($cron['hour'] == -1 && !$cron['minute']) {
$nexttime['hour'] = $hour;
$nexttime['minute'] = $minute + 1;
} elseif($cron['hour'] == -1 && $cron['minute'] != '') {
$nexttime['hour'] = $hour;
if(($nextminute = self::nextminute($cron['minute'], $minute)) === false) {
++$nexttime['hour'];
$nextminute = $cron['minute'][0];
}
$nexttime['minute'] = $nextminute;
} elseif($cron['hour'] != -1 && $cron['minute'] == '') {
if($cron['hour'] < $hour) {
$nexttime['hour'] = $nexttime['minute'] = -1;
} elseif($cron['hour'] == $hour) {
$nexttime['hour'] = $cron['hour'];
$nexttime['minute'] = $minute + 1;
} else {
$nexttime['hour'] = $cron['hour'];
$nexttime['minute'] = 0;
}
} elseif($cron['hour'] != -1 && $cron['minute'] != '') {
$nextminute = self::nextminute($cron['minute'], $minute);
if($cron['hour'] < $hour || ($cron['hour'] == $hour && $nextminute === false)) {
$nexttime['hour'] = -1;
$nexttime['minute'] = -1;
} else {
$nexttime['hour'] = $cron['hour'];
$nexttime['minute'] = $nextminute;
}
}
return $nexttime;
}
private static function nextminute($nextminutes, $minutenow) {
foreach($nextminutes as $nextminute) {
if($nextminute > $minutenow) {
return $nextminute;
}
}
return false;
}
}
?>

View File

@@ -0,0 +1,493 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_database.php 36294 2016-12-14 03:11:30Z nemohou $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_database {
public static $db;
public static $driver;
public static function init($driver, $config) {
self::$driver = $driver;
self::$db = new $driver;
self::$db->set_config($config);
self::$db->connect();
}
public static function object() {
return self::$db;
}
public static function table($table) {
return self::$db->table_name($table);
}
public static function delete($table, $condition, $limit = 0, $unbuffered = true) {
if (empty($condition)) {
return false;
} elseif (is_array($condition)) {
if (count($condition) == 2 && isset($condition['where']) && isset($condition['arg'])) {
$where = self::format($condition['where'], $condition['arg']);
} else {
$where = self::implode_field_value($condition, ' AND ');
}
} else {
$where = $condition;
}
$limit = dintval($limit);
$sql = "DELETE FROM " . self::table($table) . " WHERE $where " . ($limit > 0 ? "LIMIT $limit" : '');
return self::query($sql, ($unbuffered ? 'UNBUFFERED' : ''));
}
public static function insert($table, $data, $return_insert_id = false, $replace = false, $silent = false) {
$sql = self::implode($data);
$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$table = self::table($table);
$silent = $silent ? 'SILENT' : '';
return self::query("$cmd $table SET $sql", null, $silent, !$return_insert_id);
}
public static function update($table, $data, $condition = '', $unbuffered = false, $low_priority = false) {
$sql = self::implode($data);
if(empty($sql)) {
return false;
}
$cmd = "UPDATE " . ($low_priority ? 'LOW_PRIORITY' : '');
$table = self::table($table);
$where = '';
if (empty($condition)) {
$where = '1';
} elseif (is_array($condition)) {
$where = self::implode($condition, ' AND ');
} else {
$where = $condition;
}
$res = self::query("$cmd $table SET $sql WHERE $where", $unbuffered ? 'UNBUFFERED' : '');
return $res;
}
public static function insert_id() {
return self::$db->insert_id();
}
public static function fetch($resourceid, $type = null) {
if (!isset($type)) {
$type = constant('MYSQLI_ASSOC');
}
return self::$db->fetch_array($resourceid, $type);
}
public static function fetch_first($sql, $arg = array(), $silent = false) {
$res = self::query($sql, $arg, $silent, false);
if($res === 0){
return array();
}
$ret = self::$db->fetch_array($res);
self::$db->free_result($res);
return $ret ? $ret : array();
}
public static function fetch_all($sql, $arg = array(), $keyfield = '', $silent=false) {
$data = array();
$query = self::query($sql, $arg, $silent, false);
while ($row = self::$db->fetch_array($query)) {
if ($keyfield && isset($row[$keyfield])) {
$data[$row[$keyfield]] = $row;
} else {
$data[] = $row;
}
}
self::$db->free_result($query);
return $data;
}
public static function result($resourceid, $row = 0) {
return self::$db->result($resourceid, $row);
}
public static function result_first($sql, $arg = array(), $silent = false) {
$res = self::query($sql, $arg, $silent, false);
$ret = self::$db->result($res, 0);
self::$db->free_result($res);
return $ret;
}
public static function query($sql, $arg = array(), $silent = false, $unbuffered = false) {
if (!empty($arg)) {
if (is_array($arg)) {
$sql = self::format($sql, $arg);
} elseif ($arg === 'SILENT') {
$silent = true;
} elseif ($arg === 'UNBUFFERED') {
$unbuffered = true;
}
}
self::checkquery($sql);
$ret = self::$db->query($sql, $silent, $unbuffered);
if (!$unbuffered && $ret) {
$cmd = trim(strtoupper(substr($sql, 0, strpos($sql, ' '))));
if ($cmd === 'SELECT') {
} elseif ($cmd === 'UPDATE' || $cmd === 'DELETE') {
$ret = self::$db->affected_rows();
} elseif ($cmd === 'INSERT') {
$ret = self::$db->insert_id();
}
}
return $ret;
}
public static function num_rows($resourceid) {
return self::$db->num_rows($resourceid);
}
public static function affected_rows() {
return self::$db->affected_rows();
}
public static function free_result($query) {
return self::$db->free_result($query);
}
public static function error() {
return self::$db->error();
}
public static function errno() {
return self::$db->errno();
}
public static function checkquery($sql) {
return discuz_database_safecheck::checkquery($sql);
}
public static function quote($str, $noarray = false) {
if (is_string($str))
return '\'' . self::$db->escape_string($str) . '\'';
if (is_int($str) or is_float($str))
return '\'' . $str . '\'';
if (is_array($str)) {
if($noarray === false) {
foreach ($str as &$v) {
$v = self::quote($v, true);
}
return $str;
} else {
return '\'\'';
}
}
if (is_bool($str))
return $str ? '1' : '0';
return '\'\'';
}
public static function quote_field($field) {
if (is_array($field)) {
foreach ($field as $k => $v) {
$field[$k] = self::quote_field($v);
}
} else {
if (strpos($field, '`') !== false)
$field = str_replace('`', '', $field);
$field = '`' . $field . '`';
}
return $field;
}
public static function limit($start, $limit = 0) {
$limit = intval($limit > 0 ? $limit : 0);
$start = intval($start > 0 ? $start : 0);
if ($start > 0 && $limit > 0) {
return " LIMIT $start, $limit";
} elseif ($limit) {
return " LIMIT $limit";
} elseif ($start) {
return " LIMIT $start";
} else {
return '';
}
}
public static function order($field, $order = 'ASC') {
if(empty($field)) {
return '';
}
$order = strtoupper($order) == 'ASC' || empty($order) ? 'ASC' : 'DESC';
return self::quote_field($field) . ' ' . $order;
}
public static function field($field, $val, $glue = '=') {
$field = self::quote_field($field);
if (is_array($val)) {
$glue = $glue == 'notin' ? 'notin' : 'in';
} elseif ($glue == 'in') {
$glue = '=';
}
switch ($glue) {
case '=':
return $field . $glue . self::quote($val);
break;
case '-':
case '+':
return $field . '=' . $field . $glue . self::quote((string) $val);
break;
case '|':
case '&':
case '^':
case '&~':
return $field . '=' . $field . $glue . self::quote($val);
break;
case '>':
case '<':
case '<>':
case '<=':
case '>=':
return $field . $glue . self::quote($val);
break;
case 'like':
return $field . ' LIKE(' . self::quote($val) . ')';
break;
case 'in':
case 'notin':
$val = $val ? implode(',', self::quote($val)) : '\'\'';
return $field . ($glue == 'notin' ? ' NOT' : '') . ' IN(' . $val . ')';
break;
default:
throw new DbException('Not allow this glue between field and value: "' . $glue . '"');
}
}
public static function implode($array, $glue = ',') {
$sql = $comma = '';
$glue = ' ' . trim($glue) . ' ';
foreach ($array as $k => $v) {
$sql .= $comma . self::quote_field($k) . '=' . self::quote($v);
$comma = $glue;
}
return $sql;
}
public static function implode_field_value($array, $glue = ',') {
return self::implode($array, $glue);
}
public static function format($sql, $arg) {
$count = substr_count($sql, '%');
if (!$count) {
return $sql;
} elseif ($count > count($arg)) {
throw new DbException('SQL string format error! This SQL need "' . $count . '" vars to replace into.', 0, $sql);
}
$len = strlen($sql);
$i = $find = 0;
$ret = '';
while ($i <= $len && $find < $count) {
if ($sql[$i] == '%') {
$next = $sql[$i + 1];
if ($next == 't') {
$ret .= self::table($arg[$find]);
} elseif ($next == 's') {
$ret .= self::quote(is_array($arg[$find]) ? serialize($arg[$find]) : (string) $arg[$find]);
} elseif ($next == 'f') {
$ret .= sprintf('%F', $arg[$find]);
} elseif ($next == 'd') {
$ret .= dintval($arg[$find]);
} elseif ($next == 'i') {
$ret .= $arg[$find];
} elseif ($next == 'n') {
if (!empty($arg[$find])) {
$ret .= is_array($arg[$find]) ? implode(',', self::quote($arg[$find])) : self::quote($arg[$find]);
} else {
$ret .= '0';
}
} else {
$ret .= self::quote($arg[$find]);
}
$i++;
$find++;
} else {
$ret .= $sql[$i];
}
$i++;
}
if ($i < $len) {
$ret .= substr($sql, $i);
}
return $ret;
}
public static function begin_transaction() {
return self::$db->begin_transaction();
}
public static function commit() {
return self::$db->commit();
}
public static function rollback() {
return self::$db->rollback();
}
}
class discuz_database_safecheck {
protected static $checkcmd = array('SEL'=>1, 'UPD'=>1, 'INS'=>1, 'REP'=>1, 'DEL'=>1);
protected static $config;
public static function checkquery($sql) {
if (self::$config === null) {
self::$config = getglobal('config/security/querysafe');
}
if (self::$config['status']) {
$check = 1;
$cmd = strtoupper(substr(trim($sql), 0, 3));
if(isset(self::$checkcmd[$cmd])) {
$check = self::_do_query_safe($sql);
} elseif(substr($cmd, 0, 2) === '/*') {
$check = -1;
}
if ($check < 1) {
throw new DbException('It is not safe to do this query', 0, $sql);
}
}
return true;
}
private static function _do_query_safe($sql) {
$sql = str_replace(array('\\\\', '\\\'', '\\"', '\'\''), '', $sql);
$mark = $clean = '';
if (strpos($sql, '/') === false && strpos($sql, '#') === false && strpos($sql, '-- ') === false && strpos($sql, '@') === false && strpos($sql, '`') === false && strpos($sql, '"') === false) {
$clean = preg_replace("/'(.+?)'/s", '', $sql);
} else {
$len = strlen($sql);
$mark = $clean = '';
for ($i = 0; $i < $len; $i++) {
$str = $sql[$i];
switch ($str) {
case '`':
if(!$mark) {
$mark = '`';
$clean .= $str;
} elseif ($mark == '`') {
$mark = '';
}
break;
case '\'':
if (!$mark) {
$mark = '\'';
$clean .= $str;
} elseif ($mark == '\'') {
$mark = '';
}
break;
case '/':
if (empty($mark) && $sql[$i + 1] == '*') {
$mark = '/*';
$clean .= $mark;
$i++;
} elseif ($mark == '/*' && $sql[$i - 1] == '*') {
$mark = '';
$clean .= '*';
}
break;
case '#':
if (empty($mark)) {
$mark = $str;
$clean .= $str;
}
break;
case "\n":
if ($mark == '#' || $mark == '--') {
$mark = '';
}
break;
case '-':
if (empty($mark) && substr($sql, $i, 3) == '-- ') {
$mark = '-- ';
$clean .= $mark;
}
break;
default:
break;
}
$clean .= $mark ? '' : $str;
}
}
if(strpos($clean, '@') !== false) {
return '-3';
}
$clean = preg_replace("/[^a-z0-9_\-\(\)#\*\/\"]+/is", "", strtolower($clean));
if (self::$config['afullnote']) {
$clean = str_replace('/**/', '', $clean);
}
if (is_array(self::$config['dfunction'])) {
foreach (self::$config['dfunction'] as $fun) {
if (strpos($clean, $fun . '(') !== false)
return '-1';
}
}
if (is_array(self::$config['daction'])) {
foreach (self::$config['daction'] as $action) {
if (strpos($clean, $action) !== false)
return '-3';
}
}
if (self::$config['dlikehex'] && strpos($clean, 'like0x')) {
return '-2';
}
if (is_array(self::$config['dnote'])) {
foreach (self::$config['dnote'] as $note) {
if (strpos($clean, $note) !== false)
return '-4';
}
}
return 1;
}
public static function setconfigstatus($data) {
self::$config['status'] = $data ? 1 : 0;
}
}
?>

View File

@@ -0,0 +1,375 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_error.php 33361 2013-05-31 08:59:06Z nemohou $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_error
{
public static function system_error($message, $show = true, $save = true, $halt = true) {
if(!empty($message)) {
$message = lang('error', $message);
} else {
$message = lang('error', 'error_unknow');
}
list($showtrace, $logtrace) = discuz_error::debug_backtrace();
if($save) {
$messagesave = '<b>'.$message.'</b><br><b>PHP:</b>'.$logtrace;
discuz_error::write_error_log($messagesave);
}
if($show) {
discuz_error::show_error('system', "<li>$message</li>", $showtrace, '', md5(discuz_error::clear($messagesave)));
}
if($halt) {
exit();
} else {
return $message;
}
}
public static function template_error($message, $tplname) {
$message = lang('error', $message);
$tplname = str_replace(DISCUZ_ROOT, '', $tplname);
$message = $message.': '.$tplname;
discuz_error::system_error($message);
}
public static function debug_backtrace() {
$skipfunc[] = 'discuz_error->debug_backtrace';
$skipfunc[] = 'discuz_error->db_error';
$skipfunc[] = 'discuz_error->template_error';
$skipfunc[] = 'discuz_error->system_error';
$skipfunc[] = 'db_mysql->halt';
$skipfunc[] = 'db_mysql->query';
$skipfunc[] = 'DB::_execute';
$show = $log = '';
$debug_backtrace = debug_backtrace();
krsort($debug_backtrace);
foreach ($debug_backtrace as $k => $error) {
$file = str_replace(DISCUZ_ROOT, '', $error['file']);
$func = isset($error['class']) ? $error['class'] : '';
$func .= isset($error['type']) ? $error['type'] : '';
$func .= isset($error['function']) ? $error['function'] : '';
if(in_array($func, $skipfunc)) {
break;
}
$error['line'] = sprintf('%04d', $error['line']);
$show .= "<li>[Line: {$error['line']}]".$file."($func)</li>";
$log .= (!empty($log) ? ' -> ' : '').$file.'#'.$func.':'.$error['line'];
}
return array($show, $log);
}
public static function db_error($message, $sql) {
global $_G;
list($showtrace, $logtrace) = discuz_error::debug_backtrace();
$title = lang('error', 'db_'.$message);
$title_msg = lang('error', 'db_error_message');
$title_sql = lang('error', 'db_query_sql');
$title_backtrace = lang('error', 'backtrace');
$title_help = lang('error', 'db_help_link');
$db = &DB::object();
$dberrno = $db->errno();
$dberror = str_replace($db->tablepre, '', $db->error());
$sql = dhtmlspecialchars(str_replace($db->tablepre, '', $sql));
$msg = '<li>[Type] '.$title.'</li>';
$msg .= $dberrno ? '<li>['.$dberrno.'] '.$dberror.'</li>' : '';
$msg .= $sql ? '<li>[Query] '.$sql.'</li>' : '';
$errormsg = '<b>'.$title.'</b>';
$errormsg .= "[$dberrno]<br /><b>ERR:</b> $dberror<br />";
if($sql) {
$errormsg .= '<b>SQL:</b> '.$sql;
}
$errormsg .= "<br />";
$errormsg .= '<b>PHP:</b> '.$logtrace;
discuz_error::write_error_log($errormsg);
discuz_error::show_error('db', $msg, $showtrace, '', md5(discuz_error::clear($errormsg)));
exit();
}
public static function exception_error($exception) {
if($exception instanceof DbException) {
$type = 'db';
} else {
$type = 'system';
}
if($type == 'db') {
$errormsg = '('.$exception->getCode().') ';
$errormsg .= self::sql_clear($exception->getMessage());
if($exception->getSql()) {
$errormsg .= '<div class="sql">';
$errormsg .= self::sql_clear($exception->getSql());
$errormsg .= '</div>';
}
} else {
$errormsg = $exception->getMessage();
}
$trace = $exception->getTrace();
krsort($trace);
$trace[] = array('file'=>$exception->getFile(), 'line'=>$exception->getLine(), 'function'=> 'break');
$logmsg = '';
$phpmsg = array();
foreach ($trace as $error) {
if(!empty($error['function'])) {
$fun = '';
if(!empty($error['class'])) {
$fun .= $error['class'].$error['type'];
}
$fun .= $error['function'].'(';
if(!empty($error['args'])) {
$mark = '';
foreach($error['args'] as $arg) {
$fun .= $mark;
if(is_array($arg)) {
$fun .= 'Array';
} elseif(is_bool($arg)) {
$fun .= $arg ? 'true' : 'false';
} elseif(is_int($arg)) {
$fun .= (defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) ? $arg : '%d';
} elseif(is_float($arg)) {
$fun .= (defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) ? $arg : '%f';
} elseif(is_resource($arg)) {
$fun .= (defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) ? 'Resource' : '%f';
} elseif(is_object($arg)) {
$fun .= (defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) ? 'Object' : '%f';
} else {
$arg = (string)$arg;
$fun .= (defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) ? '\''.dhtmlspecialchars(substr(self::clear($arg), 0, 10)).(strlen($arg) > 10 ? ' ...' : '').'\'' : '%s';
}
$mark = ', ';
}
}
$fun .= ')';
$error['function'] = $fun;
}
$phpmsg[] = array(
'file' => str_replace(array(DISCUZ_ROOT, '\\'), array('', '/'), $error['file']),
'line' => $error['line'],
'function' => $error['function'],
);
$file = str_replace(array(DISCUZ_ROOT, '\\'), array('', '/'), $error['file']);
$func = isset($error['class']) ? $error['class'] : '';
$func .= isset($error['type']) ? $error['type'] : '';
$func .= isset($error['function']) ? $error['function'] : '';
$line = sprintf('%04d', $error['line']);
$logmsg .= (!empty($logmsg) ? ' -> ' : '').$file.'#'.$func.':'.$line;
}
$messagesave = '<b>'.$errormsg.'</b><br><b>PHP:</b>'.$logmsg;
self::write_error_log($messagesave);
self::show_error($type, $errormsg, $phpmsg, '', md5(discuz_error::clear($messagesave)));
exit();
}
public static function show_error($type, $errormsg, $phpmsg = '', $typemsg = '', $backtraceid = '') {
global $_G;
ob_end_clean();
$gzip = getglobal('gzipcompress');
ob_start($gzip ? 'ob_gzhandler' : null);
header("HTTP/1.1 503 Service Temporarily Unavailable");
header("Status: 503 Service Temporarily Unavailable");
header("Retry-After: 3600");
$host = $_SERVER['HTTP_HOST'];
$title = (!isset($_G['config']['security']['error']['showerror']) || !empty($_G['config']['security']['error']['showerror'])) ? ($type == 'db' ? 'Database' : 'System') : 'General';
echo <<<EOT
<!DOCTYPE html>
<html>
<head>
<title>$host - $title Error</title>
<meta charset="{$_G['config']['output']['charset']}" />
<meta name="renderer" content="webkit" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
<!--
body { background-color: white; color: black; font: 9pt/11pt verdana, arial, sans-serif;}
#container { max-width: 1024px; margin: auto; }
#message { max-width: 1024px; color: black; }
.red {color: red;}
a:link { font: 9pt/11pt verdana, arial, sans-serif; color: red; }
a:visited { font: 9pt/11pt verdana, arial, sans-serif; color: #4e4e4e; }
a.guess { font: 11pt/13pt verdana, arial, sans-serif; color: blue; }
h1 { color: #FF0000; font: 18pt "Verdana"; margin-bottom: 0.5em;}
.bg1{ background-color: #FFFFCC;}
.bg2{ background-color: #EEEEEE;}
.bg3{ background-color: #FFA66C; font-weight: bold;}
.table {background: #AAAAAA; font: 11pt Menlo,Consolas,"Lucida Console";}
.table tbody{word-break: break-all;}
.info {
background: none repeat scroll 0 0 #F3F3F3;
border: 0px solid #aaaaaa;
border-radius: 10px 10px 10px 10px;
color: #000000;
font-size: 11pt;
line-height: 160%;
margin-bottom: 1em;
padding: 1em;
}
.info svg { width: 40%; min-width: 200px; display: block; margin: auto; margin-bottom: 30px; fill: #999; }
.info svg .xicon { fill: #d31f0d; }
.help {
background: #F3F3F3;
border-radius: 10px 10px 10px 10px;
font: 14px verdana, arial, sans-serif;
text-align: center;
line-height: 160%;
padding: 1em;
margin: 1em 0;
}
.sql {
background: none repeat scroll 0 0 #FFFFCC;
border: 1px solid #aaaaaa;
color: #000000;
font: arial, sans-serif;
font-size: 9pt;
line-height: 160%;
margin-top: 1em;
padding: 4px;
}
-->
</style>
</head>
<body>
<div id="container">
<h1>Discuz! $title Error</h1>
EOT;
echo '<p>Time: ' . date('Y-m-d H:i:s O') .' IP: ' . getglobal('clientip') . ' BackTraceID: ' . $backtraceid . '</p>';
if(!empty($errormsg) && (!isset($_G['config']['security']['error']['showerror']) || !empty($_G['config']['security']['error']['showerror']))) {
echo '<div class="info">'.$errormsg.'</div>';
}
if(isset($_G['config']['security']['error']['showerror']) && empty($_G['config']['security']['error']['showerror'])) {
echo '<div class="info"><svg viewBox="0 0 16 16"><path d="M2.5 5a.5.5 0 100-1 .5.5 0 000 1zM4 5a.5.5 0 100-1 .5.5 0 000 1zm2-.5a.5.5 0 11-1 0 .5.5 0 011 0zM0 4a2 2 0 012-2h11a2 2 0 012 2v4a.5.5 0 01-1 0V7H1v5a1 1 0 001 1h5.5a.5.5 0 010 1H2a2 2 0 01-2-2V4zm1 2h13V4a1 1 0 00-1-1H2a1 1 0 00-1 1v2z"/><path d="M16 12.5a3.5 3.5 0 11-7 0 3.5 3.5 0 017 0zm-4.854-1.354a.5.5 0 000 .708l.647.646-.647.646a.5.5 0 00.708.708l.646-.647.646.647a.5.5 0 00.708-.708l-.647-.646.647-.646a.5.5 0 00-.708-.708l-.646.647-.646-.647a.5.5 0 00-.708 0z" class="xicon"/></svg></div>';
}
if(!empty($phpmsg) && (!isset($_G['config']['security']['error']['showerror']) || $_G['config']['security']['error']['showerror'] == '1')) {
echo '<div class="info">';
echo '<p><strong>PHP Debug</strong></p>';
echo '<table cellpadding="5" cellspacing="1" width="100%" class="table">';
if(is_array($phpmsg)) {
echo '<tr class="bg2"><td>No.</td><td>File</td><td>Line</td><td>Code</td></tr>';
foreach($phpmsg as $k => $msg) {
$k++;
$explode = explode("/", $msg['file']);
if (isset($explode['1']) && $explode['1'] == 'plugin') {
$guess = $explode['2'];
$bg = "bg3";
} else {
$bg = "bg1";
}
echo '<tr class="'.$bg.'">';
echo '<td>'.$k.'</td>';
echo '<td>'.$msg['file'].'</td>';
echo '<td>'.$msg['line'].'</td>';
echo '<td>'.$msg['function'].'</td>';
echo '</tr>';
}
} else {
echo '<tr><td><ul>'.$phpmsg.'</ul></td></tr>';
}
echo '</table></div>';
}
echo '<div class="help">'.lang('error', 'suggestion_user').'</div>';
if (!isset($_G['config']['security']['error']['guessplugin']) || !empty($_G['config']['security']['error']['guessplugin'])) {
if (!empty($guess)) {
$suggestion = lang('error', 'suggestion_plugin', array('guess'=>$guess));
} else {
$suggestion = lang('error', 'suggestion');
}
echo '<div class="help">'.$suggestion.'</div>';
}
$endmsg = lang('error', 'error_end_message', array('host'=>$host));
echo <<<EOT
<div class="help">$endmsg</div>
</div>
</body>
</html>
EOT;
}
public static function clear($message) {
return str_replace(array("\t", "\r", "\n"), " ", $message);
}
public static function sql_clear($message) {
$message = self::clear($message);
$message = str_replace(DB::object()->tablepre, '', $message);
$message = dhtmlspecialchars($message);
return $message;
}
public static function write_error_log($message) {
$message = discuz_error::clear($message);
$time = time();
$file = DISCUZ_ROOT.'./data/log/'.date("Ym").'_errorlog.php';
$hash = md5($message);
$uid = getglobal('uid');
$ip = getglobal('clientip');
$user = '<b>User:</b> uid='.intval($uid).'; IP='.$ip.'; RIP:'.$_SERVER['REMOTE_ADDR'];
$uri = 'Request: '.dhtmlspecialchars(discuz_error::clear($_SERVER['REQUEST_URI']));
$message = "<?PHP exit;?>\t{$time}\t$message\t$hash\t$user $uri\n";
if($fp = @fopen($file, 'rb')) {
$lastlen = 50000;
$maxtime = 60 * 10;
$offset = filesize($file) - $lastlen;
if($offset > 0) {
fseek($fp, $offset);
}
if($data = fread($fp, $lastlen)) {
$array = explode("\n", $data);
if(is_array($array)) foreach($array as $key => $val) {
$row = explode("\t", $val);
if($row[0] != '<?PHP exit;?>') continue;
if($row[3] == $hash && ($row[1] > $time - $maxtime)) {
return;
}
}
}
}
error_log($message, 3, $file);
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_extend.php 30690 2012-06-12 05:57:59Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_extend extends discuz_container
{
public $setting;
public $member;
public $group;
public $param;
public function __construct($obj) {
parent::__construct($obj);
}
public function __call($name, $p) {
if(method_exists($this->_obj, $name)) {
switch (count($p)) {
case 0: return $this->_obj->{$name}();break;
case 1: return $this->_obj->{$name}($p[0]);break;
case 2: return $this->_obj->{$name}($p[0], $p[1]);break;
case 3: return $this->_obj->{$name}($p[0], $p[1], $p[2]);break;
case 4: return $this->_obj->{$name}($p[0], $p[1], $p[2], $p[3]);break;
case 5: return $this->_obj->{$name}($p[0], $p[1], $p[2], $p[3], $p[4]);break;
default: return call_user_func_array(array($this->_obj, $name), $p);break;
}
} else {
return parent::__call($name, $p);
}
}
public function init_base_var(){
$this->setting = &$this->_obj->setting;
$this->member = &$this->_obj->member;
$this->group = &$this->_obj->group;
$this->param = &$this->_obj->param;
}
}
?>

View File

@@ -0,0 +1,258 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_ftp.php 32473 2013-01-24 07:11:38Z chenmengshu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!defined('FTP_ERR_SERVER_DISABLED')) {
define('FTP_ERR_SERVER_DISABLED', -100);
define('FTP_ERR_CONFIG_OFF', -101);
define('FTP_ERR_CONNECT_TO_SERVER', -102);
define('FTP_ERR_USER_NO_LOGGIN', -103);
define('FTP_ERR_CHDIR', -104);
define('FTP_ERR_MKDIR', -105);
define('FTP_ERR_SOURCE_READ', -106);
define('FTP_ERR_TARGET_WRITE', -107);
}
class discuz_ftp
{
var $enabled = false;
var $config = array();
var $func;
var $connectid;
var $_error;
public static function &instance($config = array()) {
static $object;
if(empty($object)) {
$object = new discuz_ftp($config);
}
return $object;
}
function __construct($config = array()) {
$this->set_error(0);
$this->config = !$config ? getglobal('setting/ftp') : $config;
$this->enabled = false;
if(empty($this->config['on']) || empty($this->config['host'])) {
$this->set_error(FTP_ERR_CONFIG_OFF);
} else {
$this->func = $this->config['ssl'] && function_exists('ftp_ssl_connect') ? 'ftp_ssl_connect' : 'ftp_connect';
if($this->func == 'ftp_connect' && !function_exists('ftp_connect')) {
$this->set_error(FTP_ERR_SERVER_DISABLED);
} else {
$this->config['host'] = discuz_ftp::clear($this->config['host']);
$this->config['port'] = intval($this->config['port']);
$this->config['ssl'] = intval($this->config['ssl']);
$this->config['username'] = discuz_ftp::clear($this->config['username']);
$this->config['password'] = authcode($this->config['password'], 'DECODE', md5(getglobal('config/security/authkey')));
$this->config['timeout'] = intval($this->config['timeout']);
$this->enabled = true;
}
}
}
function upload($source, $target) {
if($this->error()) {
return 0;
}
$old_dir = $this->ftp_pwd();
$dirname = dirname($target);
$filename = basename($target);
if(!$this->ftp_chdir($dirname)) {
if($this->ftp_mkdir($dirname)) {
$this->ftp_chmod($dirname);
if(!$this->ftp_chdir($dirname)) {
$this->set_error(FTP_ERR_CHDIR);
}
$this->ftp_put('index.htm', getglobal('setting/attachdir').'/index.htm', FTP_BINARY);
} else {
$this->set_error(FTP_ERR_MKDIR);
}
}
$res = 0;
if(!$this->error()) {
if($fp = @fopen($source, 'rb')) {
$res = $this->ftp_fput($filename, $fp, FTP_BINARY);
@fclose($fp);
!$res && $this->set_error(FTP_ERR_TARGET_WRITE);
} else {
$this->set_error(FTP_ERR_SOURCE_READ);
}
}
$this->ftp_chdir($old_dir);
return $res ? 1 : 0;
}
function connect() {
if(!$this->enabled || empty($this->config)) {
return 0;
} else {
return $this->ftp_connect(
$this->config['host'],
$this->config['username'],
$this->config['password'],
$this->config['attachdir'],
$this->config['port'],
$this->config['timeout'],
$this->config['ssl'],
$this->config['pasv']
);
}
}
function ftp_connect($ftphost, $username, $password, $ftppath, $ftpport = 21, $timeout = 30, $ftpssl = 0, $ftppasv = 0) {
$res = 0;
$fun = $this->func;
if($this->connectid = $fun($ftphost, $ftpport, 20)) {
$timeout && $this->set_option(FTP_TIMEOUT_SEC, $timeout);
if($this->ftp_login($username, $password)) {
$this->ftp_pasv($ftppasv);
if($this->ftp_chdir($ftppath)) {
$res = $this->connectid;
} else {
$this->set_error(FTP_ERR_CHDIR);
}
} else {
$this->set_error(FTP_ERR_USER_NO_LOGGIN);
}
} else {
$this->set_error(FTP_ERR_CONNECT_TO_SERVER);
}
if($res > 0) {
$this->set_error();
$this->enabled = 1;
} else {
$this->enabled = 0;
$this->ftp_close();
}
return $res;
}
function set_error($code = 0) {
$this->_error = $code;
}
function error() {
return $this->_error;
}
function clear($str) {
return str_replace(array( "\n", "\r", '..'), '', $str);
}
function set_option($cmd, $value) {
if(function_exists('ftp_set_option')) {
return @ftp_set_option($this->connectid, $cmd, $value);
}
}
function ftp_mkdir($directory) {
$directory = discuz_ftp::clear($directory);
$epath = explode('/', $directory);
$dir = '';$comma = '';
foreach($epath as $path) {
$dir .= $comma.$path;
$comma = '/';
$return = @ftp_mkdir($this->connectid, $dir);
$this->ftp_chmod($dir);
}
return $return;
}
function ftp_rmdir($directory) {
$directory = discuz_ftp::clear($directory);
return @ftp_rmdir($this->connectid, $directory);
}
function ftp_put($remote_file, $local_file, $mode = FTP_BINARY) {
$remote_file = discuz_ftp::clear($remote_file);
$local_file = discuz_ftp::clear($local_file);
$mode = intval($mode);
return @ftp_put($this->connectid, $remote_file, $local_file, $mode);
}
function ftp_fput($remote_file, $sourcefp, $mode = FTP_BINARY) {
$remote_file = discuz_ftp::clear($remote_file);
$mode = intval($mode);
return @ftp_fput($this->connectid, $remote_file, $sourcefp, $mode);
}
function ftp_size($remote_file) {
$remote_file = discuz_ftp::clear($remote_file);
return @ftp_size($this->connectid, $remote_file);
}
function ftp_close() {
return @ftp_close($this->connectid);
}
function ftp_delete($path) {
$path = discuz_ftp::clear($path);
return @ftp_delete($this->connectid, $path);
}
function ftp_get($local_file, $remote_file, $mode, $resumepos = 0) {
$remote_file = discuz_ftp::clear($remote_file);
$local_file = discuz_ftp::clear($local_file);
$mode = intval($mode);
$resumepos = intval($resumepos);
return @ftp_get($this->connectid, $local_file, $remote_file, $mode, $resumepos);
}
function ftp_login($username, $password) {
$username = $this->clear($username);
$password = str_replace(array("\n", "\r"), array('', ''), $password);
return @ftp_login($this->connectid, $username, $password);
}
function ftp_pasv($pasv) {
return @ftp_pasv($this->connectid, $pasv ? true : false);
}
function ftp_chdir($directory) {
$directory = discuz_ftp::clear($directory);
return @ftp_chdir($this->connectid, $directory);
}
function ftp_site($cmd) {
$cmd = discuz_ftp::clear($cmd);
return @ftp_site($this->connectid, $cmd);
}
function ftp_chmod($filename, $mod = 0777) {
$filename = discuz_ftp::clear($filename);
if(function_exists('ftp_chmod')) {
return @ftp_chmod($this->connectid, $mod, $filename);
} else {
return @ftp_site($this->connectid, 'CHMOD '.$mod.' '.$filename);
}
}
function ftp_pwd() {
return @ftp_pwd($this->connectid);
}
}

View File

@@ -0,0 +1,386 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_memory.php 36362 2017-02-04 02:02:03Z nemohou $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_memory extends discuz_base
{
private $config;
private $extension = array();
private $memory;
private $prefix;
private $userprefix;
public $type;
public $enable = false;
public $debug = array();
public $gotset = false;
public $gothash = false;
public $goteval = false;
public $gotsortedset = false;
public $gotcluster = false;
public $gotpipeline = false;
public function __construct() {
}
public function init($config) {
$this->config = $config;
$this->prefix = empty($config['prefix']) ? substr(md5($_SERVER['HTTP_HOST']), 0, 6).'_' : $config['prefix'];
unset($this->config['prefix']);
foreach($this->config as $cache => $config) {
$available = is_array($config) ? !empty($config['server']) : !empty($config);
if($available && !is_object($this->memory)) {
$class_name = 'memory_driver_'.$cache;
$this->memory = new $class_name();
$this->memory->init($config);
if(!$this->memory->enable) {
$this->memory = null;
} else {
$this->type = $this->memory->cacheName;
$this->enable = true;
$this->gotset = method_exists($this->memory, 'feature') && $this->memory->feature('set');
$this->gothash = method_exists($this->memory, 'feature') && $this->memory->feature('hash');
$this->goteval = method_exists($this->memory, 'feature') && $this->memory->feature('eval');
$this->gotsortedset = method_exists($this->memory, 'feature') && $this->memory->feature('sortedset');;
$this->gotcluster = method_exists($this->memory, 'feature') && $this->memory->feature('cluster');
$this->gotpipeline = method_exists($this->memory, 'feature') && $this->memory->feature('pipeline');
break;
}
}
}
}
public function get($key, $prefix = '') {
static $getmulti = null;
$ret = false;
if($this->enable) {
if(!isset($getmulti)) $getmulti = method_exists($this->memory, 'getMulti');
$this->userprefix = $prefix;
if(is_array($key)) {
if($getmulti) {
$ret = $this->memory->getMulti($this->_key($key));
if($ret !== false && !empty($ret)) {
$_ret = array();
foreach((array)$ret as $_key => $value) {
$_ret[$this->_trim_key($_key)] = $value;
}
$ret = $_ret;
}
} else {
$ret = array();
$_ret = false;
foreach($key as $id) {
if(($_ret = $this->memory->get($this->_key($id))) !== false && isset($_ret)) {
$ret[$id] = $_ret;
}
}
}
if(empty($ret)) $ret = false;
} else {
$ret = $this->memory->get($this->_key($key));
if(!isset($ret)) $ret = false;
}
}
return $ret;
}
public function set($key, $value, $ttl = 0, $prefix = '') {
$ret = false;
if($value === false) $value = '';
if($this->enable) {
$this->userprefix = $prefix;
$ret = $this->memory->set($this->_key($key), $value, $ttl);
}
return $ret;
}
public function add($key, $value, $ttl = 0, $prefix = '') {
$ret = false;
if($value === false) $value = '';
if($this->enable) {
$this->userprefix = $prefix;
$ret = $this->memory->add($this->_key($key), $value, $ttl);
}
return $ret;
}
public function exists($key, $prefix = '') {
$ret = false;
if ($this->enable && method_exists($this->memory, 'exists')) {
$this->userprefix = $prefix;
$ret = $this->memory->exists($this->_key($key));
}
return $ret;
}
public function rm($key, $prefix = '') {
$ret = false;
if($this->enable) {
$this->userprefix = $prefix;
$key = $this->_key($key);
foreach((array)$key as $id) {
$ret = $this->memory->rm($id);
}
}
return $ret;
}
public function clear() {
$ret = false;
if($this->enable && method_exists($this->memory, 'clear')) {
$ret = $this->memory->clear();
}
return $ret;
}
public function inc($key, $step = 1, $prefix = '') {
static $hasinc = null;
$ret = false;
if($this->enable) {
$this->userprefix = $prefix;
if(!isset($hasinc)) $hasinc = method_exists($this->memory, 'inc');
if($hasinc) {
$ret = $this->memory->inc($this->_key($key), $step);
} else {
if(($data = $this->memory->get($key)) !== false) {
$ret = ($this->memory->set($key, $data + ($step)) !== false ? $this->memory->get($key) : false);
}
}
}
return $ret;
}
public function incex($key, $value, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->incex($this->_key($key), $value);
}
public function dec($key, $step = 1, $prefix = '') {
static $hasdec = null;
$ret = false;
if($this->enable) {
$this->userprefix = $prefix;
if(!isset($hasdec)) $hasdec = method_exists($this->memory, 'dec');
if($hasdec) {
$ret = $this->memory->dec($this->_key($key), $step);
} else {
if(($data = $this->memory->get($key)) !== false) {
$ret = ($this->memory->set($key, $data - ($step)) !== false ? $this->memory->get($key) : false);
}
}
}
return $ret;
}
public function sadd($key, $value, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->sadd($this->_key($key), $value);
}
public function srem($key, $value, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->srem($this->_key($key), $value);
}
public function sismember($key, $value, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->sismember($this->_key($key), $value);
}
public function scard($key, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->scard($this->_key($key));
}
public function smembers($key, $prefix = '') {
if (!$this->enable || !$this->gotset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->smembers($this->_key($key));
}
public function hmset($key, $value, $prefix = '') {
if (!$this->enable || !$this->gothash) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->hmset($this->_key($key), $value);
}
public function hgetall($key, $prefix = '') {
if (!$this->enable || !$this->gothash) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->hgetall($this->_key($key));
}
public function hexists($key, $field, $prefix = '') {
if (!$this->enable || !$this->gothash) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->hexists($this->_key($key), $field);
}
public function hget($key, $field, $prefix = '') {
if (!$this->enable || !$this->gothash) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->hget($this->_key($key), $field);
}
public function evalscript($script, $argv, $sha_key, $prefix = '') {
if (!$this->enable || !$this->goteval) {
return false;
}
if (!is_array($argv)) {
$argv = array();
}
$this->userprefix = $prefix;
if ($sha_key) {
$sha_key = $sha_key . '_eval_sha';
$sha = $this->memory->get($this->_key($sha_key));
$should_load = false;
if (!$sha) {
if (!$script) return false;
$should_load = true;
} else {
if (!$this->memory->scriptexists($sha)) {
$should_load = true;
}
}
if ($should_load) {
$sha = $this->memory->loadscript($script);
$this->memory->set($this->_key($sha_key), $sha);
}
return $this->memory->evalSha($sha, array_merge(array($this->_key('')), $argv));
} else {
return $this->memory->evalscript($script, array_merge(array($this->_key('')), $argv));
}
}
public function zadd($key, $value, $score, $prefix = '') {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zadd($this->_key($key), $value, $score);
}
public function zrem($key, $value, $prefix = '') {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zrem($this->_key($key), $value);
}
public function zscore($key, $member, $prefix = '') {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zscore($this->_key($key), $member);
}
public function zcard($key, $prefix = '') {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zcard($this->_key($key));
}
public function zrevrange($key, $start, $end, $prefix = '', $withscore = false) {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zrevrange($this->_key($key), $start, $end, $withscore);
}
public function zincrby($key, $member, $value, $prefix = '') {
if (!$this->enable || !$this->gotsortedset) {
return false;
}
$this->userprefix = $prefix;
return $this->memory->zincrby($this->_key($key), $member, $value);
}
public function pipeline() {
if (!$this->enable || !$this->gotpipeline) {
return false;
}
return $this->memory->pipeline();
}
public function commit() {
if (!$this->enable || !$this->gotpipeline) {
return false;
}
return $this->memory->commit();
}
public function discard() {
if (!$this->enable || !$this->gotpipeline) {
return false;
}
return $this->memory->discard();
}
private function _key($str) {
$perfix = $this->prefix.$this->userprefix;
if(is_array($str)) {
foreach($str as &$val) {
$val = $perfix.$val;
}
} else {
$str = $perfix.$str;
}
return $str;
}
private function _trim_key($str) {
return substr($str, strlen($this->prefix.$this->userprefix));
}
public function getextension() {
return $this->extension;
}
public function getconfig() {
return $this->config;
}
}
?>

View File

@@ -0,0 +1,174 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
abstract class discuz_model extends discuz_base
{
public $data;
public $methods = array();
public $showmessage = 'showmessage';
public $app;
public $member;
public $group;
public $setting;
public $param = array();
public function __construct() {
$this->app = C::app();
$this->setting = &$this->app->var['setting'];
$this->group = &$this->app->var['group'];
$this->member = &$this->app->var['member'];
parent::__construct();
}
public function config($name) {
return getglobal('config/'.$name);
}
public function setting($name = null, $val = null) {
if(isset($val)) {
return $this->setvar($this->setting, $name, $val);
}
return $this->getvar($this->setting, $name);
}
public function table($name) {
return C::t($name);
}
public function cache($name, $val = null) {
if(isset($val)) {
savecache($name, $val);
$this->app->var['cache'][$name] = $val;
return true;
} else {
if (!isset($this->app->var['cache'][$name])) {
loadcache($name);
}
if($this->app->var['cache'][$name] === null) {
return null;
} else {
return getglobal('cache/'.$name);
}
}
}
public function member($name = null, $val = null){
if(isset($val)) {
return $this->setvar($this->member, $name, $val);
} else {
return $this->getvar($this->member, $name);
}
}
public function group($name = null, $val = null){
if(isset($val)) {
return $this->setvar($this->group, $name, $val);
} else {
return $this->getvar($this->group, $name);
}
}
public function param($name = null, $val = null){
if(isset($val)) {
return $this->setvar($this->param, $name, $val);
}
return $this->getvar($this->param, $name);
}
public function setvar(&$var, $key, $value) {
if(isset($key)) {
$key = explode('/', $key);
$p = &$var;
foreach ($key as $k) {
if(!isset($p[$k]) || !is_array($p[$k])) {
$p[$k] = array();
}
$p = &$p[$k];
}
$p = $value;
} else {
$var = $value;
}
return true;
}
public function getvar(&$var, $key = null) {
if(isset($key)) {
$key = explode('/', $key);
foreach ($key as $k) {
if (!isset($var[$k])) {
return null;
}
$var = &$var[$k];
}
}
return $var;
}
public function showmessage() {
if(!empty($this->showmessage) && is_callable($this->showmessage)) {
$p = func_get_args();
if(is_string($this->showmessage)) {
$fn = $this->showmessage;
switch (func_num_args()) {
case 0: return $fn();break;
case 1: return $fn($p[0]);break;
case 2: return $fn($p[0], $p[1]);break;
case 3: return $fn($p[0], $p[1], $p[2]);exit;break;
case 4: return $fn($p[0], $p[1], $p[2], $p[3]);break;
case 5: return $fn($p[0], $p[1], $p[2], $p[3], $p[4]);break;
default: return call_user_func_array($this->showmessage, $p);break;
}
} else {
return call_user_func_array($this->showmessage, $p);
}
} else {
return func_get_args();
}
}
public function attach_before_method($name, $fn) {
$this->methods[$name][0][] = $fn;
}
public function attach_after_method($name, $fn) {
$this->methods[$name][1][] = $fn;
}
public function attach_before_methods($name, $methods){
if(!empty($methods)) {
foreach($methods as $method) {
$this->methods[$name][0][] = $method;
}
}
}
public function attach_after_methods($name, $methods){
if(!empty($methods)) {
foreach($methods as $method) {
$this->methods[$name][1][] = $method;
}
}
}
abstract protected function _init_parameters($parameters);
}
?>

View File

@@ -0,0 +1,210 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_panel.php 26205 2011-12-05 10:09:32Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
define('ADMINCP_PANEL', 1);
define('MODCP_PANEL', 2);
define('PORTALCP_PANEL', 3);
class discuz_panel {
private $table;
var $ttl = 3600;
var $lockttl = 900;
var $uid;
var $adminid;
var $groupid;
var $panel;
var $ip;
var $storage = array();
var $session = array();
var $islogin = false;
public function __construct($panel) {
global $_G;
$this->uid = (int)$_G['uid'];
$this->adminid = (int)$_G['adminid'];
$this->groupid = (int)$_G['groupid'];
$this->panel = (int)$panel;
$this->ip = $_G['clientip'];
$this->table = C::t('common_admincp_session');
$this->_cpaccess();
}
function _session_load() {
$this->session = $this->table->fetch($this->uid, $this->panel);
if(empty($this->session) || (time() - $this->session['dateline'] > $this->ttl)) {
$this->session = array();
} elseif($this->session['errorcount'] >=5 && (time() - $this->session['dateline'] > $this->lockttl)) {
$this->session = array();
} elseif(!empty($this->session['storage'])) {
$this->storage = dunserialize(base64_decode($this->session['storage']));
$this->session['storage'] = '';
}
return $this->session;
}
function _session_destroy($uid = 0) {
$uid = empty($uid) ? $this->uid : $uid;
$this->table->delete($uid, $this->panel, $this->ttl);
}
function _loadstorage() {
$ret = $this->table->fetch($this->uid, $this->panel);
$storage = $ret['storage'];
if(!empty($storage)) {
$this->storage = dunserialize(base64_decode($storage));
} else {
$this->storage = array();
}
}
function geturl() {
$url = getglobal('basefilename').'?';
if(!empty($_GET)) {
foreach ($_GET as $key => $value) {
$url .= urlencode($key).'='.urlencode($value).'&';
}
}
return $url;
}
function isfounder($user = '') {
global $_G;
$user = empty($user) ? array('uid' => $_G['uid'], 'adminid' => $_G['adminid'], 'username' => $_G['member']['username']) : $user;
$founders = str_replace(' ', '', $GLOBALS['forumfounders']);
if($user['adminid'] <> 1) {
return FALSE;
} elseif(empty($founders)) {
return TRUE;
} elseif(strexists(",$founders,", ",{$user['uid']},")) {
return TRUE;
} elseif(!is_numeric($user['username']) && strexists(",$founders,", ",{$user['username']},")) {
return TRUE;
} else {
return FALSE;
}
}
function set($varname, $value, $updatedb = false) {
$this->storage[$varname] = $value;
$updatedb && $this->update();
}
function get($varname, $fromdb = false) {
$return = null;
$fromdb && $this->_loadstorage();
if(isset($this->storage[$varname])) {
$return = $this->storage[$varname];
}
return $return;
}
function clear($updatedb = false) {
$this->storage = array();
$updatedb && $this->update();
}
function _sesssion_creat() {
$this->_session_destroy();
$this->set('url_forward', $this->geturl());
$this->session = array(
'uid' => $this->uid,
'adminid' => $this->adminid,
'panel' => $this->panel,
'ip' => $this->ip,
'errorcount' => 0,
);
$this->update(true);
}
function update($isnew = false) {
$data = array();
$this->session['dateline'] = time();
$this->session['storage'] = !empty($this->storage) ? base64_encode((serialize($this->storage))) : '';
if($isnew) {
$this->table->insert($this->session, false, true);
} else {
$this->table->update($this->uid, $this->panel, $this->session);
}
}
function _cpaccess() {
if(empty($this->uid)) {
$this->_user_login();
} elseif($this->panel == MODCP_PANEL && $this->adminid <= 0) {
$this->showmessage('admin_cpanel_noaccess');
}
$this->_session_load();
if(empty($this->session)) {
$this->_sesssion_creat();
} elseif($this->session['errorcount'] > 5) {
$this->_panel_locked();
} elseif($this->session['errorcount'] == -1) {
$this->islogin = true;
$this->update();
} else {
$this->islogin = false;
}
}
function dologin($username, $password, $isuid = false) {
loaducenter();
if(!$isuid) {
$username = addslashes($username);
}
$ucresult = uc_user_login($username, $password, $isuid ? 1 : 0);
if($ucresult[0] > 0) {
$this->loginsucced();
} else {
$this->session['errorcount'] ++;
}
$this->update();
return $this->islogin;
}
function dologout() {
$this->_session_destroy();
}
function loginsucced() {
$this->session['errorcount'] = '-1';
$this->islogin = true;
$this->update();
dheader('Location: '.$this->get('url_forward'));
}
function showmessage($message, $url_forward = '', $values = array(), $ext = array()) {
showmessage($message, $url_forward, $values, $ext);
dexit();
}
function _panel_locked() {
$unlocktime = dgmdate($this->session['dateline'] + $this->lockttl + 30);
$this->showmessage('admin_cpanel_locked', '', array('unlocktime' => $unlocktime));
}
function _user_login() {
$this->showmessage('to_login', 'member.php?mod=logging&action=login', array(), array('showmsg' => true, 'login' => 1));
}
}
?>

View File

@@ -0,0 +1,109 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_process.php 28412 2012-02-29 06:14:48Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_process
{
public static function islocked($process, $ttl = 0, $autounlock = 0) {
$ttl = $ttl < 1 ? 600 : intval($ttl);
$status = discuz_process::_status('get', $process) || discuz_process::_find($process, $ttl);
if($autounlock && !$status) {
register_shutdown_function('discuz_process::unlock', $process);
}
return $status;
}
public static function unlock($process) {
discuz_process::_status('rm', $process);
discuz_process::_cmd('rm', $process);
}
private static function _status($action, $process) {
static $plist = array();
switch ($action) {
case 'add' : $plist[$process] = true; break;
case 'get' : return !empty($plist[$process]); break;
case 'rm' : $plist[$process] = null; break;
case 'clear' : $plist = array(); break;
}
return true;
}
private static function _find($name, $ttl) {
if(!discuz_process::_cmd('get', $name)) {
if(discuz_process::_cmd('add', $name, $ttl) == true) {
$ret = false;
} else {
$ret = true;
}
} else {
$ret = true;
}
discuz_process::_status('add', $name);
return $ret;
}
private static function _cmd($cmd, $name, $ttl = 0) {
static $allowmem;
if($allowmem === null) {
$mc = strtolower(memory('check'));
$allowmem = $mc == 'memcache' || $mc == 'redis' || $mc == 'memcached';
}
if($allowmem) {
return discuz_process::_process_cmd_memory($cmd, $name, $ttl);
} else {
return discuz_process::_process_cmd_db($cmd, $name, $ttl);
}
}
private static function _process_cmd_memory($cmd, $name, $ttl = 0) {
$ret = '';
switch ($cmd) {
case 'add' :
$ret = memory('add', 'process_lock_'.$name, time(), $ttl);
break;
case 'get' :
$ret = memory('get', 'process_lock_'.$name);
break;
case 'rm' :
$ret = memory('rm', 'process_lock_'.$name);
}
return $ret;
}
private static function _process_cmd_db($cmd, $name, $ttl = 0) {
$ret = '';
switch ($cmd) {
case 'add':
$ret = C::t('common_process')->insert(array('processid' => $name, 'expiry' => time() + $ttl), FALSE, true);
break;
case 'get':
$ret = C::t('common_process')->fetch($name);
if(empty($ret) || $ret['expiry'] < time()) {
C::t('common_process')->delete_process($name, time());
$ret = false;
} else {
$ret = true;
}
break;
case 'rm':
$ret = C::t('common_process')->delete_process($name, time());
break;
}
return $ret;
}
}
?>

View File

@@ -0,0 +1,56 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_rank.php 27449 2012-02-01 05:32:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_rank extends discuz_base
{
public $name = '';
public function __construct($name) {
if($name) {
$this->name = $name;
} else {
throw new Exception('The property "'.get_class($this).'->name" is empty');
}
}
public function fetch_list($order = 'DESC', $start = 0, $limit = 0) {
return C::t('common_rank')->fetch_list($this->name, $order, $limit);
}
public function fetch_rank($key) {
return C::t('common_rank')->fetch_rank($this->name, $key);
}
public function set($key, $value) {
return C::t('common_rank')->insert($this->name, $key, $value);
}
public function inc($key, $value) {
return C::t('common_rank')->inc($this->name, $key, $value);
}
public function dec($key, $value) {
return C::t('common_rank')->dec($this->name, $key, $value);
}
public function clear() {
return C::t('common_rank')->delete($this->name);
}
public function rm($key) {
return $key ? C::t('common_rank')->delete($this->name, $key) : false;
}
}
?>

View File

@@ -0,0 +1,232 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_session.php 36284 2016-12-12 00:47:50Z nemohou $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_session {
public $sid = null;
public $var;
public $isnew = false;
private $newguest = array('sid' => 0, 'ip' => '',
'uid' => 0, 'username' => '', 'groupid' => 7, 'invisible' => 0, 'action' => 0,
'lastactivity' => 0, 'fid' => 0, 'tid' => 0, 'lastolupdate' => 0);
private $old = array('sid' => '', 'ip' => '', 'uid' => 0);
private $table;
public function __construct($sid = '', $ip = '', $uid = 0) {
$this->old = array('sid' => $sid, 'ip' => $ip, 'uid' => $uid);
$this->var = $this->newguest;
$enable_mem = !C::memory()->gotcluster && C::memory()->gotset &&
C::memory()->gothash && C::memory()->goteval && C::memory()->gotsortedset;
if ($enable_mem) {
$this->table = new memory_common_session();
} else {
$this->table = C::t('common_session');
}
if(!empty($ip)) {
$this->init($sid, $ip, $uid);
}
}
public function set($key, $value) {
if(isset($this->newguest[$key])) {
$this->var[$key] = $value;
}
}
public function get($key) {
if(isset($this->newguest[$key])) {
return $this->var[$key];
}
}
public function init($sid, $ip, $uid) {
$this->old = array('sid' => $sid, 'ip' => $ip, 'uid' => $uid);
$session = array();
if($sid) {
$session = $this->table->fetch($sid, $ip, $uid);
}
if(empty($session) || $session['uid'] != $uid) {
$session = $this->create($ip, $uid);
}
$this->var = $session;
$this->sid = $session['sid'];
}
public function create($ip, $uid) {
$this->isnew = true;
$this->var = $this->newguest;
$this->set('sid', random(6));
$this->set('uid', $uid);
$this->set('ip', $ip);
$uid && $this->set('invisible', getuserprofile('invisible'));
$this->set('lastactivity', time());
$this->sid = $this->var['sid'];
return $this->var;
}
public function delete() {
return $this->table->delete_by_session($this->var, getglobal('setting/onlinehold'), 60);
}
public function update() {
if($this->sid !== null) {
if($this->isnew) {
$this->delete();
$this->table->insert($this->var, false, false, true);
} else {
$this->table->update($this->var['sid'], $this->var);
}
setglobal('sessoin', $this->var);
dsetcookie('sid', $this->sid, 86400);
}
}
public function count($type = 0) {
return $this->table->count($type);
}
public function fetch_member($ismember = 0, $invisible = 0, $start = 0, $limit = 0) {
return $this->table->fetch_member($ismember, $invisible, $start, $limit);
}
public function count_invisible($type = 1) {
return $this->table->count_invisible($type);
}
public function update_max_rows($max_rows) {
return $this->table->update_max_rows($max_rows);
}
public function clear() {
return $this->table->clear();
}
public function count_by_fid($fid) {
return $this->table->count_by_fid($fid);
}
public function fetch_all_by_fid($fid, $limit = 0) {
$data = array();
if(!($fid = dintval($fid))) {
return $data;
}
$onlinelist = getglobal('cache/onlinelist');
foreach($this->table->fetch_all_by_fid($fid, $limit) as $online) {
if($online['uid']) {
$online['icon'] = isset($onlinelist[$online['groupid']]) ? $onlinelist[$online['groupid']] : $onlinelist[0];
} else {
$online['icon'] = $onlinelist[7];
$online['username'] = $onlinelist['guest'];
}
$online['lastactivity'] = dgmdate($online['lastactivity'], 't');
$data[$online['uid']] = $online;
}
return $data;
}
public function fetch_by_uid($uid) {
return $this->table->fetch_by_uid($uid);
}
public function fetch_all_by_uid($uids, $start = 0, $limit = 0) {
return $this->table->fetch_all_by_uid($uids, $start, $limit);
}
public function update_by_uid($uid, $data) {
return $this->table->update_by_uid($uid, $data);
}
public function count_by_ip($ip) {
return $this->table->count_by_ip($ip);
}
public function fetch_all_by_ip($ip, $start = 0, $limit = 0) {
return $this->table->fetch_all_by_ip($ip, $start, $limit);
}
public static function updatesession() {
static $updated = false;
if(!$updated) {
global $_G;
$ulastactivity = 0;
if($_G['uid']) {
if($_G['cookie']['ulastactivity']) {
$ulastactivity = authcode($_G['cookie']['ulastactivity'], 'DECODE');
} else {
$ulastactivity = getuserprofile('lastactivity');
dsetcookie('ulastactivity', authcode($ulastactivity, 'ENCODE'), 31536000);
}
}
$ulastactivity = (int)$ulastactivity;
$oltimespan = (int)$_G['setting']['oltimespan'];
$lastolupdate = (int)C::app()->session->var['lastolupdate'];
if($_G['uid'] && $oltimespan && (int)TIMESTAMP - ($lastolupdate ? $lastolupdate : $ulastactivity) > $oltimespan * 60) {
$isinsert = false;
if(C::app()->session->isnew) {
$oldata = C::t('common_onlinetime')->fetch($_G['uid']);
if(empty($oldata)) {
$isinsert = true;
} else if(TIMESTAMP - $oldata['lastupdate'] > $oltimespan * 60) {
C::t('common_onlinetime')->update_onlinetime($_G['uid'], $oltimespan, $oltimespan, TIMESTAMP);
}
} else {
$isinsert = !C::t('common_onlinetime')->update_onlinetime($_G['uid'], $oltimespan, $oltimespan, TIMESTAMP);
}
if($isinsert) {
C::t('common_onlinetime')->insert(array(
'uid' => $_G['uid'],
'thismonth' => $oltimespan,
'total' => $oltimespan,
'lastupdate' => TIMESTAMP,
));
}
C::app()->session->set('lastolupdate', TIMESTAMP);
}
foreach(C::app()->session->var as $k => $v) {
if(isset($_G['member'][$k]) && $k != 'lastactivity') {
C::app()->session->set($k, $_G['member'][$k]);
}
}
foreach($_G['action'] as $k => $v) {
C::app()->session->set($k, $v);
}
C::app()->session->update();
if($_G['uid'] && TIMESTAMP - $ulastactivity > 21600) {
if($oltimespan && TIMESTAMP - $ulastactivity > 43200) {
$onlinetime = C::t('common_onlinetime')->fetch($_G['uid']);
C::t('common_member_count')->update($_G['uid'], array('oltime' => round(intval($onlinetime['total']) / 60)));
}
dsetcookie('ulastactivity', authcode(TIMESTAMP, 'ENCODE'), 31536000);
C::t('common_member_status')->update($_G['uid'], array('lastip' => $_G['clientip'], 'port' => $_G['remoteport'], 'lastactivity' => TIMESTAMP, 'lastvisit' => TIMESTAMP));
}
$updated = true;
}
return $updated;
}
}
?>

View File

@@ -0,0 +1,174 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_session_close.php 33707 2013-08-06 08:22:12Z andyzheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_session_close {
private $onlinehold;
private $oltimestamp;
public $sid = null;
public $var;
public $isnew = false;
protected $newguest = array('sid' => 0, 'ip' => '',
'uid' => 0, 'username' => '', 'groupid' => 7, 'invisible' => 0, 'action' => 0,
'lastactivity' => 0, 'fid' => 0, 'tid' => 0, 'lastolupdate' => 0);
protected $table;
public function __construct($sid = '', $ip = '', $uid = 0) {
$this->old = array('sid' => $sid, 'ip' => $ip, 'uid' => $uid);
$this->var = $this->newguest;
$this->onlinehold = getglobal('setting/onlinehold');
$this->oltimestamp = TIMESTAMP - $this->onlinehold;
$this->table = C::t('common_member_status');
if(!empty($ip)) {
$this->init($sid, $ip, $uid);
}
}
public function set($key, $value) {
if(isset($this->newguest[$key])) {
$this->var[$key] = $value;
}
}
public function get($key) {
if(isset($this->newguest[$key])) {
return $this->var[$key];
}
}
public function init($sid, $ip, $uid) {
if(($uid = intval($uid)) > 0) {
$this->var = $this->newguest;
$this->set('sid', 0);
$this->set('uid', $uid);
$this->set('username', getglobal('member/username'));
$this->set('groupid', getglobal('member/groupid'));
$this->set('ip', $ip);
if(($ulastactivity = getglobal('cookie/ulastactivity'))) {
list($lastactivity, $invisible) = explode('|', $ulastactivity);
$lastactivity = intval($lastactivity);
$invisible = intval($invisible);
}
if(!$lastactivity) {
$lastactivity = getuserprofile('lastactivity');
$invisible = getuserprofile('invisible');
dsetcookie('ulastactivity', $lastactivity.'|'.$invisible, 31536000);
}
if($this->oltimestamp >= $lastactivity) {
$this->isnew = true;
}
$this->set('invisible', $invisible);
$this->set('lastactivity', $lastactivity);
$this->sid = 0;
}
}
public function create($ip, $uid) {
return $this->var;
}
public function delete() {
return true;
}
public function update() {
return true;
}
public function count($type = 0) {
loadcache('onlinecount');
$onlinecount = getglobal('cache/onlinecount');
if($onlinecount && $onlinecount['dateline'] > TIMESTAMP - 600) {
$count = $onlinecount['count'];
} else {
$count = $this->table->count_by_lastactivity_invisible($this->oltimestamp);
savecache('onlinecount', array('count' => $count, 'dateline' => TIMESTAMP));
}
if($type == 1) {
return $count;
}
if(!($multiple = getglobal('setting/onlineguestsmultiple'))) $multiple = 11;
$add = mt_rand(0, $multiple);
if($type == 2) {
return intval($count * $multiple) + $add - $count;
} else {
return intval($count * $multiple) + $add;
}
}
public function fetch_member($ismember = 0, $invisible = 0, $start = 0, $limit = 0) {
return $this->table->fetch_all_by_lastactivity_invisible($this->oltimestamp, $invisible, $start, $limit);
}
public function count_invisible($type = 1) {
return $this->table->count_by_lastactivity_invisible($this->oltimestamp, $type);
}
public function update_max_rows($max_rows) {
return false;
}
public function clear() {
return false;
}
public function count_by_fid($fid) {
return 0;
}
public function fetch_all_by_fid($fid, $limit = 0) {
return array();
}
public function fetch_by_uid($uid) {
if(($member = $this->table->fetch($uid)) && $member['lastactivity'] >= $this->oltimestamp) {
return $member;
}
return array();
}
public function fetch_all_by_uid($uids, $start = 0, $limit = 0) {
return $this->table->fetch_all_onlines($uids, $this->oltimestamp, $start, $limit);
}
public function update_by_uid($uid, $data) {
return false;
}
public function count_by_ip($ip) {
return 0;
}
public function fetch_all_by_ip($ip, $start = 0, $limit = 0) {
return array();
}
public function updatesession() {
static $updated = false;
if(!$updated && $this->isnew) {
global $_G;
C::t('common_member_status')->update($_G['uid'], array('lastip' => $_G['clientip'], 'port' => $_G['remoteport'], 'lastactivity' => TIMESTAMP, 'lastvisit' => TIMESTAMP));
dsetcookie('ulastactivity', TIMESTAMP.'|'.getuserprofile('invisible'), 31536000);
$updated = true;
}
return $updated;
}
}
?>

View File

@@ -0,0 +1,247 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_table.php 30321 2012-05-22 09:09:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_table extends discuz_base
{
public $data = array();
public $methods = array();
protected $_table;
protected $_pk;
protected $_pre_cache_key;
protected $_cache_ttl;
protected $_allowmem;
public function __construct($para = array()) {
if(!empty($para)) {
$this->_table = $para['table'];
$this->_pk = $para['pk'];
}
if(isset($this->_pre_cache_key) && (($ttl = getglobal('setting/memory/'.$this->_table)) !== null || ($ttl = $this->_cache_ttl) !== null) && memory('check')) {
$this->_cache_ttl = $ttl;
$this->_allowmem = true;
}
$this->_init_extend();
parent::__construct();
}
public function getTable() {
return $this->_table;
}
public function setTable($name) {
return $this->_table = $name;
}
public function count() {
$count = (int) DB::result_first("SELECT count(*) FROM ".DB::table($this->_table));
return $count;
}
public function update($val, $data, $unbuffered = false, $low_priority = false) {
if(isset($val) && !empty($data) && is_array($data)) {
$this->checkpk();
$ret = DB::update($this->_table, $data, DB::field($this->_pk, $val), $unbuffered, $low_priority);
foreach((array)$val as $id) {
$this->update_cache($id, $data);
}
return $ret;
}
return !$unbuffered ? 0 : false;
}
public function delete($val, $unbuffered = false) {
$ret = false;
if(isset($val)) {
$this->checkpk();
$ret = DB::delete($this->_table, DB::field($this->_pk, $val), null, $unbuffered);
$this->clear_cache($val);
}
return $ret;
}
public function truncate() {
DB::query("TRUNCATE ".DB::table($this->_table));
}
public function insert($data, $return_insert_id = false, $replace = false, $silent = false) {
return DB::insert($this->_table, $data, $return_insert_id, $replace, $silent);
}
public function checkpk() {
if(!$this->_pk) {
throw new DbException('Table '.$this->_table.' has not PRIMARY KEY defined');
}
}
public function fetch($id, $force_from_db = false){
$data = array();
if(!empty($id)) {
if($force_from_db || ($data = $this->fetch_cache($id)) === false) {
$data = DB::fetch_first('SELECT * FROM '.DB::table($this->_table).' WHERE '.DB::field($this->_pk, $id));
if(!empty($data)) $this->store_cache($id, $data);
}
}
return $data;
}
public function fetch_all($ids, $force_from_db = false) {
$data = array();
if(!empty($ids)) {
if($force_from_db || ($data = $this->fetch_cache($ids)) === false || count($ids) != count($data)) {
if(is_array($data) && !empty($data)) {
$ids = array_diff($ids, array_keys($data));
}
if($data === false) $data =array();
if(!empty($ids)) {
$query = DB::query('SELECT * FROM '.DB::table($this->_table).' WHERE '.DB::field($this->_pk, $ids));
while($value = DB::fetch($query)) {
$data[$value[$this->_pk]] = $value;
$this->store_cache($value[$this->_pk], $value);
}
}
}
}
return $data;
}
public function fetch_all_field(){
$data = false;
$query = DB::query('SHOW FIELDS FROM '.DB::table($this->_table), '', 'SILENT');
if($query) {
$data = array();
while($value = DB::fetch($query)) {
$data[$value['Field']] = $value;
}
}
return $data;
}
public function range($start = 0, $limit = 0, $sort = '') {
if($sort) {
$this->checkpk();
}
return DB::fetch_all('SELECT * FROM '.DB::table($this->_table).($sort ? ' ORDER BY '.DB::order($this->_pk, $sort) : '').DB::limit($start, $limit), null, $this->_pk ? $this->_pk : '');
}
public function optimize() {
DB::query('OPTIMIZE TABLE '.DB::table($this->_table), 'SILENT');
}
public function fetch_cache($ids, $pre_cache_key = null) {
$data = false;
if($this->_allowmem) {
if($pre_cache_key === null) $pre_cache_key = $this->_pre_cache_key;
$data = memory('get', $ids, $pre_cache_key);
}
return $data;
}
public function store_cache($id, $data, $cache_ttl = null, $pre_cache_key = null) {
$ret = false;
if($this->_allowmem) {
if($pre_cache_key === null) $pre_cache_key = $this->_pre_cache_key;
if($cache_ttl === null) $cache_ttl = $this->_cache_ttl;
$ret = memory('set', $id, $data, $cache_ttl, $pre_cache_key);
}
return $ret;
}
public function clear_cache($ids, $pre_cache_key = null) {
$ret = false;
if($this->_allowmem) {
if($pre_cache_key === null) $pre_cache_key = $this->_pre_cache_key;
$ret = memory('rm', $ids, $pre_cache_key);
}
return $ret;
}
public function update_cache($id, $data, $cache_ttl = null, $pre_cache_key = null) {
$ret = false;
if($this->_allowmem) {
if($pre_cache_key === null) $pre_cache_key = $this->_pre_cache_key;
if($cache_ttl === null) $cache_ttl = $this->_cache_ttl;
if(($_data = memory('get', $id, $pre_cache_key)) !== false) {
$ret = $this->store_cache($id, array_merge($_data, $data), $cache_ttl, $pre_cache_key);
}
}
return $ret;
}
public function update_batch_cache($ids, $data, $cache_ttl = null, $pre_cache_key = null) {
$ret = false;
if($this->_allowmem) {
if($pre_cache_key === null) $pre_cache_key = $this->_pre_cache_key;
if($cache_ttl === null) $cache_ttl = $this->_cache_ttl;
if(($_data = memory('get', $ids, $pre_cache_key)) !== false) {
foreach($_data as $id => $value) {
$ret = $this->store_cache($id, array_merge($value, $data), $cache_ttl, $pre_cache_key);
}
}
}
return $ret;
}
public function reset_cache($ids, $pre_cache_key = null) {
$ret = false;
if($this->_allowmem) {
$keys = array();
if(($cache_data = $this->fetch_cache($ids, $pre_cache_key)) !== false) {
$keys = array_intersect(array_keys($cache_data), $ids);
unset($cache_data);
}
if(!empty($keys)) {
$this->fetch_all($keys, true);
$ret = true;
}
}
return $ret;
}
public function increase_cache($ids, $data, $cache_ttl = null, $pre_cache_key = null) {
if($this->_allowmem) {
if(($cache_data = $this->fetch_cache($ids, $pre_cache_key)) !== false) {
foreach($cache_data as $id => $one) {
foreach($data as $key => $value) {
if(is_array($value)) {
$one[$key] = $value[0];
} else {
$one[$key] = $one[$key] + ($value);
}
}
$this->store_cache($id, $one, $cache_ttl, $pre_cache_key);
}
}
}
}
public function __toString() {
return $this->_table;
}
protected function _init_extend() {
}
public function attach_before_method($name, $fn) {
$this->methods[$name][0][] = $fn;
}
public function attach_after_method($name, $fn) {
$this->methods[$name][1][] = $fn;
}
}
?>

View File

@@ -0,0 +1,150 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_table_archive.php 31076 2012-07-13 03:30:58Z zhangjie $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_table_archive extends discuz_table
{
public $membersplit = null;
public function __construct($para = array()) {
$this->membersplit = getglobal('setting/membersplit');
parent::__construct($para);
}
public $tablestatus = array();
public function fetch($id, $force_from_db = false, $fetch_archive = 0){
$data = array();
if(!empty($id)) {
$data = parent::fetch($id, $force_from_db);
if(isset($this->membersplit) && $fetch_archive && empty($data)) {
$data = C::t($this->_table.'_archive')->fetch($id);
}
}
return $data;
}
public function fetch_all($ids, $force_from_db = false, $fetch_archive = 1) {
$data = array();
if(!empty($ids)) {
$data = parent::fetch_all($ids, $force_from_db);
if(isset($this->membersplit) && $fetch_archive && count($data) != count($ids)) {
$data = $data + C::t($this->_table.'_archive')->fetch_all(array_diff($ids, array_keys($data)));
}
}
return $data;
}
public function delete($val, $unbuffered = false, $fetch_archive = 0) {
$ret = false;
if($val) {
$ret = parent::delete($val, $unbuffered);
if(isset($this->membersplit) && $fetch_archive) {
$_ret = C::t($this->_table.'_archive')->delete($val, $unbuffered);
if(!$unbuffered) {
$ret = $ret + $_ret;
}
}
}
return $ret;
}
public function split_check($wheresql) {
$status = helper_dbtool::gettablestatus(DB::table($this->_table), false);
if($status && $status['Data_length'] > 100 * 1048576) {//400 * 1048576
if($moverows = DB::result_first('SELECT COUNT(*) FROM %t WHERE '.$wheresql, array($this->_table))) {
$status['Move_rows'] = $moverows;
$this->tablestatus = $status;
return true;
}
}
return false;
}
public function create_relatedtable($relatedtablename) {
if(!helper_dbtool::isexisttable($relatedtablename)) {
DB::query('SET SQL_QUOTE_SHOW_CREATE=0', 'SILENT');
$tableinfo = DB::fetch_first("SHOW CREATE TABLE ".DB::table($this->_table));
$createsql = $tableinfo['Create Table'];
$createsql = str_replace($this->_table, $relatedtablename, $createsql);
DB::query($createsql);
}
return true;
}
public function split_table($wheresql) {
$limit = 2000;
$targettable = helper_dbtool::showtablecloumn($this->_table);
$fieldstr = '`'.implode('`, `', array_keys($targettable)).'`';
if(!$this->_pk && !in_array('split_id', array_keys($targettable))) {
DB::query('ALTER TABLE %t ADD split_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, ADD UNIQUE KEY split_id (split_id)', array($this->_table));
return 1;
}
$tmptable = $this->_table.'_tmp___';
$archivetable = $this->_table.'_archive';
$key = $this->_pk ? $this->_pk : 'split_id';
$this->create_relatedtable($tmptable);
$this->create_relatedtable($archivetable);
DB::query("INSERT INTO %t ($fieldstr) SELECT $fieldstr FROM %t WHERE $wheresql ".DB::limit($limit), array($tmptable, $this->_table));
if(DB::result_first('SELECT COUNT(*) FROM %t', array($tmptable))) {
$keylist = DB::fetch_all('SELECT '.$key.' FROM %t', array($tmptable), $key);
$keylist = dimplode(array_keys($keylist));
if(DB::query("INSERT INTO %t ($fieldstr) SELECT $fieldstr FROM %t WHERE $key in ($keylist)", array($archivetable, $this->_table), false, true)) {
DB::query("DELETE FROM %t WHERE $key in ($keylist)", array($this->_table), false, true);
}
DB::query('DROP TABLE %t', array($tmptable));
return 1;
} else {
DB::query('DROP TABLE %t', array($tmptable));
$this->optimize();
return 2;
}
}
public function merge_table() {
$limit = 2000;
$tmptable = $this->_table.'_tmp___';
$archivetable = $this->_table.'_archive';
$key = $this->_pk ? $this->_pk : 'split_id';
if(!helper_dbtool::isexisttable($archivetable)) {
return 2;
}
$this->create_relatedtable($tmptable);
$targettable = helper_dbtool::showtablecloumn($this->_table);
$fieldstr = '`'.implode('`, `', array_keys($targettable)).'`';
DB::query("INSERT INTO %t ($fieldstr) SELECT $fieldstr FROM %t ".DB::limit($limit), array($tmptable, $archivetable));
if(DB::result_first('SELECT COUNT(*) FROM %t', array($tmptable))) {
$keylist = DB::fetch_all('SELECT '.$key.' FROM %t', array($tmptable), $key);
$keylist = dimplode(array_keys($keylist));
if(DB::query("INSERT INTO %t ($fieldstr) SELECT $fieldstr FROM %t WHERE $key in ($keylist)", array($this->_table, $archivetable), false, true)) {
DB::query("DELETE FROM %t WHERE $key in ($keylist)", array($archivetable), false, true);
}
DB::query('DROP TABLE %t', array($tmptable));
return 1;
} else {
DB::query('DROP TABLE %t', array($tmptable));
DB::query('DROP TABLE %t', array($archivetable));
$this->optimize();
return 2;
}
}
}
?>

View File

@@ -0,0 +1,269 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_upgrade.php 31992 2012-10-30 05:44:15Z zhangjie $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class discuz_upgrade {
var $upgradeurl = 'https://upgrade.discuz.vip/DiscuzX/';
var $locale = 'SC';
var $charset = 'GBK';
public function fetch_updatefile_list($upgradeinfo) {
$file = DISCUZ_ROOT.'./data/update/Discuz! X'.$upgradeinfo['latestversion'].' Release['.$upgradeinfo['latestrelease'].']/updatelist.tmp';
$upgradedataflag = true;
$upgradedata = @file_get_contents($file);
if(!$upgradedata) {
$upgradedata = dfsockopen($this->upgradeurl.substr($upgradeinfo['upgradelist'], 0, -4).strtolower('_'.$this->locale.'_'.$this->charset).'.txt');
$upgradedataflag = false;
}
$return = array();
$upgradedataarr = explode("\r\n", $upgradedata);
foreach($upgradedataarr as $k => $v) {
if(!$v) {
continue;
}
$return['file'][$k] = trim(substr($v, 34));
$return['md5'][$k] = substr($v, 0, 32);
if(trim(substr($v, 32, 2)) != '*') {
@unlink($file);
return array();
}
}
if(!$upgradedataflag) {
$this->mkdirs(dirname($file));
if(file_put_contents($file, $upgradedata) === false) {
return array();
}
}
return $return;
}
public function compare_basefile($upgradeinfo, $upgradefilelist) {
if(!$discuzfiles = @file('./source/admincp/discuzfiles.md5')) {
return array();
}
$newupgradefilelist = array();
foreach($upgradefilelist as $v) {
$newupgradefilelist[$v] = md5_file(DISCUZ_ROOT.'./'.$v);
}
$modifylist = $showlist = $searchlist = array();
foreach($discuzfiles as $line) {
$file = trim(substr($line, 34));
$md5datanew[$file] = substr($line, 0, 32);
if(isset($newupgradefilelist[$file])) {
if($md5datanew[$file] != $newupgradefilelist[$file]) {
if(!$upgradeinfo['isupdatetemplate'] && preg_match('/\.htm$/i', $file)) {
$ignorelist[$file] = $file;
$searchlist[] = "\r\n".$file;
continue;
}
$modifylist[$file] = $file;
} else {
$showlist[$file] = $file;
}
}
}
if($searchlist) {
$file = DISCUZ_ROOT.'./data/update/Discuz! X'.$upgradeinfo['latestversion'].' Release['.$upgradeinfo['latestrelease'].']/updatelist.tmp';
$upgradedata = file_get_contents($file);
$upgradedata = str_replace($searchlist, '', $upgradedata);
if(file_put_contents($file, $upgradedata) === false) {
return array();
}
}
return array($modifylist, $showlist, $ignorelist);
}
public function compare_file_content($file, $remotefile) {
if(!preg_match('/\.php$|\.htm$/i', $file)) {
return false;
}
$content = preg_replace('/\s/', '', file_get_contents($file));
$ctx = stream_context_create(array('http' => array('timeout' => 60)));
$remotecontent = preg_replace('/\s/', '', file_get_contents($remotefile, false, $ctx));
if(strcmp($content, $remotecontent)) {
return false;
} else {
return true;
}
}
public function check_upgrade() {
include_once libfile('class/xml');
include_once libfile('function/cache');
$return = false;
$upgradefile = $this->upgradeurl.$this->versionpath().'/'.DISCUZ_RELEASE.'/upgrade.xml';
$response_xml = dfsockopen($upgradefile);
$response = xml2array($response_xml);
if(isset($response['cross']) || isset($response['patch'])) {
C::t('common_setting')->update_setting('upgrade', $response);
$return = true;
} else {
C::t('common_setting')->update_setting('upgrade', '');
$return = false;
}
updatecache('setting');
return $return;
}
public function check_folder_perm($updatefilelist) {
foreach($updatefilelist as $file) {
if(!file_exists(DISCUZ_ROOT.$file)) {
if(!$this->test_writable(dirname(DISCUZ_ROOT.$file))) {
return false;
}
} else {
if(!is_writable(DISCUZ_ROOT.$file)) {
return false;
}
}
}
return true;
}
public function test_writable($dir) {
$writeable = 0;
$this->mkdirs($dir);
if(is_dir($dir)) {
if($fp = @fopen("$dir/test.txt", 'w')) {
@fclose($fp);
@unlink("$dir/test.txt");
$writeable = 1;
} else {
$writeable = 0;
}
}
return $writeable;
}
public function download_file($upgradeinfo, $file, $folder = 'upload', $md5 = '', $position = 0, $offset = 0) {
$dir = DISCUZ_ROOT.'./data/update/Discuz! X'.$upgradeinfo['latestversion'].' Release['.$upgradeinfo['latestrelease'].']/';
$this->mkdirs(dirname($dir.$file));
$downloadfileflag = true;
if(!$position) {
$mode = 'wb';
} else {
$mode = 'ab';
}
$fp = fopen($dir.$file, $mode);
if(!$fp) {
return 0;
}
$response = dfsockopen($this->upgradeurl.$upgradeinfo['latestversion'].'/'.$upgradeinfo['latestrelease'].'/'.$this->locale.'_'.$this->charset.'/'.$folder.'/'.$file.'sc', $offset, '', '', FALSE, '', 120, TRUE, 'URLENCODE', FALSE, $position);
if($response) {
if($offset && strlen($response) == $offset) {
$downloadfileflag = false;
}
fwrite($fp, $response);
}
fclose($fp);
if($downloadfileflag) {
if(md5_file($dir.$file) == $md5) {
return 2;
} else {
return 0;
}
} else {
return 1;
}
}
public function mkdirs($dir) {
if(!is_dir($dir)) {
if(!self::mkdirs(dirname($dir))) {
return false;
}
if(!@mkdir($dir, 0777)) {
return false;
}
@touch($dir.'/index.htm'); @chmod($dir.'/index.htm', 0777);
}
return true;
}
public function copy_file($srcfile, $desfile, $type) {
global $_G;
if(!is_file($srcfile)) {
return false;
}
if($type == 'file') {
$this->mkdirs(dirname($desfile));
copy($srcfile, $desfile);
} elseif($type == 'ftp') {
$siteftp = $_GET['siteftp'];
$siteftp['on'] = 1;
$siteftp['password'] = authcode($siteftp['password'], 'ENCODE', md5($_G['config']['security']['authkey']));
$ftp = & discuz_ftp::instance($siteftp);
$ftp->connect();
$ftp->upload($srcfile, $desfile);
if($ftp->error()) {
return false;
}
}
return true;
}
public function versionpath() {
$versionpath = '';
foreach(explode(' ', substr(DISCUZ_VERSION, 1)) as $unit) {
$versionpath = $unit;
break;
}
return $versionpath;
}
function copy_dir($srcdir, $destdir) {
$dir = @opendir($srcdir);
while($entry = @readdir($dir)) {
$file = $srcdir.$entry;
if($entry != '.' && $entry != '..') {
if(is_dir($file)) {
self::copy_dir($file.'/', $destdir.$entry.'/');
} else {
self::mkdirs(dirname($destdir.$entry));
copy($file, $destdir.$entry);
}
}
}
closedir($dir);
}
function rmdirs($srcdir) {
$dir = @opendir($srcdir);
while($entry = @readdir($dir)) {
$file = $srcdir.$entry;
if($entry != '.' && $entry != '..') {
if(is_dir($file)) {
self::rmdirs($file.'/');
} else {
@unlink($file);
}
}
}
closedir($dir);
rmdir($srcdir);
}
}
?>

View File

@@ -0,0 +1,251 @@
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_upload.php 34648 2014-06-18 02:53:07Z hypowang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
Class discuz_upload{
var $attach = array();
var $type = '';
var $extid = 0;
var $errorcode = 0;
var $forcename = '';
public function __construct() {
}
function init($attach, $type = 'temp', $extid = 0, $forcename = '', $subdir = '', $dirtype = 1, $filename = '') {
if(!is_array($attach) || empty($attach) || !$this->is_upload_file($attach['tmp_name']) || trim($attach['name']) == '' || $attach['size'] == 0) {
$this->attach = array();
$this->errorcode = -1;
return false;
} else {
$this->type = $this->check_dir_type($type);
$this->extid = intval($extid);
$this->forcename = preg_match("/^[a-z0-9_]+$/i", $forcename) ? $forcename : '';
$subdir = preg_match("/^[a-z0-9_]+$/i", $subdir) ? $subdir : '';
$filename = preg_match("/^[a-z0-9_]+$/i", $filename) ? $filename : '';
$attach['size'] = intval($attach['size']);
$attach['name'] = trim($attach['name']);
$attach['thumb'] = '';
$attach['ext'] = $this->fileext($attach['name']);
$attach['name'] = dhtmlspecialchars($attach['name'], ENT_QUOTES);
if(dstrlen($attach['name']) > 90) {
$attach['name'] = cutstr($attach['name'], 80, '').'.'.$attach['ext'];
}
$attach['isimage'] = $this->is_image_ext($attach['ext']);
$attach['extension'] = $this->get_target_extension($attach['ext']);
$attach['attachdir'] = $this->get_target_dir($this->type, $extid, true, $subdir, $dirtype);
$attach['attachment'] = $attach['attachdir'].$this->get_target_filename($this->type, $this->extid, $this->forcename, $filename).'.'.$attach['extension'];
$attach['target'] = getglobal('setting/attachdir').'./'.$this->type.'/'.$attach['attachment'];
$this->attach = & $attach;
$this->errorcode = 0;
return true;
}
}
function save($ignore = 0) {
if($ignore) {
if(!$this->save_to_local($this->attach['tmp_name'], $this->attach['target'])) {
$this->errorcode = -103;
return false;
} else {
$this->errorcode = 0;
return true;
}
}
if(empty($this->attach) || empty($this->attach['tmp_name']) || empty($this->attach['target'])) {
$this->errorcode = -101;
} elseif(in_array($this->type, array('group', 'album', 'category')) && !$this->attach['isimage']) {
$this->errorcode = -102;
} elseif(in_array($this->type, array('common')) && (!$this->attach['isimage'] && !in_array($this->attach['ext'], array('ext', 'svg')))) {
$this->errorcode = -102;
} elseif(!$this->save_to_local($this->attach['tmp_name'], $this->attach['target'])) {
$this->errorcode = -103;
} elseif(($this->attach['isimage'] || $this->attach['ext'] == 'swf') && (!$this->attach['imageinfo'] = $this->get_image_info($this->attach['target'], true))) {
$this->errorcode = -104;
@unlink($this->attach['target']);
} else {
$this->errorcode = 0;
return true;
}
return false;
}
function error() {
return $this->errorcode;
}
function errormessage() {
return lang('error', 'file_upload_error_'.$this->errorcode);
}
public static function fileext($filename) {
return addslashes(strtolower(substr(strrchr($filename, '.'), 1, 10)));
}
public static function is_image_ext($ext) {
static $imgext = array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp');
return in_array($ext, $imgext) ? 1 : 0;
}
public static function get_image_info($target, $allowswf = false) {
$ext = discuz_upload::fileext($target);
$isimage = discuz_upload::is_image_ext($ext);
if(!$isimage && ($ext != 'swf' || !$allowswf)) {
return false;
} elseif(!is_readable($target)) {
return false;
} elseif($imageinfo = @getimagesize($target)) {
list($width, $height, $type) = !empty($imageinfo) ? $imageinfo : array('', '', '');
$size = $width * $height;
if((!getglobal('setting/imagelib') && $size > (getglobal('setting/gdlimit') ? getglobal('setting/gdlimit') : 16777216)) || $size < 16 ) {
return false;
} elseif($ext == 'swf' && $type != 4 && $type != 13) {
return false;
} elseif($isimage && !in_array($type, array(1,2,3,6,13,18))) {
return false;
} elseif(!$allowswf && ($ext == 'swf' || $type == 4 || $type == 13)) {
return false;
}
return $imageinfo;
} else {
return false;
}
}
public static function is_upload_file($source) {
return $source && ($source != 'none') && (is_uploaded_file($source) || is_uploaded_file(str_replace('\\\\', '\\', $source)));
}
public static function get_target_filename($type, $extid = 0, $forcename = '', $filename = '') {
if (empty($filename)) {
if($type == 'group' || ($type == 'common' && $forcename != '')) {
$filename = $type.'_'.intval($extid).($forcename != '' ? "_$forcename" : '');
} else {
$filename = date('His').strtolower(random(16));
}
}
return $filename;
}
public static function get_target_extension($ext) {
static $safeext = array('attach', 'jpg', 'jpeg', 'gif', 'png', 'webp', 'swf', 'bmp', 'txt', 'zip', 'rar', 'mp3');
if(defined('IN_ADMINCP')) {
$safeext[] = 'svg';
}
return strtolower(!in_array(strtolower($ext), $safeext) ? 'attach' : $ext);
}
public static function get_target_dir($type, $extid = '', $check_exists = true, $subdir = '', $dirtype = 1) {
$dir = $subdir1 = $subdir2 = '';
if($dirtype == 1) {
if($type == 'group' || $type == 'common') {
$dir = $subdir1 = substr(md5($extid), 0, 2).'/';
} elseif($type != 'temp') {
$subdir1 = date('Ym');
$subdir2 = date('d');
$dir = $subdir1.'/'.$subdir2.'/';
}
} elseif($dirtype == 2) {
$subdir1 = date('Ym');
$subdir2 = date('d');
$dir = $subdir1.'/'.$subdir2.'/';
} elseif($dirtype == 3) {
$dir = $subdir1 = substr(md5($extid), 0, 2).'/';
}
if($subdir) {
$dir = $subdir.'/'.$dir;
}
if($check_exists) {
if($subdir) {
discuz_upload::check_dir_exists($type, $subdir, $subdir1);
discuz_upload::check_dir_exists($type, $subdir.'/'.$subdir1.'/'.$subdir2);
} else {
discuz_upload::check_dir_exists($type, $subdir1, $subdir2);
}
}
return $dir;
}
public static function check_dir_type($type) {
return preg_match("/^[a-z]+[a-z0-9_]*$/i", $type) ? $type : 'temp';
}
public static function check_dir_exists($type = '', $sub1 = '', $sub2 = '') {
$type = discuz_upload::check_dir_type($type);
$basedir = !getglobal('setting/attachdir') ? (DISCUZ_ROOT.'./data/attachment') : getglobal('setting/attachdir');
$typedir = $type ? ($basedir.'/'.$type) : '';
$subdir1 = $type && $sub1 !== '' ? ($typedir.'/'.$sub1) : '';
$subdir2 = $sub1 && $sub2 !== '' ? ($subdir1.'/'.$sub2) : '';
$res = $subdir2 ? is_dir($subdir2) : ($subdir1 ? is_dir($subdir1) : is_dir($typedir));
if(!$res) {
$res = $typedir && discuz_upload::make_dir($typedir);
$res && $subdir1 && ($res = discuz_upload::make_dir($subdir1));
$res && $subdir1 && $subdir2 && ($res = discuz_upload::make_dir($subdir2));
}
return $res;
}
function save_to_local($source, $target) {
if(!discuz_upload::is_upload_file($source)) {
$succeed = false;
}elseif(@copy($source, $target)) {
$succeed = true;
}elseif(function_exists('move_uploaded_file') && @move_uploaded_file($source, $target)) {
$succeed = true;
}elseif (@is_readable($source) && (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($target, 'wb'))) {
while (!feof($fp_s)) {
$s = @fread($fp_s, 1024 * 512);
@fwrite($fp_t, $s);
}
fclose($fp_s); fclose($fp_t);
$succeed = true;
}
if($succeed) {
$this->errorcode = 0;
@chmod($target, 0644); @unlink($source);
} else {
$this->errorcode = 0;
}
return $succeed;
}
public static function make_dir($dir, $index = true) {
$res = true;
if(!is_dir($dir)) {
$res = @mkdir($dir, 0777);
$index && @touch($dir.'/index.html');
}
return $res;
}
}
?>

View File