code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: modcp.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
define('NOROBOT', TRUE);
define('SQL_ADD_THREAD', 't.subject, t.authorid, t.digest, ');
require_once './include/common.inc.php';
if(!$discuz_uid || !($forum['ismoderator']) || $forum['digest'] < 0) {
showmessage('admin_nopermission', NULL, 'HALTED');
}
if($action == 'editsubject') {
$query = $db->query("SELECT m.adminid, p.first, p.authorid, p.author, p.dateline, p.anonymous, p.invisible FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
WHERE p.tid='$tid' AND p.first='1' AND fid='$fid'");
$orig = $db->fetch_array($query);
if(empty($orig)) {
showmessage('thread_nonexistence', NULL, 'AJAXERROR');
}
periodscheck('postbanperiods');
if(empty($forum['allowview'])) {
if(!$forum['viewperm'] && !$readaccess) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
showmessage('forum_nopermission', NULL, 'NOPERM');
}
}
if(!$forum['ismoderator'] || !$alloweditpost || (in_array($orig['adminid'], array(1, 2, 3)) && $adminid > $orig['adminid'])) {
showmessage('post_edit_nopermission', NULL, 'HALTED');
}
require_once DISCUZ_ROOT.'./include/post.func.php';
$subject = $subjectnew;
if($post_invalid = checkpost()) {
showmessage($post_invalid);
}
if(!submitcheck('editsubjectsubmit', 1)) {
include template('modcp_editpost');
} else {
$subjectnew = dhtmlspecialchars($subjectnew);
$query = $db->query("UPDATE {$tablepre}threads SET subject='$subjectnew' WHERE tid='$tid'");
$query = $db->query("UPDATE {$tablepre}posts SET subject='$subjectnew' WHERE tid='$tid' AND first='1'");
showmessage('<a href="viewthread.php?tid='.$tid.'">'.stripslashes($subjectnew).'</a>');
}
} elseif($action == 'editmessage') {
$query = $db->query("SELECT m.adminid, p.first, p.authorid, p.author, p.dateline, p.anonymous, p.invisible, p.message FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
WHERE p.pid='$pid' AND p.invisible > -1");
$orig = $db->fetch_array($query);
if(empty($orig)) {
showmessage('post_check', NULL, 'AJAXERROR');
}
periodscheck('postbanperiods');
if(empty($forum['allowview'])) {
if(!$forum['viewperm'] && !$readaccess) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
showmessage('forum_nopermission', NULL, 'NOPERM');
}
}
if(!$forum['ismoderator'] || !$alloweditpost || (in_array($orig['adminid'], array(1, 2, 3)) && $adminid > $orig['adminid'])) {
showmessage('post_edit_nopermission', NULL, 'HALTED');
}
require_once DISCUZ_ROOT.'./include/post.func.php';
if($post_invalid = checkpost()) {
showmessage($post_invalid);
}
if(!submitcheck('editmessagesubmit', 1)) {
include template('modcp_editpost');
} else {
if($do == 'notupdate') {
$message = $orig['message'];
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
$message = discuzcode($message, 0, 0, 0, $forum['allowsmilies'], $forum['allowbbcode'], ($forum['allowimgcode'] && $showimages ? 1 : 0), $forum['allowhtml'], 0, 0, $orig['authorid']);
showmessage(stripslashes($message));
} else {
$message = dhtmlspecialchars($message);
$query = $db->query("UPDATE {$tablepre}posts SET message='$message' WHERE pid='$pid'");
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
$message = discuzcode($message, 0, 0, 0, $forum['allowsmilies'], $forum['allowbbcode'], ($forum['allowimgcode'] && $showimages ? 1 : 0), $forum['allowhtml'], 0, 0, $orig['authorid']);
showmessage(stripslashes($message));
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/modcp.php | PHP | asf20 | 3,860 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: javascript.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(0);
define('IN_DISCUZ', TRUE);
define('DISCUZ_ROOT', '../');
if(PHP_VERSION < '4.1.0') {
$_GET = &$HTTP_GET_VARS;
$_SERVER = &$HTTP_SERVER_VARS;
}
require_once DISCUZ_ROOT.'./forumdata/cache/cache_settings.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_jswizard.php';
if($_DCACHE['settings']['gzipcompress']) {
ob_start('ob_gzhandler');
}
$jsstatus = isset($_DCACHE['settings']['jsstatus']) ? $_DCACHE['settings']['jsstatus'] : 1;
if(!$jsstatus) {
exit("document.write(\"<font color=red>The webmaster did not enable this feature.</font>\");");
}
$jsrefdomains = isset($_DCACHE['settings']['jsrefdomains']) ? $_DCACHE['settings']['jsrefdomains'] : preg_replace("/([^\:]+).*/", "\\1", (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : NULL));
$REFERER = parse_url($_SERVER['HTTP_REFERER']);
if($jsrefdomains && (empty($REFERER) | !in_array($REFERER['host'], explode("\r\n", trim($jsrefdomains))))) {
exit("document.write(\"<font color=red>Referer restriction is taking effect.</font>\");");
}
if(!empty($_GET['key']) && !empty($_DCACHE['jswizard'][$_GET['key']]['url'])) {
$cachefile = DISCUZ_ROOT.'./forumdata/cache/javascript_'.$_GET['key'].'.php';
parse_str($_DCACHE['jswizard'][$_GET['key']]['url'], $_GET);
} else {
$authkey = isset($_DCACHE['settings']['authkey']) ? $_DCACHE['settings']['authkey'] : '';
$jsurl = preg_replace("/^(.+?)\&verify\=[0-9a-f]{32}$/", "\\1", $_SERVER['QUERY_STRING']);
$cachefile = DISCUZ_ROOT.'./forumdata/cache/javascript_'.md5($jsurl).'.php';
$verify = isset($_GET['verify']) ? $_GET['verify'] : NULL;
if(!$verify || !$jsurl || $verify != md5($authkey.$jsurl)) {
exit("document.write(\"<font color=red>Authentication failed.</font>\");");
}
}
$expiration = 0;
$timestamp = time();
if((@!include($cachefile)) || $expiration < $timestamp) {
require_once DISCUZ_ROOT.'./config.inc.php';
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';
require_once DISCUZ_ROOT.'./include/global.func.php';
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$function = isset($_GET['function']) ? $_GET['function'] : NULL;
$dateformat = !empty($_DCACHE['settings']['jsdateformat']) ? $_DCACHE['settings']['jsdateformat'] : (!empty($_DCACHE['settings']['dateformat']) ? $_DCACHE['settings']['dateformat'] : 'm/d');
$timeformat = isset($_DCACHE['settings']['timeformat']) ? $_DCACHE['settings']['timeformat'] : 'H:i';
$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$boardurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api|archiver|wap)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/';
$jstemplate = !empty($_GET['jstemplate']) ? (get_magic_quotes_gpc() ? stripslashes($_GET['jstemplate']) : $_GET['jstemplate']) : '';
$jstemplate = preg_replace("/\r\n|\n|\r/", '\n', $jstemplate);
$nocache = !empty($_GET['nocache']) ? 1 : 0;
$jscachelife = (isset($_GET['cachelife']) && $_GET['cachelife'] != '') ? $_GET['cachelife'] : (isset($_DCACHE['settings']['jscachelife']) ? $_DCACHE['settings']['jscachelife'] : 1800);
$jscharset = $_GET['jscharset'];
if($function != 'custom') {
$jstemplatebody = '';
if(preg_match("/\[node\](.+?)\[\/node\]/is", $jstemplate, $node)) {
$jstemplatebody = $jstemplate;
$jstemplate = $node[1];
}
$datalist = $writedata = procdata('document.write("'.jsmodule($function).'");');
if(!$nocache) {
$writedata = "\$datalist = '".addcslashes($writedata, '\\\'')."';";
UpdateCache($cachefile, $writedata);
}
} else {
$customcachefile = $cachefile;
$customnocache = $nocache;
$jscachelife = (isset($_GET['cachelife']) && $_GET['cachelife'] != '') ? $_GET['cachelife'] : (isset($_DCACHE['settings']['jscachelife']) ? $_DCACHE['settings']['jscachelife'] : 1800);
$writedata = preg_match_all("/\[module\](.+?)\[\/module\]/is", $jstemplate, $modulelist);
$modulelist = array_unique($modulelist[1]);
$writedata = $jstemplate;
$nocache = TRUE;
foreach($modulelist as $key) {
if(!empty($_DCACHE['jswizard'][$key]['url'])) {
parse_str($_DCACHE['jswizard'][$key]['url'], $_GET);
$function = isset($_GET['function']) ? $_GET['function'] : NULL;
$find = "/\[module\]".preg_quote($key)."\[\/module\]/is";
$jstemplate = !empty($_GET['jstemplate']) ? (get_magic_quotes_gpc() ? stripslashes($_GET['jstemplate']) : $_GET['jstemplate']) : '';
$jstemplate = preg_replace("/\r\n|\n|\r/", '\n', $jstemplate);
$jstemplatebody = '';
if(preg_match("/\[node\](.+?)\[\/node\]/is", $jstemplate, $node)) {
$jstemplatebody = $jstemplate;
$jstemplate = $node[1];
}
$writedata = preg_replace($find, jsmodule($function), $writedata);
}
}
$nocache = $customnocache;
$datalist = $writedata = procdata('document.write("'.$writedata.'");');
if(!$nocache) {
$writedata = "\$datalist = '".addcslashes($writedata, '\\\'')."';";
UpdateCache($customcachefile, $writedata);
}
}
}
echo $datalist;
function jsmodule($function) {
extract($GLOBALS, EXTR_SKIP);
$fids = isset($_GET['fids']) ? $_GET['fids'] : NULL;
$startrow = isset($_GET['startrow']) ? intval($_GET['startrow']) : 0;
$items = isset($_GET['items']) ? intval($_GET['items']) : 10;
$digest = isset($_GET['digest']) ? intval($_GET['digest']) : 0;
$stick = isset($_GET['stick']) ? intval($_GET['stick']) : 0;
$newwindow = isset($_GET['newwindow']) ? $_GET['newwindow'] : 1;
$LinkTarget = $newwindow == 1 ? " target='_blank'" : ($newwindow == 2 ? " target='main'" : NULL);
if($function == 'threads') {
$orderby = isset($_GET['orderby']) ? (in_array($_GET['orderby'],array('lastpost','dateline','replies','views')) ? $_GET['orderby'] : 'lastpost') : 'lastpost';
$highlight = isset($_GET['highlight']) ? $_GET['highlight'] : 0;
$picpre = isset($_GET['picpre']) ? urldecode($_GET['picpre']) : NULL;
$maxlength = !empty($_GET['maxlength']) ? intval($_GET['maxlength']) : 50;
$fnamelength = isset($_GET['fnamelength']) ? intval($_GET['fnamelength']) : 0;
$blog = !empty($_GET['blog']) ? 1 : 0;
$tids = isset($_GET['tids']) ? $_GET['tids'] : NULL;
$keyword = !empty($_GET['keyword']) ? $_GET['keyword'] : NULL;
$typeids = isset($_GET['typeids']) ? $_GET['typeids'] : NULL;
$special = isset($_GET['special']) ? intval($_GET['special']) : 0;
$rewardstatus = isset($_GET['rewardstatus']) ? intval($_GET['rewardstatus']) : 0;
$threadtype = isset($_GET['threadtype']) ? intval($_GET['threadtype']) : 0;
$tag = !empty($_GET['tag']) ? trim($_GET['tag']) : NULL;
require DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
$datalist = array();
$threadtypeids = array();
if($keyword) {
if(preg_match("(AND|\+|&|\s)", $keyword) && !preg_match("(OR|\|)", $keyword)) {
$andor = ' AND ';
$keywordsrch = '1';
$keyword = preg_replace("/( AND |&| )/is", "+", $keyword);
} else {
$andor = ' OR ';
$keywordsrch = '0';
$keyword = preg_replace("/( OR |\|)/is", "+", $keyword);
}
$keyword = str_replace('*', '%', addcslashes($keyword, '%_'));
foreach(explode('+', $keyword) as $text) {
$text = trim($text);
if($text) {
$keywordsrch .= $andor;
$keywordsrch .= "t.subject LIKE '%$text%'";
}
}
$keyword = " AND ($keywordsrch)";
} else {
$keyword = '';
}
$sql = ($fids ? ' AND t.fid IN (\''.str_replace('_', '\',\'', $fids).'\')' : '')
.$keyword
.($blog ? ' AND t.blog = 1' : '')
.($tids ? ' AND t.tid IN (\''.str_replace('_', '\',\'', $tids).'\')' : '')
.($typeids ? ' AND t.typeid IN (\''.str_replace('_', '\',\'', $typeids).'\')' : '')
.(($special >= 0 && $special < 127) ? threadrange($special, 'special', 7) : '')
.((($special & 8) && $rewardstatus) ? ($rewardstatus == 1 ? ' AND t.price < 0' : ' AND t.price > 0') : '')
.(($digest > 0 && $digest < 15) ? threadrange($digest, 'digest') : '')
.(($stick > 0 && $stick < 15) ? threadrange($stick, 'displayorder') : '');
$sqlfrom = strexists('{message}', $jstemplate) ?
"FROM `{$tablepre}threads` t" :
",p.message FROM `{$tablepre}threads` t LEFT JOIN `{$tablepre}posts` p ON p.tid=t.tid AND p.first='1'";
if($tag) {
$tags = explode(' ', $tag);
foreach($tags as $tagk => $tagv) {
if(!preg_match('/^([\x7f-\xff_-]|\w){3,20}$/', $tagv)) {
unset($tags[$tagk]);
}
}
if($tags = implode("','", $tags)) {
$sqlfrom .= " INNER JOIN `{$tablepre}threadtags` tag ON tag.tid=t.tid AND tag.tagname IN ('$tags')";
}
}
$query = $db->query("SELECT t.tid,t.fid,t.readperm,t.author,t.authorid,t.subject,t.dateline,t.lastpost,t.lastposter,t.views,t.replies,t.highlight,t.digest,t.typeid
$sqlfrom WHERE t.readperm='0'
$sql
AND t.displayorder>='0'
AND t.fid>'0'
ORDER BY t.$orderby DESC
LIMIT $startrow,$items;"
);
while($data = $db->fetch_array($query)) {
$datalist[$data['tid']]['fid'] = $data['fid'];
$datalist[$data['tid']]['fname'] = isset($_DCACHE['forums'][$data['fid']]['name']) ? str_replace('\'', ' ',addslashes($_DCACHE['forums'][$data['fid']]['name'])) : NULL;
$datalist[$data['tid']]['fnamelength'] = strlen($datalist[$data['tid']]['fname']);
$datalist[$data['tid']]['subject'] = isset($data['subject']) ? str_replace('\'', ' ',addslashes($data['subject'])) : NULL;
$datalist[$data['tid']]['dateline'] = gmdate("$dateformat $timeformat",$data['dateline'] + $_DCACHE['settings']['timeoffset'] * 3600);
$datalist[$data['tid']]['lastpost'] = gmdate("$dateformat $timeformat",$data['lastpost'] + $_DCACHE['settings']['timeoffset'] * 3600);
$datalist[$data['tid']]['lastposter'] = $data['lastposter'];
$datalist[$data['tid']]['views'] = $data['views'];
$datalist[$data['tid']]['replies'] = $data['replies'];
$datalist[$data['tid']]['highlight'] = $data['highlight'];
$datalist[$data['tid']]['message'] = str_replace(array('\'',"\n","\r"), array(' ','',''), addslashes(cutstr(dhtmlspecialchars(preg_replace("/(\[.+\])/s", '', strip_tags(nl2br($data['message'])))), 255)));
if($data['author']) {
$datalist[$data['tid']]['author'] = "<a href='".$boardurl."space.php?uid=$data[authorid]'$LinkTarget>$data[author]</a>";
} else {
$datalist[$data['tid']]['author'] = 'Anonymous';
}
if($data['lastposter']) {
$datalist[$data['tid']]['lastposter'] = "<a href='".$boardurl."space.php?username=".rawurlencode($data['lastposter'])."'$LinkTarget>$data[lastposter]</a>";
} else {
$datalist[$data['tid']]['lastposter'] = 'Anonymous';
}
$datalist[$data['tid']]['typeid'] = $data['typeid'];
$threadtypeids[] = $data['typeid'];
}
if($threadtype && $threadtypeids) {
$typelist = array();
$query = $db->query("SELECT typeid, name FROM {$tablepre}threadtypes WHERE typeid IN ('".implode('\',\'', $threadtypeids)."')");
while($typearray = $db->fetch_array($query)) {
$typelist[$typearray['typeid']] = $typearray['name'];
}
foreach($datalist AS $tid=>$value) {
if($value['typeid'] && isset($typelist[$value['typeid']])) {
$datalist[$tid]['subject'] = '['.$typelist[$value['typeid']].']'.$value['subject'];
}
}
}
$writedata = '';
if(is_array($datalist)) {
$colorarray = array('', 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'gray');
$prefix = $picpre ? "<img src='$picpre' border='0' align='absmiddle'>" : NULL;
$jstemplate = !$jstemplate ? '{prefix} {subject}<br />' : $jstemplate;
foreach($datalist AS $tid=>$value) {
$SubjectStyles = '';
if($highlight && $value['highlight']) {
$string = sprintf('%02d', $value['highlight']);
$stylestr = sprintf('%03b', $string[0]);
$SubjectStyles .= " style='";
$SubjectStyles .= $stylestr[0] ? 'font-weight: bold;' : NULL;
$SubjectStyles .= $stylestr[1] ? 'font-style: italic;' : NULL;
$SubjectStyles .= $stylestr[2] ? 'text-decoration: underline;' : NULL;
$SubjectStyles .= $string[1] ? 'color: '.$colorarray[$string[1]] : NULL;
$SubjectStyles .= "'";
}
$replace['{link}'] = $boardurl.($blog ? 'blog' : 'viewthread').".php?tid=$tid";
$replace['{subject_nolink}'] = cutstr($value['subject'],($fnamelength ? ($maxlength - $value['fnamelength']) : $maxlength));
$replace['{subject_full}'] = $value['subject'];
$replace['{prefix}'] = $prefix;
$replace['{forum}'] = "<a href='".$boardurl."forumdisplay.php?fid=$value[fid]'$LinkTarget>$value[fname]</a> ";
$replace['{dateline}'] = $value['dateline'];
$replace['{subject}'] = "<a href='".$boardurl.($blog ? 'blog' : 'viewthread').".php?tid=$tid' title='$value[subject]'$SubjectStyles$LinkTarget>".$replace['{subject_nolink}']."</a>";
$replace['{message}'] = $value['message'];
$replace['{author}'] = $value['author'];
$replace['{lastposter}'] = $value['lastposter'];
$replace['{lastpost}'] = $value['lastpost'];
$replace['{views}'] = $value['views'];
$replace['{replies}'] = $value['replies'];
$writedata .= str_replace(array_keys($replace), $replace, $jstemplate);
}
}
} elseif($function == 'forums') {
$fups = isset($_GET['fups']) ? $_GET['fups'] : NULL;
$orderby = isset($_GET['orderby']) ? (in_array($_GET['orderby'],array('displayorder','threads','posts')) ? $_GET['orderby'] : 'displayorder') : 'displayorder';
$datalist = array();
$query = $db->query("SELECT `fid`,`fup`,`name`,`status`,`threads`,`posts`,`todayposts`,`displayorder`,`type`
FROM `{$tablepre}forums`
WHERE `type`!='group'
".($fups ? "AND `fup` IN ('".str_replace('_', '\',\'', $fups)."') " : "")."
AND `status`='1'
ORDER BY ".($orderby == 'displayorder' ? " `displayorder` ASC " : " `$orderby` DESC")."
LIMIT $startrow,".($items > 0 ? $items : 65535).";"
);
while($data = $db->fetch_array($query)) {
$datalist[$data['fid']]['name'] = str_replace('\'', ' ',addslashes($data['name']));
$datalist[$data['fid']]['threads'] = $data['threads'];
$datalist[$data['fid']]['posts'] = $data['posts'];
$datalist[$data['fid']]['todayposts'] = $data['todayposts'];
}
$writedata = '';
if(is_array($datalist)) {
$jstemplate = !$jstemplate ? '{forumname}<br />' : $jstemplate;
foreach($datalist AS $fid=>$value) {
$replace['{link}'] = $boardurl."forumdisplay.php?fid=$fid";
$replace['{forumname_nolink}'] = $value['name'];
$replace['{forumname}'] = "<a href='".$boardurl."forumdisplay.php?fid=$fid'$LinkTarget>$value[name]</a>";
$replace['{threads}'] = $value['threads'];
$replace['{posts}'] = $value['posts'];
$replace['{todayposts}'] = $value['todayposts'];
$writedata .= str_replace(array_keys($replace), $replace, $jstemplate);
}
}
} elseif($function == 'memberrank') {
$orderby = isset($_GET['orderby']) ? (in_array($_GET['orderby'],array('credits','posts','digestposts','regdate','todayposts')) ? $_GET['orderby'] : 'credits') : 'credits';
$datalist = array();
switch($orderby) {
case 'credits':
$sql = "SELECT m.`username`,m.`uid`,m.`credits`,mf.`avatar`,mf.`avatarwidth` FROM `{$tablepre}members` m LEFT JOIN `{$tablepre}memberfields` mf USING(`uid`) ORDER BY m.`credits` DESC";
break;
case 'posts':
$sql = "SELECT m.`username`,m.`uid`,m.`posts`,mf.`avatar`,mf.`avatarwidth` FROM `{$tablepre}members` m LEFT JOIN `{$tablepre}memberfields` mf USING(`uid`) ORDER BY m.`posts` DESC";
break;
case 'digestposts':
$sql = "SELECT m.`username`,m.`uid`,m.`digestposts`,mf.`avatar`,mf.`avatarwidth` FROM `{$tablepre}members` m LEFT JOIN `{$tablepre}memberfields` mf USING(`uid`) ORDER BY m.`digestposts` DESC";
break;
case 'regdate':
$sql = "SELECT m.`username`,m.`uid`,m.`regdate`,mf.`avatar`,mf.`avatarwidth` FROM `{$tablepre}members` m LEFT JOIN `{$tablepre}memberfields` mf USING(`uid`) ORDER BY m.`regdate` DESC";
break;
case 'todayposts':
$sql = "SELECT DISTINCT(p.author) AS username,p.authorid AS uid,COUNT(p.pid) AS postnum,mf.`avatar`,mf.`avatarwidth` FROM `{$tablepre}posts` p LEFT JOIN `{$tablepre}memberfields` mf ON mf.`uid` = p.`authorid` WHERE p.`dateline`>=".($timestamp - 86400)." AND p.`authorid`!='0' GROUP BY p.`author` ORDER BY `postnum` DESC";
break;
}
$query = $db->query($sql." LIMIT $startrow,$items;");
while($data = $db->fetch_array($query,MYSQL_NUM)) {
$data[2] = $orderby == 'regdate' ? gmdate($dateformat,$data[2] + $_DCACHE['settings']['timeoffset'] * 3600) : $data[2];
$datalist[] = $data;
}
$writedata = '';
if(is_array($datalist)) {
$jstemplate = !$jstemplate ? '{regdate} {member} {value}<br />' : $jstemplate;
foreach($datalist AS $value) {
$replace['{regdate}'] = $replace['{value}'] = '';
if($orderby == 'regdate') {
$replace['{regdate}'] = $value[2];
} else {
$replace['{value}'] = $value[2];
}
$replace['{member}'] = "<a href='".$boardurl."space.php?uid=$value[1]'$LinkTarget>$value[0]</a>";
$replace['{avatar}'] = $value[3] ? "<a href='".$boardurl."space.php?uid=$value[1]'$LinkTarget><img src='".(preg_match('/^http:\/\//i', $value[3]) ? $value[3] :
$boardurl.'/'.$value[3])."' width='".($value[4] < $_DCACHE['settings']['maxavatarpixel'] ? $value[4] : $_DCACHE['settings']['maxavatarpixel'])."' border=0 alt='' /></a>" : '';
$writedata .= str_replace(array_keys($replace), $replace, $jstemplate);
}
}
} elseif($function == 'stats') {
$info = isset($_GET['info']) ? $_GET['info'] : NULL;
if(is_array($info)) {
$language = $info;
$info_index = '';
$statsinfo = array();
$statsinfo['forums'] = $statsinfo['threads'] = $statsinfo['posts'] = 0;
$query = $db->query("SELECT `status`,`threads`,`posts`
FROM `{$tablepre}forums` WHERE
`status`='1';
");
while($forumlist = $db->fetch_array($query)) {
$statsinfo['forums']++;
$statsinfo['threads'] += $forumlist['threads'];
$statsinfo['posts'] += $forumlist['posts'];
}
unset($info['forums'],$info['threads'],$info['posts']);
foreach($info AS $index=>$value) {
if($index == 'members') {
$sql = "SELECT COUNT(*) FROM `{$tablepre}members`;";
} elseif($index == 'online') {
$sql = "SELECT COUNT(*) FROM `{$tablepre}sessions`;";
} elseif($index == 'onlinemembers') {
$sql = "SELECT COUNT(*) FROM `{$tablepre}sessions` WHERE `uid`>'0';";
}
if($index == 'members' || $index == 'online' || $index == 'onlinemembers') {
$query = $db->query($sql);
$statsinfo[$index] = $db->result($query, 0);
}
}
unset($index, $value);
$writedata = '';
$jstemplate = !$jstemplate ? '{name} {value}<br />' : $jstemplate;
foreach($language AS $index=>$value) {
$replace['{name}'] = $value;
$replace['{value}'] = $statsinfo[$index];
$writedata .= str_replace(array_keys($replace), $replace, $jstemplate);
}
}
} elseif($function == 'images') {
$maxwidth = isset($_GET['maxwidth']) ? $_GET['maxwidth'] : 0;
$maxheight = isset($_GET['maxheight']) ? $_GET['maxheight'] : 0;
$blog = !empty($_GET['blog']) ? 1 : 0;
require DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
$datalist = array();
$sql = ($fids ? ' AND `fid` IN (\''.str_replace('_', '\',\'', $fids).'\')' : '')
.(($digest > 0 && $digest < 15) ? threadrange($digest, 'digest') : '');
$blogsql = $blog ? 'AND `t`.`blog` = 1' : '';
$query = $db->query("SELECT attach.*,t.tid,t.fid,t.digest,t.author,t.dateline,t.subject,t.displayorder
FROM `{$tablepre}attachments` attach
LEFT JOIN `{$tablepre}threads` t
ON `t`.`tid`=`attach`.`tid` $blogsql
WHERE `attach`.`readperm`='0'
AND `displayorder`>='0'
AND `isimage` = '1'
$sql
GROUP BY `attach`.`tid`
ORDER BY `attach`.`dateline` DESC,`attach`.`tid` DESC
LIMIT $startrow,$items;"
);
$attachurl = $_DCACHE['settings']['attachurl'];
$attachurl = preg_match("/^((https?|ftps?):\/\/|www\.)/i", $attachurl) ? $attachurl : $boardurl.$attachurl;
while($data = $db->fetch_array($query)) {
$datalist[$data['tid']]['threadlink'] = $boardurl.($blog ? 'blog' : 'viewthread').".php?tid=$data[tid]";
$datalist[$data['tid']]['imgfile'] = ($data['remote'] ? $_DCACHE['settings']['ftp']['attachurl'] : $attachurl)."/$data[attachment]".($_DCACHE['settings']['thumbstatus'] && $data['thumb'] ? '.thumb.jpg' : '');
$datalist[$data['tid']]['subject'] = str_replace('\'', ' ',$data['subject']);
$datalist[$data['tid']]['author'] = addslashes($data['author']);
$datalist[$data['tid']]['dateline'] = gmdate("$dateformat $timeformat",$data['dateline'] + $_DCACHE['settings']['timeoffset'] * 3600);
$datalist[$data['tid']]['fname'] = isset($_DCACHE['forums'][$data['fid']]['name']) ? str_replace('\'', ' ',addslashes($_DCACHE['forums'][$data['fid']]['name'])) : NULL;
$datalist[$data['tid']]['description'] = $data['description'] ? str_replace('\'', ' ',addslashes($data['description'])) : NULL;
}
$writedata = '';
if(is_array($datalist)) {
$imgsize = ($maxwidth ? " width='$maxwidth'" : NULL).($maxheight ? " height='$maxheight'" : NULL);
$jstemplate = !$jstemplate ? '{image}' : $jstemplate;
foreach($datalist AS $value) {
$replace['{link}'] = $value['threadlink'];
$replace['{imgfile}'] = $value['imgfile'];
$replace['{subject}'] = $value['subject'];
$replace['{image}'] = "<a href='$value[threadlink]'$LinkTarget><img$imgsize src='$value[imgfile]' border='0' alt='"
.($value['description'] ? "$value[description]
" : NULL)
."$value[subject]
$value[author]($value[dateline])
$value[fname]' /></a>";
$writedata .= str_replace(array_keys($replace), $replace, $jstemplate);
}
}
} else {
exit("document.write(\"<font color=red>Undefined action.</font>\");");
}
return parsenode($writedata);
}
function parsenode($data) {
global $jstemplatebody;
if($jstemplatebody) {
$data = preg_replace("/\[node\](.+?)\[\/node\]/is", $data, $jstemplatebody, 1);
$data = preg_replace("/\[node\](.+?)\[\/node\]/is", '', $data);
}
return $data;
}
function procdata($data) {
global $boardurl, $_DCACHE, $charset, $jscharset;
if($_DCACHE['settings']['rewritestatus']) {
$searcharray = $replacearray = array();
if($_DCACHE['settings']['rewritestatus'] & 1) {
$searcharray[] = "/\<a href\=\'".preg_quote($boardurl, '/')."forumdisplay\.php\?fid\=(\d+)\'/";
$replacearray[] = "<a href='{$boardurl}forum-\\1-1.html'";
}
if($_DCACHE['settings']['rewritestatus'] & 2) {
$searcharray[] = "/\<a href\=\'".preg_quote($boardurl, '/')."viewthread\.php\?tid\=(\d+)\'/";
$replacearray[] = "<a href='{$boardurl}thread-\\1-1-1.html'";
}
if($_DCACHE['settings']['rewritestatus'] & 4) {
$searcharray[] = "/\<a href\=\'".preg_quote($boardurl, '/')."space\.php\?uid\=(\d+)\'/";
$searcharray[] = "/\<a href\=\'".preg_quote($boardurl, '/')."space\.php\?username\=([^&]+?)\'/";
$replacearray[] = "<a href='{$boardurl}space-uid-\\1.html'";
$replacearray[] = "<a href='{$boardurl}space-username-\\1.html'";
}
$data = preg_replace($searcharray, $replacearray, $data);
}
if($jscharset) {
include DISCUZ_ROOT.'include/chinese.class.php';
if(strtoupper($charset) != 'UTF-8') {
$c = new Chinese($charset, 'utf8');
} else {
$c = new Chinese('utf8', $jscharset == 1 ? 'gbk' : 'big5');
}
$data = $c->Convert($data);
}
return $data;
}
function UpdateCache($cachfile,$data='') {
global $timestamp, $jscachelife, $_DCACHE;
if(!$fp = @fopen($cachfile, 'wb')) {
exit("document.write(\"Unable to write to cache file!<br />Please chmod ./forumdata/cache to 777 and try again.\");");
}
$fp = @fopen($cachfile, 'wb');
$cachedata = "if(!defined('IN_DISCUZ')) exit('Access Denied');\n\$expiration = '".($timestamp + $jscachelife)."';\n".$data."\n";
@fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!".
"\n//Created: ".date("M j, Y, G:i").
"\n//Identify: ".md5(basename($cachfile).$cachedata.$_DCACHE['settings']['authkey'])."\n\n$cachedata?>");
@fclose($fp);
}
function threadrange($range, $field, $params = 4) {
$range = intval($range);
$range = sprintf("%0".$params."d", decbin($range));
$range = "$range";
$range_filed = '';
for($i = 0; $i < $params - 1; $i ++) {
$range_filed .= $range[$i] == 1 ? ($i + 1) : '';
}
$range_filed .= $range[$params - 1] == 1 ? 0 : '';
return ' AND `'.$field.'` IN (\''.str_replace('_', '\',\'', substr(chunk_split($range_filed,1,"_"),0,-1)).'\')';
}
?> | zyyhong | trunk/jiaju001/bbs/api/javascript.php | PHP | asf20 | 25,201 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: passport.php 9805 2007-08-15 05:59:02Z cnteacher $
*/
error_reporting(0);
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
$table_member_columns = array('username', 'password', 'secques', 'email', 'adminid', 'groupid', 'gender', 'bday', 'regip', 'regdate', 'timeoffset', 'newsletter');
$table_memberfields_columns = array('nickname', 'site', 'location', 'qq', 'icq', 'msn', 'yahoo');
define('IN_DISCUZ', true);
define('DISCUZ_ROOT', './');
$timestamp = time();
if(PHP_VERSION < '4.1.0') {
$_GET = &$HTTP_GET_VARS;
$_SERVER = &$HTTP_SERVER_VARS;
}
chdir('../');
require_once './config.inc.php';
require_once './include/db_'.$database.'.class.php';
require_once './forumdata/cache/cache_settings.php';
if($_DCACHE['settings']['passport_status'] != 'passport') {
exit('Passport disabled');
} elseif($_GET['verify'] != md5($_GET['action'].$_GET['auth'].$_GET['forward'].$_DCACHE['settings']['passport_key'])) {
exit('Illegal request');
}
if($_GET['action'] == 'login') {
$memberfields = $remoteinfo = array();
parse_str(passport_decrypt($_GET['auth'], $_DCACHE['settings']['passport_key']), $member);
foreach($member as $key => $val) {
if(in_array($key, array('username', 'password', 'email', 'credits', 'gender', 'bday', 'regip', 'regdate', 'nickname', 'site', 'qq', 'msn', 'yahoo'))) {
$memberfields[$key] = addslashes($val);
} elseif(in_array($key, array('cookietime', 'time'))) {
$remoteinfo[$key] = $val;
} elseif($key == 'isadmin') {
if($val) {
$memberfields['groupid'] = $memberfields['adminid'] = 1;
}
}
}
if(strlen($memberfields['username'] = preg_replace("/(c:\\con\\con$|[%,\*\"\s\t\<\>\&])/i", "", $memberfields['username'])) > 15) {
$memberfields['username'] = substr($memberfields['username'], 0, 15);
}
if(empty($remoteinfo['time']) || empty($memberfields['username']) || empty($memberfields['password']) || empty($memberfields['email'])) {
exit('Lack of required parameters');
} elseif($timestamp - $remoteinfo['time'] > $_DCACHE['settings']['passport_expire']) {
exit('Request expired');
}
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
if($_DCACHE['settings']['passport_extcredits']) {
$memberfields['extcredits'.$_DCACHE['settings']['passport_extcredits']] = $memberfields['credits'];
$table_member_columns[] = 'extcredits'.$_DCACHE['settings']['passport_extcredits'];
}
$memberfields['regip'] = empty($memberfields['regip']) ? onlineip() : $memberfields['regip'];
$memberfields['regdate'] = empty($memberfields['regdate']) ? $timestamp : $memberfields['regdate'];
$query = $db->query("SELECT uid, secques FROM {$tablepre}members WHERE username='$memberfields[username]'");
if($member = $db->fetch_array($query)) {
$sql = $comma = '';
foreach($table_member_columns as $field) {
if(isset($memberfields[$field]) && !in_array($field, array('regip', 'regdate'))) {
$sql .= "$comma$field='{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("UPDATE {$tablepre}members SET $sql WHERE uid='$member[uid]'");
$sql = $comma = '';
foreach($table_memberfields_columns as $field) {
if(isset($memberfields[$field])) {
$sql .= "$comma$field='{$memberfields[$field]}'";
$comma = ', ';
}
}
if($sql) {
$db->query("UPDATE {$tablepre}memberfields SET $sql WHERE uid='$member[uid]'");
}
} else {
if(empty($memberfields['groupid'])) {
$query = $db->query("SELECT groupid FROM {$tablepre}usergroups WHERE type='member' AND creditshigher='0'");
$memberfields['groupid'] = $db->result($query, 0);
$memberfields['adminid'] = 0;
}
$memberfields['timeoffset'] = !$memberfields['timeoffset'] ? 9999 : $memberfields['timeoffset'];
$memberfields['newsletter'] = !$memberfields['newsletter'] ? 1 : $memberfields['newsletter'];
$sql1 = $sql2 = $comma = '';
foreach($table_member_columns as $field) {
if(isset($memberfields[$field])) {
$sql1 .= "$comma$field";
$sql2 .= "$comma'{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("INSERT INTO {$tablepre}members ($sql1) VALUES ($sql2)");
$table_memberfields_columns[] = 'uid';
$memberfields['uid'] = $member['uid'] = $db->insert_id();
$member['secques'] = '';
$sql1 = $sql2 = $comma = '';
foreach($table_memberfields_columns as $field) {
if(isset($memberfields[$field])) {
$sql1 .= "$comma$field";
$sql2 .= "$comma'{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("REPLACE INTO {$tablepre}memberfields ($sql1) VALUES ($sql2)");
$_DCACHE['settings']['lastmember'] = $memberfields['username'];
$_DCACHE['settings']['totalmembers']++;
updatemembercache();
}
$remoteinfo['cookietime'] = 86400;
dsetcookie('sid', '', 86400);
dsetcookie('auth', authcode("$memberfields[password]\t".(isset($memberfields['secques']) ? $memberfields['secques'] : $member['secques'])."\t$member[uid]", 'ENCODE'), ($remoteinfo['cookietime'] ? $remoteinfo['cookietime'] : 0));
header('Location: '.(empty($_GET['forward']) ? $_DCACHE['settings']['passport_url'] : $_GET['forward']));
exit;
} elseif($_GET['action'] == 'logout') {
dsetcookie('auth', '', -86400 * 365);
dsetcookie('sid', '', -86400 * 365);
header('Location: '.(empty($_GET['forward']) ? $_DCACHE['settings']['passport_url'] : $_GET['forward']));
exit;
} else {
exit('Invalid action');
}
function arrayeval($array, $level = 0) {
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "\t";
}
$evaluate = "Array\n$space(\n";
$comma = $space;
foreach($array as $key => $val) {
$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
$val = !is_array($val) && (!preg_match("/^\d+$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
} else {
$evaluate .= "$comma$key => $val";
}
$comma = ",\n$space";
}
$evaluate .= "\n$space)";
return $evaluate;
}
function authcode($string, $operation, $key = '') {
global $_DCACHE;
$key = md5($key ? $key : md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']));
$key_length = strlen($key);
$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
$string_length = strlen($string);
$rndkey = $box = array();
$result = '';
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($key[$i % $key_length]);
$box[$i] = $i;
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
return substr($result, 8);
} else {
return '';
}
} else {
return str_replace('=', '', base64_encode($result));
}
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
setcookie(($prefix ? $cookiepre : '').$var, $value,
$life ? $timestamp + $life : 0, $cookiepath,
$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function onlineip() {
global $_SERVER;
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
$onlineip = preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
return $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
function passport_encrypt($txt, $key) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}
function passport_decrypt($txt, $key) {
$txt = passport_key(base64_decode($txt), $key);
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}
function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = '';
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
function updatemembercache() {
$dir = './forumdata/cache/';
if(!is_dir($dir)) {
@mkdir($dir, 0777);
}
if(@$fp = fopen($dir.'cache_settings.php', 'w')) {
fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!\n".
"//Created on ".date("M j, Y, G:i")."\n\n\$_DCACHE['settings'] = ".arrayeval($GLOBALS['_DCACHE']['settings'])."?>");
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
}
?>
| zyyhong | trunk/jiaju001/bbs/api/passport.php | PHP | asf20 | 9,815 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: relateshopex.php 9805 2007-08-15 05:59:02Z cnteacher $
*/
error_reporting(0);
chdir('../');
require_once './include/common.inc.php';
if($passport_status == 'shopex' && ($action == 'login' || $action == 'logout') && $verify == md5($action.$forward.$passport_key) && $passport_shopex) {
$forward = preg_match("/^http:\/\//i", $forward) ? $forward : $boardurl.$forward;
if($action == 'login' && $discuz_uid) {
$creditsadd = $passport_extcredits ? 'm.extcredits'.$passport_extcredits.' as credits,' : '';
$query = $db->query("SELECT m.adminid, m.username, m.password, m.email, $creditsadd m.gender, m.bday, m.regip, m.regdate, mf.site, mf.qq, mf.msn, mf.yahoo
FROM {$tablepre}members m JOIN {$tablepre}memberfields mf USING(uid) WHERE m.uid='$discuz_uid'");
$member = $db->fetch_array($query);
if($member['adminid'] == 1) {
dheader('Location:'.$forward);
}
$auth = '';
foreach($member as $key => $value) {
$auth .= $key.'='.$value.'&';
}
$auth = passport_encrypt($auth, $passport_key);
} else {
$auth = '';
}
$verify = md5($action.$auth.$forward.$passport_key);
dheader('location:'.$passport_url.'index.php?gOo=discuz_reply.do&action='.$action.($action == 'login' ? '&auth='.rawurlencode($auth) : '').'&forward='.rawurlencode($forward).'&verify='.$verify);
} else {
dheader('location:'.$boardurl.'index.php');
}
function passport_encrypt($txt, $key) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}
function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = '';
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
?> | zyyhong | trunk/jiaju001/bbs/api/relateshopex.php | PHP | asf20 | 2,126 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: shopex.php 9805 2007-08-15 05:59:02Z cnteacher $
*/
error_reporting(0);
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
$table_member_columns = array('username', 'password', 'secques', 'email', 'adminid', 'groupid', 'gender', 'bday', 'regip', 'regdate', 'timeoffset', 'newsletter');
$table_memberfields_columns = array('site', 'location', 'qq', 'icq', 'msn', 'yahoo');
define('IN_DISCUZ', true);
define('DISCUZ_ROOT', './');
$timestamp = time();
if(PHP_VERSION < '4.1.0') {
$_GET = &$HTTP_GET_VARS;
$_SERVER = &$HTTP_SERVER_VARS;
}
chdir('../');
require_once './config.inc.php';
require_once './include/db_'.$database.'.class.php';
require_once './forumdata/cache/cache_settings.php';
if($_DCACHE['settings']['passport_status'] != 'shopex') {
exit('Passport disabled');
} elseif($_GET['verify'] != md5($_GET['action'].$_GET['auth'].$_GET['forward'].$_DCACHE['settings']['passport_key'])) {
exit('Illegal request');
}
if($_GET['action'] == 'login') {
$memberfields = $remoteinfo = array();
parse_str(passport_decrypt($_GET['auth'], $_DCACHE['settings']['passport_key']), $member);
foreach($member as $key => $val) {
if(in_array($key, array('username', 'password', 'email', 'credits', 'gender', 'bday', 'regip', 'regdate', 'site', 'qq', 'msn', 'yahoo'))) {
$memberfields[$key] = addslashes($val);
} elseif(in_array($key, array('cookietime', 'time'))) {
$remoteinfo[$key] = $val;
} elseif($key == 'isadmin') {
if($val) {
$memberfields['groupid'] = $memberfields['adminid'] = 1;
}
}
}
if(strlen($memberfields['username'] = preg_replace("/(c:\\con\\con$|[%,\*\"\s\t\<\>\&])/i", "", $memberfields['username'])) > 15) {
$memberfields['username'] = substr($memberfields['username'], 0, 15);
}
if(empty($remoteinfo['time']) || empty($memberfields['username']) || empty($memberfields['password']) || empty($memberfields['email'])) {
exit('Lack of required parameters');
} elseif($timestamp - $remoteinfo['time'] > $_DCACHE['settings']['passport_expire']) {
exit('Request expired');
}
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
if($_DCACHE['settings']['passport_extcredits']) {
$memberfields['extcredits'.$_DCACHE['settings']['passport_extcredits']] = $memberfields['credits'];
$table_member_columns[] = 'extcredits'.$_DCACHE['settings']['passport_extcredits'];
}
$memberfields['regip'] = empty($memberfields['regip']) ? onlineip() : $memberfields['regip'];
$memberfields['regdate'] = empty($memberfields['regdate']) ? $timestamp : $memberfields['regdate'];
$query = $db->query("SELECT uid, secques FROM {$tablepre}members WHERE username='$memberfields[username]'");
if($member = $db->fetch_array($query)) {
$sql = $comma = '';
foreach($table_member_columns as $field) {
if(isset($memberfields[$field])) {
$sql .= "$comma$field='{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("UPDATE {$tablepre}members SET $sql WHERE uid='$member[uid]'");
$sql = $comma = '';
foreach($table_memberfields_columns as $field) {
if(isset($memberfields[$field])) {
$sql .= "$comma$field='{$memberfields[$field]}'";
$comma = ', ';
}
}
if($sql) {
$db->query("UPDATE {$tablepre}memberfields SET $sql WHERE uid='$member[uid]'");
}
} else {
if(empty($memberfields['groupid'])) {
$query = $db->query("SELECT groupid FROM {$tablepre}usergroups WHERE type='member' AND creditshigher='0'");
$memberfields['groupid'] = $db->result($query, 0);
$memberfields['adminid'] = 0;
}
$memberfields['timeoffset'] = !$memberfields['timeoffset'] ? 9999 : $memberfields['timeoffset'];
$memberfields['newsletter'] = !$memberfields['newsletter'] ? 1 : $memberfields['newsletter'];
$sql1 = $sql2 = $comma = '';
foreach($table_member_columns as $field) {
if(isset($memberfields[$field])) {
$sql1 .= "$comma$field";
$sql2 .= "$comma'{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("INSERT INTO {$tablepre}members ($sql1) VALUES ($sql2)");
$table_memberfields_columns[] = 'uid';
$memberfields['uid'] = $member['uid'] = $db->insert_id();
$member['secques'] = '';
$sql1 = $sql2 = $comma = '';
foreach($table_memberfields_columns as $field) {
if(isset($memberfields[$field])) {
$sql1 .= "$comma$field";
$sql2 .= "$comma'{$memberfields[$field]}'";
$comma = ', ';
}
}
$db->query("REPLACE INTO {$tablepre}memberfields ($sql1) VALUES ($sql2)");
$_DCACHE['settings']['lastmember'] = $memberfields['username'];
$_DCACHE['settings']['totalmembers']++;
updatemembercache();
}
dsetcookie('sid', '', -86400 * 365);
dsetcookie('auth', authcode("$memberfields[password]\t".(isset($memberfields['secques']) ? $memberfields['secques'] : $member['secques'])."\t$member[uid]", 'ENCODE'), ($remoteinfo['cookietime'] ? $remoteinfo['cookietime'] : 0));
header('Location: '.(empty($_GET['forward']) ? $_DCACHE['settings']['passport_url'] : $_GET['forward']));
exit;
} elseif($_GET['action'] == 'logout') {
dsetcookie('auth', '', -86400 * 365);
dsetcookie('sid', '', -86400 * 365);
header('Location: '.(empty($_GET['forward']) ? $_DCACHE['settings']['passport_url'] : $_GET['forward']));
exit;
} else {
exit('Invalid action');
}
function arrayeval($array, $level = 0) {
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "\t";
}
$evaluate = "Array\n$space(\n";
$comma = $space;
foreach($array as $key => $val) {
$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
$val = !is_array($val) && (!preg_match("/^\d+$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
} else {
$evaluate .= "$comma$key => $val";
}
$comma = ",\n$space";
}
$evaluate .= "\n$space)";
return $evaluate;
}
function authcode($string, $operation, $key = '') {
global $_DCACHE;
$key = md5($key ? $key : md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']));
$key_length = strlen($key);
$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
$string_length = strlen($string);
$rndkey = $box = array();
$result = '';
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($key[$i % $key_length]);
$box[$i] = $i;
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
return substr($result, 8);
} else {
return '';
}
} else {
return str_replace('=', '', base64_encode($result));
}
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
setcookie(($prefix ? $cookiepre : '').$var, $value,
$life ? $timestamp + $life : 0, $cookiepath,
$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function onlineip() {
global $_SERVER;
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
$onlineip = preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
return $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
function passport_encrypt($txt, $key) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}
function passport_decrypt($txt, $key) {
$txt = passport_key(base64_decode($txt), $key);
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}
function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = '';
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
function updatemembercache() {
$dir = './forumdata/cache/';
if(!is_dir($dir)) {
@mkdir($dir, 0777);
}
if(@$fp = fopen($dir.'cache_settings.php', 'w')) {
fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!\n".
"//Created on ".date("M j, Y, G:i")."\n\n\$_DCACHE['settings'] = ".arrayeval($GLOBALS['_DCACHE']['settings'])."?>");
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
}
?> | zyyhong | trunk/jiaju001/bbs/api/shopex.php | PHP | asf20 | 9,704 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewpro.php 10320 2007-08-26 01:19:05Z cnteacher $
*/
$uid = intval($_GET['uid']);
$username = urlencode(trim($_GET['username']));
if($uid) {
header("Location: space.php?action=viewpro&uid=$uid");
} else {
header("Location: space.php?action=viewpro&username=$username");
}
?> | zyyhong | trunk/jiaju001/bbs/viewpro.php | PHP | asf20 | 407 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: misc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
define('NOROBOT', TRUE);
require_once './include/common.inc.php';
if($action == 'maxpages') {
$pages = intval($pages);
if(empty($pages)) {
showmessage('undefined_action', NULL, 'HALTED');
} else {
showmessage('max_pages');
}
} elseif($action == 'customtopics') {
if(!submitcheck('keywordsubmit', 1)) {
if($_DCOOKIE['customkw']) {
$customkwlist = array();
foreach(@explode("\t", trim($_DCOOKIE['customkw'])) as $key => $keyword) {
$keyword = dhtmlspecialchars(trim(stripslashes($keyword)));
$customkwlist[$key]['keyword'] = $keyword;
$customkwlist[$key]['url'] = '<a href="topic.php?keyword='.rawurlencode($keyword).'" target="_blank">'.$keyword.'</a> ';
}
}
include template('customtopics');
} else {
if(!empty($delete) && is_array($delete)) {
$keywords = implode("\t", array_diff(explode("\t", $_DCOOKIE['customkw']), $delete));
} else {
$keywords = $_DCOOKIE['customkw'];
}
if($newkeyword = cutstr(dhtmlspecialchars(preg_replace("/[\s\|\t\,\'\<\>]/", '', $newkeyword)), 20)) {
if($_DCOOKIE['customkw']) {
if(!preg_match("/(^|\t)".preg_quote($newkeyword, '/')."($|\t)/i", $keywords)) {
if(count(explode("\t", $keywords)) >= $qihoo['maxtopics']) {
$keywords = substr($keywords, (strpos($keywords, "\t") + 1))."\t".$newkeyword;
} else {
$keywords .= "\t".$newkeyword;
}
}
} else {
$keywords = $newkeyword;
}
}
dsetcookie('customkw', stripslashes($keywords), 315360000);
dheader("Location: {$boardurl}misc.php?action=customtopics");
}
} elseif($action == 'attachpay') {
$aid = intval($aid);
if(!$aid) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif(!isset($extcredits[$creditstrans])) {
showmessage('credits_transaction_disabled');
} elseif(!$discuz_uid) {
showmessage('group_nopermission', NULL, 'NOPERM');
} else {
$query = $db->query("SELECT a.tid, a.uid, a.price, a.filename, a.description, m.username AS author FROM {$tablepre}attachments a LEFT JOIN {$tablepre}members m ON a.uid=m.uid WHERE a.aid='$aid'");
$attach = $db->fetch_array($query);
if($attach['price'] <= 0) {
showmessage('undefined_action', NULL, 'HALTED');
}
}
if(($balance = ${'extcredits'.$creditstrans} - $attach['price']) < ($minbalance = 0)) {
showmessage('credits_balance_insufficient');
}
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}attachpaymentlog WHERE aid='$aid' AND uid='$discuz_uid'");
if($db->result($query, 0)) {
showmessage('attachment_yetpay', "attachment.php?aid=$aid");
}
$discuz_action = 81;
$attach['netprice'] = floor($attach['price'] * (1 - $creditstax));
if(!submitcheck('paysubmit')) {
include template('attachpay');
} else {
$updateauthor = 1;
if($maxincperthread > 0) {
$query = $db->query("SELECT SUM(netamount) FROM {$tablepre}attachpaymentlog WHERE aid='$aid'");
if(($db->result($query, 0)) > $maxincperthread) {
$updateauthor = 0;
}
}
if($updateauthor) {
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans+$attach[netprice] WHERE uid='$attach[uid]'");
}
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans-$attach[price] WHERE uid='$discuz_uid'");
$db->query("INSERT INTO {$tablepre}attachpaymentlog (uid, aid, authorid, dateline, amount, netamount)
VALUES ('$discuz_uid', '$aid', '$attach[uid]', '$timestamp', '$attach[price]', '$attach[netprice]')");
showmessage('attachment_buy', "attachment.php?aid=$aid");
}
} elseif($action == 'viewattachpayments') {
$discuz_action = 82;
$loglist = array();
$query = $db->query("SELECT a.*, m.username FROM {$tablepre}attachpaymentlog a
LEFT JOIN {$tablepre}members m USING (uid)
WHERE aid='$aid' ORDER BY dateline");
while($log = $db->fetch_array($query)) {
$log['dateline'] = gmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$loglist[] = $log;
}
include template('attachpay_view');
} elseif($action == 'getonlines') {
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}sessions");
$num = $db->result($query, 0);
showmessage($num);
} elseif($action == 'virtualforum') {
$query = $db->query("SELECT value FROM {$tablepre}settings WHERE variable='insenz'");
$insenz = ($insenz = $db->result($query, 0)) ? unserialize($insenz) : array();
if(!$fid || !isset($insenz['virtualforums'][$fid])) {
showmessage('forum_nonexistence', NULL, 'HALTED');
}
$forumheight = $forumurl = '';
if($checksum && $redirect && $checksum == md5($insenz['authkey'].$redirect)) {
$redirect = str_replace(array('<', '>', '"'), array('<', '>', '"e;'), $redirect);
$forumurl = $redirect;
} else {
$forumname = $forum['name'];
$forum = $insenz['virtualforums'][$fid];
$forum['link'] = urldecode($forum['link']);
$forumurl = $forum['link']."s_sid=$insenz[siteid]&s_name=".urlencode($sitename)."&s_uname=$discuz_uid&s_url=".urlencode($boardurl)."&s_charset=$charset&s_styleid=$styleid";
$forumurl .= "&s_checksum=".md5($forumurl.$insenz['authcode']);
$forumheight = $forum['height'];
}
include template('virtualforum');
exit;
} else {
if(empty($forum['allowview'])) {
if(!$forum['viewperm'] && !$readaccess) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
showmessage('forum_nopermission', NULL, 'NOPERM');
}
} elseif($thread['readperm'] && $thread['readperm'] > $readaccess && !$forum['ismoderator'] && $thread['authorid'] != $discuz_uid) {
showmessage('thread_nopermission', NULL, 'NOPERM');
}
$query = $db->query("SELECT * FROM {$tablepre}threads WHERE tid='$tid' AND displayorder>='0'");
if(!$thread = $db->fetch_array($query)) {
showmessage('thread_nonexistence');
}
if($forum['type'] == 'forum') {
$navigation = "» <a href=\"forumdisplay.php?fid=$fid\">$forum[name]</a> » <a href=\"viewthread.php?tid=$tid\">$thread[subject]</a> ";
$navtitle = strip_tags($forum['name']).' - '.$thread['subject'];
} elseif($forum['type'] == 'sub') {
$query = $db->query("SELECT name, fid FROM {$tablepre}forums WHERE fid='$forum[fup]'");
$fup = $db->fetch_array($query);
$navigation = "» <a href=\"forumdisplay.php?fid=$fup[fid]\">$fup[name]</a> » <a href=\"forumdisplay.php?fid=$fid\">$forum[name]</a> » <a href=\"viewthread.php?tid=$tid\">$thread[subject]</a> ";
$navtitle = strip_tags($fup['name']).' - '.strip_tags($forum['name']).' - '.$thread['subject'];
}
}
if($action == 'votepoll' && submitcheck('pollsubmit')) {
if($supe['status'] && $forum['status'] == 2 && $thread['sgid']) {
require_once DISCUZ_ROOT.'./include/supesite.func.php';
$allowvote = supe_circlepermission($thread['sgid']);
}
if(!$allowvote) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if(!empty($thread['closed'])) {
showmessage('thread_poll_closed');
}
if(empty($pollanswers)) {
showmessage('thread_poll_invalid');
}
$query = $db->query("SELECT maxchoices, expiration FROM {$tablepre}polls WHERE tid='$tid'");
if(!$pollarray = $db->fetch_array($query)) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif($pollarray['expiration'] && $pollarray['expiration'] < $timestamp) {
showmessage('poll_overdue');
} elseif($pollarray['maxchoices'] && $pollarray['maxchoices'] < count($pollanswers)) {
showmessage('poll_choose_most');
}
$voterids = $discuz_uid ? $discuz_uid : $onlineip;
$polloptionid = array();
$query = $db->query("SELECT polloptionid, voterids FROM {$tablepre}polloptions WHERE tid='$tid'");
while($pollarray = $db->fetch_array($query)) {
if(strexists("\t".$pollarray['voterids']."\t", "\t".$voterids."\t")) {
showmessage('thread_poll_voted');
}
$polloptionid[] = $pollarray['polloptionid'];
}
$polloptionids = '';
foreach($pollanswers as $key => $id) {
if(!in_array($id, $polloptionid)) {
showmessage('undefined_action', NULL, 'HALTED');
}
unset($polloptionid[$key]);
$polloptionids[] = $id;
}
$pollanswers = implode('\',\'', $polloptionids);
$db->query("UPDATE {$tablepre}polloptions SET votes=votes+1, voterids=CONCAT(voterids,'$voterids\t') WHERE polloptionid IN ('$pollanswers')", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}threads SET lastpost='$timestamp' WHERE tid='$tid'", 'UNBUFFERED');
$db->query("REPLACE INTO {$tablepre}myposts (uid, tid, pid, position, dateline, special) VALUES ('$discuz_uid', '$tid', '', '', '$timestamp', '1')", 'UNBUFFERED');
updatecredits($discuz_uid, $creditspolicy['votepoll']);
showmessage('thread_poll_succeed', "viewthread.php?tid=$tid");
} elseif($action == 'viewvote') {
if(empty($forum['allowview'])) {
if(!$forum['viewperm'] && !$readaccess) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
showmessage('forum_nopermission', NULL, 'NOPERM');
}
}
if($thread['readperm'] && $thread['readperm'] > $readaccess && !$forum['ismoderator'] && $thread['authorid'] != $discuz_uid) {
showmessage('thread_nopermission', NULL, 'NOPERM');
}
if($forum['password'] && $forum['password'] != $_DCOOKIE['fidpw'.$fid]) {
dheader("Location: {$boardurl}forumdisplay.php?fid=$fid&sid=$sid");
}
$voterpp = 180;
$page = $_GET['page'];
if(empty($polloptionid)) {
$voterids = '';
$query = $db->query("SELECT voterids FROM {$tablepre}polloptions WHERE tid='$tid'");
while($polloption = $db->fetch_array($query)) {
$voterids .= ($voterids ? "\t" : '').trim($polloption['voterids']);
}
unset($polloption);
$arrvoterids = explode("\t", trim($voterids));
$num = count($arrvoterids);
$page = max(1, intval($page));
$start_limit = ($page - 1) * $voterpp;
$multipage = multi($num, $voterpp, $page, "misc.php?action=viewvote&tid=$tid");
} elseif($adminid == 1) {
$voterids = '';
$query = $db->query("SELECT voterids FROM {$tablepre}polloptions WHERE polloptionid='$polloptionid'");
$voterids = $db->result($query, 0);
$arrvoterids = explode("\t", trim($voterids));
$num = count($arrvoterids);
$page = max(1, intval($page));
$start_limit = ($page - 1) * $voterpp;
$multipage = multi($num, $voterpp, $page, "misc.php?action=viewvote&tid=$tid&polloptionid=$polloptionid");
}
$arrvoterids = @array_slice($arrvoterids, $start_limit, $voterpp);
$voterids = @implode("','", $arrvoterids);
$voterlist = $voter = array();
$query = $db->query("SELECT uid, username FROM {$tablepre}members WHERE uid IN ('$voterids')");
while($voter = $db->fetch_array($query)) {
$voterlist[] = $voter;
}
include template('viewthread_poll_voters');
} elseif($action == 'emailfriend') {
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'NOPERM');
}
$discuz_action = 122;
if(!submitcheck('sendsubmit')) {
$fromuid = $creditspolicy['promotion_visit'] ? '&fromuid='.$discuz_uid : '';
$threadurl = "{$boardurl}viewthread.php?tid=$tid$fromuid";
$query = $db->query("SELECT email FROM {$tablepre}members WHERE uid='$discuz_uid'");
$email = $db->result($query, 0);
include template('emailfriend');
} else {
if(empty($fromname) || empty($fromemail) || empty($sendtoname) || empty($sendtoemail)) {
showmessage('email_friend_invalid', NULL, 'HALTED');
}
sendmail("$sendtoname <$sendtoemail>", 'email_to_friend_subject', 'email_to_friend_message', "$fromname <$fromemail>");
showmessage('email_friend_succeed', "viewthread.php?tid=$tid", NULL, 'HALTED');
}
} elseif($action == 'rate' && $pid) {
if(!$raterange) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($modratelimit && $adminid == 3 && !$forum['ismoderator']) {
showmessage('thread_rate_moderator_invalid', NULL, 'HALTED');
}
$reasonpmcheck = $reasonpm == 2 || $reasonpm == 3 ? 'checked="checked" disabled' : '';
if(($reasonpm == 2 || $reasonpm == 3) || !empty($sendreasonpm)) {
$forumname = strip_tags($forum['name']);
$sendreasonpm = 1;
} else {
$sendreasonpm = 0;
}
foreach($raterange as $id => $rating) {
$maxratetoday[$id] = $rating['mrpd'];
}
$query = $db->query("SELECT extcredits, SUM(ABS(score)) AS todayrate FROM {$tablepre}ratelog
WHERE uid='$discuz_uid' AND dateline>=$timestamp-86400
GROUP BY extcredits");
while($rate = $db->fetch_array($query)) {
$maxratetoday[$rate['extcredits']] = $raterange[$rate['extcredits']]['mrpd'] - $rate['todayrate'];
}
$query = $db->query("SELECT * FROM {$tablepre}posts WHERE pid='$pid' AND invisible='0' AND authorid<>'0'");
if(!($post = $db->fetch_array($query)) || $post['tid'] != $thread['tid'] || !$post['authorid']) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif(!$forum['ismoderator'] && $karmaratelimit && $timestamp - $post['dateline'] > $karmaratelimit * 3600) {
showmessage('thread_rate_timelimit', NULL, 'HALTED');
} elseif($post['authorid'] == $discuz_uid || $post['tid'] != $tid) {
showmessage('thread_rate_member_invalid', NULL, 'HALTED');
} elseif($post['anonymous']) {
showmessage('thread_rate_anonymous', NULL, 'HALTED');
} elseif($post['status']) {
showmessage('thread_rate_banned', NULL, 'HALTED');
}
$allowrate = TRUE;
if(!$dupkarmarate) {
$query = $db->query("SELECT pid FROM {$tablepre}ratelog WHERE uid='$discuz_uid' AND pid='$pid' LIMIT 1");
if($db->num_rows($query)) {
showmessage('thread_rate_duplicate', NULL, 'HALTED');
}
}
$discuz_action = 71;
$page = intval($page);
require_once DISCUZ_ROOT.'./include/misc.func.php';
if(!submitcheck('ratesubmit')) {
$referer = $boardurl.'viewthread.php?tid='.$tid.'&page='.$page.'#pid'.$pid;
$ratelist = array();
foreach($raterange as $id => $rating) {
if(isset($extcredits[$id])) {
$ratelist[$id] = '';
$offset = abs(ceil(($rating['max'] - $rating['min']) / 32));
for($vote = $rating['min']; $vote <= $rating['max']; $vote += $offset) {
$ratelist[$id] .= $vote ? '<option value="'.$vote.'">'.($vote > 0 ? '+'.$vote : $vote).'</option>' : '';
}
}
}
include template('rate');
} else {
checkreasonpm();
$rate = $ratetimes = 0;
$creditsarray = array();
foreach($raterange as $id => $rating) {
$score = intval(${'score'.$id});
if(isset($extcredits[$id]) && !empty($score)) {
if(abs($score) <= $maxratetoday[$id]) {
if($score > $rating['max'] || $score < $rating['min']) {
showmessage('thread_rate_range_invalid');
} else {
$creditsarray[$id] = $score;
$rate += $score;
$ratetimes += ceil(max(abs($rating['min']), abs($rating['max'])) / 5);
}
} else {
showmessage('thread_rate_ctrl');
}
}
}
if(!$creditsarray) {
showmessage('thread_rate_range_invalid', NULL, 'HALTED');
}
updatecredits($post['authorid'], $creditsarray);
$db->query("UPDATE {$tablepre}posts SET rate=rate+($rate), ratetimes=ratetimes+$ratetimes WHERE pid='$pid'");
if($post['first']) {
$threadrate = intval(@($post['rate'] + $rate) / abs($post['rate'] + $rate));
$db->query("UPDATE {$tablepre}threads SET rate='$threadrate' WHERE tid='$tid'");
}
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
$sqlvalues = $comma = '';
$sqlreason = censor(trim($reason));
$sqlreason = cutstr(dhtmlspecialchars($sqlreason), 40);
foreach($creditsarray as $id => $addcredits) {
$sqlvalues .= "$comma('$pid', '$discuz_uid', '$discuz_user', '$id', '$timestamp', '$addcredits', '$sqlreason')";
$comma = ', ';
}
$db->query("INSERT INTO {$tablepre}ratelog (pid, uid, username, extcredits, dateline, score, reason)
VALUES $sqlvalues", 'UNBUFFERED');
include_once DISCUZ_ROOT.'./include/post.func.php';
$forum['threadcaches'] && @deletethreadcaches($tid);
$reason = dhtmlspecialchars(censor(trim($reason)));
if($sendreasonpm) {
$ratescore = $slash = '';
foreach($creditsarray as $id => $addcredits) {
$ratescore .= $slash.$extcredits[$id]['title'].' '.($addcredits > 0 ? '+'.$addcredits : $addcredits).' '.$extcredits[$id]['unit'];
$slash = ' / ';
}
sendreasonpm('post', 'rate_reason');
}
$logs = array();
foreach($creditsarray as $id => $addcredits) {
$logs[] = dhtmlspecialchars("$timestamp\t$discuz_userss\t$adminid\t$post[author]\t$id\t$addcredits\t$tid\t$thread[subject]\t$reason");
}
writelog('ratelog', $logs);
showmessage('thread_rate_succeed', dreferer());
}
} elseif($action == 'removerate' && $pid) {
if(!$forum['ismoderator'] || !$raterange) {
showmessage('undefined_action');
}
$reasonpmcheck = $reasonpm == 2 || $reasonpm == 3 ? 'checked="checked" disabled' : '';
if(($reasonpm == 2 || $reasonpm == 3) || !empty($sendreasonpm)) {
$forumname = strip_tags($forum['name']);
$sendreasonpm = 1;
} else {
$sendreasonpm = 0;
}
foreach($raterange as $id => $rating) {
$maxratetoday[$id] = $rating['mrpd'];
}
$query = $db->query("SELECT * FROM {$tablepre}posts WHERE pid='$pid' AND invisible='0' AND authorid<>'0'");
if(!($post = $db->fetch_array($query)) || $post['tid'] != $thread['tid'] || !$post['authorid']) {
showmessage('undefined_action');
}
$discuz_action = 71;
require_once DISCUZ_ROOT.'./include/misc.func.php';
if(!submitcheck('ratesubmit')) {
$referer = $boardurl.'viewthread.php?tid='.$tid.'&page='.$page.'#pid'.$pid;
$ratelogs = array();
$query = $db->query("SELECT * FROM {$tablepre}ratelog WHERE pid='$pid' ORDER BY dateline");
while($ratelog = $db->fetch_array($query)) {
$ratelog['dbdateline'] = $ratelog['dateline'];
$ratelog['dateline'] = gmdate("$dateformat $timeformat", $ratelog['dateline'] + $timeoffset * 3600);
$ratelog['scoreview'] = $ratelog['score'] > 0 ? '+'.$ratelog['score'] : $ratelog['score'];
$ratelogs[] = $ratelog;
}
include template('rate');
} else {
checkreasonpm();
if(!empty($logidarray)) {
if($sendreasonpm) {
$ratescore = $slash = '';
}
$query = $db->query("SELECT * FROM {$tablepre}ratelog WHERE pid='$pid'");
$rate = $ratetimes = 0;
$logs = array();
while($ratelog = $db->fetch_array($query)) {
if(in_array($ratelog['uid'].' '.$ratelog['extcredits'].' '.$ratelog['dateline'], $logidarray)) {
$rate += $ratelog['score'] = -$ratelog['score'];
$ratetimes += ceil(max(abs($rating['min']), abs($rating['max'])) / 5);
updatecredits($post['authorid'], array($ratelog['extcredits'] => $ratelog['score']));
$db->query("DELETE FROM {$tablepre}ratelog WHERE pid='$pid' AND uid='$ratelog[uid]' AND extcredits='$ratelog[extcredits]' AND dateline='$ratelog[dateline]'", 'UNBUFFERED');
$logs[] = dhtmlspecialchars("$timestamp\t$discuz_userss\t$adminid\t$post[author]\t$ratelog[extcredits]\t$ratelog[score]\t$tid\t$thread[subject]\t$reason\tD");
if($sendreasonpm) {
$ratescore .= $slash.$extcredits[$ratelog['extcredits']]['title'].' '.($ratelog['score'] > 0 ? '+'.$ratelog['score'] : $ratelog['score']).' '.$extcredits[$ratelog['extcredits']]['unit'];
$slash = ' / ';
}
}
}
writelog('ratelog', $logs);
if($sendreasonpm) {
sendreasonpm('post', 'rate_removereason');
}
$db->query("UPDATE {$tablepre}posts SET rate=rate+($rate), ratetimes=ratetimes-$ratetimes WHERE pid='$pid'");
if($post['first']) {
$threadrate = @intval(@($post['rate'] + $rate) / abs($post['rate'] + $rate));
$db->query("UPDATE {$tablepre}threads SET rate='$threadrate' WHERE tid='$tid'");
}
}
showmessage('thread_rate_removesucceed', dreferer());
}
} elseif($action == 'viewratings' && $pid) {
$queryr = $db->query("SELECT * FROM {$tablepre}ratelog WHERE pid='$pid' ORDER BY dateline");
$queryp = $db->query("SELECT p.* ".($bannedmessages ? ", m.groupid " : '').
" FROM {$tablepre}posts p ".
($bannedmessages ? "LEFT JOIN {$tablepre}members m ON m.uid=p.authorid" : '').
" WHERE p.pid='$pid' AND p.invisible='0'");
if(!($db->num_rows($queryr)) || !($db->num_rows($queryp))) {
showmessage('thread_rate_log_nonexistence');
}
$post = $db->fetch_array($queryp);
if($post['tid'] != $thread['tid']) {
showmessage('undefined_action', NULL, 'HALTED');
}
$discuz_action = 72;
if(!$bannedmessages || !$post['authorid'] || ($bannedmessages && $post['authorid'] && !in_array(intval($author['groupid']), array(0, 4, 5)))) {
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
$post['dateline'] = gmdate("$dateformat $timeformat", $post['dateline'] + $timeoffset * 3600);
$post['message'] = discuzcode($post['message'], $post['smileyoff'], $post['bbcodeoff'], sprintf('%00b', $post['htmlon']), $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'], $forum['allowhtml'], $forum['jammer']);
} else {
$post['message'] = '';
}
$loglist = array();
while($log = $db->fetch_array($queryr)) {
$log['dateline'] = gmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$log['score'] = $log['score'] > 0 ? '+'.$log['score'] : $log['score'];
$log['reason'] = dhtmlspecialchars($log['reason']);
$loglist[] = $log;
}
include template('rate_view');
} elseif($action == 'pay') {
if(!isset($extcredits[$creditstrans])) {
showmessage('credits_transaction_disabled');
} elseif($thread['price'] <= 0 || $thread['special'] <> 0) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif(!$discuz_uid) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if(($balance = ${'extcredits'.$creditstrans} - $thread['price']) < ($minbalance = 0)) {
showmessage('credits_balance_insufficient');
}
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}paymentlog WHERE tid='$tid' AND uid='$discuz_uid'");
if($db->result($query, 0)) {
showmessage('credits_buy_thread', 'viewthread.php?tid='.$tid);
}
$discuz_action = 81;
$thread['netprice'] = floor($thread['price'] * (1 - $creditstax));
if(!submitcheck('paysubmit')) {
include template('pay');
} else {
$updateauthor = true;
if($maxincperthread > 0) {
$query = $db->query("SELECT SUM(netamount) FROM {$tablepre}paymentlog WHERE tid='$tid'");
if(($db->result($query, 0)) > $maxincperthread) {
$updateauthor = false;
}
}
if($updateauthor) {
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans+$thread[netprice] WHERE uid='$thread[authorid]'");
}
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans-$thread[price] WHERE uid='$discuz_uid'");
$db->query("INSERT INTO {$tablepre}paymentlog (uid, tid, authorid, dateline, amount, netamount)
VALUES ('$discuz_uid', '$tid', '$thread[authorid]', '$timestamp', '$thread[price]', '$thread[netprice]')");
showmessage('thread_pay_succeed', "viewthread.php?tid=$tid");
}
} elseif($action == 'viewpayments') {
$discuz_action = 82;
$loglist = array();
$query = $db->query("SELECT p.*, m.username FROM {$tablepre}paymentlog p
LEFT JOIN {$tablepre}members m USING (uid)
WHERE tid='$tid' ORDER BY dateline");
while($log = $db->fetch_array($query)) {
$log['dateline'] = gmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$loglist[] = $log;
}
include template('pay_view');
} elseif($action == 'report') {
if(!$reportpost) {
showmessage('thread_report_disabled');
}
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'HALTED');
}
if(!$thread || !is_numeric($pid)) {
showmessage('undefined_action', NULL, 'HALTED');
}
$discuz_action = 123;
$floodctrl = $floodctrl * 3;
if($timestamp - $lastpost < $floodctrl) {
showmessage('thread_report_flood_ctrl');
}
if(!submitcheck('reportsubmit')) {
include template('reportpost');
exit;
} else {
$posturl = "{$boardurl}viewthread.php?tid=$tid".($page || $pid ? "&page=$page#pid$pid" : NULL);
$uids = 0;
$adminids = '';
$reportto = array();
if(is_array($to) && count($to)) {
if(isset($to[3])) {
$query = $db->query("SELECT uid FROM {$tablepre}moderators WHERE fid='$fid'");
while($member = $db->fetch_array($query)) {
$uids .= ','.$member['uid'];
}
}
if(!$uids || ($reportpost >= 2 && $to[2])) {
$adminids .= ',2';
}
if($reportpost == 3 && $to[1]) {
$adminids .= ',1';
}
if($adminids) {
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE adminid IN (".substr($adminids, 1).")");
if(!$db->num_rows($query)) {
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE adminid='1'");
}
while($member = $db->fetch_array($query)) {
$uids .= ','.$member['uid'];
}
}
$query = $db->query("SELECT uid, ignorepm FROM {$tablepre}memberfields WHERE uid IN ($uids)");
while($member = $db->fetch_array($query)) {
if(!preg_match("/(^{ALL}$|(,|^)\s*".preg_quote($discuz_user, '/')."\s*(,|$))/i", $member['ignorepm'])) {
if(!in_array($member['uid'], $reportto)) {
$reportto[] = $member['uid'];
}
}
}
if($reportto) {
$reason = stripslashes($reason);
sendpm(implode(',', $reportto), 'reportpost_subject', 'reportpost_message');
}
$db->query("UPDATE {$tablepre}members SET lastpost='$timestamp' WHERE uid='$discuz_uid'");
showmessage('thread_report_succeed', "viewthread.php?tid=$tid");
} else {
showmessage('thread_report_invalid');
}
}
} elseif($action == 'blog') {
if(!$discuz_uid || (!$thread['blog'] && (!$allowuseblog || !$forum['allowshare']))) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if($thread['authorid'] != $discuz_uid) {
$query = $db->query("SELECT adminid FROM {$tablepre}members WHERE uid='$thread[authorid]'");
$thread['adminid'] = $db->result($query, 0);
if(!$forum['ismoderator'] || (in_array($thread['adminid'], array(1, 2, 3)) && $adminid > $thread['adminid'])) {
showmessage('blog_add_illegal');
}
}
$blog = $thread['blog'] ? 0 : 1;
$db->query("UPDATE {$tablepre}threads SET blog='$blog' WHERE tid='$tid'", 'UNBUFFERED');
if($forum['ismoderator'] && $thread['authorid'] != $discuz_uid && $blog != $thread['blog']) {
$reason = '';
require_once DISCUZ_ROOT.'./include/misc.func.php';
modlog($thread, ($thread['blog'] ? 'RBL' : 'ABL'));
}
showmessage('blog_add_succeed', "viewthread.php?tid=$tid");
} elseif($action == 'viewthreadmod' && $tid) {
$loglist = array();
$query = $db->query("SELECT * FROM {$tablepre}threadsmod WHERE tid='$tid' ORDER BY dateline DESC");
while($log = $db->fetch_array($query)) {
$log['dateline'] = gmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$log['expiration'] = !empty($log['expiration']) ? gmdate("$dateformat", $log['expiration'] + $timeoffset * 3600) : '';
$log['status'] = empty($log['status']) ? 'style="text-decoration: line-through" disabled' : '';
if($log['magicid']) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_magics.php';
$log['magicname'] = $_DCACHE['magics'][$log['magicid']]['name'];
}
$loglist[] = $log;
}
if(empty($loglist)) {
showmessage('threadmod_nonexistence');
} else {
include_once language('modactions');
}
include template('viewthread_mod');
} elseif($action == 'bestanswer' && $tid && $pid && submitcheck('bestanswersubmit')) {
$forward = 'viewthread.php?tid='.$tid;
$query = $db->query("SELECT authorid, first FROM {$tablepre}posts WHERE pid='$pid' and tid='$tid'");
if(!($thread['special'] == 3 && ($post = $db->fetch_array($query)) && ($forum['ismoderator'] || $thread['authorid'] == $discuz_uid) && $post['authorid'] != $thread['authorid'] && $post['first'] == 0 && $discuz_uid != $post['authorid'])) {
showmessage('reward_cant_operate');
} elseif($post['authorid'] == $thread['authorid']) {
showmessage('reward_cant_self');
} elseif($thread['price'] < 0) {
showmessage('reward_repeat_selection');
}
$thread['netprice'] = ceil($price * ( 1 + $creditstax) );
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans+$thread[price] WHERE uid='$post[authorid]'");
$db->query("DELETE FROM {$tablepre}rewardlog WHERE tid='$tid' and answererid='$post[authorid]'");
$db->query("UPDATE {$tablepre}rewardlog SET answererid='$post[authorid]' WHERE tid='$tid' and authorid='$thread[authorid]'");
$thread['price'] = '-'.$thread['price'];
$db->query("UPDATE {$tablepre}threads SET price='$thread[price]' WHERE tid='$tid'");
$db->query("UPDATE {$tablepre}posts SET dateline=$thread[dateline]+1 WHERE pid='$pid'");
$thread['dateline'] = gmdate("$dateformat $timeformat", $thread['dateline'] + $timeoffset * 3600);
if($discuz_uid != $thread['authorid']) {
sendpm($thread['authorid'], 'reward_question_subject', 'reward_question_message', $discuz_uid, $discuz_user);
}
sendpm($post['authorid'], 'reward_bestanswer_subject', 'reward_bestanswer_message', $discuz_uid, $discuz_user);
showmessage('reward_completion', $forward);
} elseif($action == 'activityapplies') {
$allowjoinactivity = 1;
if($supe['status'] && $forum['status'] == 2 && $thread['sgid']) {
require_once DISCUZ_ROOT.'./include/supesite.func.php';
$allowjoinactivity = supe_circlepermission($thread['sgid']);
}
if(!$discuz_uid || !$allowjoinactivity) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(submitcheck('activitysubmit')) {
$query = $db->query("SELECT expiration FROM {$tablepre}activities WHERE tid='$tid'");
$expiration = $db->result($query, 0);
if($expiration && $expiration < $timestamp - date('Z')) {
showmessage('activity_stop');
}
$query = $db->query("SELECT applyid FROM {$tablepre}activityapplies WHERE tid='$tid' and username='$discuz_user'");
if($db->num_rows($query)) {
showmessage('activity_repeat_apply', "viewthread.php?tid=$tid&extra=$extra");
}
$payvalue = intval($payvalue);
$payment = $payment ? $payvalue : -1;
$message = cutstr(dhtmlspecialchars($message), 200);
$contact = cutstr(dhtmlspecialchars($contact), 200);
$db->query("INSERT INTO {$tablepre}activityapplies (tid, username, uid, message, verified, dateline, payment, contact)
VALUES ('$tid', '$discuz_user', '$discuz_uid', '$message', '0', '$timestamp', '$payment', '$contact')");
showmessage('activity_completion', "viewthread.php?tid=$tid&extra=$extra");
}
} elseif($action == 'activityapplylist') {
$query = $db->query("SELECT * FROM {$tablepre}activities WHERE tid='$tid'");
$activity = $db->fetch_array($query);
if(!$activity || $thread['special'] != 4) {
showmessage('undefined_action');
}
if(!submitcheck('applylistsubmit')) {
$sqlverified = $thread['authorid'] == $discuz_uid ? '' : 'AND verified=1';
$applylist = array();
$query = $db->query("SELECT applyid, username, uid, message, verified, dateline, payment, contact FROM {$tablepre}activityapplies WHERE tid='$tid' $sqlverified ORDER BY dateline DESC");
while($activityapplies = $db->fetch_array($query)) {
$activityapplies['dateline'] = gmdate("$dateformat $timeformat", $activityapplies['dateline'] + $timeoffset * 3600);
$applylist[] = $activityapplies;
}
$activity['starttimefrom'] = gmdate("$dateformat $timeformat", $activity['starttimefrom'] + $timeoffset * 3600);
$activity['starttimeto'] = $activity['starttimeto'] ? gmdate("$dateformat $timeformat", $activity['starttimeto'] + $timeoffset * 3600) : 0;
$activity['expiration'] = $activity['expiration'] ? gmdate("$dateformat $timeformat", $activity['expiration'] + $timeoffset * 3600) : 0;
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}activityapplies WHERE tid='$tid' AND verified=1");
$applynumbers = $db->result($query, 0);
include template('activity_applylist');
} else {
if(empty($applyidarray)) {
showmessage('activity_choice_applicant', "viewthread.php?tid=$tid&do=viewapplylist");
} else {
$uidarray = array();
$ids = implode('\',\'', $applyidarray);
$query=$db->query("SELECT a.uid FROM {$tablepre}activityapplies a RIGHT JOIN {$tablepre}members m USING(uid) WHERE a.applyid IN ('$ids')");
while($uid = $db->fetch_array($query)) {
$uidarray[] = $uid['uid'];
}
$activity_subject = $thread['subject'];
if($operation == 'delete') {
$db->query("DELETE FROM {$tablepre}activityapplies WHERE applyid IN ('$ids')", 'UNBUFFERED');
sendpm(implode(',', $uidarray), 'activity_delete_subject', 'activity_delete_message', $fromid = '0', $from = 'System Message');
showmessage('activity_delete_completion', "viewthread.php?tid=$tid&do=viewapplylist");
} else {
$db->query("UPDATE {$tablepre}activityapplies SET verified=1 WHERE applyid IN ('$ids')", 'UNBUFFERED');
sendpm(implode(',', $uidarray), 'activity_apply_subject', 'activity_apply_message', $fromid = '0', $from = 'System Message');
showmessage('activity_auditing_completion', "viewthread.php?tid=$tid&do=viewapplylist");
}
}
}
} elseif($action == 'tradeorder') {
$trades = array();
$query=$db->query("SELECT * FROM {$tablepre}trades WHERE tid='$tid' ORDER BY displayorder");
if($thread['authorid'] != $discuz_uid) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(!submitcheck('tradesubmit')) {
$stickcount = 0;$trades = $tradesstick = array();
while($trade = $db->fetch_array($query)) {
$stickcount = $trade['displayorder'] > 0 ? $stickcount + 1 : $stickcount;
$trade['displayorderview'] = $trade['displayorder'] < 0 ? 128 + $trade['displayorder'] : $trade['displayorder'];
if($trade['expiration']) {
$trade['expiration'] = ($trade['expiration'] - $timestamp) / 86400;
if($trade['expiration'] > 0) {
$trade['expirationhour'] = floor(($trade['expiration'] - floor($trade['expiration'])) * 24);
$trade['expiration'] = floor($trade['expiration']);
} else {
$trade['expiration'] = -1;
}
}
if($trade['displayorder'] < 0) {
$trades[] = $trade;
} else {
$tradesstick[] = $trade;
}
}
$trades = array_merge($tradesstick, $trades);
include template('trade_displayorder');
} else {
$count = 0;
while($trade = $db->fetch_array($query)) {
$displayordernew = abs(intval($displayorder[$trade['pid']]));
$displayordernew = $displayordernew > 128 ? 0 : $displayordernew;
if($stick[$trade['pid']]) {
$count++;
$displayordernew = $displayordernew == 0 ? 1 : $displayordernew;
}
if(!$stick[$trade['pid']] || $displayordernew > 0 && $tradestick < $count) {
$displayordernew = -1 * (128 - $displayordernew);
}
$db->query("UPDATE {$tablepre}trades SET displayorder='".$displayordernew."' WHERE tid='$tid' AND pid='$trade[pid]'");
}
showmessage('trade_displayorder_updated', "viewthread.php?tid=$tid");
}
} elseif($action == 'debatevote') {
if(!empty($thread['closed'])) {
showmessage('thread_poll_closed');
}
if(!$discuz_uid) {
showmessage('debate_poll_nopermission');
}
$isfirst = empty($pid) ? TRUE : FALSE;
$query = $db->query("SELECT uid, endtime, affirmvoterids, negavoterids FROM {$tablepre}debates WHERE tid='$tid'");
$debate = $db->fetch_array($query);
if(empty($debate)) {
showmessage('debate_nofound');
}
if($isfirst) {
$stand = intval($stand);
if($stand == 1 || $stand == 2) {
if(strpos($debate['affirmvoterids'], "$discuz_uid\t") !== FALSE || strpos($debate['negavoterids'], "$discuz_uid\t") !== FALSE) {
showmessage('debate_poll_voted');
}
}
if($stand == 1) {
$db->query("UPDATE {$tablepre}debates SET affirmvotes=affirmvotes+1");
$db->query("UPDATE {$tablepre}debates SET affirmvoterids=CONCAT(affirmvoterids, '$discuz_uid\t') WHERE tid='$tid'");
} elseif($stand == 2) {
$db->query("UPDATE {$tablepre}debates SET negavotes=negavotes+1");
$db->query("UPDATE {$tablepre}debates SET negavoterids=CONCAT(negavoterids, '$discuz_uid\t') WHERE tid='$tid'");
}
showmessage('debate_poll_succeed');
}
$query = $db->query("SELECT stand, voterids, uid FROM {$tablepre}debateposts WHERE pid='$pid' AND tid='$tid'");
$debatepost = $db->fetch_array($query);
if(empty($debatepost)) {
showmessage('debate_nofound');
}
$debate = array_merge($debate, $debatepost);
unset($debatepost);
if($debate['uid'] == $discuz_uid) {
showmessage('debate_poll_myself', "viewthread.php?tid=$tid");
}
if(strpos($debate['voterids'], "$discuz_uid\t") !== FALSE) {
showmessage('debate_poll_voted', "viewthread.php?tid=$tid");
}
if($debate['endtime'] && $debate['endtime'] < $timestamp) {
showmessage('debate_poll_end', "viewthread.php?tid=$tid");
}
/*
if($isfirst) {
$sqladd = $debate['stand'] == 1 ? 'affirmvotes=affirmvotes+1' : ($debate['stand'] == 2 ? 'negavotes=negavotes+1' : '');
if($sqladd) {
$db->query("UPDATE {$tablepre}debates SET $sqladd WHERE tid='$tid'");
}
unset($sqladd);
}
*/
$db->query("UPDATE {$tablepre}debateposts SET voters=voters+1, voterids=CONCAT(voterids, '$discuz_uid\t') WHERE pid='$pid'");
showmessage('debate_poll_succeed', "viewthread.php?tid=$tid");
}elseif($action == 'debateumpire') {
$query = $db->query("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
$debate = $db->fetch_array($query);
if(empty($debate)) {
showmessage('debate_nofound');
}
if(!empty($thread['closed']) && $timestamp - $debate['endtime'] > 3600) {
showmessage('debate_umpire_edit_invalid');
}
$debate = array_merge($debate, $thread);
if($discuz_user != $debate['umpire']) {
showmessage('debate_umpire_nopermission');
}
if(!submitcheck('umpiresubmit')) {
$query = $db->query("SELECT SUM(dp.voters) as voters, dp.stand, m.uid, m.username FROM {$tablepre}debateposts dp
LEFT JOIN {$tablepre}members m ON m.uid=dp.uid
WHERE dp.tid='$tid' AND dp.stand<>0
GROUP BY m.uid
ORDER BY voters DESC
LIMIT 30");
$candidate = $candidates = array();
while($candidate = $db->fetch_array($query)) {
$candidate['username'] = dhtmlspecialchars($candidate['username']);
$candidates[$candidate['username']] = $candidate;
}
$winnerchecked = array($debate['winner'] => ' checked="checked"');
list($debate['bestdebater']) = preg_split("/\s/", $debate['bestdebater']);
include template('debate_umpire');
} else {
if(empty($bestdebater)) {
showmessage('debate_umpire_nofound_bestdebater');
} elseif(empty($winner)) {
showmessage('debate_umpire_nofound_winner');
} elseif(empty($umpirepoint)) {
showmessage('debate_umpire_nofound_point');
}
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username='$bestdebater' LIMIT 1");
$bestdebateruid = $db->result($query, 0);
if(!$bestdebateruid) {
showmessage('debate_umpire_bestdebater_invalid');
}
$query = $db->query("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$bestdebateruid' AND stand>'0' AND uid<>'$debate[uid]' AND uid<>'$discuz_uid' LIMIT 1");
if(!$bestdebaterstand = $db->result($query, 0)) {
showmessage('debate_umpire_bestdebater_invalid');
}
$query = $db->query("SELECT SUM(voters) as voters, COUNT(*) as replies FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$bestdebateruid'");
$arr = $db->fetch_array($query);
$bestdebatervoters = $arr['voters'];
$bestdebaterreplies = $arr['replies'];
$umpirepoint = dhtmlspecialchars($umpirepoint);
$bestdebater = dhtmlspecialchars($bestdebater);
$winner = intval($winner);
$db->query("UPDATE {$tablepre}threads SET closed='1' WHERE tid='$tid'");
$db->query("UPDATE {$tablepre}debates SET umpirepoint='$umpirepoint', winner='$winner', bestdebater='$bestdebater\t$bestdebateruid\t$bestdebaterstand\t$bestdebatervoters\t$bestdebaterreplies', endtime='$timestamp' WHERE tid='$tid'");
showmessage('debate_umpire_comment_succeed', 'viewthread.php?tid='.$tid);
}
}
?> | zyyhong | trunk/jiaju001/bbs/misc.php | PHP | asf20 | 40,656 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tag.php 10311 2007-08-25 10:07:14Z monkey $
*/
require_once './include/common.inc.php';
if(!$tagstatus) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(!empty($name)) {
if(!preg_match('/^([\x7f-\xff_-]|\w)+$/', $name) || strlen($name) > 20) {
showmessage('undefined_action', NULL, 'HALTED');
}
require_once DISCUZ_ROOT.'./include/misc.func.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_icons.php';
$tpp = $inajax ? 5 : $tpp;
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$tag = $db->fetch_array($db->query("SELECT * FROM {$tablepre}tags WHERE tagname='$name'"));
if($tag['closed']) {
showmessage('tag_closed');
}
$count = $db->result($db->query("SELECT count(*) FROM {$tablepre}threadtags WHERE tagname='$name'"), 0);
$query = $db->query("SELECT t.*,tt.tid as tagtid FROM {$tablepre}threadtags tt LEFT JOIN {$tablepre}threads t USING(tid) WHERE tt.tagname='$name' ORDER BY lastpost DESC LIMIT $start_limit, $tpp");
$cleantid = $threadlist = array();
while($tagthread = $db->fetch_array($query)) {
if($tagthread['tid']) {
$threadlist[] = procthread($tagthread);
} else {
$cleantid[] = $tagthread['tagtid'];
}
}
if($cleantid) {
$db->query("DELETE FROM {$tablepre}threadtags WHERE tagname='$name' AND tid IN (".implodeids($cleantid).")", 'UNBUFFERED');
$cleancount = count($cleantid);
if($count > $cleancount) {
$db->query("UPDATE {$tablepre}tags SET total=total-'$cleancount' WHERE tagname='$name'", 'UNBUFFERED');
} else {
$db->query("DELETE FROM {$tablepre}tags WHERE tagname='$name'", 'UNBUFFERED');
}
}
$tagnameenc = rawurlencode($name);
$navtitle = $name.' - ';
$multipage = multi($count, $tpp, $page, "tag.php?name=$tagnameenc");
include template('tag_threads');
} else {
$viewthreadtags = intval($viewthreadtags);
$query = $db->query("SELECT tagname,total FROM {$tablepre}tags WHERE closed=0 ORDER BY total DESC LIMIT $viewthreadtags");
$hottaglist = array();
while($tagrow = $db->fetch_array($query)) {
$tagrow['tagnameenc'] = rawurlencode($tagrow['tagname']);
$hottaglist[] = $tagrow;
}
$count = $db->result($db->query("SELECT count(*) FROM {$tablepre}tags WHERE closed=0"), 0);
$randlimit = mt_rand(0, $count <= $viewthreadtags ? 0 : $count - $viewthreadtags);
$query = $db->query("SELECT tagname,total FROM {$tablepre}tags WHERE closed=0 LIMIT $randlimit, $viewthreadtags");
$randtaglist = array();
while($tagrow = $db->fetch_array($query)) {
$tagrow['tagnameenc'] = rawurlencode($tagrow['tagname']);
$randtaglist[] = $tagrow;
}
shuffle($randtaglist);
include template('tag');
}
?> | zyyhong | trunk/jiaju001/bbs/tag.php | PHP | asf20 | 2,878 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: search_trade.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$orderby = in_array($orderby, array('dateline', 'price', 'expiration')) ? $orderby : 'dateline';
$ascdesc = isset($ascdesc) && $ascdesc == 'asc' ? 'asc' : 'desc';
if(isset($searchid)) {
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$query = $db->query("SELECT searchstring, keywords, threads, tids FROM {$tablepre}searchindex WHERE searchid='$searchid'");
if(!$index = $db->fetch_array($query)) {
showmessage('search_id_invalid');
}
$index['keywords'] = rawurlencode($index['keywords']);
$index['searchtype'] = preg_replace("/^([a-z]+)\|.*/", "\\1", $index['searchstring']);
$threadlist = $tradelist = array();
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE pid IN ($index[tids]) ORDER BY $orderby $ascdesc LIMIT $start_limit, $tpp");
while($tradethread = $db->fetch_array($query)) {
$tradethread['lastupdate'] = gmdate("$dateformat $timeformat", $tradethread['lastupdate'] + $timeoffset * 3600);
$tradethread['lastbuyer'] = rawurlencode($tradethread['lastbuyer']);
if($tradethread['expiration']) {
$tradethread['expiration'] = ($tradethread['expiration'] - $timestamp) / 86400;
if($tradethread['expiration'] > 0) {
$tradethread['expirationhour'] = floor(($tradethread['expiration'] - floor($tradethread['expiration'])) * 24);
$tradethread['expiration'] = floor($tradethread['expiration']);
} else {
$tradethread['expiration'] = -1;
}
}
$tradelist[] = $tradethread;
}
$multipage = multi($index['threads'], $tpp, $page, "search.php?searchid=$searchid".($orderby ? "&orderby=$orderby" : '')."&srchtype=trade&searchsubmit=yes");
$url_forward = 'search.php?'.$_SERVER['QUERY_STRING'];
include template('search_trade');
} else {
checklowerlimit($creditspolicy['search'], -1);
$srchtxt = isset($srchtxt) ? trim($srchtxt) : '';
$srchuname = isset($srchuname) ? trim($srchuname) : '';
$forumsarray = array();
if(!empty($srchfid)) {
foreach((is_array($srchfid) ? $srchfid : explode('_', $srchfid)) as $forum) {
if($forum = intval(trim($forum))) {
$forumsarray[] = $forum;
}
}
}
$fids = $comma = '';
foreach($_DCACHE['forums'] as $fid => $forum) {
if($forum['type'] != 'group' && (!$forum['viewperm'] && $readaccess) || ($forum['viewperm'] && forumperm($forum['viewperm']))) {
if(!$forumsarray || in_array($fid, $forumsarray)) {
$fids .= "$comma'$fid'";
$comma = ',';
}
}
}
$srchfilter = in_array($srchfilter, array('all', 'digest', 'top')) ? $srchfilter : 'all';
$searchstring = 'trade|'.addslashes($srchtxt).'|'.intval($srchtypeid).'|'.intval($srchuid).'|'.$srchuname.'|'.addslashes($fids).'|'.intval($srchfrom).'|'.intval($before).'|'.$srchfilter;
$searchindex = array('id' => 0, 'dateline' => '0');
$query = $db->query("SELECT searchid, dateline,
('$searchctrl'<>'0' AND ".(empty($discuz_uid) ? "useip='$onlineip'" : "uid='$discuz_uid'")." AND $timestamp-dateline<$searchctrl) AS flood,
(searchstring='$searchstring' AND expiration>'$timestamp') AS indexvalid
FROM {$tablepre}searchindex
WHERE ('$searchctrl'<>'0' AND ".(empty($discuz_uid) ? "useip='$onlineip'" : "uid='$discuz_uid'")." AND $timestamp-dateline<$searchctrl) OR (searchstring='$searchstring' AND expiration>'$timestamp')
ORDER BY flood");
while($index = $db->fetch_array($query)) {
if($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']) {
$searchindex = array('id' => $index['searchid'], 'dateline' => $index['dateline']);
break;
} elseif($index['flood']) {
showmessage('search_ctrl', 'search.php');
}
}
if($searchindex['id']) {
$searchid = $searchindex['id'];
} else {
if(!$srchtxt && !$srchtypeid && !$srchuid && !$srchuname && !$srchfrom && !in_array($srchfilter, array('digest', 'top'))) {
showmessage('search_invalid', 'search.php');
} elseif(isset($srchfid) && $srchfid != 'all' && !(is_array($srchfid) && in_array('all', $srchfid)) && empty($forumsarray)) {
showmessage('search_forum_invalid', 'search.php');
} elseif(!$fids) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if($maxspm) {
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}searchindex WHERE dateline>'$timestamp'-60");
if(($db->result($query, 0)) >= $maxspm) {
showmessage('search_toomany', 'search.php');
}
}
$digestltd = $srchfilter == 'digest' ? "t.digest>'0' AND" : '';
$topltd = $srchfilter == 'top' ? "AND t.displayorder>'0'" : "AND t.displayorder>='0'";
if(!empty($srchfrom) && empty($srchtxt) && empty($srchtypeid) && empty($srchuid) && empty($srchuname)) {
$searchfrom = $before ? '<=' : '>=';
$searchfrom .= $timestamp - $srchfrom;
$sqlsrch = "FROM {$tablepre}trades tr INNER JOIN {$tablepre}threads t ON tr.tid=t.tid AND $digestltd t.fid IN ($fids) $topltd WHERE tr.dateline$searchfrom";
$expiration = $timestamp + $cachelife_time;
$keywords = '';
} else {
$sqlsrch = "FROM {$tablepre}trades tr INNER JOIN {$tablepre}threads t ON tr.tid=t.tid AND $digestltd t.fid IN ($fids) $topltd WHERE 1";
if($srchuname) {
$srchuid = $comma = '';
$srchuname = str_replace('*', '%', addcslashes($srchuname, '%_'));
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username LIKE '".str_replace('_', '\_', $srchuname)."' LIMIT 50");
while($member = $db->fetch_array($query)) {
$srchuid .= "$comma'$member[uid]'";
$comma = ', ';
}
if(!$srchuid) {
$sqlsrch .= ' AND 0';
}
} elseif($srchuid) {
$srchuid = "'$srchuid'";
}
if($srchtypeid) {
$srchtypeid = intval($srchtypeid);
$sqlsrch .= " AND tr.typeid='$srchtypeid'";
}
if($srchtxt) {
if(preg_match("(AND|\+|&|\s)", $srchtxt) && !preg_match("(OR|\|)", $srchtxt)) {
$andor = ' AND ';
$sqltxtsrch = '1';
$srchtxt = preg_replace("/( AND |&| )/is", "+", $srchtxt);
} else {
$andor = ' OR ';
$sqltxtsrch = '0';
$srchtxt = preg_replace("/( OR |\|)/is", "+", $srchtxt);
}
$srchtxt = str_replace('*', '%', addcslashes($srchtxt, '%_'));
foreach(explode('+', $srchtxt) as $text) {
$text = trim($text);
if($text) {
$sqltxtsrch .= $andor;
$sqltxtsrch .= "tr.subject LIKE '%$text%'";
}
}
$sqlsrch .= " AND ($sqltxtsrch)";
}
if($srchuid) {
$sqlsrch .= " AND tr.sellerid IN ($srchuid)";
}
if(!empty($srchfrom)) {
$searchfrom = ($before ? '<=' : '>=').($timestamp - $srchfrom);
$sqlsrch .= " AND tr.dateline$searchfrom";
}
$keywords = str_replace('%', '+', $srchtxt).(trim($srchuname) ? '+'.str_replace('%', '+', $srchuname) : '');
$expiration = $timestamp + $cachelife_text;
}
$threads = $tids = 0;
$query = $db->query("SELECT tr.tid, tr.pid, t.closed $sqlsrch ORDER BY tr.pid DESC LIMIT $maxsearchresults");
while($post = $db->fetch_array($query)) {
if($thread['closed'] <= 1) {
$tids .= ','.$post['pid'];
$threads++;
}
}
$db->free_result($query);
$db->query("INSERT INTO {$tablepre}searchindex (keywords, searchstring, useip, uid, dateline, expiration, threads, tids)
VALUES ('$keywords', '$searchstring', '$onlineip', '$discuz_uid', '$timestamp', '$expiration', '$threads', '$tids')");
$searchid = $db->insert_id();
updatecredits($discuz_uid, $creditspolicy['search'], -1);
}
showmessage('search_redirect', "search.php?searchid=$searchid&srchtype=trade&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");
}
?> | zyyhong | trunk/jiaju001/bbs/include/search_trade.inc.php | PHP | asf20 | 7,874 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: advertisements.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$advarray = array();
if(!empty($_DCACHE['advs'])) {
$advs = $_DCACHE['advs']['type'];
$advitems = $_DCACHE['advs']['items'];
if(in_array(CURSCRIPT, array('forumdisplay', 'viewthread')) && !empty($fid)) {
foreach($advs AS $type => $advitem) {
if($advitem = array_unique(array_merge((!empty($advitem['forum_'.$fid]) ? $advitem['forum_'.$fid] : array()), (!empty($advitem['forum_all']) ? $advitem['forum_all'] : array())))) {
if(substr($type, 0, 6) == 'thread') {
$advarray[substr($type, 0, 7)][substr($type, 8, strlen($type))] = $advitem;
} else {
$advarray[$type] = $advitem;
}
}
}
$advs = $advarray;
}
if($globaladvs) {
foreach($globaladvs['type'] AS $key => $value) {
if(isset($advs[$key])) {
$advs[$key] = array_merge($advs[$key], $value);
} else {
$advs[$key] = $value;
}
}
$advitems = $advitems + $globaladvs['items'];
}
$advarray = $advs;
} else {
$advarray = $globaladvs['type'];
$advitems = $globaladvs['items'];
}
foreach($advarray as $advtype => $advcodes) {
if(substr($advtype, 0, 6) == 'thread') {
for($i = 1; $i <= $ppp; $i++) {
$adv_codes = @array_unique(array_merge((isset($advcodes[$i]) ? $advcodes[$i] : array()), (isset($advcodes[0]) ? $advcodes[0] : array())));
$advcount = count($adv_codes);
$advlist[$advtype][$i - 1] = $advitems[$advcount > 1 ? $adv_codes[mt_rand(0, $advcount -1)] : $adv_codes[0]];
}
} elseif($advtype == 'intercat') {
$advlist['intercat'] = $advcodes;
} else {
$advcount = count($advcodes);
if($advtype == 'text') {
if($advcount > 5) {
$minfillpercent = 0;
for($cols = 5; $cols >= 3; $cols--) {
if(($remainder = $advcount % $cols) == 0) {
$advcols = $cols;
break;
} elseif($remainder / $cols > $minfillpercent) {
$minfillpercent = $remainder / $cols;
$advcols = $cols;
}
}
} else {
$advcols = $advcount;
}
$advlist[$advtype] = '';
for($i = 0; $i < $advcols * ceil($advcount / $advcols); $i++) {
$advlist[$advtype] .= (($i + 1) % $advcols == 1 || $advcols == 1 ? '<tr>' : '').
'<td width="'.intval(100 / $advcols).'%">'.(isset($advcodes[$i]) ? $advitems[$advcodes[$i]] : ' ').'</td>'.
(($i + 1) % $advcols == 0 ? "</tr>\n" : '');
}
} else {
$advlist[$advtype] = $advitems[$advcount > 1 ? $advcodes[mt_rand(0, $advcount - 1)] : $advcodes[0]];
}
}
}
unset($_DCACHE['advs'], $advs, $advarray);
if(empty($advlist['intercat'])) {
unset($advitems);
}
?> | zyyhong | trunk/jiaju001/bbs/include/advertisements.inc.php | PHP | asf20 | 3,108 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: template.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function parse_template($file, $templateid, $tpldir) {
global $language;
$nest = 5;
$tplfile = DISCUZ_ROOT."./$tpldir/$file.htm";
$objfile = DISCUZ_ROOT."./forumdata/templates/{$templateid}_$file.tpl.php";
if(!@$fp = fopen($tplfile, 'r')) {
dexit("Current template file './$tpldir/$file.htm' not found or have no access!");
} elseif($language['discuz_lang'] != 'templates' && !include language('templates', $templateid, $tpldir)) {
dexit("<br />Current template pack do not have a necessary language file 'templates.lang.php' or have syntax error!");
}
$template = @fread($fp, filesize($tplfile));
fclose($fp);
$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
//$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
$template = preg_replace("/\{lang\s+(.+?)\}/ies", "languagevar('\\1')", $template);
$template = preg_replace("/\{faq\s+(.+?)\}/ies", "faqvar('\\1')", $template);
$template = str_replace("{LF}", "<?=\"\\n\"?>", $template);
$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
$template = preg_replace("/$var_regexp/es", "addquote('<?=\\1?>')", $template);
$template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "addquote('<?=\\1?>')", $template);
$template = "<? if(!defined('IN_DISCUZ')) exit('Access Denied'); ?>\n$template";
$template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_]+)\}[\n\r\t]*/is", "\n<? include template('\\1'); ?>\n", $template);
$template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n<? include template(\\1); ?>\n", $template);
$template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "stripvtags('<? \\1 ?>','')", $template);
$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "stripvtags('<? echo \\1; ?>','')", $template);
$template = preg_replace("/([\n\r\t]*)\{elseif\s+(.+?)\}([\n\r\t]*)/ies", "stripvtags('\\1<? } elseif(\\2) { ?>\\3','')", $template);
$template = preg_replace("/([\n\r\t]*)\{else\}([\n\r\t]*)/is", "\\1<? } else { ?>\\2", $template);
for($i = 0; $i < $nest; $i++) {
$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $template);
$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<? } } ?>')", $template);
$template = preg_replace("/([\n\r\t]*)\{if\s+(.+?)\}([\n\r]*)(.+?)([\n\r]*)\{\/if\}([\n\r\t]*)/ies", "stripvtags('\\1<? if(\\2) { ?>\\3','\\4\\5<? } ?>\\6')", $template);
}
$template = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);
$template = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);
if(!@$fp = fopen($objfile, 'w')) {
dexit("Directory './forumdata/templates/' not found or have no access!");
}
$template = preg_replace("/\"(http)?[\w\.\/:]+\?[^\"]+?&[^\"]+?\"/e", "transamp('\\0')", $template);
$template = preg_replace("/\<script[^\>]*?src=\"(.+?)\".*?\>\s*\<\/script\>/ise", "stripscriptamp('\\1')", $template);
$template = preg_replace("/[\n\r\t]*\{block\s+([a-zA-Z0-9_]+)\}(.+?)\{\/block\}/ies", "stripblock('\\1', '\\2')", $template);
flock($fp, 2);
fwrite($fp, $template);
fclose($fp);
}
function transamp($str) {
$str = str_replace('&', '&', $str);
$str = str_replace('&amp;', '&', $str);
$str = str_replace('\"', '"', $str);
return $str;
}
function addquote($var) {
return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}
function languagevar($var) {
if(isset($GLOBALS['language'][$var])) {
return $GLOBALS['language'][$var];
} else {
return "!$var!";
}
}
function faqvar($var) {
global $_DCACHE;
include_once DISCUZ_ROOT.'./forumdata/cache/cache_faqs.php';
if(isset($_DCACHE['faqs'][$var])) {
return '<a href="faq.php?action=message&id='.$_DCACHE['faqs'][$var]['id'].'" target="_blank">'.$_DCACHE['faqs'][$var]['keyword'].'</a>';
} else {
return "!$var!";
}
}
function stripvtags($expr, $statement) {
$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
$statement = str_replace("\\\"", "\"", $statement);
return $expr.$statement;
}
function stripscriptamp($s) {
$s = str_replace('&', '&', $s);
return "<script src=\"$s\" type=\"text/javascript\"></script>";
}
function stripblock($var, $s) {
$s = str_replace('\\"', '"', $s);
$s = preg_replace("/<\?=\\\$(.+?)\?>/", "{\$\\1}", $s);
preg_match_all("/<\?=(.+?)\?>/e", $s, $constary);
$constadd = '';
$constary[1] = array_unique($constary[1]);
foreach($constary[1] as $const) {
$constadd .= '$__'.$const.' = '.$const.';';
}
$s = preg_replace("/<\?=(.+?)\?>/", "{\$__\\1}", $s);
$s = str_replace('?>', "\n\$$var .= <<<EOF\n", $s);
$s = str_replace('<?', "\nEOF;\n", $s);
return "<?\n$constadd\$$var = <<<EOF\n".$s."\nEOF;\n?>";
}
?> | zyyhong | trunk/jiaju001/bbs/include/template.func.php | PHP | asf20 | 5,543 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function checkautoclose() {
global $timestamp, $forum, $thread;
if(!$forum['ismoderator'] && $forum['autoclose']) {
$closedby = $forum['autoclose'] > 0 ? 'dateline' : 'lastpost';
$forum['autoclose'] = abs($forum['autoclose']);
if($timestamp - $thread[$closedby] > $forum['autoclose'] * 86400) {
return 'post_thread_closed_by_'.$closedby;
}
}
return FALSE;
}
function forum(&$forum) {
global $_DCOOKIE, $timestamp, $timeformat, $dateformat, $discuz_uid, $groupid, $lastvisit, $moddisplay, $timeoffset, $hideprivate, $onlinehold;
if(!$forum['viewperm'] || ($forum['viewperm'] && forumperm($forum['viewperm'])) || !empty($forum['allowview']) || (isset($forum['users']) && strstr($forum['users'], "\t$discuz_uid\t"))) {
$forum['permission'] = 2;
} elseif(!$hideprivate) {
$forum['permission'] = 1;
} else {
return FALSE;
}
if($forum['icon']) {
if(strstr($forum['icon'], ',')) {
$flash = explode(",", $forum['icon']);
$forum['icon'] = "<a href=\"forumdisplay.php?fid=$forum[fid]\"><embed style=\"margin-right: 10px\" src=\"".trim($flash[0])."\" width=\"".trim($flash[1])."\" height=\"".trim($flash[2])."\" type=\"application/x-shockwave-flash\" align=\"left\"></embed></a>";
} else {
$forum['icon'] = "<a href=\"forumdisplay.php?fid=$forum[fid]\"><img style=\"margin-right: 10px\" src=\"$forum[icon]\" align=\"left\" alt=\"\" border=\"0\" /></a>";
}
}
$lastpost = array('tid' => 0, 'dateline' => 0, 'subject' => '', 'author' => '');
list($lastpost['tid'], $lastpost['subject'], $lastpost['dateline'], $lastpost['author']) = is_array($forum['lastpost']) ? $forum['lastpost'] : explode("\t", $forum['lastpost']);
$forum['folder'] = (isset($_DCOOKIE['fid'.$forum['fid']]) && $_DCOOKIE['fid'.$forum['fid']] > $lastvisit ? $_DCOOKIE['fid'.$forum['fid']] : $lastvisit) < $lastpost['dateline'] ? ' class="new"' : '';
if($lastpost['tid']) {
$lastpost['dateline'] = gmdate("$dateformat $timeformat", $lastpost['dateline'] + $timeoffset * 3600);
if($lastpost['author']) {
$lastpost['author'] = '<a href="space.php?username='.rawurlencode($lastpost['author']).'">'.$lastpost['author'].'</a>';
}
$forum['lastpost'] = $lastpost;
} else {
$forum['lastpost'] = '';
}
$forum['moderators'] = moddisplay($forum['moderators'], $moddisplay, !empty($forum['inheritedmod']));
if(isset($forum['subforums'])) {
$forum['subforums'] = implode(', ', $forum['subforums']);
}
return TRUE;
}
function forumselect($groupselectable = FALSE, $tableformat = 0) {
global $_DCACHE, $discuz_uid, $groupid, $fid, $gid, $indexname;
if(!isset($_DCACHE['forums'])) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
}
$forumlist = $tableformat ? '<dl><dd><ul>' : '<optgroup label=" ">';
foreach($_DCACHE['forums'] as $forum) {
if($forum['type'] == 'group') {
if($tableformat) {
$forumlist .= '</ul></dd></dl><dl><dt><a href="'.$indexname.'?gid='.$forum['fid'].'">'.$forum['name'].'</a></dt><dd><ul>';
} else {
$forumlist .= $groupselectable ? '<option value="'.$forum['fid'].'">'.$forum['name'].'</option>' : '</optgroup><optgroup label="'.$forum['name'].'">';
}
$visible[$forum['fid']] = true;
} elseif($forum['type'] == 'forum' && isset($visible[$forum['fup']]) && (!$forum['viewperm'] || ($forum['viewperm'] && forumperm($forum['viewperm'])) || strstr($forum['users'], "\t$discuz_uid\t"))) {
if($tableformat) {
$forumlist .= '<li'.($fid == $forum['fid'] ? ' class="current"' : '').'><a href="forumdisplay.php?fid='.$forum['fid'].'">'.$forum['name'].'</a></li>';
} else {
$forumlist .= '<option value="'.$forum['fid'].'"> > '.$forum['name'].'</option>';
}
$visible[$forum['fid']] = true;
} elseif($forum['type'] == 'sub' && isset($visible[$forum['fup']]) && (!$forum['viewperm'] || ($forum['viewperm'] && forumperm($forum['viewperm'])) || strstr($forum['users'], "\t$discuz_uid\t"))) {
if($tableformat) {
$forumlist .= '<li class="sub'.($fid == $forum['fid'] ? ' current"' : '').'"><a href="forumdisplay.php?fid='.$forum['fid'].'">'.$forum['name'].'</a></li>';
} else {
$forumlist .= '<option value="'.$forum['fid'].'"> > '.$forum['name'].'</option>';
}
}
}
$forumlist .= $tableformat ? '</ul></dd></dl>' : '</optgroup>';
$forumlist = str_replace($tableformat ? '<dl><dd><ul></ul></dd></dl>' : '<optgroup label=" "></optgroup>', '', $forumlist);
return $forumlist;
}
function visitedforums() {
global $_DCACHE, $_DCOOKIE, $forum;
$count = 0;
$visitedforums = '';
$fidarray = array($forum['fid']);
foreach(explode('D', $_DCOOKIE['visitedfid']) as $fid) {
if(isset($_DCACHE['forums'][$fid]) && !in_array($fid, $fidarray)) {
$fidarray[] = $fid;
if($fid != $forum['fid']) {
$visitedforums .= '<option value="'.$fid.'">'.$_DCACHE['forums'][$fid]['name'].'</option>';
if(++$count >= $GLOBALS['visitedforums']) {
break;
}
}
}
}
if(($visitedfid = implode('D', $fidarray)) != $_DCOOKIE['visitedfid']) {
dsetcookie('visitedfid', $visitedfid, 2592000);
}
return $visitedforums;
}
function moddisplay($moderators, $type, $inherit = 0) {
if($type == 'selectbox') {
if($moderators) {
$modlist = '';
foreach(explode("\t", $moderators) as $moderator) {
$modlist .= '<li><a href="space.php?username='.rawurlencode($moderator).'">'.($inherit ? '<strong>'.$moderator.'</strong>' : $moderator).'</a></li>';
}
} else {
$modlist = '';
}
return $modlist;
} else {
if($moderators) {
$modlist = $comma = '';
foreach(explode("\t", $moderators) as $moderator) {
$modlist .= $comma.'<a class="notabs" href="space.php?username='.rawurlencode($moderator).'">'.($inherit ? '<strong>'.$moderator.'</strong>' : $moderator).'</a>';
$comma = ', ';
}
} else {
$modlist = '';
}
return $modlist;
}
}
function getcacheinfo($tid) {
global $timestamp, $cachethreadlife, $cachethreaddir;
$tid = intval($tid);
$cachethreaddir2 = DISCUZ_ROOT.'./'.$cachethreaddir;
$cache = array('filemtime' => 0, 'filename' => '');
$tidmd5 = substr(md5($tid), 3);
$fulldir = $cachethreaddir2.'/'.$tidmd5[0].'/'.$tidmd5[1].'/'.$tidmd5[2].'/';
$cache['filename'] = $fulldir.$tid.'.htm';
if(file_exists($cache['filename'])) {
$cache['filemtime'] = filemtime($cache['filename']);
} else {
if(!is_dir($fulldir)) {
for($i=0; $i<3; $i++) {
$cachethreaddir2 .= '/'.$tidmd5{$i};
if(!is_dir($cachethreaddir2)) {
@mkdir($cachethreaddir2, 0777);
@touch($cachethreaddir2.'/index.htm');
}
}
}
}
return $cache;
}
function recommendupdate($fid, $modrecommend, $force = '') {
global $db, $tablepre, $timestamp;
$recommendlist = array();
$num = $modrecommend['num'] ? intval($modrecommend['num']) : 10;
$query = $db->query("SELECT * FROM {$tablepre}forumrecommend WHERE fid='$fid' ORDER BY displayorder LIMIT 0, $num");
while($recommend = $db->fetch_array($query)) {
if(($recommend['expiration'] && $recommend['expiration'] > $timestamp) || !$recommend['expiration']) {
$recommendlist[] = $recommend;
}
}
if($modrecommend['sort'] && (!$recommendlist || $timestamp - $modrecommend['updatetime'] > $modrecommend['cachelife'] || $force)) {
if($recommendlist) {
$db->query("DELETE FROM {$tablepre}forumrecommend WHERE fid='$fid'");
}
$orderby = 'dateline';
$conditions = $modrecommend['dateline'] ? 'AND dateline>'.($timestamp - $modrecommend['dateline'] * 3600) : '';
switch($modrecommend['orderby']) {
case '1': $orderby = 'lastpost'; break;
case '2': $orderby = 'views'; break;
case '3': $orderby = 'replies'; break;
case '4': $orderby = 'digest'; break;
}
$addthread = $comma = $i = '';
$recommendlist = array();
$query = $db->query("SELECT fid, tid, author, authorid, subject FROM {$tablepre}threads WHERE fid='$fid' AND displayorder>='0' $conditions ORDER BY $orderby DESC LIMIT 0, $num");
while($thread = $db->fetch_array($query)) {
$recommendlist[] = $thread;
$addthread .= $comma."('$thread[fid]', '$thread[tid]', '$i', '".addslashes($thread['subject'])."', '".addslashes($thread['author'])."', '$thread[authorid]', '0', '0')";
$comma = ', ';
$i++;
}
if($addthread) {
$db->query("REPLACE INTO {$tablepre}forumrecommend (fid, tid, displayorder, subject, author, authorid, moderatorid, expiration) VALUES $addthread");
$modrecommend['updatetime'] = $timestamp;
$modrecommendnew = addslashes(serialize($modrecommend));
$db->query("UPDATE {$tablepre}forumfields SET modrecommend='$modrecommendnew' WHERE fid='$fid'");
}
}
$recommendlists = array();
if($recommendlist) {
foreach($recommendlist as $thread) {
$recommendlists[$thread['tid']]['author'] = $thread['author'];
$recommendlists[$thread['tid']]['authorid'] = $thread['authorid'];
$recommendlists[$thread['tid']]['subject'] = $modrecommend['maxlength'] ? cutstr($thread['subject'], $modrecommend['maxlength']) : $thread['subject'];
}
}
return $recommendlists;
}
?> | zyyhong | trunk/jiaju001/bbs/include/forum.func.php | PHP | asf20 | 9,424 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_debate.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$debate = $thread;
$query = $db->query("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
$debate = $db->fetch_array($query);
$debate['dbendtime'] = $debate['endtime'];
if($debate['dbendtime']) {
$debate['endtime'] = gmdate("$dateformat $timeformat", $debate['dbendtime'] + $timeoffset * 3600);
}
if($debate['dbendtime'] > $timestamp) {
$debate['remaintime'] = remaintime($debate['dbendtime'] - $timestamp);
}
$debate['starttime'] = gmdate("$dateformat $timeformat", $debate['starttime'] + $timeoffset * 3600);
$debate['affirmpoint'] = discuzcode($debate['affirmpoint'], 0, 0, 0, 1, 1, 0, 0, 0, 0, 0);
$debate['negapoint'] = discuzcode($debate['negapoint'], 0, 0, 0, 1, 1, 0, 0, 0, 0, 0);
$debate['affirmvoteswidth'] = $debate['affirmvotes'] ? intval(80 * (($debate['affirmvotes'] + 1) / ($debate['affirmvotes'] + $debate['negavotes'] + 1))) : 1;
$debate['negavoteswidth'] = $debate['negavotes'] ? intval(80 * (($debate['negavotes'] + 1) / ($debate['affirmvotes'] + $debate['negavotes'] + 1))) : 1;
if($debate['umpirepoint']) {
$debate['umpirepoint'] = discuzcode($debate['umpirepoint'], 0, 0, 0, 1, 1, 1, 0, 0, 0, 0);
}
$debate['umpireurl'] = rawurlencode($debate['umpire']);
list($debate['bestdebater'], $debate['bestdebateruid'], $debate['bestdebaterstand'], $debate['bestdebatervoters'], $debate['bestdebaterreplies']) = explode("\t", $debate['bestdebater']);
$debate['bestdebaterurl'] = rawurlencode($debate['bestdebater']);
if(empty($do) || $do == 'viewdebate') {
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.customstatus, mf.spacename $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE tid='$tid' AND first=1 LIMIT 1");
$post = array_merge($debate, $post = $db->fetch_array($query));
$pid = $post['pid'];
$postlist[$post['pid']] = viewthread_procpost($post);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$post = $postlist[$post['pid']];
if($fastpost && $allowpostreply && $thread['closed'] == 0) {
$standquery = $db->query("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$discuz_uid' AND stand<>'0' ORDER BY dateline LIMIT 1");
$firststand = $db->result($standquery, 0);
$firststandselect[$firststand] = ' selected="selected"';
$firststanddisabled = $firststand != 0 ? ' disabled="disabled"' : '';
}
include template('viewthread_debate');
exit;
} elseif($do == 'viewdebatepost') {
$ppp = $forum['threadcaches'] && !$discuz_uid ? $_DCACHE['settings']['postperpage'] : $ppp;
$debatesqladd = $debateurladd = $sqladd = '';
$rows = $thread['replies'];
if(isset($stand)) {
switch($stand = intval($stand)) {
case 0: $rows = $thread['replies'] - $debate['affirmreplies'] - $debate['negareplies']; $debatesqladd = "AND dp.stand='$stand'"; break;
case 1: $rows = $debate['affirmreplies']; $debatesqladd = "AND dp.stand='$stand'"; break;
case 2: $rows = $debate['negareplies']; $debatesqladd = "AND dp.stand='$stand'"; break;
case 3: $rows = $debate['bestdebaterreplies']; $debatesqladd = "AND dp.uid='$debate[bestdebateruid]'"; break;
}
$debateurladd = "&stand=$stand";
}
$start_limit = $numpost = ($page - 1) * $ppp;
if($start_limit > $rows) {
$start_limit = $numpost = 0;
$page = 1;
}
$multipage = multi($rows, $ppp, $page, "viewthread.php?do=viewdebatepost&tid=$tid$debateurladd&extra=$extra".(isset($highlight) ? "&highlight=".rawurlencode($highlight) : ''));
$query = $db->query("SELECT p.*,m.username,m.adminid,m.groupid,m.credits,dp.stand,dp.voters FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}debateposts dp ON p.pid=dp.pid
WHERE p.tid='$tid' AND p.invisible='0' AND p.first='0' $debatesqladd ORDER BY p.dateline LIMIT $start_limit, $ppp");
$postlist = $post = array();
while($post = $db->fetch_array($query)) {
$post['stand'] = intval($post['stand']);
$postlist[$post['pid']] = viewthread_procpost($post, 1);
}
ksort($postlist);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
$standchecked = array((!isset($stand) ? 'all' : $stand) => 'class="current"');
include template('viewthread_debate_posts');
exit;
}
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_debate.inc.php | PHP | asf20 | 5,234 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_reward.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$rewardprice = abs($thread['price']);
$limit = $thread['price'] < 0 ? 2 : 1;
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.sightml AS signature, mf.customstatus, mf.spacename $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE p.tid='$tid' ORDER BY dateline LIMIT $limit");
$bapid = 0;$bestpost = array();
while($post = $db->fetch_array($query)) {
if($post['first'] == 1) {
$pid = $post['pid'];
} else {
$thread['price'] < 0 && $bapid = $post['pid'];
}
$postlist[$post['pid']] = viewthread_procpost($post);
}
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$post = $postlist[$pid];
$bapid && $bestpost = $postlist[$bapid];
include template('viewthread_reward');
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_reward.inc.php | PHP | asf20 | 1,630 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cron.func.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function runcron($cronid = 0) {
global $timestamp, $db, $tablepre, $_DCACHE;
$query = $db->query("SELECT * FROM {$tablepre}crons WHERE ".($cronid ? "cronid='$cronid'" : "available>'0' AND nextrun<='$timestamp'")." ORDER BY nextrun LIMIT 1");
if($cron = $db->fetch_array($query)) {
$lockfile = DISCUZ_ROOT.'./forumdata/runcron_'.$cron['cronid'].'.lock';
$cron['filename'] = str_replace(array('..', '/', '\\'), '', $cron['filename']);
$cronfile = DISCUZ_ROOT.'./include/crons/'.$cron['filename'];
if(is_writable($lockfile) && filemtime($lockfile) > $timestamp - 600) {
return NULL;
} else {
@touch($lockfile);
}
@set_time_limit(1000);
@ignore_user_abort(TRUE);
$cron['minute'] = explode("\t", $cron['minute']);
cronnextrun($cron);
extract($GLOBALS, EXTR_SKIP);
if(!@include $cronfile) {
errorlog('CRON', $cron['name'].' : Cron script('.$cron['filename'].') not found or syntax error', 0);
}
@unlink($lockfile);
}
$query = $db->query("SELECT nextrun FROM {$tablepre}crons WHERE available>'0' ORDER BY nextrun LIMIT 1");
$nextrun = $db->result($query, 0);
if(!$nextrun === FALSE) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
$_DCACHE['settings']['cronnextrun'] = $db->result($query, 0);
updatesettings();
}
}
function cronnextrun($cron) {
global $db, $tablepre, $_DCACHE, $timestamp;
if(empty($cron)) return FALSE;
list($yearnow, $monthnow, $daynow, $weekdaynow, $hournow, $minutenow) = explode('-', gmdate('Y-m-d-w-H-i', $timestamp + $_DCACHE['settings']['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 + $_DCACHE['settings']['timeoffset'] * 3600);
}
} else {
$firstday = $daynow + ($cron['weekday'] - $weekdaynow);
$secondday = $firstday + 7;
}
if($firstday < $daynow) {
$firstday = $secondday;
}
if($firstday == $daynow) {
$todaytime = crontodaynextrun($cron);
if($todaytime['hour'] == -1 && $todaytime['minute'] == -1) {
$cron['day'] = $secondday;
$nexttime = crontodaynextrun($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 = crontodaynextrun($cron, 0, -1);
$cron['hour'] = $nexttime['hour'];
$cron['minute'] = $nexttime['minute'];
}
$nextrun = @gmmktime($cron['hour'], $cron['minute'], 0, $monthnow, $cron['day'], $yearnow) - $_DCACHE['settings']['timeoffset'] * 3600;
$availableadd = $nextrun > $timestamp ? '' : ', available=\'0\'';
$db->query("UPDATE {$tablepre}crons SET lastrun='$timestamp', nextrun='$nextrun' $availableadd WHERE cronid='$cron[cronid]'");
return TRUE;
}
function crontodaynextrun($cron, $hour = -2, $minute = -2) {
global $timestamp, $_DCACHE;
$hour = $hour == -2 ? gmdate('H', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600) : $hour;
$minute = $minute == -2 ? gmdate('i', $timestamp + $_DCACHE['settings']['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 = cronnextminute($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 = cronnextminute($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;
}
function cronnextminute($nextminutes, $minutenow) {
foreach($nextminutes as $nextminute) {
if($nextminute > $minutenow) {
return $nextminute;
}
}
return false;
}
?> | zyyhong | trunk/jiaju001/bbs/include/cron.func.php | PHP | asf20 | 4,845 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_activity.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($iscircle) {
$allowjoinactivity = ($circle['allowshare'] && ($circle['ispublic'] == 1 || ($circle['ispublic'] == 2 && $circle['password'] == $_DCOOKIE['gidpw'.$gid]))) || $incircle;
}
$applylist = array();
$query = $db->query("SELECT * FROM {$tablepre}activities WHERE tid='$tid'");
$activity = $db->fetch_array($query);
$activityclose = $activity['expiration'] ? ($activity['expiration'] > $timestamp - date('Z') ? 0 : 1) : 0;
$activity['starttimefrom'] = gmdate("$dateformat $timeformat", $activity['starttimefrom'] + $timeoffset * 3600);
$activity['starttimeto'] = $activity['starttimeto'] ? gmdate("$dateformat $timeformat", $activity['starttimeto'] + $timeoffset * 3600) : 0;
$activity['expiration'] = $activity['expiration'] ? gmdate("$dateformat $timeformat", $activity['expiration'] + $timeoffset * 3600) : 0;
$isverified = $applied = 0;
if($discuz_uid) {
$query = $db->query("SELECT verified FROM {$tablepre}activityapplies WHERE tid='$tid' AND uid='$discuz_uid'");
if($db->num_rows($query)) {
$isverified = $db->result($query, 0);
$applied = 1;
}
}
$sqlverified = $thread['authorid'] == $discuz_uid ? '' : 'AND aa.verified=1';
$query = $db->query("SELECT aa.username, aa.uid, aa.dateline, m.groupid, mf.avatar FROM {$tablepre}activityapplies aa
LEFT JOIN {$tablepre}members m USING(uid)
LEFT JOIN {$tablepre}memberfields mf USING(uid)
WHERE aa.tid='$tid' $sqlverified ORDER BY aa.dateline DESC LIMIT 9");
while($activityapplies = $db->fetch_array($query)) {
$activityapplies['dateline'] = gmdate("$dateformat $timeformat", $activityapplies['dateline'] + $timeoffset * 3600);
if($_DCACHE['usergroups'][$activityapplies['groupid']]['groupavatar']) {
$activityapplies['avatar'] = '<img onload="thumbImg(this)" style="padding: 3px" width="45" height="45" src="'.$_DCACHE['usergroups'][$activityapplies['groupid']]['groupavatar'].'" border="0" alt="" />';
} elseif($_DCACHE['usergroups'][$activityapplies['groupid']]['allowavatar'] && $activityapplies['avatar']) {
$activityapplies['avatar'] = '<img onload="thumbImg(this)" style="padding: 3px" width="45" height="45" src="'.$activityapplies['avatar'].'" border="0" alt="" />';
} else {
$activityapplies['avatar'] = '<img onload="thumbImg(this)" style="padding: 3px" width="45" height="45" src="images/avatars/noavatar.gif" border="0" alt="" />';
}
$applylist[] = $activityapplies;
}
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}activityapplies WHERE tid='$tid' AND verified=1");
$applynumbers = $db->result($query, 0);
$aboutmembers = $activity['number'] >= $applynumbers ? $activity['number'] - $applynumbers : 0;
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.sightml AS signature, mf.customstatus, mf.spacename $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE p.tid='$tid' AND first=1 LIMIT 1");
$post = $db->fetch_array($query);
$pid = $post['pid'];
$postlist[$post['pid']] = viewthread_procpost($post);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$post = $postlist[$post['pid']];
include template('viewthread_activity');
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_activity.inc.php | PHP | asf20 | 4,026 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: supesite.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function supe_xspace2forum($itemid, &$subject, &$message, &$special, &$iconid, &$trade) {
global $timestamp, $timeoffset, $dateformat, $timeformat, $supe;
include_once language('misc');
supe_dbconnect();
$query = $supe['db']->query("SELECT * FROM {$supe[tablepre]}spaceitems WHERE itemid='$itemid'");
if(!$item = $supe['db']->fetch_array($query)) {
return array();
}
$subject .= str_replace('"', '"', $item['subject']);
switch($item['type']) {
case 'blog':
$special = 0;
$query = $supe['db']->query("SELECT message, postip, weather, mood, customfieldid, customfieldtext FROM {$supe[tablepre]}spaceblogs WHERE itemid='$itemid'");
$item += $supe['db']->fetch_array($query);
$message .= supe_html2bbcode($item['message']);
break;
case 'image':
$special = 0;
$query = $supe['db']->query("SELECT message, postip, customfieldid, customfieldtext FROM {$supe[tablepre]}spaceimages WHERE itemid='$itemid'");
$item += $supe['db']->fetch_array($query);
$message .= "[b]$language[supe_picture_story]:[/b] \r\n ".supe_html2bbcode($item[message]);
break;
case 'goods':
$special = 2;
$query = $supe['db']->query("SELECT * FROM {$supe[tablepre]}spacegoods WHERE itemid='$itemid'");
$item += $supe['db']->fetch_array($query);
$message .= supe_html2bbcode($item['message']);
$trade['trade_expiration'] = $timestamp + 30 * 86400;
$trade['seller'] = $item['alipay'];
$trade['item_name'] = $item['subject'];
$trade['item_price'] = $item['price'];
$trade['item_number'] = $item['salednum'] ? $item['salednum'] : 1;
$trade['item_quality'] = $item['quality'] == 'new' ? 1 : 2;
$trade['item_locus'] = $item['province'].' '.$item['city'];
$trade['item_transport'] = $item['chargemode'] == 'buy' ? 2 : 1;
$trade['postage_mail'] = $item['chargemail'];
$trade['postage_express'] = $item['chargeexpress'];
$trade['postage_ems'] = $item['chargeems'];
$trade['item_type'] = 1;
break;
case 'file':
$special = 0;
$query = $supe['db']->query("SELECT message, relativetags, postip, relativeitemids, customfieldid, customfieldtext, includetags, filesize, filesizeunit, version, producer, downfrom, language, permission, system, remoteurl FROM {$supe[tablepre]}spacefiles WHERE itemid='$itemid'");
$item += $supe['db']->fetch_array($query);
$message .= '[list]';
$message .= "[*][b]$language[supe_software_size]:[/b] $item[filesize]\r\n";
$message .= "[*][b]$language[supe_software_version]:[/b] $item[version]\r\n";
$message .= "[*][b]$language[supe_software_producer]:[/b] $item[producer]\r\n";
$message .= "[*][b]$language[supe_software_downfrom]:[/b] $item[downfrom]\r\n";
$message .= "[*][b]$language[supe_software_language]:[/b] $item[language]\r\n";
$message .= "[*][b]$language[supe_software_permission]:[/b] $item[permission] \r\n";
$message .= "[*][b]$language[supe_software_system]:[/b] $item[system]\r\n";
$item['digest'] = $language['supe_digest_'.intval($item['digest'])];
$message .= "[*][b]$language[supe_digest_level]:[/b] $item[digest] \r\n";
$message .= "[*][b]$language[supe_software_introduce]:[/b]\r\n".supe_html2bbcode($item[message])."\r\n\r\n";
if($item['remoteurl'] = unserialize($item['remoteurl'])) {
$message .= "[*][b]$language[supe_download_from_remote]:[/b]\r\n";
foreach($item['remoteurl'] as $val) {
$message .= "[url=$val[remoteurl]][/b]{$val[remoteurlname]}[/b][/url]\r\n";
}
}
$message .= '[/list]';
break;
case 'link':
$special = 0;
$query = $supe['db']->query("SELECT url, message, postip, customfieldid, customfieldtext FROM {$supe[tablepre]}spacelinks WHERE itemid='$itemid'");
$item += $supe['db']->fetch_array($query);
$message .= '[list]';
$message .= "[*][b]$language[supe_linkurl]:[/b] [url]{$item[url]}[/url]\r\n";
$message .= "[*][b]$language[supe_snapshot]:[/b] [url={$supe[siteurl]}/batch.snapshot.php?itemid=$item[itemid]]$language[supe_viewsnapshot][/url] \r\n";
$message .= "[*][b]$language[supe_urldescription]:[/b]\r\n";
$message .= supe_html2bbcode($item['message']);
$message .= '[/list]';
break;
default:
$special = 0;
}
$message_customfield = '';
if($item['customfieldid'] && $item['customfieldtext']) {
$customfielddata = unserialize($item['customfieldtext']);
$query = $supe['db']->query("SELECT name, customfieldtext FROM {$supe[tablepre]}customfields WHERE customfieldid='$item[customfieldid]'");
$querydata = $supe['db']->fetch_array($query);
$customfieldname = $querydata['name'];
$customfieldstruct = unserialize($querydata['customfieldtext']);
unset($querydata);
$len = count($customfieldstruct);
$message_customfield .= "[quote][b]{$customfieldname}[/b]:\r\n";
for($i = 0; $i < $len; $i++) {
switch($customfieldstruct[$i]['type']) {
case 'input':
case 'textarea':
case 'select':
$message_customfield .= "[*][b]{$customfieldstruct[$i][name]}[/b] : {$customfielddata[$i]} \r\n";
break;
case 'checkbox':
$message_customfield .= "[*][b]{$customfieldstruct[$i][name]}[/b] : ".join(',', $customfielddata[$i])."\r\n";
break;
}
}
unset($customfieldstruct, $customfieldname, $len);
$message_customfield .= "[/quote]\r\n";
}
$message_attachments = '';
if($item['haveattach']) {
$message_attachments = $item['type'] != 'file' ? "\r\n[b]$language[attach]:[/b]\r\n" : "[b]$language[supe_donwload_from_local]:[/b] \r\n";
$query = $supe['db']->query("SELECT aid, dateline, filename, subject, attachtype, isimage, size, filepath, thumbpath, downloads FROM {$supe[tablepre]}attachments WHERE hash='$item[hash]'");
while($attach = $supe['db']->fetch_array($query)) {
if($attach['isimage']) {
$attach['dateline'] = gmdate("$dateformat $timeformat", $attach['dateline'] + $timeoffset * 3600);
if($item['message'] && !preg_match("/src=\"[^\"]*".preg_quote($attach[filepath], '/')."\"/is", $item['message'])) {
$message_attachments .= "[url={$supe[siteurl]}/attachments/$attach[filepath]][img]{$supe[siteurl]}/attachments/{$attach[thumbpath]}[/img][/url]\r\n";
$message_attachments .= "[b]{$attach[subject]}[/b] [$language[supe_dateline]:$attach[dateline]]\r\n";
}
} else {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
$attach['dateline'] = gmdate("$dateformat $timeformat", $attach['dateline'] + $timeoffset * 3600);
$attach['filesize'] = sizecount($attach['filesize']);
$attach['filetype'] = supe_html2bbcode(attachtype(fileext($attach['attachment'])."\t".$attach['filetype']));
$message_attachments .= "$attach[filetype] [url={$supe[siteurl]}/batch.download.php?aid=$attach[aid]][b]{$attach[filename]}[/b][/url]\r\n";
$message_attachments .= "[$language[supe_dateline]:$attach[dateline] - $language[supe_download_count]:$attach[downloads]]\r\n";
}
}
}
$message .= $message_customfield.$message_attachments;
return $item;
}
function supe_html2bbcode($text) {
global $forum, $allowhtml;
require_once DISCUZ_ROOT.'./include/editor.func.php';
return $forum['allowhtml'] || $allowhtml ? $text : html2bbcode($text);
}
function supe_circlepermission($gid, $permission = 'allowshare') {
global $supe, $discuz_uid, $_DCOOKIE;
supe_dbconnect();
$query = $supe['db']->query("SELECT ispublic, allowshare, password FROM {$supe[tablepre]}groups WHERE gid='$gid' AND flag=1");
$circle = $supe['db']->fetch_array($query);
$incircle = $discuz_uid ? $supe['db']->result($supe['db']->query("SELECT COUNT(*) FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND gid='$gid' AND flag>0"), 0) : 0;
return $permission == 'allowshare' ? ($circle['allowshare'] && ($circle['ispublic'] == 1 || ($circle['ispublic'] == 2 && $circle['password'] == $_DCOOKIE['gidpw'.$gid]))) || $incircle : $incircle;
}
?> | zyyhong | trunk/jiaju001/bbs/include/supesite.func.php | PHP | asf20 | 8,228 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Technology Ltd.
This is NOT a freeware, use is subject to license terms
$Id: ec_credit.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function updatecreditcache($uid, $type, $return = 0) {
global $db, $tablepre;
$all = countcredit($uid, $type);
$halfyear = countcredit($uid, $type, 180);
$thismonth = countcredit($uid, $type, 30);
$thisweek = countcredit($uid, $type, 7);
$before = array(
'good' => $all['good'] - $halfyear['good'],
'soso' => $all['soso'] - $halfyear['soso'],
'bad' => $all['bad'] - $halfyear['bad'],
'total' => $all['total'] - $halfyear['total']
);
$data = array('all' => $all, 'before' => $before, 'halfyear' => $halfyear, 'thismonth' => $thismonth, 'thisweek' => $thisweek);
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$uid', '$type', '".addslashes(serialize($data))."', '".getexpiration()."')");
if($return) {
return $data;
}
}
function countcredit($uid, $type, $days = 0) {
global $timestamp, $db, $tablepre;
$type = $type == 'buyercredit' ? 1 : 0;
$timeadd = $days ? ("AND dateline>='".($timestamp - $days * 86400)."'") : '';
$query = $db->query("SELECT score FROM {$tablepre}tradecomments WHERE rateeid='$uid' AND type='$type' $timeadd");
$good = $soso = $bad = 0;
while($credit = $db->fetch_array($query)) {
if($credit['score'] == 1) {
$good++;
} elseif($credit['score'] == 0) {
$soso++;
} else {
$bad++;
}
}
return array('good' => $good, 'soso' => $soso, 'bad' => $bad, 'total' => $good + $soso + $bad);
}
function updateusercredit($uid, $type, $level) {
global $timestamp, $db, $tablepre;
$uid = intval($uid);
if(!$uid || !in_array($type, array('buyercredit', 'sellercredit')) || !in_array($level, array('good', 'soso', 'bad'))) {
return;
}
$query = $db->query("SELECT value, expiration FROM {$tablepre}spacecaches WHERE uid='$uid' AND variable='$type'");
if($cache = $db->fetch_array($query)) {
$expiration = $cache['expiration'];
$cache = unserialize($cache['value']);
} else {
$init = array('good' => 0, 'soso' => 0, 'bad' => 0, 'total' => 0);
$cache = array('all' => $init, 'before' => $init, 'halfyear' => $init, 'thismonth' => $init, 'thisweek' => $init);
$expiration = getexpiration();
}
foreach(array('all', 'before', 'halfyear', 'thismonth', 'thisweek') as $key) {
$cache[$key][$level]++;
$cache[$key]['total']++;
}
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$uid', '$type', '".addslashes(serialize($cache))."', '$expiration')");
$score = $level == 'good' ? 1 : ($level == 'soso' ? 0 : -1);
$db->query("UPDATE {$tablepre}memberfields SET $type=$type+($score) WHERE uid='$uid'");
}
function getexpiration() {
$date = getdate($GLOBALS['timestamp']);
return mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']) + 86400;
}
?> | zyyhong | trunk/jiaju001/bbs/include/ec_credit.func.php | PHP | asf20 | 3,054 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: xmlparser.class.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class XMLParser {
function getChildren($vals, &$i) {
$children = array();
if(isset($vals[$i]['value'])) {
$children['VALUE'] = $vals[$i]['value'];
}
while(++$i < count($vals)) {
switch($vals[$i]['type']) {
case 'cdata':
if(isset($children['VALUE'])) {
$children['VALUE'] .= $vals[$i]['value'];
} else {
$children['VALUE'] = $vals[$i]['value'];
}
break;
case 'complete':
if(isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']]) - 1;
if(isset($vals[$i]['value'])) {
$children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
} else {
$children[$vals[$i]['tag']][$index]['VALUE'] = '';
}
} else {
if(isset($vals[$i]['value'])) {
$children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
} else {
$children[$vals[$i]['tag']][]['VALUE'] = '';
}
}
break;
case 'open':
if(isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']]) - 1;
$children[$vals[$i]['tag']][$index] = array_merge($children[$vals[$i]['tag']][$index], $this->getChildren($vals, $i));
} else {
$children[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
}
break;
case 'close':
return $children;
}
}
}
function getXMLTree($data) {
$parser = xml_parser_create('UTF-8');
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $data, $vals, $index);
xml_parser_free($parser);
$tree = array();
$i = 0;
if(isset($vals[$i]['attributes'])) {
$tree[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($tree[$vals[$i]['tag']]) - 1;
$tree[$vals[$i]['tag']][$index] = array_merge($tree[$vals[$i]['tag']][$index], $this->getChildren($vals, $i));
} else {
$tree[$vals[$i]['tag']][] = $this->getChildren($vals, $i);
}
return $tree;
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/xmlparser.class.php | PHP | asf20 | 2,450 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: threadpay.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!isset($extcredits[$creditstrans])) {
showmessage('credits_transaction_disabled');
}
$query = $db->query("SELECT COUNT(*) AS payers, SUM(netamount) AS income FROM {$tablepre}paymentlog WHERE tid='$tid'");
$payment = $db->fetch_array($query);
$thread['payers'] = $payment['payers'];
$thread['netprice'] = !$maxincperthread || ($maxincperthread && $payment['income'] < $maxincperthread) ? floor($thread['price'] * (1 - $creditstax)) : 0;
$thread['creditstax'] = sprintf('%1.2f', $creditstax * 100).'%';
$thread['endtime'] = $maxchargespan ? gmdate("$dateformat $timeformat", $timestamp + $maxchargespan * 3600 + $timeoffset * 3600) : 0;
$query = $db->query("SELECT * FROM {$tablepre}posts WHERE tid='$tid' AND first='1' LIMIT 1");
$firstpost = $db->fetch_array($query);
$pid = $firstpost['pid'];
$thread['freemessage'] = '';
if(preg_match_all("/\[free\](.+?)\[\/free\]/is", $firstpost['message'], $matches)) {
foreach($matches[1] AS $match) {
$thread['freemessage'] .= discuzcode($match, $firstpost['smileyoff'], $firstpost['bbcodeoff'], sprintf('%00b', $firstpost['htmlon']), $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'], $forum['allowhtml'], 0).'<br />';
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/threadpay.inc.php | PHP | asf20 | 1,459 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: supesite_circle.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ') || !in_array(CURSCRIPT, array('forumdisplay', 'viewthread'))) {
exit('Access Denied');
}
supe_dbconnect();
if(CURSCRIPT == 'forumdisplay') {
$mycircles = $circle = array();
if($discuz_uid) {
$query = $supe['db']->query("SELECT gid, groupname FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND flag>0");
while($mycircle = $supe['db']->fetch_array($query)) {
$mycircles[$mycircle['gid']] = cutstr($mycircle['groupname'], 30);
}
}
if($sgids) {
$query = $supe['db']->query("SELECT gid, groupname FROM {$supe[tablepre]}groups WHERE gid IN (".implode(',', $sgids).") AND flag=1");
while($group = $supe['db']->fetch_array($query)) {
$circle[$group['gid']] = $group['groupname'];
}
}
$cachefile = DISCUZ_ROOT.'./forumdata/cache/cache_updatecircles.php';
if(@filemtime($cachefile) + 1800 < $timestamp) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('supe_updatecircles');
}
@require_once $cachefile;
if($_DCACHE['supe_updatecircles']) {
$circlenum = count($_DCACHE['supe_updatecircles']);
foreach($_DCACHE['supe_updatecircles'] AS $k => $v) {
$_DCACHE['supe_updatecircles'][$k]['lastpost'] = gmdate($dateformat.' H:i', $v['lastpost'] + ($timeoffset * 3600));
$_DCACHE['supe_updatecircles'][$k]['logo'] = $v['logo'] ? $supe['attachurl'].'/'.$v['logo'] : 'images/common/circle_logo.gif';
$_DCACHE['supe_updatecircles'][$k]['width'] = $circlenum < 4 ? (1 / $circlenum * 100).'%' : '25%';
}
}
} elseif(CURSCRIPT == 'viewthread') {
$sgid = $thread['sgid'];
$query = $supe['db']->query("SELECT g.groupname, g.ispublic, g.allowshare, g.password, gf.headerimage, gf.css FROM {$supe[tablepre]}groups g, {$supe[tablepre]}groupfields gf WHERE g.gid='$sgid' AND g.flag=1 AND g.gid=gf.gid");
if($circle = $supe['db']->fetch_array($query)) {
if($action == 'pwverify') {
if(md5($pw) != $circle['password']) {
showmessage('supe_pwverify', NULL, 'HALTED');
} else {
dsetcookie('gidpw'.$sgid, md5($pw));
showmessage('supe_pwpass', "viewthread.php?tid=$tid");
}
}
$incircle = 0;
if($discuz_uid) {
$query = $supe['db']->query("SELECT COUNT(*) FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND gid='$sgid' AND flag>0");
$incircle = $supe['db']->result($query, 0);
}
if($circle['ispublic'] == 2 && !$incircle && $circle['password'] != $_DCOOKIE['gidpw'.$sgid] && !$forum['ismoderator']) {
include template('supesite_viewthread_passwd');
exit();
}
if(!$circle['ispublic'] && !$incircle && !$forum['ismoderator']) {
showmessage('supe_permission_limit');
}
if(!$circle['allowshare'] && !$incircle) {
$allowreply = 0;
}
} else {
$db->query("UPDATE {$tablepre}threads SET sgid=0 WHERE tid='$tid'", 'UNBUFFERED');
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/supesite_circle.inc.php | PHP | asf20 | 3,640 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editor.func.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function absoluteurl($url) {
global $boardurl;
if($url{0} == '/') {
return 'http://'.$_SERVER['HTTP_HOST'].$url;
} else {
return $boardurl.$url;
}
}
function atag($aoptions, $text) {
$href = getoptionvalue('href', $aoptions);
if(substr($href, 0, 7) == 'mailto:') {
$tag = 'email';
$href = substr($href, 7);
} else {
$tag = 'url';
if(!preg_match("/^[a-z0-9]+:/i", $href)) {
$href = absoluteurl($href);
}
}
return "[$tag=$href]".trim(recursion('a', $text, 'atag'))."[/$tag]";
}
function divtag($divoptions, $text) {
$prepend = $append = '';
parsestyle($divoptions, $prepend, $append);
$align = getoptionvalue('align', $divoptions);
switch($align) {
case 'left':
case 'center':
case 'right':
break;
default:
$align = '';
}
if($align) {
$prepend .= "[align=$align]";
$append .= "[/align]";
}
$append .= "\n";
return $prepend.recursion('div', $text, 'divtag').$append;
}
function fetchoptionvalue($option, $text) {
if(($position = strpos($text, $option)) !== false) {
$delimiter = $position + strlen($option);
if($text{$delimiter} == '"') {
$delimchar = '"';
} elseif($text{$delimiter} == '\'') {
$delimchar = '\'';
} else {
$delimchar = ' ';
}
$delimloc = strpos($text, $delimchar, $delimiter + 1);
if($delimloc === false) {
$delimloc = strlen($text);
} elseif($delimchar == '"' OR $delimchar == '\'') {
$delimiter++;
}
return trim(substr($text, $delimiter, $delimloc - $delimiter));
} else {
return '';
}
}
function fonttag($fontoptions, $text) {
$tags = array('font' => 'face=', 'size' => 'size=', 'color' => 'color=');
$prependtags = $appendtags = '';
foreach($tags AS $bbcode => $locate) {
$optionvalue = fetchoptionvalue($locate, $fontoptions);
if($optionvalue) {
$prependtags .= "[$bbcode=$optionvalue]";
$appendtags = "[/$bbcode]$appendtags";
}
}
parsestyle($fontoptions, $prependtags, $appendtags);
return $prependtags.recursion('font', $text, 'fonttag').$appendtags;
}
function getoptionvalue($option, $text) {
preg_match("/$option(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)/is", $text, $matches);
return trim($matches[3]);
}
function html2bbcode($text) {
$text = strip_tags($text, '<table><tr><td><b><strong><i><em><u><a><div><span><p><strike><blockquote><ol><ul><li><font><img><br><br/><h1><h2><h3><h4><h5><h6><script>');
if(ismozilla()) {
$text = preg_replace("/(?<!<br>|<br \/>|\r)(\r\n|\n|\r)/", ' ', $text);
}
$pregfind = array(
"/<script.*>.*<\/script>/siU",
'/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i',
"/(\r\n|\n|\r)/",
"/<table([^>]*(width|background|background-color|bgcolor)[^>]*)>/siUe",
"/<table.*>/siU",
"/<tr.*>/siU",
"/<td>/i",
"/<td(.+)>/siUe",
"/<\/td>/i",
"/<\/tr>/i",
"/<\/table>/i",
'/<h([0-9]+)[^>]*>(.*)<\/h\\1>/siU',
"/<img[^>]+smilieid=\"(\d+)\".*>/esiU",
"/<img([^>]*src[^>]*)>/eiU",
"/<a\s+?name=.+?\".\">(.+?)<\/a>/is",
"/<br.*>/siU"
);
$pregreplace = array(
'',
'',
'',
"tabletag('\\1')",
'[table]',
'[tr]',
'[td]',
"tdtag('\\1')",
'[/td]',
'[/tr]',
'[/table]',
"[size=\\1]\\2[/size]\n\n",
"smileycode('\\1')",
"imgtag('\\1')",
'\1',
"\n"
);
$text = preg_replace($pregfind, $pregreplace, $text);
$text = recursion('b', $text, 'simpletag', 'b');
$text = recursion('strong', $text, 'simpletag', 'b');
$text = recursion('i', $text, 'simpletag', 'i');
$text = recursion('em', $text, 'simpletag', 'i');
$text = recursion('u', $text, 'simpletag', 'u');
$text = recursion('a', $text, 'atag');
$text = recursion('font', $text, 'fonttag');
$text = recursion('blockquote', $text, 'simpletag', 'indent');
$text = recursion('ol', $text, 'listtag');
$text = recursion('ul', $text, 'listtag');
$text = recursion('div', $text, 'divtag');
$text = recursion('span', $text, 'spantag');
$text = recursion('p', $text, 'ptag');
$pregfind = array("/(?<!\r|\n|^)\[(\/list|list|\*)\]/", "/<li>(.*)((?=<li>)|<\/li>)/iU", "/<p.*>/iU", "/<p><\/p>/i", "/(<a>|<\/a>|<\/li>)/is", "/<\/?(A|LI|FONT|DIV|SPAN)>/siU", "/\[url[^\]]*\]\[\/url\]/i", "/\[url=javascript:[^\]]*\](.+?)\[\/url\]/is");
$pregreplace = array("\n[\\1]", "\\1\n", "\n", '', '', '', '', "\\1");
$text = preg_replace($pregfind, $pregreplace, $text);
$strfind = array(' ', '<', '>', '&');
$strreplace = array(' ', '<', '>', '&');
$text = str_replace($strfind, $strreplace, $text);
return trim($text);
}
function imgtag($attributes) {
$value = array('src' => '', 'width' => '', 'height' => '');
preg_match_all("/(src|width|height)=([\"|\']?)([^\"']+)(\\2)/is", stripslashes($attributes), $matches);
if(is_array($matches[1])) {
foreach($matches[1] AS $key => $attribute) {
$value[strtolower($attribute)] = $matches[3][$key];
}
}
@extract($value);
if(!preg_match("/^http:\/\//i", $src)) {
$src = absoluteurl($src);
}
return $src ? ($width && $height ? '[img='.$width.','.$height.']'.$src.'[/img]' : '[img]'.$src.'[/img]') : '';
}
function ismozilla() {
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(strpos($useragent, 'gecko') !== FALSE) {
preg_match("/gecko\/(\d+)/", $useragent, $regs);
return $regs[1];
}
return FALSE;
}
function litag($listoptions, $text) {
return '[*]'.rtrim($text);
}
function listtag($listoptions, $text, $tagname) {
require_once DISCUZ_ROOT.'./include/post.func.php';
$text = preg_replace('/<li>((.(?!<\/li))*)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/siU', '<li>\\1</li>', $text).(isopera() ? '</li>' : NULL);
$text = recursion('li', $text, 'litag');
if($tagname == 'ol') {
$listtype = fetchoptionvalue('type=', $listoptions) ? fetchoptionvalue('type=', $listoptions) : 1;
if(in_array($listtype, array('1', 'a', 'A'))) {
$opentag = '[list='.$listtype.']';
}
} else {
$opentag = '[list]';
}
return $text ? $opentag.recursion($tagname, $text, 'listtag').'[/list]' : FALSE;
}
function parsestyle($tagoptions, &$prependtags, &$appendtags) {
$searchlist = array(
array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(left);?', 'match' => 1),
array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(center);?', 'match' => 1),
array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(right);?', 'match' => 1),
array('tag' => 'color', 'option' => TRUE, 'regex' => '(?<![a-z0-9-])color:\s*([^;]+);?', 'match' => 1),
array('tag' => 'font', 'option' => TRUE, 'regex' => 'font-family:\s*([^;]+);?', 'match' => 1),
array('tag' => 'size', 'option' => TRUE, 'regex' => 'font-size:\s*(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 'match' => 1),
array('tag' => 'b', 'option' => FALSE, 'regex' => 'font-weight:\s*(bold);?'),
array('tag' => 'i', 'option' => FALSE, 'regex' => 'font-style:\s*(italic);?'),
array('tag' => 'u', 'option' => FALSE, 'regex' => 'text-decoration:\s*(underline);?')
);
$style = getoptionvalue('style', $tagoptions);
$style = preg_replace(
"/(?<![a-z0-9-])color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/ie",
'sprintf("color: #%02X%02X%02X$4", $1, $2, $3)',
$style
);
foreach($searchlist AS $searchtag) {
if(preg_match('/'.$searchtag['regex'].'/i', $style, $match)) {
$opnvalue = $match["$searchtag[match]"];
$prependtags .= '['.$searchtag['tag'].($searchtag['option'] == TRUE ? '='.$opnvalue.']' : ']');
$appendtags = '[/'.$searchtag['tag']."]$appendtags";
}
}
}
function ptag($poptions, $text) {
$align = getoptionvalue('align', $poptions);
switch($align) {
case 'left':
case 'center':
case 'right':
break;
default:
$align = '';
}
$prepend = $append = '';
parsestyle($poptions, $prepend, $append);
if($align) {
$prepend .= "[align=$align]";
$append .= "[/align]";
}
$append .= "\n";
return $prepend.recursion('p', $text, 'ptag').$append;
}
function recursion($tagname, $text, $function, $extraargs = '') {
$tagname = strtolower($tagname);
$open_tag = "<$tagname";
$open_tag_len = strlen($open_tag);
$close_tag = "</$tagname>";
$close_tag_len = strlen($close_tag);
$beginsearchpos = 0;
do {
$textlower = strtolower($text);
$tagbegin = @strpos($textlower, $open_tag, $beginsearchpos);
if($tagbegin === FALSE) {
break;
}
$strlen = strlen($text);
$inquote = '';
$found = FALSE;
$tagnameend = FALSE;
for($optionend = $tagbegin; $optionend <= $strlen; $optionend++) {
$char = $text{$optionend};
if(($char == '"' || $char == "'") && $inquote == '') {
$inquote = $char;
} elseif(($char == '"' || $char == "'") && $inquote == $char) {
$inquote = '';
} elseif($char == '>' && !$inquote) {
$found = TRUE;
break;
} elseif(($char == '=' || $char == ' ') && !$tagnameend) {
$tagnameend = $optionend;
}
}
if(!$found) {
break;
}
if(!$tagnameend) {
$tagnameend = $optionend;
}
$offset = $optionend - ($tagbegin + $open_tag_len);
$tagoptions = substr($text, $tagbegin + $open_tag_len, $offset);
$acttagname = substr($textlower, $tagbegin + 1, $tagnameend - $tagbegin - 1);
if($acttagname != $tagname) {
$beginsearchpos = $optionend;
continue;
}
$tagend = strpos($textlower, $close_tag, $optionend);
if($tagend === FALSE) {
break;
}
$nestedopenpos = strpos($textlower, $open_tag, $optionend);
while($nestedopenpos !== FALSE && $tagend !== FALSE) {
if($nestedopenpos > $tagend) {
break;
}
$tagend = strpos($textlower, $close_tag, $tagend + $close_tag_len);
$nestedopenpos = strpos($textlower, $open_tag, $nestedopenpos + $open_tag_len);
}
if($tagend === FALSE) {
$beginsearchpos = $optionend;
continue;
}
$localbegin = $optionend + 1;
$localtext = $function($tagoptions, substr($text, $localbegin, $tagend - $localbegin), $tagname, $extraargs);
$text = substr_replace($text, $localtext, $tagbegin, $tagend + $close_tag_len - $tagbegin);
$beginsearchpos = $tagbegin + strlen($localtext);
} while($tagbegin !== FALSE);
return $text;
}
function simpletag($options, $text, $tagname, $parseto) {
if(trim($text) == '') {
return '';
}
$text = recursion($tagname, $text, 'simpletag', $parseto);
return "[$parseto]{$text}[/$parseto]";
}
function smileycode($smileyid) {
global $_DCACHE;
if(!is_array($_DCACHE['smilies_display'])) {
@include DISCUZ_ROOT.'./forumdata/cache/cache_post.php';
}
foreach($_DCACHE['smilies_display'] AS $typeid => $smilies) {
if(is_array($smilies)) {
foreach($smilies AS $key => $smiley) {
if($smileyid == $key) {
return $smiley['code'];
}
}
}
}
}
function spantag($spanoptions, $text) {
$prependtags = $appendtags = '';
parsestyle($spanoptions, $prependtags, $appendtags);
return $prependtags.recursion('span', $text, 'spantag').$appendtags;
}
function tabletag($attributes) {
$attributes = stripslashes($attributes);
$width = '';
if(preg_match("/width=([\"|\']?)(\d{1,4}%?)(\\1)/is", $attributes, $matches)) {
$width = substr($matches[2], -1) == '%' ? (substr($matches[2], 0, -1) <= 98 ? $matches[2] : '98%') : ($matches[2] <= 560 ? $matches[2] : '560');
} elseif(preg_match("/width\s?:\s?(\d{1,4})([px|%])/is", $attributes, $matches)) {
$width = $matches[2] == '%' ? ($matches[1] <= 98 ? $matches[1] : '98%') : ($matches[1] <= 560 ? $matches[1] : '560');
}
if(preg_match("/(?:background|background-color|bgcolor)[:=]\s*([\"']?)((rgb\(\d{1,3}%?,\s*\d{1,3}%?,\s*\d{1,3}%?\))|(#[0-9a-fA-F]{3,6})|([a-zA-Z]{1,20}))(\\1)/i", $attributes, $matches)) {
$bgcolor = $matches[2];
$width = $width ? $width : '98%';
} else {
$bgcolor = '';
}
return $bgcolor ? "[table=$width,$bgcolor]" :($width ? "[table=$width]" : '[table]');
}
function tdtag($attributes) {
$value = array('colspan' => 1, 'rowspan' => 1, 'width' => '');
preg_match_all("/(colspan|rowspan|width)=([\"|\']?)(\d{1,4}%?)(\\2)/is", stripslashes($attributes), $matches);
if(is_array($matches[1])) {
foreach($matches[1] AS $key => $attribute) {
$value[strtolower($attribute)] = $matches[3][$key];
}
}
@extract($value);
return $width == '' ? ($colspan == 1 && $rowspan == 1 ? '[td]' : "[td=$colspan,$rowspan]") : "[td=$colspan,$rowspan,$width]";
}
?> | zyyhong | trunk/jiaju001/bbs/include/editor.func.php | PHP | asf20 | 12,730 |
var theform = $('insenz_regform');
function validate() {
return checkusername(theform.username.value)
&& checkpassword(theform.password.value, theform.password2.value)
&& checkname(theform.name.value)
&& checkidcard(theform.idcard.value)
&& checkemail(theform.email1.value, 'email1')
&& (theform.email2.value ? checkemail(theform.email2.value, 'email2') : true)
&& checkqq(theform.qq.value)
&& checktel(theform.tel1.value, theform.tel2.value, theform.tel3.value, '电话号码')
&& (theform.fax2.value ? checktel(theform.fax1.value, theform.fax2.value, theform.fax3.value, '传真号码') : true)
&& (theform.msn.value ? checkemail(theform.msn.value, 'msn') : true)
&& checkmobile(theform.mobile.value)
&& checkcpc(theform.country.value, theform.province.value, theform.city.value)
&& checkaddress(theform.address.value)
&& checkpostcode(theform.postcode.value)
&& checkemail(theform.alipay.value, 'alipay');
}
function checkusername(username) {
username = trim(username);
if(mb_strlen(username) < 4 || mb_strlen(username) > 20) {
return dalert('用户名长度不少于 4 字节不超过 20 字节!请重新填写', theform.username);
} else if(!preg_match(/^\w+$/i, username)) {
return dalert('用户名不合法!请重新填写', theform.username);
}
return true;
}
function checkpassword(password, password2) {
if(mb_strlen(password) < 6 || mb_strlen(password) > 20) {
return dalert('密码长度范围 6~20!请重新填写', theform.password);
} else if(!preg_match(/^\w+$/i, password)) {
return dalert('密码不能包含特殊字符!请重新填写', theform.password);
} else if(password != password2) {
return dalert('两次输入的密码不一致!请重新填写', theform.password2);
}
return true;
}
function checkname(name) {
name = trim(name);
if(mb_strlen(name) < 4 || mb_strlen(name) > 30) {
return dalert('姓名长度不少于 4 字节不超过 30 字节!请重新填写', theform.name);
}
return true;
}
function checkemail(email, en) {
email = trim(email);
if(mb_strlen(email) < 7 || !preg_match(/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/, email)) {
var s = {'email1':'E-mail','email2':'备用 E-mail','msn':'MSN','alipay':'支付宝帐号'};
return dalert(s[en] + ' 不合法!请重新填写', en == 'email1' ? theform.email1 : (en == 'email2' ? theform.email2 : (en == 'msn' ? theform.msn : theform.alipay)));
}
return true;
}
function checkidcard(idcard) {
idcard = trim(idcard);
len = mb_strlen(idcard);
if(len == 18 && preg_match(/^\d{17}[\dX]$/i, idcard)) {
return true;
}
return dalert('身份证号码不合法!请重新填写', theform.idcard);
}
function checktel(tel1, tel2, tel3, telname) {
if(!preg_match(/^\d{2,4}$/, tel1) || !preg_match(/^\d{5,10}$/, tel2) || (tel3 && tel3 != '分机号码' && !preg_match(/^\d{1,5}$/, tel3))) {
return dalert(telname + ' 不合法!请重新填写', theform.tel1);
}
return true;
}
function checkqq(qq) {
if(!(preg_match(/^([0-9]+)$/, qq) && mb_strlen(qq) >= 5 && mb_strlen(qq) <= 12)) {
return dalert('QQ 号码不合法!请重新填写', theform.qq);
}
return true;
}
function checkmobile(mobile) {
if(!preg_match(/^1(3|5)\d{9}$/, mobile)) {
return dalert('手机号码不合法!请重新填写', theform.mobile);
}
return true;
}
function checkcpc(country, province, city) {
country = parseInt(country);
if(country < 10000 || country > 70300) {
return dalert('请选择国家!', theform.country);
}
province = parseInt(province);
if(country == 10000 && (province < 10100 || province > 13100)) {
return dalert('请选择省份!', theform.province);
}
city = parseInt(city);
if(country == 10000 && (city < 10101 || city > 13107)) {
return dalert('请选择城市!', theform.city);
}
return true;
}
function checkaddress(address) {
address = trim(address);
if(mb_strlen(address) < 8) {
return dalert('请填写您的真实地址!', theform.address);
}
return true;
}
function checkpostcode(postcode) {
if(!preg_match(/^\d{6}$/, postcode)) {
return dalert('邮政编码不合法!请重新填写', theform.postcode);
}
return true;
}
function preg_match(re, str) {
var matches = re.exec(str);
return matches != null;
}
function dalert(str, focusobj) {
alert(str);
focusobj.focus();
return false;
} | zyyhong | trunk/jiaju001/bbs/include/javascript/insenz_reg.js | JavaScript | asf20 | 4,447 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: common.js,v $
$Revision: 1.103 $
$Date: 2007/07/30 09:16:52 $
*/
var lang = new Array();
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function $(id) {
return document.getElementById(id);
}
Array.prototype.push = function(value) {
this[this.length] = value;
return this.length;
}
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name && e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
e.checked = form.elements[checkall].checked;
}
}
}
function doane(event) {
e = event ? event : window.event;
if(is_ie) {
e.returnValue = false;
e.cancelBubble = true;
} else if(e) {
e.stopPropagation();
e.preventDefault();
}
}
function fetchCheckbox(cbn) {
return $(cbn) && $(cbn).checked == true ? 1 : 0;
}
function getcookie(name) {
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function thumbImg(obj) {
var zw = obj.width;
var zh = obj.height;
if(is_ie && zw == 0 && zh == 0) {
var matches
re = /width=(["']?)(\d+)(\1)/i
matches = re.exec(obj.outerHTML);
zw = matches[2];
re = /height=(["']?)(\d+)(\1)/i
matches = re.exec(obj.outerHTML);
zh = matches[2];
}
obj.resized = true;
obj.style.width = zw + 'px';
obj.style.height = 'auto';
if(obj.offsetHeight > zh) {
obj.style.height = zh + 'px';
obj.style.width = 'auto';
}
if(is_ie) {
var imgid = 'img_' + Math.random();
obj.id = imgid;
setTimeout('try {if ($(\''+imgid+'\').offsetHeight > '+zh+') {$(\''+imgid+'\').style.height = \''+zh+'px\';$(\''+imgid+'\').style.width = \'auto\';}} catch(e){}', 1000);
}
obj.onload = null;
}
function imgzoom(obj) {}
function in_array(needle, haystack) {
if(typeof needle == 'string' || typeof needle == 'number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function setcopy(text, alertmsg){
if(is_ie) {
clipboardData.setData('Text', text);
alert(alertmsg);
} else if(prompt('Press Ctrl+C Copy to Clipboard', text)) {
alert(alertmsg);
}
}
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
}
return len;
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
expires.setTime(expires.getTime() + seconds);
document.cookie = escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function strlen(str) {
return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
function updatestring(str1, str2, clear) {
str2 = '_' + str2 + '_';
return clear ? str1.replace(str2, '') : (str1.indexOf(str2) == -1 ? str1 + str2 : str1);
}
function toggle_collapse(objname, noimg) {
var obj = $(objname);
obj.style.display = obj.style.display == '' ? 'none' : '';
if(!noimg) {
var img = $(objname + '_img');
img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif')
}
var collapsed = getcookie('discuz_collapse');
collapsed = updatestring(collapsed, objname, !obj.style.display);
setcookie('discuz_collapse', collapsed, (collapsed ? 86400 * 30 : -(86400 * 30 * 1000)));
}
function trim(str) {
return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function updateseccode() {
type = seccodedata[2];
var rand = Math.random();
if(type == 2) {
$('seccodeimage').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + seccodedata[0] + '" height="' + seccodedata[1] + '" align="middle">'
+ '<param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="seccode.php?update=' + rand + '" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" />'
+ '<embed src="seccode.php?update=' + rand + '" quality="high" wmode="transparent" bgcolor="#ffffff" width="' + seccodedata[0] + '" height="' + seccodedata[1] + '" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
} else {
$('seccodeimage').innerHTML = '<img id="seccode" onclick="updateseccode()" width="' + seccodedata[0] + '" height="' + seccodedata[1] + '" src="seccode.php?update=' + rand + '" class="absmiddle" alt="" />';
}
}
function updatesecqaa() {
var x = new Ajax();
x.get('ajax.php?action=updatesecqaa&inajax=1', function(s) {
$('secquestion').innerHTML = s;
});
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/common.js | JavaScript | asf20 | 5,963 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: floatadv.js,v $
$Revision: 1.5 $
$Date: 2007/06/01 22:31:15 $
*/
var delta=0.15;
var collection;
var closeB=false;
function floaters() {
this.items = [];
this.addItem = function(id,x,y,content) {
document.write('<div id=' + id + ' style="z-index: 10; position: absolute; width:' + (document.body.clientWidth - (typeof(x) == 'string' ? eval(x) : x)*2) + 'px; left:' + (typeof(x) == 'string' ? eval(x) : x) + ';top:' + (typeof(y) == 'string'? eval(y) : y) + '">' + content + '</div>');
var newItem = {};
newItem.object = document.getElementById(id);
newItem.x = x;
newItem.y = y;
this.items[this.items.length] = newItem;
}
this.play = function() {
collection = this.items;
setInterval('play()',30);
}
}
function play() {
if(screen.width <= 800 || closeB) {
for(var i = 0;i < collection.length;i++) {
collection[i].object.style.display = 'none';
}
return;
}
for(var i = 0;i < collection.length;i++) {
var followObj = collection[i].object;
var followObj_x = (typeof(collection[i].x) == 'string' ? eval(collection[i].x) : collection[i].x);
var followObj_y = (typeof(collection[i].y) == 'string' ? eval(collection[i].y) : collection[i].y);
if(followObj.offsetLeft != (document.documentElement.scrollLeft + followObj_x)) {
var dx = (document.documentElement.scrollLeft + followObj_x - followObj.offsetLeft) * delta;
dx = (dx > 0 ? 1 : -1) * Math.ceil(Math.abs(dx));
followObj.style.left = (followObj.offsetLeft + dx) + 'px';
}
if(followObj.offsetTop != (document.documentElement.scrollTop + followObj_y)) {
var dy = (document.documentElement.scrollTop + followObj_y - followObj.offsetTop) * delta;
dy = (dy > 0 ? 1 : -1) * Math.ceil(Math.abs(dy));
followObj.style.top = (followObj.offsetTop + dy) + 'px';
}
followObj.style.display = '';
}
}
function closeBanner() {
closeB = true;
return;
}
var theFloaters = new floaters(); | zyyhong | trunk/jiaju001/bbs/include/javascript/floatadv.js | JavaScript | asf20 | 2,058 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: tree.js,v $
$Revision: 1.17 $
$Date: 2007/06/25 17:56:32 $
*/
var icon = new Object();
icon.root = IMGDIR + '/tree_root.gif';
icon.folder = IMGDIR + '/tree_folder.gif';
icon.folderOpen = IMGDIR + '/tree_folderopen.gif';
icon.file = IMGDIR + '/tree_file.gif';
icon.empty = IMGDIR + '/tree_empty.gif';
icon.line = IMGDIR + '/tree_line.gif';
icon.lineMiddle = IMGDIR + '/tree_linemiddle.gif';
icon.lineBottom = IMGDIR + '/tree_linebottom.gif';
icon.plus = IMGDIR + '/tree_plus.gif';
icon.plusMiddle = IMGDIR + '/tree_plusmiddle.gif';
icon.plusBottom = IMGDIR + '/tree_plusbottom.gif';
icon.minus = IMGDIR + '/tree_minus.gif';
icon.minusMiddle = IMGDIR + '/tree_minusmiddle.gif';
icon.minusBottom = IMGDIR + '/tree_minusbottom.gif';
function treeNode(id, pid, name, url, target, open) {
//public
var obj = new Object();
obj.id = id;
obj.pid = pid;
obj.name = name;
obj.url = url;
obj.target = target;
obj.open = open;
//private
obj._isOpen = open;
obj._lastChildId = 0;
obj._pid = 0;
return obj;
}
function dzTree(treeName) {
this.nodes = new Array();
this.openIds = getcookie('discuz_leftmenu_openids');
this.pushNodes = new Array();
this.addNode = function(id, pid, name, url, target, open) {
var theNode = new treeNode(id, pid, name, url, target, open);
this.pushNodes.push(id);
if(!this.nodes[pid]) {
this.nodes[pid] = new Array();
}
this.nodes[pid]._lastChildId = id;
for(k in this.nodes) {
if(this.openIds && this.openIds.indexOf('_' + theNode.id) != -1) {
theNode._isOpen = true;
}
if(this.nodes[k].pid == id) {
theNode._lastChildId = this.nodes[k].id;
}
}
this.nodes[id] = theNode;
}
this.show = function() {
var s = '<div class="tree">';
s += this.createTree(this.nodes[0]);
s += '</div>';
document.write(s);
}
this.createTree = function(node, padding) {
padding = padding ? padding : '';
if(node.id == 0){
var icon1 = '';
} else {
var icon1 = '<img src="' + this.getIcon1(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon1_' + node.id + '" style="cursor: pointer;">';
}
var icon2 = '<img src="' + this.getIcon2(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon2_' + node.id + '" style="cursor: pointer;">';
var s = '<div class="node" id="node_' + node.id + '">' + padding + icon1 + icon2 + this.getName(node) + '</div>';
s += '<div class="nodes" id="nodes_' + node.id + '" style="display:' + (node._isOpen ? '' : 'none') + '">';
for(k in this.pushNodes) {
var id = this.pushNodes[k];
var theNode = this.nodes[id];
if(theNode.pid == node.id) {
if(node.id == 0){
var thePadding = '';
} else {
var thePadding = padding + (node.id == this.nodes[node.pid]._lastChildId ? '<img src="' + icon.empty + '">' : '<img src="' + icon.line + '">');
}
if(!theNode._lastChildId) {
var icon1 = '<img src="' + this.getIcon1(theNode) + '"' + ' id="icon1_' + theNode.id + '">';
var icon2 = '<img src="' + this.getIcon2(theNode) + '" id="icon2_' + theNode.id + '">';
s += '<div class="node" id="node_' + theNode.id + '">' + thePadding + icon1 + icon2 + this.getName(theNode) + '</div>';
} else {
s += this.createTree(theNode, thePadding);
}
}
}
s += '</div>';
return s;
}
this.getIcon1 = function(theNode) {
var parentNode = this.nodes[theNode.pid];
var src = '';
if(theNode._lastChildId) {
if(theNode._isOpen) {
if(theNode.id == 0) {
return icon.minus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.minusBottom;
} else {
src = icon.minusMiddle;
}
} else {
if(theNode.id == 0) {
return icon.plus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.plusBottom;
} else {
src = icon.plusMiddle;
}
}
} else {
if(theNode.id == parentNode._lastChildId) {
src = icon.lineBottom;
} else {
src = icon.lineMiddle;
}
}
return src;
}
this.getIcon2 = function(theNode) {
var src = '';
if(theNode.id == 0 ) {
return icon.root;
}
if(theNode._lastChildId) {
if(theNode._isOpen) {
src = icon.folderOpen;
} else {
src = icon.folder;
}
} else {
src = icon.file;
}
return src;
}
this.getName = function(theNode) {
if(theNode.url) {
return '<a href="'+theNode.url+'" target="' + theNode.target + '"> '+theNode.name+'</a>';
} else {
return theNode.name;
}
}
this.switchDisplay = function(nodeId) {
eval('var theTree = ' + treeName);
var theNode = theTree.nodes[nodeId];
if($('nodes_' + nodeId).style.display == 'none') {
theTree.openIds = updatestring(theTree.openIds, nodeId);
setcookie('discuz_leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = true;
$('nodes_' + nodeId).style.display = '';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
} else {
theTree.openIds = updatestring(theTree.openIds, nodeId, true);
setcookie('discuz_leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = false;
$('nodes_' + nodeId).style.display = 'none';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
}
}
} | zyyhong | trunk/jiaju001/bbs/include/javascript/tree.js | JavaScript | asf20 | 5,575 |
/*
[Discuz!] (C)2001-2006 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: drag_space.js,v $
$Revision: 1.20 $
$Date: 2007/05/29 14:43:29 $
*/
function Space_Memcp() {
this.init = function() {
Drag.rootTable = $("parentTable");
Drag.mozinit();
}
this.dragStart = function() {
}
this.onDrag = function(tX, tY) {
for(var i = 0; i < Drag.rootTable.cells.length; i++) {
var parentCell = Drag.getInfo(Drag.rootTable.cells[i]);
if(tX >= parentCell.left && tX <= parentCell.right && tY >= parentCell.top && tY <= parentCell.bottom) {
var layouti = Drag.rootTable.cells[i].id.replace('main_layout', '');
if((',' + Drag.disable + ',').indexOf(',' + layouti + ',') != -1) {
return;
}
var subTables = Drag.rootTable.cells[i].getElementsByTagName("DIV");
if(subTables.length == 0) {
if(tX >= parentCell.left && tX <= parentCell.right && tY >= parentCell.top && tY <= parentCell.bottom) {
Drag.rootTable.cells[i].appendChild(Drag.obj);
Drag.handler.resize();
}
break;
}
Drag.layout = layouti;
for(var j = 0; j < subTables.length; j++) {
var subTable = Drag.getInfo(subTables[j]);
if(tX >= subTable.left && tX <= subTable.right && tY >= subTable.top && tY <= subTable.bottom) {
Drag.rootTable.cells[i].insertBefore(Drag.obj, subTables[j]);
Drag.handler.resize();
break;
} else {
Drag.rootTable.cells[i].appendChild(Drag.obj);
Drag.handler.resize();
}
}
}
}
}
this.dragEnd = function() {
var pid = Drag.obj;
do {
if(!pid.previousSibling) {
pid = pid.parentNode;
break;
}
pid = pid.previousSibling;
} while(pid.tagName != 'DIV');
pid = pid.id;
if(Drag.layout != null) {
Drag.handler.clearResult(Drag.obj);
if(layout[Drag.layout].indexOf(pid) != -1) {
layout[Drag.layout] = layout[Drag.layout].replace('[' + pid + ']', '[' + pid + '][' + Drag.obj.id + ']');
} else {
layout[Drag.layout] = '[' + Drag.obj.id + '][' + layout[Drag.layout] + ']';
}
Drag.handler.trimResult();
}
}
this.resize = function() {
Drag.tdiv.style.width = Drag.obj.offsetWidth + 'px';
}
this.del = function(obj) {
try {
if($('check_' + obj.id)) {
$('check_' + obj.id).checked = false;
$('menuitem_' + obj.id).style.display = 'none';
}
} catch (e) {}
Drag.handler.clearResult(obj);
Drag.handler.trimResult();
obj.parentNode.removeChild(obj);
}
this.add = function(layoutn, divid, title, disable) {
var clone = $('dragClone').innerHTML;
layoutid = 'main_layout' + layoutn;
if($(layoutid).style.display == 'none') {
if(layoutn == 2) {
layoutn = 0;
} else if(layoutn == 0) {
layoutn = 2;
}
layoutid = 'main_layout' + layoutn;
}
clone = clone.replace(/\[id\]/g, divid);
clone = clone.replace(/\[title\]/g, title);
clone = clone.replace('[disable]', disable);
$(layoutid).innerHTML += clone;
layout[layoutn] += '[' + divid + ']';
Drag.handler.trimResult();
}
this.check = function(layoutn, divid, title, disable) {
var exist = 0;
for (var side in layout) {
var s = ']' + layout[side] + '[';
s = s.split('][');
for (var i in s) {
if(s[i] == divid) {
exist = 1;break;
}
}
}
try {
if(exist) {
Drag.handler.del($(divid));
$('menuitem_' + divid).style.display = 'none';
} else {
Drag.handler.add(layoutn, divid, title, disable);
$('menuitem_' + divid).style.display = '';
}
} catch(e) {}
}
this.clearResult = function(o) {
for(i = 0; i < layout.length; i++) {
layout[i] = layout[i].replace('[' + o.id + ']', '');
}
}
this.trimResult = function() {
for(i = 0; i < layout.length; i++) {
layout[i] = layout[i].replace('[]', '');
layout[i] = layout[i].replace('[[', '[');
layout[i] = layout[i].replace(']]', ']');
}
}
}
function clearSide(side) {
if(side == 0) {
targetside = 2;
} else if(side == 2) {
targetside = 0;
} else {
return;
}
targetcellid = 'main_layout' + targetside;
layout[targetside] += layout[side];
var s = ']' + layout[side] + '[';
s = s.split('][');
for (var i in s) {
if(s[i] != '') {
$(targetcellid).appendChild($(s[i]));
}
}
layout[side] = '';
}
function leftSide() {
$('main_layout0').style.display = '';
$('main_layout2').style.display = 'none';
$('side_1').checked = true;
tmp_spaceside = 1;
clearSide(2);
Drag.mozinit();
}
function rightSide() {
$('main_layout0').style.display = 'none';
$('main_layout2').style.display = '';
$('side_2').checked = true;
tmp_spaceside = 2;
clearSide(0);
Drag.mozinit();
}
function bothSide() {
$('main_layout0').style.display = '';
$('main_layout2').style.display = '';
$('side_0').checked = true;
tmp_spaceside = 0;
Drag.mozinit();
}
function setStyle(styledir, stylename) {
$('style_' + styledir).checked = true;
$('stylecss').href = '';
$('stylecss').href = 'mspace/' + styledir + '/style.css';
tmp_styledir = styledir;
if(is_ie) {
$('stylecss').onload = setStyleonLoad;
}
}
function setStyleonLoad() {
var obj = document.styleSheets['stylecss'].rules;
for (i in obj) {
if(obj[i].selectorText == '#menu_top' && obj[i].style.width) {
$('menu_top').style.width = obj[i].style.width;
}
if(obj[i].selectorText == '#header' && obj[i].style.width) {
$('header').style.width = obj[i].style.width;
}
if(obj[i].selectorText == '#header DIV.bg' && obj[i].style.width) {
$('headerbg').style.width = obj[i].style.width;
}
if(obj[i].selectorText == '#menu' && obj[i].style.width) {
$('menu').style.width = obj[i].style.width;
}
if(obj[i].selectorText == '.outer' && obj[i].style.width) {
$('outer').style.width = obj[i].style.width;
}
if(obj[i].selectorText == '#footer' && obj[i].style.width) {
$('footer').style.width = obj[i].style.width;
}
}
}
function saveLayout() {
if(layout[1] == '') {
alert(space_layout_nocenter);
} else {
$('spacelayout0').value = layout[0];
$('spacelayout1').value = layout[1];
$('spacelayout2').value = layout[2];
$('dragform').submit();
}
}
function previewLayout(uid) {
if(layout[0] == '') {
tmp_spaceside = 2;
}
if(layout[2] == '') {
tmp_spaceside = 1;
}
window.open('space.php?uid=' + uid + '&preview=' + layout[0] + '|' + layout[1] + '|' + layout[2] + '&spaceside=' + tmp_spaceside + '&style=' + tmp_styledir, '', '');
}
function previewtext(obj, text) {
if(obj == 'pre_title' && text == '') {
text = $('pre_title_default').innerHTML;
}
$(obj).innerHTML = htmlspecialchars(text);
}
function checkinit(module) {
try {
if($('check_' + module)) {
$('check_' + module).checked = true;
$('menuitem_' + module).style.display = '';
}
} catch(e) {}
} | zyyhong | trunk/jiaju001/bbs/include/javascript/drag_space.js | JavaScript | asf20 | 6,965 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: post_attach.js,v $
$Revision: 1.7 $
$Date: 2007/06/04 21:58:23 $
*/
var aid = 1;
var attachexts = new Array();
var attachwh = new Array();
function delAttach(id) {
$('attachbody').removeChild($('attach_' + id).parentNode.parentNode);
$('attachbody').innerHTML == '' && addAttach();
$('localimgpreview_' + id + '_menu') ? document.body.removeChild($('localimgpreview_' + id + '_menu')) : null;
}
function addAttach() {
newnode = $('attachbodyhidden').firstChild.cloneNode(true);
var id = aid;
var tags;
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach[]') {
tags[i].id = 'attach_' + id;
tags[i].onchange = function() {insertAttach(id)};
tags[i].unselectable = 'on';
}
if(tags[i].name == 'localid[]') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile[]') {
tags[i].id = 'localfile_' + id;
}
}
aid++;
$('attachbody').appendChild(newnode);
}
addAttach();
function insertAttach(id) {
var localimgpreview = '';
var path = $('attach_' + id).value;
var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert(lang['post_attachment_ext_notallowed']);
return;
}
attachexts[id] = is_ie && in_array(ext, ['gif', 'jpg', 'png', 'bmp']) && typeof supe == 'undefined' ? 2 : 1;
if(attachexts[id] == 2) {
$('img_hidden').alt = id;
$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'image';
try {
$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $('attach_' + id).value;
} catch (e) {
alert(lang['post_attachment_img_invalid']);
return;
}
var wh = {'w' : $('img_hidden').offsetWidth, 'h' : $('img_hidden').offsetHeight};
var aid = $('img_hidden').alt;
if(wh['w'] >= thumbwidth || wh['h'] >= thumbheight) {
wh = attachthumbImg(wh['w'], wh['h']);
}
attachwh[id] = wh;
$('img_hidden').style.width = wh['w']
$('img_hidden').style.height = wh['h'];
$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'scale';
div = document.createElement('div');
div.id = 'localimgpreview_' + id + '_menu';
div.style.display = 'none';
div.style.marginLeft = '20px';
div.className = 'popupmenu_popup';
document.body.appendChild(div);
div.innerHTML = '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + $('attach_' + id).value+'\');width:'+wh['w']+';height:'+wh['h']+'" src=\'images/common/none.gif\' border="0" aid="attach_'+ aid +'" alt="" />';
}
$('localfile_' + id).innerHTML = '<a href="###delAttach" onclick="delAttach(' + id + ')">[' + lang['post_attachment_deletelink'] + ']</a> <a href="###insertAttach" title="' + lang['post_attachment_insert'] + '" onclick="insertAttachtext(' + id + ');return false;">[' + lang['post_attachment_insertlink'] + ']</a> ' +
(attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showMenu(this.id, 0, 0, 1, 0)"> <span class="smalltxt">[' +id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ');return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);
$('attach_' + id).style.display = 'none';
addAttach();
}
function attachpreview(obj, preview, width, height) {
if(is_ie) {
$(preview + '_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'image';
try {
$(preview + '_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = obj.value;
} catch (e) {
alert(lang['post_attachment_img_invalid']);
return;
}
var wh = {'w' : $(preview + '_hidden').offsetWidth, 'h' : $(preview + '_hidden').offsetHeight};
var aid = $(preview + '_hidden').alt;
if(wh['w'] >= width || wh['h'] >= height) {
wh = attachthumbImg(wh['w'], wh['h'], width, height);
}
$(preview + '_hidden').style.width = wh['w']
$(preview + '_hidden').style.height = wh['h'];
$(preview + '_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'scale';
$(preview).style.width = 'auto';
$(preview).innerHTML = '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + obj.value+'\');width:'+wh['w']+';height:'+wh['h']+'" src=\'images/common/none.gif\' border="0" alt="" />';
}
}
function insertAttachtext(id) {
if(!attachexts[id]) {
return;
}
if(attachexts[id] == 2) {
bbinsert && wysiwyg ? insertText($('localimgpreview_' + id + '_menu').innerHTML, false) : AddText('[localimg=' + attachwh[id]['w'] + ',' + attachwh[id]['h'] + ']' + id + '[/localimg]');
} else {
bbinsert && wysiwyg ? insertText('[local]' + id + '[/local]', false) : AddText('[local]' + id + '[/local]');
}
}
function attachthumbImg(w, h, twidth, theight) {
twidth = !twidth ? thumbwidth : twidth;
theight = !theight ? thumbheight : theight;
var x_ratio = twidth / w;
var y_ratio = theight / h;
var wh = new Array();
if((x_ratio * h) < theight) {
wh['h'] = Math.ceil(x_ratio * h);
wh['w'] = twidth;
} else {
wh['w'] = Math.ceil(y_ratio * w);
wh['h'] = theight;
}
return wh;
}
function restore(aid) {
obj = $('attach'+aid);
objupdate = $('attachupdate'+aid);
obj.style.display = '';
objupdate.innerHTML = '';
}
function attachupdate(aid) {
obj = $('attach'+aid);
objupdate = $('attachupdate'+aid);
obj.style.display = 'none';
objupdate.innerHTML = '<input type="file" name="attachupdate[paid' + aid + ']" size="15"> <input class="button" type="button" value="' + lang['cancel'] + '" onclick="restore(\'' + aid + '\')">';
}
function insertAttachTag(aid) {
if(bbinsert && wysiwyg) {
insertText('[attach]' + aid + '[/attach]', false);
} else {
AddText('[attach]' + aid + '[/attach]');
}
}
function insertAttachimgTag(aid) {
if(bbinsert && wysiwyg) {
eval('var attachimg = $(\'preview_' + aid + '\')');
insertText('<img src="' + attachimg.src + '" border="0" aid="attachimg_' + aid + '" width="' + attachimg.width + '" alt="" />', false);
} else {
AddText('[attachimg]' + aid + '[/attachimg]');
}
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/post_attach.js | JavaScript | asf20 | 6,743 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: msn.js,v $
$Revision: 1.4 $
$Date: 2007/03/21 15:57:53 $
*/
function msnoperate(action, msn) {
var actionArray = new Array();
actionArray = {
'reghotmail' : 'http://go.discuz.com/?app=msn&linkid=1',
'reglivemail' : 'http://go.discuz.com/?app=msn&linkid=2',
'regliveid' : 'http://go.discuz.com/?app=msn&linkid=3',
'download' : 'http://go.discuz.com/?app=msn&linkid=4',
'add' : 'http://go.discuz.com/?app=msn&linkid=5&msn=' + msn,
'chat' : 'http://go.discuz.com/?app=msn&linkid=6&msn=' + msn
}
if(messengerInstalled()) {
window.open(actionArray[action]);
} else {
window.open('http://go.discuz.com/msn/msn.html','_blank','width=571, height=498');
}
}
function messengerInstalled() {
try {
new ActiveXObject("MSNMessenger.P4QuickLaunch");
return true;
}
catch (e) {
return false;
}
} | zyyhong | trunk/jiaju001/bbs/include/javascript/msn.js | JavaScript | asf20 | 1,011 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: calendar.js,v $
$Revision: 1.17 $
$Date: 2007/06/15 13:53:53 $
*/
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function getposition(obj) {
var r = new Array();
r['x'] = obj.offsetLeft;
r['y'] = obj.offsetTop;
while(obj = obj.offsetParent) {
r['x'] += obj.offsetLeft;
r['y'] += obj.offsetTop;
}
return r;
}
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:9;" onclick="doane(event)">';
s += '<div style="width: 210px; border: 1px solid #FFF;"><table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;">';
s += '<tr align="center" id="calendar_week"><td><a href="###" onclick="refreshcalendar(yy, mm-1)" title="上一月">《</a></td><td colspan="5" style="text-align: center"><a href="###" onclick="showdiv(\'year\');doane(event)" class="dropmenu" title="点击选择年份" id="year"></a> - <a id="month" class="dropmenu" title="点击选择月份" href="###" onclick="showdiv(\'month\');doane(event)"></a></td><td><A href="###" onclick="refreshcalendar(yy, mm+1)" title="下一月">》</A></td></tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="2" value="" id="hour" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="2" value="" id="minute" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td></tr>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="doane(event)" style="display: none"><div class="col">';
for(var k = 1930; k <= 2019; k++) {
s += k != 1930 && k % 10 == 0 ? '</div><div class="col">' : '';
s += '<a href="###" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="calendar_today"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="doane(event)" style="display: none">';
for(var k = 1; k <= 12; k++) {
s += '<a href="###" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'"><span' + (today.getMonth()+1 == k ? ' class="calendar_today"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
if(is_ie && is_ie < 7) {
s += '<iframe id="calendariframe" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_year" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_month" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
}
var div = document.createElement('div');
div.innerHTML = s;
$('append_parent').appendChild(div);
document.onclick = function(event) {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(is_ie && is_ie < 7) {
$('calendariframe').style.display = 'none';
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
}
$('calendar').onclick = function(event) {
doane(event);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(is_ie && is_ie < 7) {
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
if(is_ie && is_ie < 7) {
$('calendariframe').style.display = 'none';
}
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function showcalendar(event, controlid1, addtime1, startdate1, enddate1) {
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = getposition(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['x']+'px';
$('calendar').style.top = (p['y'] + 20)+'px';
doane(event);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = 'calendar_default';
$('calendar_year_' + today.getFullYear()).className = 'calendar_today';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = 'calendar_default';
$('calendar_month_' + (today.getMonth() + 1)).className = 'calendar_today';
}
$('calendar_year_' + currday.getFullYear()).className = 'calendar_checked';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'calendar_checked';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
if(is_ie && is_ie < 7) {
$('calendariframe').style.top = $('calendar').style.top;
$('calendariframe').style.left = $('calendar').style.left;
$('calendariframe').style.width = $('calendar').offsetWidth;
$('calendariframe').style.height = $('calendar').offsetHeight;
$('calendariframe').style.display = 'block';
}
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'calendar_expire';
} else {
dd.className = 'calendar_default';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'calendar_today';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'calendar_checked';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = getposition($(id));
$('calendar_' + id).style.left = p['x']+'px';
$('calendar_' + id).style.top = (p['y'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
if(is_ie && is_ie < 7) {
$('calendariframe_' + id).style.top = $('calendar_' + id).style.top;
$('calendariframe_' + id).style.left = $('calendar_' + id).style.left;
$('calendariframe_' + id).style.width = $('calendar_' + id).offsetWidth;
$('calendariframe_' + id ).style.height = $('calendar_' + id).offsetHeight;
$('calendariframe_' + id).style.display = 'block';
}
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
loadcalendar(); | zyyhong | trunk/jiaju001/bbs/include/javascript/calendar.js | JavaScript | asf20 | 9,236 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: post_editor.js,v $
$Revision: 1.17 $
$Date: 2007/07/30 00:38:39 $
*/
function checklength(theform) {
var message = bbinsert && wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
var showmessage = postmaxchars != 0 ? lang['board_allowed'] + ': ' + postminchars + ' ' + lang['lento'] + ' ' + postmaxchars + ' ' + lang['bytes'] : '';
alert('\n' + lang['post_curlength'] + ': ' + mb_strlen(message) + ' ' + lang['bytes'] + '\n\n' + showmessage);
}
if(!tradepost) {
var tradepost = 0;
}
function validate(theform, previewpost) {
var message = bbinsert && wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
if(($('postsubmit').name != 'replysubmit' && !($('postsubmit').name == 'editsubmit' && !isfirstpost) && theform.subject.value == "") || message == "") {
alert(lang['post_subject_and_message_isnull']);
if(special != 2) {
theform.subject.focus();
}
return false;
} else if(mb_strlen(theform.subject.value) > 80) {
alert(lang['post_subject_toolong']);
theform.subject.focus();
return false;
}
if(tradepost) {
if(theform.item_name.value == '') {
alert(lang['post_trade_goodsname_null']);
theform.item_name.focus();
return false;
} else if(theform.item_price.value == '') {
alert(lang['post_trade_price_null']);
theform.item_price.focus();
return false;
} else if(!parseInt(theform.item_price.value)) {
alert(lang['post_trade_price_is_number']);
theform.item_price.focus();
return false;
} else if(theform.item_costprice.value != '' && !parseInt(theform.item_costprice.value)) {
alert(lang['post_trade_costprice_is_number']);
theform.item_costprice.focus();
return false;
} else if(theform.item_number.value != '0' && !parseInt(theform.item_number.value)) {
alert(lang['post_trade_amount_is_number']);
theform.item_number.focus();
return false;
}
}
if(in_array($('postsubmit').name, ['topicsubmit', 'editsubmit'])) {
if(theform.typeid && (theform.typeid.options && theform.typeid.options[theform.typeid.selectedIndex].value == 0) && typerequired) {
alert(lang['post_type_isnull']);
theform.typeid.focus();
return false;
}
if(special == 3 && isfirstpost) {
if(theform.rewardprice.value == "") {
alert(lang['post_reward_credits_null']);
theform.rewardprice.focus();
return false;
}
} else if(special == 4 && isfirstpost) {
if(theform.activityclass.value == "") {
alert(lang['post_activity_sort_null']);
theform.activityclass.focus();
return false;
} else if($('starttimefrom_0').value == "" && $('starttimefrom_1').value == "") {
alert(lang['post_activity_fromtime_null']);
return false;
} else if(theform.activityplace.value == "") {
alert(lang['post_activity_addr_null']);
theform.activityplace.focus();
return false;
}
} else if(special == 6 && isfirstpost) {
$('subjectu8').value = encodeURIComponent($('subject').value);
if($('tags') != null) $('tagsu8').value = encodeURIComponent($('tags').value);
if($('vid').value == '') {
alert(lang['post_video_uploading']);
return false;
} else if($('vclass') && getradiovalue('vclass') == '') {
alert(lang['post_video_vclass_required']);
return false;
}
}
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(message) < postminchars) || (postmaxchars != 0 && mb_strlen(message) > postmaxchars))) {
alert(lang['post_message_length_invalid'] + '\n\n' + lang['post_curlength'] + ': ' + mb_strlen(message) + ' ' + lang['bytes'] + '\n' +lang['board_allowed'] + ': ' + postminchars + ' ' + lang['lento'] + ' ' + postmaxchars + ' ' + lang['bytes']);
return false;
}
theform.message.value = message;
if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit'])) seccheck(theform, seccodecheck, secqaacheck, previewpost);
if(previewpost || $('postsubmit').name == 'editsubmit') return true;
}
function seccheck(theform, seccodecheck, secqaacheck, previewpost) {
if(!previewpost && (seccodecheck || secqaacheck)) {
var url = 'ajax.php?inajax=1&action=';
if(seccodecheck) {
var x = new Ajax();
x.get(url + 'checkseccode&seccodeverify=' + (is_ie && document.charset == 'utf-8' ? encodeURIComponent($('seccodeverify').value) : $('seccodeverify').value), function(s) {
if(s != 'succeed') {
alert(s);
$('seccodeverify').focus();
} else if(secqaacheck) {
checksecqaa(url, theform);
} else {
postsubmit(theform);
}
});
} else if(secqaacheck) {
checksecqaa(url, theform);
}
} else {
postsubmit(theform, previewpost);
}
}
function checksecqaa(url, theform) {
var x = new Ajax();
var secanswer = $('secanswer').value;
secanswer = is_ie && document.charset == 'utf-8' ? encodeURIComponent(secanswer) : secanswer;
x.get(url + 'checksecanswer&secanswer=' + secanswer, function(s) {
if(s != 'succeed') {
alert(s);
$('secanswer').focus();
} else {
postsubmit(theform);
}
});
}
function postsubmit(theform, previewpost) {
if(!previewpost) {
theform.replysubmit ? theform.replysubmit.disabled = true : theform.topicsubmit.disabled = true;
theform.submit();
}
}
function previewpost(){
if(!validate($('postform'), true)) {
$('subject').focus();
return;
}
$("previewmessage").innerHTML = '<span class="bold"><span class="smalltxt">' + $('subject').value + '</span></span><br /><br /><span style="font-size: {MSGFONTSIZE}">' + bbcode2html($('postform').message.value) + '</span>';
$("previewtable").style.display = '';
window.scroll(0, 0);
}
function clearcontent() {
if(wysiwyg && bbinsert) {
editdoc.body.innerHTML = is_moz ? '<br />' : '';
} else {
textobj.value = '';
}
}
function resizeEditor(change) {
var editorbox = bbinsert ? editbox : textobj;
var newheight = parseInt(editorbox.style.height, 10) + change;
if(newheight >= 100) {
editorbox.style.height = newheight + 'px';
}
}
function relatekw() {
var message = getEditorContents();
message = message.substr(0, 500);
message = message.replace(/&/ig, '', message);
ajaxget('relatekw.php?subjectenc=' + $('subject').value + '&messageenc=' + message, 'tagselect');
}
function getradiovalue(radioname) {
var tags = document.getElementsByTagName('input');
for(var i=0; i<tags.length; i++) {
if(tags[i].name == radioname && tags[i].checked) {
return tags[i].value;
}
}
return '';
} | zyyhong | trunk/jiaju001/bbs/include/javascript/post_editor.js | JavaScript | asf20 | 6,767 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: post.js,v $
$Revision: 1.27 $
$Date: 2007/08/06 08:27:23 $
*/
var postSubmited = false;
var smdiv = new Array();
var codecount = '-1';
var codehtml = new Array();
function AddText(txt) {
obj = $('postform').message;
selection = document.selection;
checkFocus();
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = txt;
sel.moveStart('character', -strlen(txt));
} else {
obj.value += txt;
}
}
function checkFocus() {
var obj = typeof wysiwyg == 'undefined' || !wysiwyg ? $('postform').message : editwin;
if(!obj.hasfocus) {
obj.focus();
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && $('postsubmit')) {
if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit', 'editsubmit', 'pmsubmit']) && !validate($('postform'))) {
doane(event);
return;
}
postSubmited = true;
$('postsubmit').disabled = true;
$('postform').submit();
}
}
function deleteData() {
if(is_ie) {
saveData('', 'delete');
} else if(window.sessionStorage) {
try {
sessionStorage.removeItem('Discuz!');
} catch(e) {}
}
}
function insertSmiley(smilieid) {
checkFocus();
var src = $('smilie_' + smilieid).src;
var code = $('smilie_' + smilieid).code;
if(typeof wysiwyg != 'undefined' && wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
if(is_moz) {
applyFormat('InsertImage', false, src);
var smilies = editdoc.body.getElementsByTagName('img');
for(var i = 0; i < smilies.length; i++) {
if(smilies[i].src == src && smilies[i].getAttribute('smilieid') < 1) {
smilies[i].setAttribute('smilieid', smilieid);
smilies[i].setAttribute('border', "0");
}
}
} else {
insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" /> ', false);
}
} else {
code += ' ';
AddText(code);
}
}
function parseurl(str, mode) {
str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, mode == 'html' ? '$1<img src="$2" border="0">' : '$1[img]$2[/img]');
str = str.replace(/([^>=\]"'\/@]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast):\/\/))([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w>=\]"'\/@]|^)((www\.)([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w->=\]:"'\.\/]|^)(([\-\.\w]+@[\.\-\w]+(\.\w+)+))/ig, mode == 'html' ? '$1<a href="mailto:$2">$2</a>' : '$1[email]$2[/email]');
for(var i = 0; i <= codecount; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
}
return str;
}
function codetag(text) {
codecount++;
text = text.replace(/<br[^\>]*>/ig, '\n');
text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
if(typeof wysiwyg != 'undefined' && wysiwyg) text = text.replace(/<(\/|)[A-Za-z].*?>/ig, '');
codehtml[codecount] = '[code]' + text + '[/code]';
return '[\tDISCUZ_CODE_' + codecount + '\t]';
}
function loadData() {
var message = '';
if(is_ie) {
try {
textobj.load('Discuz!');
var oXMLDoc = textobj.XMLDocument;
var nodes = oXMLDoc.documentElement.childNodes;
message = nodes.item(nodes.length - 1).getAttribute('message');
} catch(e) {}
} else if(window.sessionStorage) {
try {
message = sessionStorage.getItem('Discuz!');
} catch(e) {}
}
message = message.toString();
if(in_array((message = trim(message)), ['', 'null', 'false', null, false])) {
alert(lang['post_autosave_none']);
return;
}
if(!confirm(lang['post_autosave_confirm'])) {
return;
}
var formdata = message.split(/\x09\x09/);
for(var i = 0; i < $('postform').elements.length; i++) {
var el = $('postform').elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio'))) {
for(var j = 0; j < formdata.length; j++) {
var ele = formdata[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(typeof wysiwyg == 'undefined' || !wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
}
break
}
}
}
}
}
function evalevent(obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
}
function saveData(data, del) {
if(!data && isUndefined(del)) {
return;
}
if(typeof wysiwyg != 'undefined' && typeof editorid != 'undefined' && typeof bbinsert != 'undefined' && bbinsert && $(editorid + '_mode') && $(editorid + '_mode').value == 1) {
data = html2bbcode(data);
}
var formdata = '';
if(isUndefined(del)) {
for(var i = 0; i < $('postform').elements.length; i++) {
var el = $('postform').elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.name == 'message' ? data : el.value;
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
}
formdata += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(is_ie) {
try {
var oXMLDoc = textobj.XMLDocument;
var root = oXMLDoc.firstChild;
if(root.childNodes.length > 0) {
root.removeChild(root.firstChild);
}
var node = oXMLDoc.createNode(1, 'POST', '');
var oTimeNow = new Date();
oTimeNow.setHours(oTimeNow.getHours() + 24);
textobj.expires = oTimeNow.toUTCString();
node.setAttribute('message', formdata);
oXMLDoc.documentElement.appendChild(node);
textobj.save('Discuz!');
} catch(e) {}
} else if(window.sessionStorage) {
try {
sessionStorage.setItem('Discuz!', formdata);
} catch(e) {}
}
}
function setCaretAtEnd() {
var obj = typeof wysiwyg == 'undefined' || !wysiwyg ? $('postform').message : editwin;
if(typeof wysiwyg != 'undefined' && wysiwyg) {
if(is_moz || is_opera) {
} else {
var sel = editdoc.selection.createRange();
sel.moveStart('character', strlen(getEditorContents()));
sel.select();
}
} else {
if(obj.createTextRange) {
var sel = obj.createTextRange();
sel.moveStart('character', strlen(obj.value));
sel.collapse();
sel.select();
}
}
}
function smileyMenu(ctrl) {
var smiley = ctrl.firstChild;
ctrl.style.cursor = 'pointer';
if(smiley.alt) {
smiley.code = smiley.alt;
smiley.alt = '';
}
if(smiley.title) {
smiley.lw = smiley.title;
smiley.title = '';
}
smdiv[ctrl.id] = document.createElement('div');
smdiv[ctrl.id].id = smiley.id + '_menu';
smdiv[ctrl.id].style.display = 'none';
smdiv[ctrl.id].style.width = '60px';
smdiv[ctrl.id].style.height = '60px';
smdiv[ctrl.id].className = 'popupmenu_popup';
$('smilieslist').appendChild(smdiv[ctrl.id]);
smdiv[ctrl.id].innerHTML = '<table width="100%" height="100%"><tr><td align="center" valign="middle"><img src="' + smiley.src + '" border="0" width="' + smiley.lw + '" /></td></tr></table>';
showMenu(ctrl.id, 0, 0, 1, 0, 0, smiley.id);
}
function storeCaret(textEl){
if(textEl.createTextRange){
textEl.caretPos = document.selection.createRange().duplicate();
}
}
if(is_ie >= 5 || is_moz >= 2) {
window.onbeforeunload = function () {
try {
saveData(wysiwyg && bbinsert ? editdoc.body.innerHTML : textobj.value);
} catch(e) {}
};
}
function setmediacode(editorid) {
insertText('[media='+$(editorid + '_mediatype').value+
','+$(editorid + '_mediawidth').value+
','+$(editorid + '_mediaheight').value+
','+$(editorid + '_mediaautostart').value+']'+
$(editorid + '_mediaurl').value+'[/media]');
hideMenu();
}
function setmediatype(editorid) {
var ext = $(editorid + '_mediaurl').value.lastIndexOf('.') == -1 ? '' : $(editorid + '_mediaurl').value.substr($(editorid + '_mediaurl').value.lastIndexOf('.') + 1, $(editorid + '_mediaurl').value.length).toLowerCase();
if(ext == 'rmvb') {
ext = 'rm';
}
if($(editorid + '_mediatyperadio_' + ext)) {
$(editorid + '_mediatyperadio_' + ext).checked = true;
$(editorid + '_mediatype').value = ext;
}
}
var divdragstart = new Array();
function divdrag(e, op, obj) {
if(op == 1) {
if(is_ie) {
document.body.onselectstart = function() {
return false;
}
}
divdragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
divdragstart[2] = parseInt(obj.style.left);
divdragstart[3] = parseInt(obj.style.top);
doane(e);
} else if(op == 2 && divdragstart[0]) {
var divdragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
obj.style.left = (divdragstart[2] + divdragnow[0] - divdragstart[0]) + 'px';
obj.style.top = (divdragstart[3] + divdragnow[1] - divdragstart[1]) + 'px';
doane(e);
} else if(op == 3) {
if(is_ie) {
document.body.onselectstart = function() {
return true;
}
}
divdragstart = [];
doane(e);
}
} | zyyhong | trunk/jiaju001/bbs/include/javascript/post.js | JavaScript | asf20 | 10,620 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: menu.js,v $
$Revision: 1.66 $
$Date: 2007/07/26 07:35:27 $
*/
var jsmenu = new Array();
var ctrlobjclassName;
jsmenu['active'] = new Array();
jsmenu['timer'] = new Array();
jsmenu['iframe'] = new Array();
function initCtrl(ctrlobj, click, duration, timeout, layer) {
if(ctrlobj && !ctrlobj.initialized) {
ctrlobj.initialized = true;
ctrlobj.unselectable = true;
ctrlobj.outfunc = typeof ctrlobj.onmouseout == 'function' ? ctrlobj.onmouseout : null;
ctrlobj.onmouseout = function() {
if(this.outfunc) this.outfunc();
if(duration < 3) jsmenu['timer'][ctrlobj.id] = setTimeout('hideMenu(' + layer + ')', timeout);
}
if(click && duration) {
ctrlobj.clickfunc = typeof ctrlobj.onclick == 'function' ? ctrlobj.onclick : null;
ctrlobj.onclick = function (e) {
doane(e);
if(jsmenu['active'][layer] == null || jsmenu['active'][layer].ctrlkey != this.id) {
if(this.clickfunc) this.clickfunc();
else showMenu(this.id, true);
} else {
hideMenu(layer);
}
}
}
ctrlobj.overfunc = typeof ctrlobj.onmouseover == 'function' ? ctrlobj.onmouseover : null;
ctrlobj.onmouseover = function(e) {
doane(e);
if(this.overfunc) this.overfunc();
if(click) {
clearTimeout(jsmenu['timer'][this.id]);
} else {
for(var id in jsmenu['timer']) {
if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
}
}
}
}
}
function initMenu(ctrlid, menuobj, duration, timeout, layer) {
if(menuobj && !menuobj.initialized) {
menuobj.initialized = true;
menuobj.ctrlkey = ctrlid;
menuobj.onclick = ebygum;
menuobj.style.position = 'absolute';
if(duration < 3) {
if(duration > 1) {
menuobj.onmouseover = function() {
clearTimeout(jsmenu['timer'][ctrlid]);
}
}
if(duration != 1) {
menuobj.onmouseout = function() {
jsmenu['timer'][ctrlid] = setTimeout('hideMenu(' + layer + ')', timeout);
}
}
}
menuobj.style.zIndex = 50;
if(is_ie) {
menuobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
}
}
}
function showMenu(ctrlid, click, offset, duration, timeout, layer, showid, maxh) {
e = window.event ? window.event : showMenu.caller.arguments[0];
var ctrlobj = $(ctrlid);
if(!ctrlobj) return;
if(isUndefined(click)) click = false;
if(isUndefined(offset)) offset = 0;
if(isUndefined(duration)) duration = 2;
if(isUndefined(timeout)) timeout = 500;
if(isUndefined(layer)) layer = 0;
if(isUndefined(showid)) showid = ctrlid;
var showobj = $(showid);
var menuobj = $(showid + '_menu');
if(!showobj|| !menuobj) return;
if(isUndefined(maxh)) maxh = 400;
hideMenu(layer);
for(var id in jsmenu['timer']) {
if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
}
initCtrl(ctrlobj, click, duration, timeout, layer);
ctrlobjclassName = ctrlobj.className;
ctrlobj.className += ' hover';
initMenu(ctrlid, menuobj, duration, timeout, layer);
menuobj.style.display = '';
if(!is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
setMenuPosition(showid, offset);
if(is_ie && is_ie < 7) {
if(!jsmenu['iframe'][layer]) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.style.position = 'absolute';
iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
$('append_parent') ? $('append_parent').appendChild(iframe) : menuobj.parentNode.appendChild(iframe);
jsmenu['iframe'][layer] = iframe;
}
jsmenu['iframe'][layer].style.top = menuobj.style.top;
jsmenu['iframe'][layer].style.left = menuobj.style.left;
jsmenu['iframe'][layer].style.width = menuobj.w;
jsmenu['iframe'][layer].style.height = menuobj.h;
jsmenu['iframe'][layer].style.display = 'block';
}
if(maxh && menuobj.scrollHeight > maxh) {
menuobj.style.height = maxh + 'px';
if(is_opera) {
menuobj.style.overflow = 'auto';
} else {
menuobj.style.overflowY = 'auto';
}
}
if(!duration) {
setTimeout('hideMenu(' + layer + ')', timeout);
}
jsmenu['active'][layer] = menuobj;
}
function setMenuPosition(showid, offset) {
var showobj = $(showid);
var menuobj = $(showid + '_menu');
if(isUndefined(offset)) offset = 0;
if(showobj) {
showobj.pos = fetchOffset(showobj);
showobj.X = showobj.pos['left'];
showobj.Y = showobj.pos['top'];
showobj.w = showobj.offsetWidth;
showobj.h = showobj.offsetHeight;
menuobj.w = menuobj.offsetWidth;
menuobj.h = menuobj.offsetHeight;
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';
menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > document.documentElement.scrollTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');
if(menuobj.style.clip && !is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
}
function hideMenu(layer) {
if(isUndefined(layer)) layer = 0;
if(jsmenu['active'][layer]) {
try {
$(jsmenu['active'][layer].ctrlkey).className = ctrlobjclassName;
} catch(e) {}
clearTimeout(jsmenu['timer'][jsmenu['active'][layer].ctrlkey]);
jsmenu['active'][layer].style.display = 'none';
if(is_ie && is_ie < 7 && jsmenu['iframe'][layer]) {
jsmenu['iframe'][layer].style.display = 'none';
}
jsmenu['active'][layer] = null;
}
}
function fetchOffset(obj) {
var left_offset = obj.offsetLeft;
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
return { 'left' : left_offset, 'top' : top_offset };
}
function ebygum(eventobj) {
if(!eventobj || is_ie) {
window.event.cancelBubble = true;
return window.event;
} else {
if(eventobj.target.type == 'submit') {
eventobj.target.form.submit();
}
eventobj.stopPropagation();
return eventobj;
}
}
function menuoption_onclick_function(e) {
this.clickfunc();
hideMenu();
}
function menuoption_onclick_link(e) {
choose(e, this);
}
function menuoption_onmouseover(e) {
this.className = 'popupmenu_highlight';
}
function menuoption_onmouseout(e) {
this.className = 'popupmenu_option';
}
function choose(e, obj) {
var links = obj.getElementsByTagName('a');
if(links[0]) {
if(is_ie) {
links[0].click();
window.event.cancelBubble = true;
} else {
if(e.shiftKey) {
window.open(links[0].href);
e.stopPropagation();
e.preventDefault();
} else {
window.location = links[0].href;
e.stopPropagation();
e.preventDefault();
}
}
hideMenu();
}
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/menu.js | JavaScript | asf20 | 7,045 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: viewthread.js,v $
$Revision: 1.78 $
$Date: 2007/08/01 05:55:44 $
*/
var msgwidth = 0;
function attachimg(obj, action) {
if(action == 'load') {
if(is_ie && is_ie < 7) {
var objinfo = fetchOffset(obj);
msgwidth = document.body.clientWidth - objinfo['left'] - 20;
} else {
if(!msgwidth) {
var re = /postcontent|message/i;
var testobj = obj;
while((testobj = testobj.parentNode) != null) {
var matches = re.exec(testobj.className);
if(matches != null) {
msgwidth = testobj.clientWidth - 20;
break;
}
}
if(msgwidth < 1) {
msgwidth = window.screen.width;
}
}
}
if(obj.width > msgwidth) {
obj.resized = true;
obj.width = msgwidth;
obj.style.cursor = 'pointer';
} else {
obj.onclick = null;
}
} else if(action == 'mouseover') {
if(obj.resized) {
obj.style.cursor = 'pointer';
}
}
}
function attachimginfo(obj, infoobj, show, event) {
objinfo = fetchOffset(obj);
if(show) {
$(infoobj).style.left = objinfo['left'] + 'px';
$(infoobj).style.top = obj.offsetHeight < 40 ? (objinfo['top'] + obj.offsetHeight) + 'px' : objinfo['top'] + 'px';
$(infoobj).style.display = '';
} else {
if(is_ie) {
$(infoobj).style.display = 'none';
return;
} else {
var mousex = document.body.scrollLeft + event.clientX;
var mousey = document.documentElement.scrollTop + event.clientY;
if(mousex < objinfo['left'] || mousex > objinfo['left'] + objinfo['width'] || mousey < objinfo['top'] || mousey > objinfo['top'] + objinfo['height']) {
$(infoobj).style.display = 'none';
}
}
}
}
function copycode(obj) {
if(is_ie && obj.style.display != 'none') {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.scrollIntoView();
rng.select();
rng.execCommand("Copy");
rng.collapse(false);
}
}
function signature(obj) {
if(obj.style.maxHeightIE != '') {
var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight;
if(obj.innerHTML.indexOf('<IMG ') == -1) {
obj.style.maxHeightIE = '';
}
return height;
}
}
function fastreply(subject, postnum) {
if($('postform')) {
$('postform').subject.value = subject.replace(/#/, $(postnum).innerHTML.replace(/<[\/\!]*?[^<>]*?>/ig, ''));
$('postform').message.focus();
}
}
function tagshow(event) {
var obj = is_ie ? event.srcElement : event.target;
obj.id = !obj.id ? 'tag_' + Math.random() : obj.id;
ajaxmenu(event, obj.id, 0, '', 1, 3, 0);
obj.onclick = null;
}
var zoomobj = Array();var zoomadjust;var zoomstatus = 1;
function zoom(obj, zimg) {
if(!zoomstatus) {
window.open(zimg, '', '');
return;
}
if(!zimg) {
zimg = obj.src;
}
if(!$('zoomimglayer_bg')) {
div = document.createElement('div');div.id = 'zoomimglayer_bg';
div.style.position = 'absolute';
div.style.left = div.style.top = '0px';
div.style.width = '100%';
div.style.height = document.body.scrollHeight + 'px';
div.style.backgroundColor = '#000';
div.style.display = 'none';
div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=80,finishOpacity=100,style=0)';
div.style.opacity = 0.8;
$('append_parent').appendChild(div);
div = document.createElement('div');div.id = 'zoomimglayer';
div.style.position = 'absolute';
div.className = 'popupmenu_popup';
div.style.padding = 0;
$('append_parent').appendChild(div);
}
zoomobj['srcinfo'] = fetchOffset(obj);
zoomobj['srcobj'] = obj;
zoomobj['zimg'] = zimg;
$('zoomimglayer').style.display = '';
$('zoomimglayer').style.left = zoomobj['srcinfo']['left'] + 'px';
$('zoomimglayer').style.top = zoomobj['srcinfo']['top'] + 'px';
$('zoomimglayer').style.width = zoomobj['srcobj'].width + 'px';
$('zoomimglayer').style.height = zoomobj['srcobj'].height + 'px';
$('zoomimglayer').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=40,finishOpacity=100,style=0)';
$('zoomimglayer').style.opacity = 0.4;
$('zoomimglayer').style.zIndex = 999;
$('zoomimglayer').innerHTML = '<table width="100%" height="100%" cellspacing="0" cellpadding="0"><tr><td align="center" valign="middle"><img src="' + IMGDIR + '/loading.gif"></td></tr></table><div style="position:absolute;top:-100000px;visibility:hidden"><img onload="zoomimgresize(this)" src="' + zoomobj['zimg'] + '"></div>';
}
var zoomdragstart = new Array();
var zoomclick = 0;
function zoomdrag(e, op) {
if(op == 1) {
zoomclick = 1;
zoomdragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
zoomdragstart[2] = parseInt($('zoomimglayer').style.left);
zoomdragstart[3] = parseInt($('zoomimglayer').style.top);
doane(e);
} else if(op == 2 && zoomdragstart[0]) {
zoomclick = 0;
var zoomdragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
$('zoomimglayer').style.left = (zoomdragstart[2] + zoomdragnow[0] - zoomdragstart[0]) + 'px';
$('zoomimglayer').style.top = (zoomdragstart[3] + zoomdragnow[1] - zoomdragstart[1]) + 'px';
doane(e);
} else if(op == 3) {
if(zoomclick) zoomclose();
zoomdragstart = [];
doane(e);
}
}
function zoomST(c) {
if($('zoomimglayer').style.display == '') {
$('zoomimglayer').style.left = (parseInt($('zoomimglayer').style.left) + zoomobj['x']) + 'px';
$('zoomimglayer').style.top = (parseInt($('zoomimglayer').style.top) + zoomobj['y']) + 'px';
$('zoomimglayer').style.width = (parseInt($('zoomimglayer').style.width) + zoomobj['w']) + 'px';
$('zoomimglayer').style.height = (parseInt($('zoomimglayer').style.height) + zoomobj['h']) + 'px';
var opacity = c * 20;
$('zoomimglayer').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ',finishOpacity=100,style=0)';
$('zoomimglayer').style.opacity = opacity / 100;
c++;
if(c <= 5) {
setTimeout('zoomST(' + c + ')', 5);
} else {
zoomadjust = 1;
$('zoomimglayer').style.filter = '';
$('zoomimglayer_bg').style.display = '';
$('zoomimglayer').innerHTML = '<table cellspacing="0" cellpadding="2"><tr><td style="text-align: right">鼠标滚轮缩放图片 <a href="' + zoomobj['zimg'] + '" target="_blank"><img src="' + IMGDIR + '/newwindow.gif" border="0" style="vertical-align: middle" title="在新窗口打开" /></a> <a href="###" onclick="zoomimgadjust(event, 1)"><img src="' + IMGDIR + '/resize.gif" border="0" style="vertical-align: middle" title="实际大小" /></a> <a href="###" onclick="zoomclose()"><img style="vertical-align: middle" src="' + IMGDIR +'/close.gif" title="关闭" /></a> </td></tr><tr><td align="center" id="zoomimgbox"><img id="zoomimg" style="cursor: move; margin: 5px;" src="' + zoomobj['zimg'] + '" width="' + $('zoomimglayer').style.width + '" height="' + $('zoomimglayer').style.height + '"></td></tr></table>';
$('zoomimglayer').style.overflow = 'visible';
$('zoomimglayer').style.width = $('zoomimglayer').style.height = 'auto';
if(is_ie){
$('zoomimglayer').onmousewheel = zoomimgadjust;
} else {
$('zoomimglayer').addEventListener("DOMMouseScroll", zoomimgadjust, false);
}
$('zoomimgbox').onmousedown = function(event) {try{zoomdrag(event, 1);}catch(e){}};
$('zoomimgbox').onmousemove = function(event) {try{zoomdrag(event, 2);}catch(e){}};
$('zoomimgbox').onmouseup = function(event) {try{zoomdrag(event, 3);}catch(e){}};
}
}
}
function zoomimgresize(obj) {
zoomobj['zimginfo'] = [obj.width, obj.height];
var r = obj.width / obj.height;
var w = document.body.clientWidth * 0.95;
w = obj.width > w ? w : obj.width;
var h = w / r;
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
if(h > clientHeight) {
h = clientHeight;
w = h * r;
}
var l = (document.body.clientWidth - w) / 2;
var t = h < clientHeight ? (clientHeight - h) / 2 : 0;
t += + scrollTop;
zoomobj['x'] = (l - zoomobj['srcinfo']['left']) / 5;
zoomobj['y'] = (t - zoomobj['srcinfo']['top']) / 5;
zoomobj['w'] = (w - zoomobj['srcobj'].width) / 5;
zoomobj['h'] = (h - zoomobj['srcobj'].height) / 5;
$('zoomimglayer').style.filter = '';
$('zoomimglayer').innerHTML = '';
setTimeout('zoomST(1)', 5);
}
function zoomimgadjust(e, a) {
if(!a) {
if(!e) e = window.event;
if(e.altKey || e.shiftKey || e.ctrlKey) return;
var l = parseInt($('zoomimglayer').style.left);
var t = parseInt($('zoomimglayer').style.top);
if(e.wheelDelta <= 0 || e.detail > 0) {
if($('zoomimg').width <= 200 || $('zoomimg').height <= 200) {
doane(e);return;
}
$('zoomimg').width -= zoomobj['zimginfo'][0] / 10;
$('zoomimg').height -= zoomobj['zimginfo'][1] / 10;
l += zoomobj['zimginfo'][0] / 20;
t += zoomobj['zimginfo'][1] / 20;
} else {
if($('zoomimg').width >= zoomobj['zimginfo'][0]) {
zoomimgadjust(e, 1);return;
}
$('zoomimg').width += zoomobj['zimginfo'][0] / 10;
$('zoomimg').height += zoomobj['zimginfo'][1] / 10;
l -= zoomobj['zimginfo'][0] / 20;
t -= zoomobj['zimginfo'][1] / 20;
}
} else {
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
$('zoomimg').width = zoomobj['zimginfo'][0];$('zoomimg').height = zoomobj['zimginfo'][1];
var l = (document.body.clientWidth - $('zoomimg').clientWidth) / 2;l = l > 0 ? l : 0;
var t = (clientHeight - $('zoomimg').clientHeight) / 2 + scrollTop;t = t > 0 ? t : 0;
}
$('zoomimglayer').style.left = l + 'px';
$('zoomimglayer').style.top = t + 'px';
$('zoomimglayer_bg').style.height = t + $('zoomimglayer').clientHeight > $('zoomimglayer_bg').clientHeight ? (t + $('zoomimglayer').clientHeight) + 'px' : $('zoomimglayer_bg').style.height;
doane(e);
}
function zoomclose() {
$('zoomimglayer').innerHTML = '';
$('zoomimglayer').style.display = 'none';
$('zoomimglayer_bg').style.display = 'none';
}
function videoPlay(vid, vtime, tid, pid) {
ajaxget('api/video.php?action=updatevideoinfo&vid='+vid+'&vtime='+vtime+'&tid='+tid+'&pid='+pid, '');
} | zyyhong | trunk/jiaju001/bbs/include/javascript/viewthread.js | JavaScript | asf20 | 10,528 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: drag.js,v $
$Revision: 1.9 $
$Date: 2007/05/29 14:43:29 $
*/
var _Event = new Moz_event();
var Drag = new Drag_Events();
is_moz = is_moz || is_opera;
function Moz_event() {
this.srcElement = null,
this.setEvent = function(e) {
_Event.srcElement = e.target;
_Event.clientX = e.clientX;
_Event.clientY = e.clientY;
}
}
function Drag_Events() {
this.handler = null;
this.dragged = false;
this.obj = null;
this.tdiv = null;
this.rootTable = null;
this.layout = null;
this.disable = null;
this.getEvent = function() {
if(is_ie) {
return event;
} else if(is_moz) {
return _Event;
}
}
this.dragStart = function(event, disable) {
if(Drag.dragged) return;
Drag.disable = disable;
if(is_ie) {
document.body.onselectstart = function() {
return false;
}
}
Drag.obj = Drag.getEvent().srcElement;
if(Drag.obj.tagName == "TD" || Drag.obj.tagName == "TR") {
Drag.obj = Drag.obj.offsetParent.parentNode;
Drag.obj.style.zIndex = 100;
} else if(Drag.obj.parentNode.tagName == "TD" || Drag.obj.parentNode.tagName == "TR") {
Drag.obj = Drag.obj.parentNode;
Drag.obj = Drag.obj.offsetParent.parentNode;
Drag.obj.style.zIndex = 100;
} else if(Drag.obj.tagName == "DIV") {
Drag.obj = Drag.obj.parentNode;
Drag.obj.style.zIndex = 100;
} else {
return;
}
Drag.dragged = true;
Drag.tdiv = document.createElement("DIV");
Drag.tdiv.innerHTML = Drag.obj.innerHTML;
Drag.tdiv.className = "tempDIV";
Drag.tdiv.style.filter = "alpha(opacity=50)";
Drag.tdiv.style.opacity = 0.5;
Drag.tdiv.style.width = Drag.obj.offsetWidth + 'px';
Drag.tdiv.style.Height = Drag.obj.offsetHeight + 'px';
Drag.tdiv.style.top = Drag.getInfo(Drag.obj).top + 'px';
Drag.tdiv.style.left = Drag.getInfo(Drag.obj).left + 'px';
Drag.obj.parentNode.appendChild(Drag.tdiv);
Drag.lastX = Drag.getEvent().clientX;
Drag.lastY = Drag.getEvent().clientY;
Drag.lastLeft = parseInt(Drag.tdiv.style.left);
Drag.lastTop = parseInt(Drag.tdiv.style.top);
Drag.lastTop = parseInt(Drag.lastTop) - document.body.scrollTop;
if(is_ie) {
event.returnValue = false;
} else {
event.preventDefault();
}
Drag.handler.dragStart();
}
this.onDrag = function() {
if((!Drag.dragged) || Drag.obj == null) {
return;
}
var tX = Drag.getEvent().clientX;
var tY = Drag.getEvent().clientY;
Drag.tdiv.style.left = (parseInt(Drag.lastLeft) + tX - Drag.lastX) + 'px';
Drag.tdiv.style.top = (parseInt(Drag.lastTop) + tY - Drag.lastY) + 'px';
Drag.tdiv.style.top = (parseInt(Drag.tdiv.style.top) + document.body.scrollTop) + 'px';
tY = tY + document.body.scrollTop;
Drag.handler.onDrag(tX, tY);
var s_area = Drag.getInfo(Drag.tdiv);
if(tX > s_area.right) {
Drag.tdiv.style.left = tX - 20 + 'px';
}
if(tY > s_area.bottom) {
Drag.tdiv.style.top = tY - 10 + 'px';
}
}
this.dragEnd = function() {
if(is_ie) {
document.body.onselectstart = function() {
return true;
}
}
if(!Drag.dragged) {
return;
}
Drag.dragged = false;
Drag.handler.dragEnd();
Drag.obj.style.zIndex = 1;
Drag.tdiv.parentNode.removeChild(Drag.tdiv);
Drag.obj = null;
}
this.getInfo = function(o) {
var to = new Object();
to.left = to.right = to.top = to.bottom = 0;
var twidth = o.offsetWidth;
var theight = o.offsetHeight;
while(o) {
to.left += o.offsetLeft;
to.top += o.offsetTop;
o = o.offsetParent;
}
to.right = to.left + twidth;
to.bottom = to.top + theight;
return to;
}
this.mozinit = function() {
if(is_moz) {
Drag.rootTable.cells = new Array();
var tcells = Drag.rootTable.getElementsByTagName("TD");
for(var i = 0; i < tcells.length; i++) {
if(tcells[i].offsetParent == Drag.rootTable) {
Drag.rootTable.cells.push(tcells[i]);
}
}
}
}
this.init = function(handler) {
Drag.handler = new handler();
Drag.handler.init();
if(is_ie) {
document.onmousemove = Drag.onDrag;
document.onmouseup = Drag.dragEnd;
} else if(is_moz) {
document.body.setAttribute("onMouseMove", "_Event.setEvent(event);Drag.onDrag();");
document.body.setAttribute("onMouseUp", "_Event.setEvent(event);Drag.dragEnd();");
}
}
} | zyyhong | trunk/jiaju001/bbs/include/javascript/drag.js | JavaScript | asf20 | 4,437 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: bbcode.js,v $
$Revision: 1.55 $
$Date: 2007/07/30 05:17:52 $
*/
var is_mac = userAgent.indexOf('mac') != -1;
var re;
if(isUndefined(codecount)) var codecount = '-1';
if(isUndefined(codehtml)) var codehtml = new Array();
function addslashes(str) {
return preg_replace(['\\\\', '\\\'', '\\\/', '\\\(', '\\\)', '\\\[', '\\\]', '\\\{', '\\\}', '\\\^', '\\\$', '\\\?', '\\\.', '\\\*', '\\\+', '\\\|'], ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|'], str);
}
function atag(aoptions, text) {
if(trim(text) == '') {
return '';
}
href = getoptionvalue('href', aoptions);
if(href.substr(0, 11) == 'javascript:') {
return trim(recursion('a', text, 'atag'));
} else if(href.substr(0, 7) == 'mailto:') {
tag = 'email';
href = href.substr(7);
} else {
tag = 'url';
}
return '[' + tag + '=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/' + tag + ']';
}
function bbcode2html(str) {
str = trim(str);
if(str == '') {
return '';
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return parsecode($2);});
}
if(!forumallowhtml && !(allowhtml && fetchCheckbox('htmlon'))) {
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'html');
}
}
if(!fetchCheckbox('smileyoff') && allowsmilies) {
for(id in smilies) {
re = new RegExp(addslashes(smilies[id]['code']), "g");
str = str.replace(re, '<img src="./images/smilies/' + smilies[id]['url'] + '" border="0" smilieid="' + id + '" alt="' + smilies[id]['code'] + '" />');
}
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str= str.replace(/\[url\]\s*(www.|https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|bctp:\/\/|ed2k:\/\/){1}([^\[\"']+?)\s*\[\/url\]/ig, function($1, $2, $3) {return cuturl($2 + $3);});
str= str.replace(/\[url=www.([^\[\"']+?)\](.+?)\[\/url\]/ig, '<a href="http://www.$1" target="_blank">$2</a>');
str= str.replace(/\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k){1}:\/\/([^\[\"']+?)\]([\s\S]+?)\[\/url\]/ig, '<a href="$1://$2" target="_blank">$3</a>');
str= str.replace(/\[email\](.*?)\[\/email\]/ig, '<a href="mailto:$1">$1</a>');
str= str.replace(/\[email=(.[^\[]*)\](.*?)\[\/email\]/ig, '<a href="mailto:$1" target="_blank">$2</a>');
str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">');
str = str.replace(/\[size=(\d+?)\]/ig, '<font size="$1">');
str = str.replace(/\[size=(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%)+?)\]/ig, '<font style="font-size: $1">');
str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">');
str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<p align="$1">');
str = str.replace(/\[float=([^\[\<]+?)\]/ig, '<br style="clear: both"><span style="float: $1;">');
re = /\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*([\s\S]+?)\s*\[\/table\]/ig;
for (i = 0; i < 4; i++) {
str = str.replace(re, function($1, $2, $3, $4) {return parsetable($2, $3, $4);});
}
str = preg_replace([
'\\\[\\\/color\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
'\\\[list=A\\\]', '\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]', '\\\[\\\/float\\\]'
], [
'</font>', '</font>', '</font>', '</p>', '<b>', '</b>', '<i>',
'</i>', '<u>', '</u>', '<ul>', '<ul type=1>', '<ul type=a>',
'<ul type=A>', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
], str);
}
if(!fetchCheckbox('bbcodeoff')) {
if(allowimgcode) {
str = str.replace(/\[localimg=(\d{1,4}),(\d{1,4})\](\d+)\[\/localimg\]/ig, function ($1, $2, $3, $4) {if($('attach_' + $4)) {var src = $('attach_' + $4).value; if(src != '') return '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + src + '\');width:' + $2 + ';height=' + $3 + '" src=\'images/common/none.gif\' border="0" aid="attach_' + $4 + '" alt="" />';}});
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src="$1" border="0" alt="" />');
str = str.replace(/\[attachimg\](\d+)\[\/attachimg\]/ig, function ($1, $2) {eval('var attachimg = $(\'preview_' + $2 + '\')');return '<img src="' + attachimg.src + '" border="0" aid="attachimg_' + $2 + '" width="' + attachimg.clientWidth + '" alt="" />';});
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img width="$1" height="$2" src="$3" border="0" alt="" />');
} else {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
}
}
for(var i = 0; i <= codecount; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
}
if(!forumallowhtml && !(allowhtml && fetchCheckbox('htmlon'))) {
str = preg_replace(['\t', ' ', ' ', '(\r\n|\n|\r)'], [' ', ' ', ' ', '<br />'], str);
}
return str;
}
function cuturl(url) {
var length = 65;
var urllink = '<a href="' + (url.toLowerCase().substr(0, 4) == 'www.' ? 'http://' + url : url) + '" target="_blank">';
if(url.length > length) {
url = url.substr(0, parseInt(length * 0.5)) + ' ... ' + url.substr(url.length - parseInt(length * 0.3));
}
urllink += url + '</a>';
return urllink;
}
function dpstag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
var pend = parsestyle(options, '', '');
var prepend = pend['prepend'];
var append = pend['append'];
if(in_array(tagname, ['div', 'p'])) {
align = getoptionvalue('align', options);
if(in_array(align, ['left', 'center', 'right'])) {
prepend = '[align=' + align + ']' + prepend;
append += '[/align]';
} else {
append += '\n';
}
}
return prepend + recursion(tagname, text, 'dpstag') + append;
}
function fetchoptionvalue(option, text) {
if((position = strpos(text, option)) !== false) {
delimiter = position + option.length;
if(text.charAt(delimiter) == '"') {
delimchar = '"';
} else if(text.charAt(delimiter) == '\'') {
delimchar = '\'';
} else {
delimchar = ' ';
}
delimloc = strpos(text, delimchar, delimiter + 1);
if(delimloc === false) {
delimloc = text.length;
} else if(delimchar == '"' || delimchar == '\'') {
delimiter++;
}
return trim(text.substr(delimiter, delimloc - delimiter));
} else {
return '';
}
}
function fonttag(fontoptions, text) {
var prepend = '';
var append = '';
var tags = new Array();
tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
for(bbcode in tags) {
optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
if(optionvalue) {
prepend += '[' + bbcode + '=' + optionvalue + ']';
append = '[/' + bbcode + ']' + append;
}
}
var pend = parsestyle(fontoptions, prepend, append);
return pend['prepend'] + recursion('font', text, 'fonttag') + pend['append'];
}
function getoptionvalue(option, text) {
re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
var matches = re.exec(text);
if(matches != null) {
return trim(matches[3]);
}
return '';
}
function html2bbcode(str) {
if(forumallowhtml || (allowhtml && fetchCheckbox('htmlon')) || trim(str) == '') {
str = str.replace(/<img([^>]*aid=[^>]*)>/ig, function($1, $2) {return imgtag($2);});
return str;
}
str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
str = preg_replace(['<style.*?>[\\\s\\\S]*?<\/style>', '<script.*?>[\\\s\\\S]*?<\/script>', '<noscript.*?>[\\\s\\\S]*?<\/noscript>', '<select.*?>[\s\S]*?<\/select>', '<object.*?>[\s\S]*?<\/object>', '<!--[\\\s\\\S]*?-->', 'on[a-zA-Z]{3,16}\\\s?=\\\s?"[\\\s\\\S]*?"'], '', str);
str= str.replace(/(\r\n|\n|\r)/ig, '');
str= trim(str.replace(/&((#(32|127|160|173))|shy|nbsp);/ig, ' '));
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'bbcode');
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = preg_replace(['<table([^>]*(width|background|background-color|bgcolor)[^>]*)>', '<table[^>]*>', '<tr[^>]*(?:background|background-color|bgcolor)[:=]\\\s*(["\']?)([\(\)%,#\\\w]+)(\\1)[^>]*>', '<tr[^>]*>', '<t[dh]([^>]*(width|colspan|rowspan)[^>]*)>', '<t[dh][^>]*>', '<\/t[dh]>', '<\/tr>', '<\/table>'], [function($1, $2) {return tabletag($2);}, '[table]', function($1, $2, $3) {return '[tr=' + $3 + ']';}, '[tr]', function($1, $2) {return tdtag($2);}, '[td]', '[/td]', '[/tr]', '[/table]'], str);
str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smilies[$3]['code'];});
str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, '$4');
str = str.replace(/<br\s+?style=(["']?)clear: both;?(\1)[^\>]*>/ig, '');
str = str.replace(/<br[^\>]*>/ig, "\n");
str = recursion('b', str, 'simpletag', 'b');
str = recursion('strong', str, 'simpletag', 'b');
str = recursion('i', str, 'simpletag', 'i');
str = recursion('em', str, 'simpletag', 'i');
str = recursion('u', str, 'simpletag', 'u');
str = recursion('a', str, 'atag');
str = recursion('font', str, 'fonttag');
str = recursion('blockquote', str, 'simpletag', 'indent');
str = recursion('ol', str, 'listtag');
str = recursion('ul', str, 'listtag');
str = recursion('div', str, 'dpstag');
str = recursion('p', str, 'dpstag');
str = recursion('span', str, 'dpstag');
}
str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');
for(var i = 0; i <= codecount; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
}
return preg_replace(['&', ' ', '<', '>'], ['&', ' ', '<', '>'], str);
}
function htmlspecialchars(str) {
return preg_replace([(is_mac && is_ie ? '&' : '&(?!#[0-9]+;)'), '<', '>', '"'], ['&', '<', '>', '"'], str);
}
function imgtag(attributes) {
var width = '';
var height = '';
re = /src=(["']?)([\s\S]*?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
var src = matches[2];
} else {
return '';
}
re = /width\s?:\s?(\d{1,4})px/ig;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[1];
}
re = /height\s?:\s?(\d{1,4})px/ig;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[1];
}
if(!width || !height) {
re = /width=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
re = /height=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[2];
}
}
re = /aid=(["']?)attach_(\d+)(\1)/i;
var matches = re.exec(attributes);
var imgtag = 'img';
if(matches != null) {
imgtag = 'localimg';
src = matches[2];
}
re = /aid=(["']?)attachimg_(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
return '[attachimg]' + matches[2] + '[/attachimg]';
}
return width > 0 && height > 0 ?
'[' + imgtag + '=' + width + ',' + height + ']' + src + '[/' + imgtag + ']' :
'[img]' + src + '[/img]';
}
function listtag(listoptions, text, tagname) {
text = text.replace(/<li>(([\s\S](?!<\/li))*?)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (is_opera ? '</li>' : '');
text = recursion('li', text, 'litag');
var opentag = '[list]';
var listtype = fetchoptionvalue('type=', listoptions);
listtype = listtype != '' ? listtype : (tagname == 'ol' ? '1' : '');
if(in_array(listtype, ['1', 'a', 'A'])) {
opentag = '[list=' + listtype + ']';
}
return text ? opentag + recursion(tagname, text, 'listtag') + '[/list]' : '';
}
function litag(listoptions, text) {
return '[*]' + text.replace(/(\s+)$/g, '');
}
function parsecode(text) {
codecount++;
text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
text = htmlspecialchars(text);
codehtml[codecount] = '[code]' + text + '[/code]';
return "[\tDISCUZ_CODE_" + codecount + "\t]";
}
function parsestyle(tagoptions, prepend, append) {
var searchlist = [
['align', true, 'text-align:\\s*(left|center|right);?', 1],
['float', true, 'float:\\s*(left|right);?', 1],
['color', true, '^(?:\\s|)color:\\s*([^;]+);?', 1],
['font', true, 'font-family:\\s*([^;]+);?', 1],
['size', true, 'font-size:\\s*(\\d+(\\.\\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
['b', false, 'font-weight:\\s*(bold);?'],
['i', false, 'font-style:\\s*(italic);?'],
['u', false, 'text-decoration:\\s*(underline);?']
];
var style = getoptionvalue('style', tagoptions);
re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/ig;
style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});
var len = searchlist.length;
for(var i = 0; i < len; i++) {
re = new RegExp(searchlist[i][2], "ig");
match = re.exec(style);
if(match != null) {
opnvalue = match[searchlist[i][3]];
prepend += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
append = '[/' + searchlist[i][0] + ']' + append;
}
}
return {'prepend' : prepend, 'append' : append};
}
function parsetable(width, bgcolor, str) {
if(isUndefined(width)) {
var width = '';
} else {
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
}
str = str.replace(/\[tr(?:=([\(\)%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4, $5) {
return '<tr' + ($2 ? ' style="background: ' + $2 + '"' : '') + '><td' + ($3 ? ' colspan="' + $3 + '"' : '') + ($4 ? ' rowspan="' + $4 + '"' : '') + ($5 ? ' width="' + $5 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4) {
return '</td><td' + ($2 ? ' colspan="' + $2 + '"' : '') + ($3 ? ' rowspan="' + $3 + '"' : '') + ($4 ? ' width="' + $4 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[\/tr\]/ig, '</td></tr>');
return '<table ' + (width == '' ? '' : 'width="' + width + '" ') + 'class="t_table"' + (isUndefined(bgcolor) ? '' : ' style="background: ' + bgcolor + '"') + '>' + str + '</table>';
}
function preg_replace(search, replace, str) {
var len = search.length;
for(var i = 0; i < len; i++) {
re = new RegExp(search[i], "ig");
str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
}
return str;
}
function recursion(tagname, text, dofunction, extraargs) {
if(extraargs == null) {
extraargs = '';
}
tagname = tagname.toLowerCase();
var open_tag = '<' + tagname;
var open_tag_len = open_tag.length;
var close_tag = '</' + tagname + '>';
var close_tag_len = close_tag.length;
var beginsearchpos = 0;
do {
var textlower = text.toLowerCase();
var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
if(tagbegin == -1) {
break;
}
var strlen = text.length;
var inquote = '';
var found = false;
var tagnameend = false;
var optionend = 0;
var t_char = '';
for(optionend = tagbegin; optionend <= strlen; optionend++) {
t_char = text.charAt(optionend);
if((t_char == '"' || t_char == "'") && inquote == '') {
inquote = t_char;
} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
inquote = '';
} else if(t_char == '>' && !inquote) {
found = true;
break;
} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
tagnameend = optionend;
}
}
if(!found) {
break;
}
if(!tagnameend) {
tagnameend = optionend;
}
var offset = optionend - (tagbegin + open_tag_len);
var tagoptions = text.substr(tagbegin + open_tag_len, offset)
var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);
if(acttagname != tagname) {
beginsearchpos = optionend;
continue;
}
var tagend = textlower.indexOf(close_tag, optionend);
if(tagend == -1) {
break;
}
var nestedopenpos = textlower.indexOf(open_tag, optionend);
while(nestedopenpos != -1 && tagend != -1) {
if(nestedopenpos > tagend) {
break;
}
tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
}
if(tagend == -1) {
beginsearchpos = optionend;
continue;
}
var localbegin = optionend + 1;
var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);
text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);
beginsearchpos = tagbegin + localtext.length;
} while(tagbegin != -1);
return text;
}
function simpletag(options, text, tagname, parseto) {
if(trim(text) == '') {
return '';
}
text = recursion(tagname, text, 'simpletag', parseto);
return '[' + parseto + ']' + text + '[/' + parseto + ']';
}
function strpos(haystack, needle, offset) {
if(isUndefined(offset)) {
offset = 0;
}
index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return index == -1 ? false : index;
}
function tabletag(attributes) {
var width = '';
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
(matches[2] <= 560 ? matches[2] : '98%');
} else {
re = /width\s?:\s?(\d{1,4})([px|%])/ig;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] : '98%') : (matches[1] <= 560 ? matches[1] : '98%');
}
}
var bgcolor = '';
re = /(?:background|background-color|bgcolor)[:=]\s*(["']?)((rgb\(\d{1,3}%?,\s*\d{1,3}%?,\s*\d{1,3}%?\))|(#[0-9a-fA-F]{3,6})|([a-zA-Z]{1,20}))(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
bgcolor = matches[2];
width = width ? width : '98%';
}
return bgcolor ? '[table=' + width + ',' + bgcolor + ']' : (width ? '[table=' + width + ']' : '[table]');
}
function tdtag(attributes) {
var colspan = 1;
var rowspan = 1;
var width = '';
re = /colspan=(["']?)(\d{1,2})(\1)/ig;
var matches = re.exec(attributes);
if(matches != null) {
colspan = matches[2];
}
re = /rowspan=(["']?)(\d{1,2})(\1)/ig;
var matches = re.exec(attributes);
if(matches != null) {
rowspan = matches[2];
}
re = /width=(["']?)(\d{1,4}%?)(\1)/ig;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
return in_array(width, ['', '0', '100%']) ?
(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
'[td=' + colspan + ',' + rowspan + ',' + width + ']';
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/bbcode.js | JavaScript | asf20 | 19,759 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: editor.js,v $
$Revision: 1.62 $
$Date: 2007/08/03 09:38:16 $
*/
var editbox = editwin = editdoc = editcss = null;
var cursor = -1;
var stack = new Array();
var initialized = false;
newEditor(wysiwyg);
function newEditor(mode, initialtext) {
wysiwyg = parseInt(mode);
if(!(is_ie || is_moz || (is_opera >= 9))) {
allowswitcheditor = wysiwyg = 0;
}
var bbcodemode = $('bbcodemode');
var wysiwygmode = $('wysiwygmode');
bbcodemode.className = wysiwyg ? 'editor_switcher' : 'editor_switcher_highlight';
wysiwygmode.className = wysiwyg ? 'editor_switcher_highlight' : 'editor_switcher';
if(!allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
$(editorid + '_cmd_table').style.display = wysiwyg ? '' : 'none';
if(wysiwyg) {
if($(editorid + '_iframe')) {
editbox = $(editorid + '_iframe');
} else {
var iframe = document.createElement('iframe');
editbox = textobj.parentNode.appendChild(iframe);
editbox.id = editorid + '_iframe';
}
editwin = editbox.contentWindow;
editdoc = editwin.document;
writeEditorContents(isUndefined(initialtext) ? textobj.value : initialtext);
} else {
editbox = editwin = editdoc = textobj;
if(!isUndefined(initialtext)) {
writeEditorContents(initialtext);
}
addSnapshot(textobj.value);
}
setEditorEvents();
initEditor();
}
function initEditor() {
var buttons = $(editorid + '_controls').getElementsByTagName('a');
for(var i = 0; i < buttons.length; i++) {
if(buttons[i].id.indexOf(editorid + '_cmd_') != -1) {
buttons[i].href = '###';
buttons[i].onclick = function(e) {discuzcode(this.id.substr(this.id.lastIndexOf('_cmd_') + 5))};
} else if(buttons[i].id.indexOf(editorid + '_popup_') != -1) {
buttons[i].href = '###';
buttons[i].onclick = function(e) {showMenu(this.id, true, 0, 3)};
}
}
setUnselectable($(editorid + '_controls'));
textobj.onselect = textobj.onclick = textobj.onkeyup = function(e) {storeCaret(this)};
textobj.onkeydown = function(e) {ctlent(e ? e : event)};
$('bbcodemode').onclick = function() {switchEditor(0)};
$('wysiwygmode').onclick = function() {switchEditor(1)};
$(editorid + '_buttonctrl').href = '###';
$(editorid + '_buttonctrl').onclick = function() {advanceeditor()};
}
function setUnselectable(obj) {
if(is_ie && is_ie > 4 && typeof obj.tagName != 'undefined') {
if(obj.hasChildNodes()) {
for(var i = 0; i < obj.childNodes.length; i++) {
setUnselectable(obj.childNodes[i]);
}
}
obj.unselectable = 'on';
}
}
function writeEditorContents(text) {
if(wysiwyg) {
if(text == '' && is_moz) {
text = '<br />';
}
if(initialized) {
editdoc.body.innerHTML = text;
} else {
editdoc.designMode = 'on';
editdoc = editwin.document;
editdoc.open('text/html', 'replace');
editdoc.write(text);
editdoc.close();
editdoc.body.contentEditable = true;
initialized = true;
}
} else {
textobj.value = text;
}
setEditorStyle();
}
function getEditorContents() {
return wysiwyg ? editdoc.body.innerHTML : editdoc.value;
}
function setEditorStyle() {
if(wysiwyg) {
textobj.style.display = 'none';
editbox.style.display = '';
if(editcss == null) {
var cssarray = [editorcss, editorcss_append];
for(var i = 0; i < 2; i++) {
editcss = editdoc.createElement('link');
editcss.type = 'text/css';
editcss.rel = 'stylesheet';
editcss.href = cssarray[i];
var headNode = editdoc.getElementsByTagName("head")[0];
headNode.appendChild(editcss);
}
}
if(is_moz || is_opera) {
editbox.style.border = '0px';
} else if(is_ie) {
editdoc.body.style.border = '0px';
editdoc.body.addBehavior('#default#userData');
}
editbox.style.width = textobj.style.width;
editbox.style.height = textobj.style.height;
editdoc.body.style.backgroundColor = TABLEBG;
editdoc.body.style.textAlign = 'left';
editdoc.body.id = 'wysiwyg';
} else {
var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
if(iframe) {
textobj.style.display = '';
textobj.style.width = iframe.style.width;
textobj.style.height = iframe.style.height;
iframe.style.display = 'none';
}
}
}
function setEditorEvents() {
if(wysiwyg) {
if(is_moz || is_opera) {
editdoc.addEventListener('mouseup', function(e) {setContext();}, true);
editdoc.addEventListener('keyup', function(e) {setContext();}, true);
editwin.addEventListener('focus', function(e) {this.hasfocus = true;}, true);
editwin.addEventListener('blur', function(e) {this.hasfocus = false;}, true);
editwin.addEventListener('keydown', function(e) {ctlent(e);}, true);
} else {
editdoc.onmouseup = function(e) {setContext();};
editdoc.onkeyup = function(e) {setContext();};
if(editdoc.attachEvent) {
editdoc.body.attachEvent("onkeydown", ctlent);
}
}
}
editwin.onfocus = function(e) {this.hasfocus = true;};
editwin.onblur = function(e) {this.hasfocus = false;};
}
function wrapTags(tagname, useoption, selection) {
if(isUndefined(selection)) {
var selection = getSel();
if(selection === false) {
selection = '';
} else {
selection += '';
}
}
if(useoption !== false) {
var opentag = '[' + tagname + '=' + useoption + ']';
} else {
var opentag = '[' + tagname + ']';
}
var closetag = '[/' + tagname + ']';
var text = opentag + selection + closetag;
insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);
}
function applyFormat(cmd, dialog, argument) {
if(wysiwyg) {
editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
return;
}
switch(cmd) {
case 'bold':
case 'italic':
case 'underline':
wrapTags(cmd.substr(0, 1), false);
break;
case 'justifyleft':
case 'justifycenter':
case 'justifyright':
wrapTags('align', cmd.substr(7));
break;
case 'floatleft':
case 'floatright':
wrapTags('float', cmd.substr(5));
break;
case 'indent':
wrapTags(cmd, false);
break;
case 'fontname':
wrapTags('font', argument);
break;
case 'fontsize':
wrapTags('size', argument);
break;
case 'forecolor':
wrapTags('color', argument);
break;
case 'createlink':
var sel = getSel();
if(sel) {
wrapTags('url', argument);
} else {
wrapTags('url', argument, argument);
}
break;
case 'insertimage':
wrapTags('img', false, argument);
break;
}
}
function getCaret() {
if(wysiwyg) {
var obj = editdoc.body;
var s = document.selection.createRange();
s.setEndPoint("StartToStart", obj.createTextRange());
return s.text.replace(/\r?\n/g, ' ').length;
} else {
var obj = editbox;
var wR = document.selection.createRange();
obj.select();
var aR = document.selection.createRange();
wR.setEndPoint("StartToStart", aR);
var len = wR.text.replace(/\r?\n/g, ' ').length;
wR.collapse(false);
wR.select();
return len;
}
}
function setCaret(pos) {
var obj = wysiwyg ? editdoc.body : editbox;
var r = obj.createTextRange();
r.moveStart('character', pos);
r.collapse(true);
r.select();
}
function insertlink(cmd) {
var sel;
if(is_ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
var pos = getCaret();
}
var selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
var ctrlid = editorid + '_cmd_' + cmd;
var tag = cmd == 'insertimage' ? 'img' : (cmd == 'createlink' ? 'url' : 'email');
var str = (tag == 'img' ? lang['enter_image_url'] : (tag == 'url' ? lang['enter_link_url'] : lang['enter_email_link'])) + '<br /><input type="text" id="' + ctrlid + '_param_1" size="50" value="">';
var div = editorMenu(ctrlid, str);
$(ctrlid + '_param_1').focus();
$(ctrlid + '_param_1').onkeydown = editorMenuEvent_onkeydown;
$(ctrlid + '_submit').onclick = function() {
checkFocus();
if(is_ie) {
setCaret(pos);
}
var input = $(ctrlid + '_param_1').value;
if(input != '') {
var v = selection ? selection : input;
var href = tag != 'email' && /^(www\.)/.test(input) ? 'http://' + input : input;
var text = wysiwyg ? (tag == 'img' ? '<img src="' + input + '" border="0">' : '<a href="' + (tag == 'email' ? 'mailto:' : '') + href + '">' + v + '</a>') : (tag == 'img' ? '[' + tag + ']' + input + '[/' + tag + ']' : '[' + tag + '=' + href + ']' + v + '[/' + tag + ']');
var closetaglen = tag == 'email' ? 8 : 6;
if(wysiwyg) insertText(text, text.length - v.length, 0, (selection ? true : false), sel);
else insertText(text, text.length - v.length - closetaglen, closetaglen, (selection ? true : false), sel);
}
hideMenu();
document.body.removeChild(div);
}
}
function editorMenuEvent_onkeydown(e) {
e = e ? e : event;
var ctrlid = this.id.substr(0, this.id.lastIndexOf('_param_'));
if((this.type == 'text' && e.keyCode == 13) || (this.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
$(ctrlid + '_submit').click();
doane(e);
} else if(e.keyCode == 27) {
hideMenu();
document.body.removeChild($(ctrlid + '_menu'));
}
}
function customTags(tagname, params) {
var sel;
if(is_ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
var pos = getCaret();
}
var selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
var opentag = '[' + tagname + ']';
var closetag = '[/' + tagname + ']';
var haveSel = selection == null || selection == false || in_array(trim(selection), ['', 'null', 'undefined', 'false']) ? 0 : 1;
if(params == 1 && haveSel) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var ctrlid = editorid + '_cmd_custom' + params + '_' + tagname;
var ordinal = {1 : 'first', 2 : 'second', 3 : 'third'}
var promptlang = custombbcodes[tagname]['prompt'].split("\t");
var str = '';
for(var i = 1; i <= params; i++) {
if(i != params || !haveSel) {
str += (promptlang[i - 1] ? promptlang[i - 1] : 'Please input the ' + ordinal[i] + ' parameter:') + '<br /><input type="text" id="' + ctrlid + '_param_' + i + '" size="50" value="">' + (i < params ? '<br />' : '');
}
}
var div = editorMenu(ctrlid, str);
$(ctrlid + '_param_1').focus();
for(var i = 1; i <= params; i++) {if(i != params || !haveSel) $(ctrlid + '_param_' + i).onkeydown = editorMenuEvent_onkeydown;}
$(ctrlid + '_submit').onclick = function() {
var first = $(ctrlid + '_param_1').value;
if($(ctrlid + '_param_2')) var second = $(ctrlid + '_param_2').value;
if($(ctrlid + '_param_3')) var third = $(ctrlid + '_param_3').value;
checkFocus();
if(is_ie) {
setCaret(pos);
}
if((params == 1 && first) || (params == 2 && first && (haveSel || second)) || (params == 3 && first && second && (haveSel || third))) {
var text;
if(params == 1) {
text = first;
} else if(params == 2) {
text = haveSel ? selection : second;
opentag = '[' + tagname + '=' + first + ']';
} else {
text = haveSel ? selection : third;
opentag = '[' + tagname + '=' + first + ',' + second + ']';
}
insertText((opentag + text + closetag), strlen(opentag), strlen(closetag), true, sel);
}
hideMenu();
document.body.removeChild(div);
};
}
function editorMenu(ctrlid, str) {
var div = document.createElement('div');
div.id = ctrlid + '_menu';
div.style.display = 'none';
div.className = 'popupmenu_popup';
document.body.appendChild(div);
div.innerHTML = '<div class="popupmenu_option" unselectable="on">' + str + '<br /><center><input type="button" id="' + ctrlid + '_submit" value="' + lang['submit'] + '" /> <input type="button" onClick="hideMenu();try{document.body.removeChild(' + div.id + ')}catch(e){}" value="' + lang['cancel'] + '" /></center></div>';
showMenu(ctrlid, true, 0, 3);
return div;
}
function discuzcode(cmd, arg) {
if(cmd != 'redo') {
addSnapshot(getEditorContents());
}
checkFocus();
if(in_array(cmd, ['quote', 'code', 'free', 'hide'])) {
var sel;
if(is_ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
var pos = getCaret();
}
var selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
var opentag = '[' + cmd + ']';
var closetag = '[/' + cmd + ']';
if(cmd != 'hide' && selection) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var ctrlid = editorid + '_cmd_' + cmd;
var str = '';
if(cmd != 'hide' || !selection) {
str += lang['post_discuzcode_' + cmd] + ':<br /><textarea id="' + ctrlid + '_param_1" cols="50" rows="5"></textarea>';
}
str += cmd == 'hide' && selection ? '' : '<br />';
str += cmd == 'hide' ? '<input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_1" checked="checked">只有当浏览者回复本帖时才显示<br /><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_2">只有当浏览者积分高于 <input type="text" size="3" id="' + ctrlid + '_param_2"> 时才显示' : '';
var div = editorMenu(ctrlid, str);
$(ctrlid + '_param_' + (cmd == 'hide' && selection ? 2 : 1)).focus();
$(ctrlid + '_param_' + (cmd == 'hide' && selection ? 2 : 1)).onkeydown = editorMenuEvent_onkeydown;
$(ctrlid + '_submit').onclick = function() {
checkFocus();
if(is_ie) {
setCaret(pos);
}
if(cmd == 'hide' && $(ctrlid + '_radio_2').checked) {
var mincredits = parseInt($(ctrlid + '_param_2').value);
opentag = mincredits > 0 ? '[hide=' + mincredits + ']' : '[hide]';
}
var text = selection ? selection : $(ctrlid + '_param_1').value;
text = wysiwyg ? text.replace(/\r?\n/g, '<br />') : text;
text = opentag + text + closetag;
insertText(text, strlen(opentag), strlen(closetag), false, sel);
hideMenu();
document.body.removeChild(div);
}
return;
} else if(cmd.substr(0, 6) == 'custom') {
var ret = customTags(cmd.substr(8), cmd.substr(6, 1));
} else if(!wysiwyg && cmd == 'removeformat') {
var simplestrip = new Array('b', 'i', 'u');
var complexstrip = new Array('font', 'color', 'size');
var str = getSel();
if(str === false) {
return;
}
for(var tag in simplestrip) {
str = stripSimple(simplestrip[tag], str);
}
for(var tag in complexstrip) {
str = stripComplex(complexstrip[tag], str);
}
insertText(str);
} else if(!wysiwyg && cmd == 'undo') {
addSnapshot(getEditorContents());
moveCursor(-1);
if((str = getSnapshot()) !== false) {
editdoc.value = str;
}
} else if(!wysiwyg && cmd == 'redo') {
moveCursor(1);
if((str = getSnapshot()) !== false) {
editdoc.value = str;
}
} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
var listtype = cmd == 'insertorderedlist' ? '1' : '';
var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
var closetag = '[/list]';
if(txt = getSel()) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
while(listvalue = prompt(lang['enter_list_item'], '')) {
if(is_opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertText(listvalue, strlen(listvalue) + 1, 0);
} else {
listvalue = '[*]' + listvalue + '\n';
insertText(listvalue, strlen(listvalue), 0);
}
}
}
} else if(!wysiwyg && cmd == 'outdent') {
var sel = getSel();
sel = stripSimple('indent', sel, 1);
insertText(sel);
} else if(cmd == 'createlink') {
insertlink('createlink');
} else if(!wysiwyg && cmd == 'unlink') {
var sel = getSel();
sel = stripSimple('url', sel);
sel = stripComplex('url', sel);
insertText(sel);
} else if(cmd == 'email') {
insertlink('email');
} else if(cmd == 'insertimage') {
insertlink('insertimage');
} else if(cmd == 'table') {
if(wysiwyg) {
var selection = getSel();
if(is_ie) {
var pos = getCaret();
}
var ctrlid = editorid + '_cmd_table';
var str = '表格行数: <input type="text" id="' + ctrlid + '_param_rows" size="10" value="2" /> 表格列数: <input type="text" id="' + ctrlid + '_param_columns" size="10" value="2" /><br />表格宽度: <input type="text" id="' + ctrlid + '_param_width" size="10" value="" /> 背景颜色: <input type="text" id="' + ctrlid + '_param_bgcolor" size="10" />';
var div = editorMenu(ctrlid, str);
$(ctrlid + '_param_rows').focus();
var params = ['rows', 'columns', 'width', 'bgcolor'];
for(var i = 0; i < 4; i++) {$(ctrlid + '_param_' + params[i]).onkeydown = editorMenuEvent_onkeydown;}
$(ctrlid + '_submit').onclick = function() {
var rows = $(ctrlid + '_param_rows').value;
var columns = $(ctrlid + '_param_columns').value;
var width = $(ctrlid + '_param_width').value;
var bgcolor = $(ctrlid + '_param_bgcolor').value;
rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
bgcolor = /[\(\)%,#\w]+/.test(bgcolor) ? bgcolor : '';
var html = '<table cellspacing="0" cellpadding="0" width="' + (width ? width : '50%') + '" class="t_table"' + (bgcolor ? ' bgcolor="' + bgcolor + '"' : '') + '>';
for (var row = 0; row < rows; row++) {
html += '<tr>\n';
for (col = 0; col < columns; col++) {
html += '<td> </td>\n';
}
html+= '</tr>\n';
}
html += '</table>\n';
insertText(html);
hideMenu();
document.body.removeChild(div);
}
}
return false;
} else if(cmd == 'floatleft' || cmd == 'floatright') {
if(wysiwyg) {
var selection = getSel();
if(selection) {
insertText('<br style="clear: both"><span style="float: ' + cmd.substr(5) + '">' + selection + '</span>', true);
}
} else {
return applyFormat(cmd, false);
}
} else {
try {
var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
} catch(e) {
var ret = false;
}
}
if(cmd != 'undo') {
addSnapshot(getEditorContents());
}
if(wysiwyg) {
setContext(cmd);
if(cmd == 'forecolor') {
$(editorid + '_color_bar').style.backgroundColor = arg;
}
}
//checkFocus();
return ret;
}
function setContext(cmd) {
var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
for(var i in contextcontrols) {
var obj = $(editorid + '_cmd_' + contextcontrols[i]);
if(obj != null) {
try {
var state = editdoc.queryCommandState(contextcontrols[i]);
} catch(e) {
var state = false;
}
if(isUndefined(obj.state)) {
obj.state = false;
}
if(obj.state != state) {
obj.state = state;
buttonContext(obj, (obj.id.substr(obj.id.indexOf('_cmd_') + 5) == cmd ? 'mouseover' : 'mouseout'));
}
}
}
var fs = editdoc.queryCommandValue('fontname');
if(fs == '' && !is_ie && window.getComputedStyle) {
fs = editdoc.body.style.fontFamily;
} else if(fs == null) {
fs = '';
}
fs = fs ? fs : '字体';
if(fs != $(editorid + '_font_out').fontstate) {
thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
$(editorid + '_font_out').innerHTML = thingy;
$(editorid + '_font_out').fontstate = fs;
}
var ss = editdoc.queryCommandValue('fontsize');
if(ss == null || ss == '') {
ss = formatFontsize(editdoc.body.style.fontSize);
}
if(ss != $(editorid + '_size_out').sizestate) {
if($(editorid + '_size_out').sizestate == null) {
$(editorid + '_size_out').sizestate = '';
}
$(editorid + '_size_out').innerHTML = ss;
$(editorid + '_size_out').sizestate = ss;
}
var cs = editdoc.queryCommandValue('forecolor');
$(editorid + '_color_bar').style.backgroundColor = rgbToColor(cs);
}
function buttonContext(obj, state) {
if(state == 'mouseover') {
obj.style.cursor = 'pointer';
var mode = obj.state ? 'down' : 'hover';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = 'hover';
}
} else {
var mode = obj.state ? 'selected' : 'normal';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = mode == 'selected' ? 'hover' : '';
}
}
}
function menuContext(obj, state) {
obj.style.cursor = 'pointer';
var mode = state == 'mouseover' ? 'hover' : 'normal';
obj.className = 'editor_button' + mode;
var tds = obj.getElementsByTagName('td');
for(var i = 0; i < tds.length; i++) {
if(tds[i].id.substr(0, tds[i].id.lastIndexOf('_')) == editorid + '_menu') {
tds[i].className = 'editor_menu' + mode;
} else if(tds[i].id == editorid + '_colormenu') {
tds[i].className = 'editor_colormenu' + mode;
}
}
}
function colorContext(obj, state) {
obj.style.cursor = 'pointer';
var mode = state == 'mouseover' ? 'hover' : 'normal';
obj.className = 'editor_color' + mode;
}
function getSel() {
if(wysiwyg) {
if(is_moz || is_opera) {
selection = editwin.getSelection();
checkFocus();
range = selection ? selection.getRangeAt(0) : editdoc.createRange();
return readNodes(range.cloneContents(), false);
} else {
var range = editdoc.selection.createRange();
if(range.htmlText && range.text) {
return range.htmlText;
} else {
var htmltext = '';
for(var i = 0; i < range.length; i++) {
htmltext += range.item(i).outerHTML;
}
return htmltext;
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
}
function insertText(text, movestart, moveend, select, sel) {
if(wysiwyg) {
if(is_moz || is_opera) {
applyFormat('removeformat');
var fragment = editdoc.createDocumentFragment();
var holder = editdoc.createElement('span');
holder.innerHTML = text;
while(holder.firstChild) {
fragment.appendChild(holder.firstChild);
}
insertNodeAtSelection(fragment);
} else {
checkFocus();
if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
movestart = false;
editdoc.selection.clear();
}
if(isUndefined(sel)) {
sel = editdoc.selection.createRange();
}
sel.pasteHTML(text);
if(text.indexOf('\n') == -1) {
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) + movestart);
sel.moveEnd('character', -moveend);
} else if(movestart != false) {
sel.moveStart('character', -strlen(text));
}
if(!isUndefined(select) && select) {
sel.select();
}
}
}
} else {
checkFocus();
if(!isUndefined(editdoc.selectionStart)) {
var opn = editdoc.selectionStart + 0;
editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
if(!isUndefined(movestart)) {
editdoc.selectionStart = opn + movestart;
editdoc.selectionEnd = opn + strlen(text) - moveend;
} else if(movestart !== false) {
editdoc.selectionStart = opn;
editdoc.selectionEnd = opn + strlen(text);
}
} else if(document.selection && document.selection.createRange) {
if(isUndefined(sel)) {
sel = document.selection.createRange();
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) +movestart);
sel.moveEnd('character', -moveend);
} else if(movestart !== false) {
sel.moveStart('character', -strlen(text));
}
sel.select();
} else {
editdoc.value += text;
}
}
}
function stripSimple(tag, str, iterations) {
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
}
return str;
}
function stripComplex(tag, str, iterations) {
var opentag = '[' + tag + '=';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var openend = stripos(str, ']', startindex);
if(openend !== false && openend > startindex && openend < stopindex) {
var text = str.substr(openend + 1, stopindex - openend - 1);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
} else {
break;
}
}
return str;
}
function stripos(haystack, needle, offset) {
if(isUndefined(offset)) {
offset = 0;
}
var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return (index == -1 ? false : index);
}
function switchEditor(mode) {
mode = parseInt(mode);
if(mode == wysiwyg || !allowswitcheditor) {
return;
}
if(!mode) {
var controlbar = $(editorid + '_controls');
var controls = new Array();
var buttons = controlbar.getElementsByTagName('a');
var buttonslength = buttons.length;
for(var i = 0; i < buttonslength; i++) {
if(buttons[i].id) {
controls[controls.length] = buttons[i].id;
}
}
var controlslength = controls.length;
for(var i = 0; i < controlslength; i++) {
var control = $(controls[i]);
if(control.id.indexOf(editorid + '_cmd_') != -1) {
control.className = '';
control.state = false;
control.mode = 'normal';
} else if(control.id.indexOf(editorid + '_popup_') != -1) {
control.state = false;
}
}
}
cursor = -1;
stack = new Array();
$(editorid + '_font_out').innerHTML = lang['fontname'];
$(editorid + '_size_out').innerHTML = lang['fontsize'];
$(editorid + '_font_out').fontstate = null;
$(editorid + '_size_out').sizestate = null;
$(editorid + '_color_bar').style.backgroundColor = '#000000';
var parsedtext = getEditorContents();
parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
wysiwyg = mode;
$(editorid + '_mode').value = mode;
newEditor(mode, parsedtext);
editwin.focus();
setCaretAtEnd();
}
function formatFontsize(csssize) {
switch(csssize) {
case '7.5pt':
case '10px': return 1;
case '10pt': return 2;
case '12pt': return 3;
case '14pt': return 4;
case '18pt': return 5;
case '24pt': return 6;
case '36pt': return 7;
default: return lang['fontsize'];
}
}
function rgbToColor(forecolor) {
if(!is_moz && !is_opera) {
return rgbhexToColor((forecolor & 0xFF).toString(16), ((forecolor >> 8) & 0xFF).toString(16), ((forecolor >> 16) & 0xFF).toString(16));
}
if(forecolor == '' || forecolor == null) {
forecolor = window.getComputedStyle(editdoc.body, null).getPropertyValue('color');
}
if(forecolor.toLowerCase().indexOf('rgb') == 0) {
var matches = forecolor.match(/^rgb\s*\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)$/);
if(matches) {
return rgbhexToColor((matches[1] & 0xFF).toString(16), (matches[2] & 0xFF).toString(16), (matches[3] & 0xFF).toString(16));
} else {
return rgbToColor(null);
}
} else {
return forecolor;
}
}
function rgbhexToColor(r, g, b) {
var coloroptions = {'#000000' : 'Black', '#a0522d' : 'Sienna', '#556b2f' : 'DarkOliveGreen', '#006400' : 'DarkGreen', '#483d8b' : 'DarkSlateBlue', '#000080' : 'Navy', '#4b0082' : 'Indigo', '#2f4f4f' : 'DarkSlateGray', '#8b0000' : 'DarkRed', '#ff8c00' : 'DarkOrange', '#808000' : 'Olive', '#008000' : 'Green', '#008080' : 'Teal', '#0000ff' : 'Blue', '#708090' : 'SlateGray', '#696969' : 'DimGray', '#ff0000' : 'Red', '#f4a460' : 'SandyBrown', '#9acd32' : 'YellowGreen', '#2e8b57' : 'SeaGreen', '#48d1cc' : 'MediumTurquoise', '#4169e1' : 'RoyalBlue', '#800080' : 'Purple', '#808080' : 'Gray', '#ff00ff' : 'Magenta', '#ffa500' : 'Orange', '#ffff00' : 'Yellow', '#00ff00' : 'Lime', '#00ffff' : 'Cyan', '#00bfff' : 'DeepSkyBlue', '#9932cc' : 'DarkOrchid', '#c0c0c0' : 'Silver', '#ffc0cb' : 'Pink', '#f5deb3' : 'Wheat', '#fffacd' : 'LemonChiffon', '#98fb98' : 'PaleGreen', '#afeeee' : 'PaleTurquoise', '#add8e6' : 'LightBlue', '#dda0dd' : 'Plum', '#ffffff' : 'White'};
return coloroptions['#' + (str_pad(r, 2, 0) + str_pad(g, 2, 0) + str_pad(b, 2, 0))];
}
function str_pad(text, length, padstring) {
text += '';
padstring += '';
if(text.length < length) {
padtext = padstring;
while(padtext.length < (length - text.length)) {
padtext += padstring;
}
text = padtext.substr(0, (length - text.length)) + text;
}
return text;
}
function insertNodeAtSelection(text) {
checkFocus();
var sel = editwin.getSelection();
var range = sel ? sel.getRangeAt(0) : editdoc.createRange();
sel.removeAllRanges();
range.deleteContents();
var node = range.startContainer;
var pos = range.startOffset;
switch(node.nodeType) {
case Node.ELEMENT_NODE:
if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
selNode = text.firstChild;
} else {
selNode = text;
}
node.insertBefore(text, node.childNodes[pos]);
add_range(selNode);
break;
case Node.TEXT_NODE:
if(text.nodeType == Node.TEXT_NODE) {
var text_length = pos + text.length;
node.insertData(pos, text.data);
range = editdoc.createRange();
range.setEnd(node, text_length);
range.setStart(node, text_length);
sel.addRange(range);
} else {
node = node.splitText(pos);
var selNode;
if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
selNode = text.firstChild;
} else {
selNode = text;
}
node.parentNode.insertBefore(text, node);
add_range(selNode);
}
break;
}
}
function add_range(node) {
checkFocus();
var sel = editwin.getSelection();
var range = editdoc.createRange();
range.selectNodeContents(node);
sel.removeAllRanges();
sel.addRange(range);
}
function readNodes(root, toptag) {
var html = "";
var moz_check = /_moz/i;
switch(root.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
var closed;
if(toptag) {
closed = !root.hasChildNodes();
html = '<' + root.tagName.toLowerCase();
var attr = root.attributes;
for(var i = 0; i < attr.length; ++i) {
var a = attr.item(i);
if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
continue;
}
html += " " + a.name.toLowerCase() + '="' + a.value + '"';
}
html += closed ? " />" : ">";
}
for(var i = root.firstChild; i; i = i.nextSibling) {
html += readNodes(i, true);
}
if(toptag && !closed) {
html += "</" + root.tagName.toLowerCase() + ">";
}
break;
case Node.TEXT_NODE:
html = htmlspecialchars(root.data);
break;
}
return html;
}
function moveCursor(increment) {
var test = cursor + increment;
if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
cursor += increment;
}
}
function addSnapshot(str) {
if(stack[cursor] == str) {
return;
} else {
cursor++;
stack[cursor] = str;
if(!isUndefined(stack[cursor + 1])) {
stack[cursor + 1] = null;
}
}
}
function getSnapshot() {
if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
return stack[cursor];
} else {
return false;
}
}
function advanceeditor() {
if($(editorid + '_morebuttons0').style.display == '') {
$(editorid + '_morebuttons0').style.display = 'none';
for(var i = 1; i < 3; i++) {
if($(editorid + '_morebuttons' + i)) $(editorid + '_morebuttons' + i).style.display = 'none';
}
$(editorid + '_left').style.display = 'none';
$(editorid + '_bottom').style.display = 'none';
$(editorid + '_buttonctrl').innerHTML = lang['post_advanceeditor'];
} else {
$(editorid + '_morebuttons0').style.display = '';
for(var i = 1; i < 3; i++) {
if($(editorid + '_morebuttons' + i)) $(editorid + '_morebuttons' + i).style.display = '';
}
$(editorid + '_left').style.display = '';
$(editorid + '_bottom').style.display = '';
$(editorid + '_buttonctrl').innerHTML = lang['post_simpleeditor'];
}
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/editor.js | JavaScript | asf20 | 33,468 |
document.writeln('<script type="text/javascript">');
document.writeln('function validate_google(theform) {');
document.writeln(' if(theform.site.value == 1) {');
document.writeln(' theform.q.value = \'site:' + google_host + ' \' + theform.q.value;');
document.writeln(' }');
document.writeln('}');
document.writeln('function submitFormWithChannel(channelname) {');
document.writeln(' document.gform.channel.value=channelname;');
document.writeln(' document.gform.submit();');
document.writeln(' return;');
document.writeln('}');
document.writeln('</script>');
document.writeln('<form name="gform" id="gform" method="get" action="http://www.google.cn/search?" target="_blank" onSubmit="validate_google(this);">');
document.writeln('<input type="hidden" name="client" value="aff-discuz" />');
document.writeln('<input type="hidden" name="ie" value="' + google_charset + '" />');
document.writeln('<input type="hidden" name="oe" value="UTF-8" />');
document.writeln('<input type="hidden" name="hl" value="' + google_hl + '" />');
document.writeln('<input type="hidden" name="lr" value="' + google_lr + '" />');
document.writeln('<input type="hidden" name="channel" value="search" />');
document.write('<div onclick="javascript:submitFormWithChannel(\'logo\')" style="cursor:pointer;float: left;width:70px;height:23px;background: url(images/common/Google_small.png) !important;background: none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/common/Google_small.png\', sizingMethod=\'scale\')"><img src="images/common/none.gif" border="0" alt="Google" /></div>');
document.writeln(' <input type="text" size="10" name="q" id="q" maxlength="255" value=""></input>');
document.writeln('<select name="site">');
document.writeln('<option value="0">网页搜索</option>');
document.writeln('<option value="1">站内搜索</option>');
document.writeln('</select>');
document.writeln(' <button type="submit" name="sa" value="true">搜索</button>');
document.writeln('</form>');
| zyyhong | trunk/jiaju001/bbs/include/javascript/google.js | JavaScript | asf20 | 2,035 |
var Ajaxs = new Array();
function Ajax(waitId) {
var aj = new Object();
aj.waitId = waitId ? $(waitId) : null;
aj.targetUrl = '';
aj.sendString = '';
aj.resultHandle = null;
aj.loading = '<img src="image/common/loading.gif" style="margin: 3px; vertical-align: middle" />Loading... ';
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) request.overrideMimeType('text/xml');
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) return request;
} catch(e) {/*alert(e.message);*/}
}
}
return request;
}
aj.request = aj.createXMLHttpRequest();
if(aj.waitId) {
aj.waitId.orgdisplay = aj.waitId.style.display;
aj.waitId.style.display = '';
aj.waitId.innerHTML = aj.loading;
}
aj.processHandle = function() {
if(aj.request.readyState == 4 && aj.request.status == 200) {
for(k in Ajaxs) {
if(Ajaxs[k] == aj.targetUrl) Ajaxs[k] = null;
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
aj.waitId.style.display = aj.waitId.orgdisplay;
}
aj.resultHandle(aj.request.responseXML.lastChild.firstChild.nodeValue);
}
}
aj.get = function(targetUrl, resultHandle) {
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
if(window.XMLHttpRequest) {
aj.request.open('GET', aj.targetUrl);
aj.request.send(null);
} else {
aj.request.open("GET", targetUrl, true);
aj.request.send();
}
}
/* aj.post = function(targetUrl, sendString, resultHandle) {
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.request.open('POST', targetUrl);
aj.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.request.send(aj.sendString);
}*/
return aj;
}
function show(id, display) {
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
}
/*
ajaxget('www.baidu.com', 'showid', 'waitid', 'display(\'showid\', 1)');
*/
function ajaxget(url, showId, waitId, display, recall) {
e = is_ie ? event : ajaxget.caller.arguments[0];
ajaxget2(e, url, showId, waitId, display, recall);
_cancelBubble(e);
}
function ajaxget2(e, url, showId, waitId, display, recall) {
target = e ? (is_ie ? e.srcElement : e.target) : null;
display = display ? display : '';
var x = new Ajax(waitId);
x.showId = showId;
x.display = display;
var sep = url.indexOf('?') != -1 ? '&' : '?';
x.target = target;
x.recall = recall;
x.get(url+sep+'inajax=1', function(s) {
if(x.display == 'auto' && x.target) {
x.target.onclick = newfunc('show', x.showId, 'auto');
}
show(x.showId, x.display);
$(x.showId).innerHTML = s;
evalscript(s);
if(x.recall)eval(x.recall);
});
_cancelBubble(e);
}
/*
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}*/
var evalscripts = new Array();
function evalscript(s) {
if(!s || s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\x00]+?)\"[^\>]*( reload=\"1\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2]);
p = /<script[^\>]*?( reload=\"1\")?>([^\x00]+?)<\/script>/ig;
while(arr = p.exec(s)) appendscript('', arr[2], arr[1]);
return s;
}
function appendscript(src, text, reload) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
if(src) {
scriptNode.src = src;
} else if(text){
scriptNode.text = text;
}
$('append').appendChild(scriptNode);
}
// 得到一个定长的 hash 值, 依赖于 stringxor()
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function in_array(needle, haystack) {
for(var i in haystack) {if(haystack[i] == needle) return true;}
return false;
}
function newfunc(func){
var args = new Array();
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(e){
window[func].apply(window, args);
_cancelBubble(is_ie ? event : e);
}
}
function ajaxmenu(url, position) {
e = is_ie ? event : ajaxmenu.caller.arguments[0];
controlid = is_ie ? e.srcElement : e.target;
var menuid = hash(url);// 使每个 url 对应一个弹出层,避免重复请求
createmenu(menuid);
showmenu2(e, menuid, position, controlid);
if(!$(menuid).innerHTML) {
ajaxget2(e, url, menuid, menuid, '', "setposition('" + menuid + "', '" + position + "', '" + controlid + "')");
} else {
//alert(menuid.innerHTML);
}
_cancelBubble(e);
}
var ajaxpostHandle = null;
function ajaxpost(formid, showid, recall) {
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
if(ajaxframe == null) {
if (is_ie) {
ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");
} else {
ajaxframe = document.createElement("iframe");
ajaxframe.name = ajaxframeid;
ajaxframe.id = ajaxframeid;
}
ajaxframe.style.display = 'none';
$('append').appendChild(ajaxframe);
}
$(formid).target = ajaxframeid;
ajaxpostHandle = [formid, showid, ajaxframeid, recall];
_attachEvent(ajaxframe, 'load', ajaxpost_load);
$(formid).submit();
return false;
}
function ajaxpost_load() {
var s = (is_ie && $(ajaxpostHandle[2])) ? $(ajaxpostHandle[2]).contentWindow.document.XMLDocument.text : $(ajaxpostHandle[2]).contentWindow.document.documentElement.firstChild.nodeValue;
evalscript(s);
if(s) {
// setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);
$(ajaxpostHandle[1]).innerHTML = s;
if(ajaxpostHandle[3]) {
eval(ajaxpostHandle[3]);
}
// setTimeout("hideMenu()", 3000);
}
// $(ajaxpostHandle[2]).target = ajaxpostHandle[3];
// ajaxpostHandle = null;
}
| zyyhong | trunk/jiaju001/bbs/include/javascript/ajax.js | JavaScript | asf20 | 7,173 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: qihoo.js,v $
$Revision: 1.8 $
$Date: 2007/07/13 13:24:53 $
*/
var qihoo_num = 0;
var qihoo_perpage = 0;
var qihoo_threads = "";
function qihoothreads(num) {
var threadslist = "";
if(num) {
for(i = 0; i < num; i++) {
threadslist += "<tr><td><a href=\"viewthread.php?tid=" + qihoo_threads[i][1] + "\" target=\"_blank\">" + qihoo_threads[i][0] + "</a></td>" +
"<td><a href=\"forumdisplay.php?fid=" + qihoo_threads[i][8] + "\" target=\"_blank\">" + qihoo_threads[i][2] + "</a></td>" +
"<td><a href=\"space.php?action=viewpro&username=" + qihoo_threads[i][3] + "\" target=\"_blank\">" + qihoo_threads[i][3] + "</a><br />" + qihoo_threads[i][6] + "</td>" +
"<td>" + qihoo_threads[i][4] + "</td>" +
"<td>" + qihoo_threads[i][5] + "</td>" +
"<td>" + qihoo_threads[i][7] + "</td></tr>";
}
}
return threadslist;
}
function multi(num, perpage, curpage, mpurl, maxpages) {
var multipage = "";
if(num > perpage) {
var page = 10;
var offset = 2;
var form = 0;
var to = 0;
var maxpages = !maxpages ? 0 : maxpages;
var realpages = Math.ceil(num / perpage);
var pages = maxpages && maxpages < realpages ? maxpages : realpages;
if(page > pages) {
from = 1;
to = pages;
} else {
from = curpage - offset;
to = from + page - 1;
if(from < 1) {
to = curpage + 1 - from;
from = 1;
if(to - from < page) {
to = page;
}
} else if(to > pages) {
from = pages - page + 1;
to = pages;
}
}
multipage = (curpage - offset > 1 && pages > page ? "<a href=\"" + mpurl + "&page=1\" class=\"first\">1 ...</a>" : "") + (curpage > 1 ? "<a href=\"" + mpurl + "&page=" + (curpage - 1) + "\" class=\"prev\">‹‹</a>" : "");
for(i = from; i <= to; i++) {
multipage += (i == curpage ? "<strong>" + i + "</strong>" : "<a href=\"" + mpurl + "&page=" + i + "\">" + i + "</a>");
}
multipage += (curpage < pages ? "<a href=\"" + mpurl + "&page=" + (curpage + 1) + "\" class=\"next\" >››</a>" : "") +
(to < pages ? "<a href=\"" + mpurl + "&page=" + pages + "\ class=\"last\">... " + realpages + "</a>" : "") +
(pages > page ? "<input type=\"text\" name=\"custompage\" size=\"3\" onKeyDown=\"if(event.keyCode==13) {window.location='" + mpurl + "&page=\'+this.value;}\">" : "");
multipage = "<div class=\"pages\">" + multipage + "</div>";
}
return multipage;
} | zyyhong | trunk/jiaju001/bbs/include/javascript/qihoo.js | JavaScript | asf20 | 2,543 |
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: iframe.js,v $
$Revision: 1.9 $
$Date: 2007/05/22 16:54:11 $
*/
function refreshmain(e) {
e = e ? e : window.event;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(actualCode == 116 && parent.main) {
parent.main.location.reload();
if(document.all) {
e.keyCode = 0;
e.returnValue = false;
} else {
e.cancelBubble = true;
//e.calcelable = true;
e.preventDefault();
}
}
}
_attachEvent(document.documentElement, "keydown", refreshmain); | zyyhong | trunk/jiaju001/bbs/include/javascript/iframe.js | JavaScript | asf20 | 600 |
<?
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: image.class.php 10590 2007-09-07 08:42:50Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class Image {
var $attachinfo = '';
var $srcfile = '';
var $targetfile = '';
var $imagecreatefromfunc = '';
var $imagefunc = '';
var $attach = array();
var $animatedgif = 0;
function Image($srcfile, $targetfile, $attach = array()) {
global $imagelib, $watermarktext;
$this->srcfile = $srcfile;
$this->targetfile = $targetfile;
$this->attach = $attach;
$this->attachinfo = @getimagesize($targetfile);
if(!$imagelib) {
switch($this->attachinfo['mime']) {
case 'image/jpeg':
$this->imagecreatefromfunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : '';
$this->imagefunc = function_exists('imagejpeg') ? 'imagejpeg' : '';
break;
case 'image/gif':
$this->imagecreatefromfunc = function_exists('imagecreatefromgif') ? 'imagecreatefromgif' : '';
$this->imagefunc = function_exists('imagegif') ? 'imagegif' : '';
break;
case 'image/png':
$this->imagecreatefromfunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : '';
$this->imagefunc = function_exists('imagepng') ? 'imagepng' : '';
break;
}
} else {
$this->imagecreatefromfunc = $this->imagefunc = TRUE;
}
$this->attach['size'] = empty($this->attach['size']) ? @filesize($targetfile) : $this->attach['size'];
if($this->attachinfo['mime'] == 'image/gif') {
$fp = fopen($targetfile, 'rb');
$targetfilecontent = fread($fp, $this->attach['size']);
fclose($fp);
$this->animatedgif = strpos($targetfilecontent, 'NETSCAPE2.0') === FALSE ? 0 : 1;
}
}
function Thumb($thumbwidth, $thumbheight, $preview = 0) {
global $imagelib, $imageimpath, $thumbstatus, $watermarkstatus;
$imagelib && $imageimpath ? $this->Thumb_IM($thumbwidth, $thumbheight, $preview) : $this->Thumb_GD($thumbwidth, $thumbheight, $preview);
if($thumbstatus == 2 && $watermarkstatus) {
$this->Image($this->srcfile, $this->targetfile, $this->attach);
$this->attach['size'] = filesize($this->targetfile);
}
}
function Watermark($preview = 0) {
global $imagelib, $imageimpath, $watermarktype, $watermarktext, $watermarkminwidth, $watermarkminheight;
if(($watermarkminwidth && $this->attachinfo[0] <= $watermarkminwidth && $watermarkminheight && $this->attachinfo[1] <= $watermarkminheight) || ($watermarktype == 2 && (!file_exists($watermarktext['fontpath']) || !is_file($watermarktext['fontpath'])))) {
return;
}
$imagelib && $imageimpath ? $this->Watermark_IM($preview) : $this->Watermark_GD($preview);
}
function Thumb_GD($thumbwidth, $thumbheight, $preview = 0) {
global $thumbstatus;
if($thumbstatus && function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled') && function_exists('imagejpeg')) {
$imagecreatefromfunc = $this->imagecreatefromfunc;
$imagefunc = $thumbstatus == 1 ? 'imagejpeg' : $this->imagefunc;
list($img_w, $img_h) = $this->attachinfo;
if(!$this->animatedgif && ($img_w >= $thumbwidth || $img_h >= $thumbheight)) {
$attach_photo = $imagecreatefromfunc($this->targetfile);
$x_ratio = $thumbwidth / $img_w;
$y_ratio = $thumbheight / $img_h;
if(($x_ratio * $img_h) < $thumbheight) {
$thumb['height'] = ceil($x_ratio * $img_h);
$thumb['width'] = $thumbwidth;
} else {
$thumb['width'] = ceil($y_ratio * $img_w);
$thumb['height'] = $thumbheight;
}
$targetfile = !$preview ? ($thumbstatus == 1 ? $this->targetfile.'.thumb.jpg' : $this->targetfile) : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
$thumb_photo = imagecreatetruecolor($thumb['width'], $thumb['height']);
imageCopyreSampled($thumb_photo, $attach_photo ,0, 0, 0, 0, $thumb['width'], $thumb['height'], $img_w, $img_h);
if($this->attachinfo['mime'] == 'image/jpeg') {
$imagefunc($thumb_photo, $targetfile, 100);
} else {
$imagefunc($thumb_photo, $targetfile);
}
$this->attach['thumb'] = $thumbstatus == 1 ? 1 : 0;
}
}
}
function Watermark_GD($preview = 0) {
global $watermarkstatus, $watermarktype, $watermarktrans, $watermarkquality, $watermarktext;
$watermarkstatus = $GLOBALS['forum']['disablewatermark'] ? 0 : $watermarkstatus;
if($watermarkstatus && function_exists('imagecopy') && function_exists('imagealphablending') && function_exists('imagecopymerge')) {
$imagecreatefromfunc = $this->imagecreatefromfunc;
$imagefunc = $this->imagefunc;
list($img_w, $img_h) = $this->attachinfo;
if($watermarktype < 2) {
$watermark_file = $watermarktype == 1 ? './images/common/watermark.png' : './images/common/watermark.gif';
$watermarkinfo = @getimagesize($watermark_file);
$watermark_logo = $watermarktype == 1 ? @imageCreateFromPNG($watermark_file) : @imageCreateFromGIF($watermark_file);
if(!$watermark_logo) {
return;
}
list($logo_w, $logo_h) = $watermarkinfo;
} else {
$watermarktextcvt = pack("H*", $watermarktext['text']);
$box = imagettfbbox($watermarktext['size'], $watermarktext['angle'], $watermarktext['fontpath'], $watermarktextcvt);
$logo_h = max($box[1], $box[3]) - min($box[5], $box[7]);
$logo_w = max($box[2], $box[4]) - min($box[0], $box[6]);
$ax = min($box[0], $box[6]) * -1;
$ay = min($box[5], $box[7]) * -1;
}
$wmwidth = $img_w - $logo_w;
$wmheight = $img_h - $logo_h;
if(($watermarktype < 2 && is_readable($watermark_file) || $watermarktype == 2) && $wmwidth > 10 && $wmheight > 10 && !$this->animatedgif) {
switch($watermarkstatus) {
case 1:
$x = +5;
$y = +5;
break;
case 2:
$x = ($img_w - $logo_w) / 2;
$y = +5;
break;
case 3:
$x = $img_w - $logo_w - 5;
$y = +5;
break;
case 4:
$x = +5;
$y = ($img_h - $logo_h) / 2;
break;
case 5:
$x = ($img_w - $logo_w) / 2;
$y = ($img_h - $logo_h) / 2;
break;
case 6:
$x = $img_w - $logo_w;
$y = ($img_h - $logo_h) / 2;
break;
case 7:
$x = +5;
$y = $img_h - $logo_h - 5;
break;
case 8:
$x = ($img_w - $logo_w) / 2;
$y = $img_h - $logo_h - 5;
break;
case 9:
$x = $img_w - $logo_w - 5;
$y = $img_h - $logo_h - 5;
break;
}
$dst_photo = imagecreatetruecolor($img_w, $img_h);
$target_photo = @$imagecreatefromfunc($this->targetfile);
imageCopy($dst_photo, $target_photo, 0, 0, 0, 0, $img_w, $img_h);
if($watermarktype == 1) {
imageCopy($dst_photo, $watermark_logo, $x, $y, 0, 0, $logo_w, $logo_h);
} elseif($watermarktype == 2) {
if(($watermarktext['shadowx'] || $watermarktext['shadowy']) && $watermarktext['shadowcolor']) {
$shadowcolorrgb = explode(',', $watermarktext['shadowcolor']);
$shadowcolor = imagecolorallocate($dst_photo, $shadowcolorrgb[0], $shadowcolorrgb[1], $shadowcolorrgb[2]);
imagettftext($dst_photo, $watermarktext['size'], $watermarktext['angle'], $x + $ax + $watermarktext['shadowx'], $y + $ay + $watermarktext['shadowy'], $shadowcolor, $watermarktext['fontpath'], $watermarktextcvt);
}
$colorrgb = explode(',', $watermarktext['color']);
$color = imagecolorallocate($dst_photo, $colorrgb[0], $colorrgb[1], $colorrgb[2]);
imagettftext($dst_photo, $watermarktext['size'], $watermarktext['angle'], $x + $ax, $y + $ay, $color, $watermarktext['fontpath'], $watermarktextcvt);
} else {
imageAlphaBlending($watermark_logo, true);
imageCopyMerge($dst_photo, $watermark_logo, $x, $y, 0, 0, $logo_w, $logo_h, $watermarktrans);
}
$targetfile = !$preview ? $this->targetfile : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
if($this->attachinfo['mime'] == 'image/jpeg') {
$imagefunc($dst_photo, $targetfile, $watermarkquality);
} else {
$imagefunc($dst_photo, $targetfile);
}
$this->attach['size'] = filesize($this->targetfile);
}
}
}
function Thumb_IM($thumbwidth, $thumbheight, $preview = 0) {
global $thumbstatus, $imageimpath;
if($thumbstatus) {
list($img_w, $img_h) = $this->attachinfo;
$targetfile = !$preview ? ($thumbstatus == 1 ? $this->targetfile.'.thumb.jpg' : $this->targetfile) : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
if(!$this->animatedgif && ($img_w >= $thumbwidth || $img_h >= $thumbheight)) {
$exec_str = $imageimpath.'/convert -geometry '.$thumbwidth.'x'.$thumbheight.' '.$this->targetfile." ".$targetfile;
@exec($exec_str, $output, $return);
if(empty($return) && empty($output)) {
$this->attach['thumb'] = $thumbstatus == 1 ? 1 : 0;
}
}
}
}
function Watermark_IM($preview = 0) {
global $watermarkstatus, $watermarktype, $watermarktrans, $watermarkquality, $watermarktext, $imageimpath;
switch($watermarkstatus) {
case 1:
$gravity = 'NorthWest';
break;
case 2:
$gravity = 'North';
break;
case 3:
$gravity = 'NorthEast';
break;
case 4:
$gravity = 'West';
break;
case 5:
$gravity = 'Center';
break;
case 6:
$gravity = 'East';
break;
case 7:
$gravity = 'SouthWest';
break;
case 8:
$gravity = 'South';
break;
case 9:
$gravity = 'SouthEast';
break;
}
$targetfile = !$preview ? $this->targetfile : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
if($watermarktype < 2) {
$watermark_file = $watermarktype == 1 ? DISCUZ_ROOT.'./images/common/watermark.png' : DISCUZ_ROOT.'./images/common/watermark.gif';
$exec_str = $imageimpath.'/composite'.
($watermarktype != 1 && $watermarktrans != '100' ? ' -watermark '.$watermarktrans.'%' : '').
' -gravity '.$gravity.
' '.$watermark_file.' '.$this->targetfile.' '.$targetfile;
} else {
$watermarktextcvt = str_replace(array("\n", "\r", "'"), array('', '', '\''), pack("H*", $watermarktext['text']));
$watermarktext['angle'] = -$watermarktext['angle'];
$translate = $watermarktext['translatex'] || $watermarktext['translatey'] ? ' translate '.$watermarktext['translatex'].','.$watermarktext['translatey'] : '';
$skewX = $watermarktext['skewx'] ? ' skewX '.$watermarktext['skewx'] : '';
$skewY = $watermarktext['skewy'] ? ' skewY '.$watermarktext['skewy'] : '';
$exec_str = $imageimpath.'/convert'.
' -font "'.$watermarktext['fontpath'].'"'.
' -pointsize '.$watermarktext['size'].
(($watermarktext['shadowx'] || $watermarktext['shadowy']) && $watermarktext['shadowcolor'] ?
' -fill "rgb('.$watermarktext['shadowcolor'].')"'.
' -draw "'.
' gravity '.$gravity.$translate.$skewX.$skewY.
' rotate '.$watermarktext['angle'].
' text '.$watermarktext['shadowx'].','.$watermarktext['shadowy'].' \''.$watermarktextcvt.'\'"' : '').
' -fill "rgb('.$watermarktext['color'].')"'.
' -draw "'.
' gravity '.$gravity.$translate.$skewX.$skewY.
' rotate '.$watermarktext['angle'].
' text 0,0 \''.$watermarktextcvt.'\'"'.
' '.$this->targetfile.' '.$targetfile;
}
@exec($exec_str, $output, $return);
if(empty($return) && empty($output)) {
$this->attach['size'] = filesize($this->targetfile);
}
}
} | zyyhong | trunk/jiaju001/bbs/include/image.class.php | PHP | asf20 | 11,513 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: post.func.php 10329 2007-08-27 00:58:57Z heyond $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function attach_upload($varname = 'attach') {
global $db, $tablepre, $extension, $typemaxsize, $allowsetattachperm, $attachperm, $maxprice, $attachprice, $attachdesc, $attachsave, $attachdir, $thumbstatus, $thumbwidth, $thumbheight,
$maxattachsize, $maxsizeperday, $attachextensions, $watermarkstatus, $watermarktype, $watermarktrans, $watermarkquality, $watermarktext, $_FILES, $discuz_uid;
$attachments = $attacharray = array();
static $safeext = array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp', 'txt', 'zip', 'rar', 'doc', 'mp3');
static $imgext = array('jpg', 'gif', 'png', 'bmp');
if(isset($_FILES[$varname]) && is_array($_FILES[$varname])) {
foreach($_FILES[$varname] as $key => $var) {
foreach($var as $id => $val) {
$attachments[$id][$key] = $val;
}
}
}
if(empty($attachments)) {
return FALSE;
}
foreach($attachments as $key => $attach) {
$attach_saved = false;
$attach['uid'] = $discuz_uid;
if(!disuploadedfile($attach['tmp_name']) || !($attach['tmp_name'] != 'none' && $attach['tmp_name'] && $attach['name'])) {
continue;
}
$filename = daddslashes($attach['name']);
$attach['ext'] = strtolower(fileext($attach['name']));
$extension = in_array($attach['ext'], $safeext) ? $attach['ext'] : 'attach';
if(in_array($attach['ext'], $imgext)) {
$attach['isimage'] = 1;
}else{
$attach['isimage'] = 0;
}
$attach['thumb'] = 0;
$attach['name'] = htmlspecialchars($attach['name'], ENT_QUOTES);
if(strlen($attach['name']) > 90) {
$attach['name'] = 'abbr_'.md5($attach['name']).'.'.$attach['ext'];
}
if($attachextensions && (!preg_match("/(^|\s|,)".preg_quote($attach['ext'], '/')."($|\s|,)/i", $attachextensions) || !$attach['ext'])) {
upload_error('post_attachment_ext_notallowed', $attacharray);
}
if(empty($attach['size'])) {
upload_error('post_attachment_size_invalid', $attacharray);
}
if($maxattachsize && $attach['size'] > $maxattachsize) {
upload_error('post_attachment_toobig', $attacharray);
}
$query = $db->query("SELECT maxsize FROM {$tablepre}attachtypes WHERE extension='".addslashes($attach['ext'])."'");
if($type = $db->fetch_array($query)) {
if($type['maxsize'] == 0) {
upload_error('post_attachment_ext_notallowed', $attacharray);
} elseif($attach['size'] > $type['maxsize']) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
$typemaxsize = sizecount($type['maxsize']);
upload_error('post_attachment_type_toobig', $attacharray);
}
}
if($attach['size'] && $maxsizeperday) {
if(!isset($todaysize)) {
$query = $db->query("SELECT SUM(filesize) FROM {$tablepre}attachments
WHERE uid='$GLOBALS[discuz_uid]' AND dateline>'$GLOBALS[timestamp]'-86400");
$todaysize = intval($db->result($query, 0));
}
$todaysize += $attach['size'];
if($todaysize >= $maxsizeperday) {
upload_error('post_attachment_quota_exceed', $attacharray);
}
}
if($attachsave) {
switch($attachsave) {
case 1: $attach_subdir = 'forumid_'.$GLOBALS['fid']; break;
case 2: $attach_subdir = 'ext_'.$extension; break;
case 3: $attach_subdir = 'month_'.date('ym'); break;
case 4: $attach_subdir = 'day_'.date('ymd'); break;
}
$attach_dir = $attachdir.'/'.$attach_subdir;
if(!is_dir($attach_dir)) {
@mkdir($attach_dir, 0777);
@fclose(fopen($attach_dir.'/index.htm', 'w'));
}
$attach['attachment'] = $attach_subdir.'/';
} else {
$attach['attachment'] = '';
}
$attach['attachment'] .= preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2",
date('Ymd').'_'.substr(md5($filename.microtime()), 12).random(12).'.'.$extension);
$target = $attachdir.'/'.$attach['attachment'];
if(@copy($attach['tmp_name'], $target) || (function_exists('move_uploaded_file') && @move_uploaded_file($attach['tmp_name'], $target))) {
@unlink($attach['tmp_name']);
$attach_saved = true;
}
if(!$attach_saved && @is_readable($attach['tmp_name'])) {
@$fp = fopen($attach['tmp_name'], 'rb');
@flock($fp, 2);
@$attachedfile = fread($fp, $attach['size']);
@fclose($fp);
@$fp = fopen($target, 'wb');
@flock($fp, 2);
if(@fwrite($fp, $attachedfile)) {
@unlink($attach['tmp_name']);
$attach_saved = true;
}
@fclose($fp);
}
if($attach_saved) {
@chmod($target, 0644);
if(in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($target)) {
@unlink($target);
upload_error('post_attachment_ext_notallowed', $attacharray);
} else {
require_once DISCUZ_ROOT.'./include/image.class.php';
$image = new Image($attachedfile, $target, $attach);
if($image->imagecreatefromfunc && $image->imagefunc) {
$image->Thumb($thumbwidth, $thumbheight);
$image->Watermark();
$attach = $image->attach;
}
$attach['remote'] = ftpupload($target, $attach['attachment'], $attach['thumb']);
$attach['perm'] = $allowsetattachperm ? $attachperm[$key] : 0;
$attach['description'] = cutstr(dhtmlspecialchars($attachdesc[$key]), 100);
$attach['price'] = $maxprice ? (intval($attachprice[$key]) <= $maxprice ? intval($attachprice[$key]) : $maxprice) : 0;
$attacharray[$key] = $attach;
}
} else {
upload_error('post_attachment_save_error', $attacharray);
}
}
return !empty($attacharray) ? $attacharray : false;
}
function upload_error($message, $attacharray = array()) {
if(!empty($attacharray)) {
foreach($attacharray as $attach) {
@unlink($GLOBALS['attachdir'].'/'.$attach['attachment']);
}
}
showmessage($message);
}
$ftp['pwd'] = FALSE;
function ftpupload($source, $dest, $havethumb = 0) {
global $authkey, $ftp;
if($ftp['on']) {
require_once DISCUZ_ROOT.'./include/ftp.func.php';
if(!$ftp['connid']) {
if(!($ftp['connid'] = dftp_connect($ftp['host'], $ftp['username'], authcode($ftp['password'], 'DECODE', md5($authkey)), $ftp['attachdir'], $ftp['port'], $ftp['ssl']))) {
return 0;
}
$ftp['pwd'] = FALSE;
}
$tmp = explode('/', $dest);
if(count($tmp) > 1) {
if(!$ftp['pwd'] && !dftp_chdir($ftp['connid'], $tmp[0])) {
if(!dftp_mkdir($ftp['connid'], $tmp[0])) {
errorlog('FTP', "Mkdir '$ftp[attachdir]/$tmp[0]' error.", 0);
return 0;
}
if(!function_exists('ftp_chmod') || !dftp_chmod($ftp['connid'], 0777, $tmp[0])) {
dftp_site($ftp['connid'], "'CHMOD 0777 $tmp[0]'");
}
if(!dftp_chdir($ftp['connid'], $tmp[0])) {
errorlog('FTP', "Chdir '$ftp[attachdir]/$tmp[0]' error.", 0);
return 0;
}
dftp_put($ftp['connid'], 'index.htm', $GLOBALS['attachdir'].'/index.htm', FTP_BINARY);
}
$dest = $tmp[1];
$ftp['pwd'] = TRUE;
}
if(dftp_put($ftp['connid'], $dest, $source, FTP_BINARY)) {
if($havethumb) {
if(dftp_put($ftp['connid'], $dest.'.thumb.jpg', $source.'.thumb.jpg', FTP_BINARY)) {
@unlink($source);
@unlink($source.'.thumb.jpg');
return 1;
} else {
dftp_delete($ftp['connid'], $dest);
}
} else {
@unlink($source);
return 1;
}
}
errorlog('FTP', "Upload '$source' error.", 0);
}
return 0;
}
function checkflood() {
global $db, $tablepre, $disablepostctrl, $floodctrl, $maxpostsperhour, $discuz_uid, $timestamp, $lastpost, $forum;
if(!$disablepostctrl && $discuz_uid) {
$floodmsg = $floodctrl && ($timestamp - $floodctrl <= $lastpost) ? 'post_flood_ctrl' : '';
if(empty($floodmsg) && $maxpostsperhour) {
$query = $db->query("SELECT COUNT(*) from {$tablepre}posts WHERE authorid='$discuz_uid' AND dateline>$timestamp-3600");
$floodmsg = ($userposts = $db->result($query, 0)) && ($userposts >= $maxpostsperhour) ? 'thread_maxpostsperhour_invalid' : '';
}
if(empty($floodmsg)) {
return FALSE;
} elseif(CURSCRIPT != 'wap') {
showmessage($floodmsg);
} else {
wapmsg($floodmsg);
}
}
return FALSE;
}
function checkpost() {
global $subject, $message, $disablepostctrl, $minpostsize, $maxpostsize;
if(strlen($subject) > 80) {
return 'post_subject_toolong';
}
if(!$disablepostctrl) {
if($maxpostsize && strlen($message) > $maxpostsize) {
return 'post_message_toolong';
} elseif($minpostsize && strlen(preg_replace("/\[quote\].+?\[\/quote\]/is", '', $message)) < $minpostsize) {
return 'post_message_tooshort';
}
}
return FALSE;
}
function checkbbcodes($message, $bbcodeoff) {
return !$bbcodeoff && !preg_match("/\[.+\]/s", $message) ? -1 : $bbcodeoff;
}
function checksmilies($message, $smileyoff) {
$smilies = array();
if(!empty($GLOBALS['_DCACHE']['smilies']) && is_array($GLOBALS['_DCACHE']['smilies'])) {
foreach($GLOBALS['_DCACHE']['smilies']['searcharray'] as $smiley) {
$smilies[] = substr($smiley, 1, -1);
}
}
return !$smileyoff && !preg_match('/'.implode('|', $smilies).'/', stripslashes($message)) ? -1 : $smileyoff;
}
function updatepostcredits($operator, $uidarray, $creditsarray) {
global $db, $tablepre, $discuz_uid, $timestamp;
$membersarray = $postsarray = array();
foreach((is_array($uidarray) ? $uidarray : array($uidarray)) as $id) {
$membersarray[intval(trim($id))]++;
}
foreach($membersarray as $uid => $posts) {
$postsarray[$posts][] = $uid;
}
$lastpostadd = $uidarray == $discuz_uid ? ", lastpost='$timestamp'" : '';
$creditsadd1 = '';
if(is_array($creditsarray)) {
foreach($creditsarray as $id => $addcredits) {
$creditsadd1 .= ", extcredits$id=extcredits$id$operator$addcredits*\$posts";
}
}
foreach($postsarray as $posts => $uidarray) {
$uids = implode(',', $uidarray);
eval("\$creditsadd2 = \"$creditsadd1\";");
$db->query("UPDATE {$tablepre}members SET posts=posts+('$operator$posts') $lastpostadd $creditsadd2 WHERE uid IN ($uids)", 'UNBUFFERED');
}
}
function updateattachcredits($operator, $uidarray, $creditsarray) {
global $db, $tablepre, $discuz_uid;
$creditsadd1 = '';
if(is_array($creditsarray)) {
foreach($creditsarray as $id => $addcredits) {
$creditsadd1[] = "extcredits$id=extcredits$id$operator$addcredits*\$attachs";
}
}
if(is_array($creditsadd1)) {
$creditsadd1 = implode(', ', $creditsadd1);
foreach($uidarray as $uid => $attachs) {
eval("\$creditsadd2 = \"$creditsadd1\";");
$db->query("UPDATE {$tablepre}members SET $creditsadd2 WHERE uid = $uid", 'UNBUFFERED');
}
}
}
function updateforumcount($fid) {
global $db, $tablepre, $lang;
$query = $db->query("SELECT COUNT(*) AS threadcount, SUM(t.replies)+COUNT(*) AS replycount
FROM {$tablepre}threads t, {$tablepre}forums f
WHERE f.fid='$fid' AND t.fid=f.fid AND t.displayorder>='0'");
extract($db->fetch_array($query));
$query = $db->query("SELECT tid, subject, author, lastpost, lastposter FROM {$tablepre}threads
WHERE fid='$fid' AND displayorder>='0' ORDER BY lastpost DESC LIMIT 1");
$thread = $db->fetch_array($query);
$thread['subject'] = addslashes($thread['subject']);
$thread['lastposter'] = $thread['author'] ? addslashes($thread['lastposter']) : $lang['anonymous'];
$db->query("UPDATE {$tablepre}forums SET posts='$replycount', threads='$threadcount', lastpost='$thread[tid]\t$thread[subject]\t$thread[lastpost]\t$thread[lastposter]' WHERE fid='$fid'", 'UNBUFFERED');
}
function updatethreadcount($tid, $updateattach = 0) {
global $db, $tablepre, $lang;
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0'");
$replycount = $db->result($query, 0) - 1;
$query = $db->query("SELECT author, anonymous, dateline FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0' ORDER BY dateline DESC LIMIT 1");
$lastpost = $db->fetch_array($query);
$lastpost['author'] = $lastpost['anonymous'] ? $lang['anonymous'] : addslashes($lastpost['author']);
if($updateattach) {
$query = $db->query("SELECT attachment FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0' AND attachment>0 LIMIT 1");
$attachadd = ', attachment=\''.($db->num_rows($query)).'\'';
} else {
$attachadd = '';
}
$db->query("UPDATE {$tablepre}threads SET replies='$replycount', lastposter='$lastpost[author]', lastpost='$lastpost[dateline]' $attachadd WHERE tid='$tid'", 'UNBUFFERED');
}
function updatemodlog($tids, $action, $expiration = 0, $iscron = 0) {
global $db, $tablepre, $timestamp;
$uid = empty($iscron) ? $GLOBALS['discuz_uid'] : 0;
$username = empty($iscron) ? $GLOBALS['discuz_user'] : 0;
$expiration = empty($expiration) ? 0 : intval($expiration);
$data = $comma = '';
foreach(explode(',', str_replace(array('\'', ' '), array('', ''), $tids)) as $tid) {
if($tid) {
$data .= "{$comma} ('$tid', '$uid', '$username', '$timestamp', '$action', '$expiration', '1')";
$comma = ',';
}
}
!empty($data) && $db->query("INSERT INTO {$tablepre}threadsmod (tid, uid, username, dateline, action, expiration, status) VALUES $data", 'UNBUFFERED');
}
function isopera() {
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(strpos($useragent, 'opera') !== false) {
preg_match('/opera(\/| )([0-9\.]+)/', $useragent, $regs);
return $regs[2];
}
return FALSE;
}
function deletethreadcaches($tids) {
global $cachethreadon;
if(!$cachethreadon) {
return FALSE;
}
include_once DISCUZ_ROOT.'./include/forum.func.php';
if(!empty($tids)) {
foreach(explode(',', $tids) as $tid) {
$fileinfo = getcacheinfo($tid);
@unlink($fileinfo['filename']);
}
}
return TRUE;
}
function arrayslice($array, $offset, $length) {
if(PHP_VERSION >= '5.0.2') {
return array_slice($array, $offset, $length, TRUE);
} else {
$array = array_chunk($array, $length, TRUE);
return $array[$offset / $length];
}
}
function threadtype_checkoption($unchangeable = 1, $trade = 0) {
global $selecttypeid, $optionlist, $trade_create, $tradetypeid, $typeid, $_DTYPE, $checkoption, $forum, $action;
if($trade) {
$selecttypeid = $tradetypeid ? intval($tradetypeid) : '';
} else {
$selecttypeid = $typeid ? intval($typeid) : '';
}
@include_once DISCUZ_ROOT.'./forumdata/cache/threadtype_'.$selecttypeid.'.php';
$optionlist = $_DTYPE;
foreach($_DTYPE as $optionid => $option) {
$checkoption[$option['identifier']]['optionid'] = $optionid;
$checkoption[$option['identifier']]['title'] = $option['title'];
$checkoption[$option['identifier']]['type'] = $option['type'];
$checkoption[$option['identifier']]['required'] = $option['required'] ? 1 : 0;
$checkoption[$option['identifier']]['unchangeable'] = $action == 'edit' && $unchangeable && $option['unchangeable'] ? 1 : 0;
$checkoption[$option['identifier']]['maxnum'] = $option['maxnum'] ? intval($option['maxnum']) : '';
$checkoption[$option['identifier']]['minnum'] = $option['minnum'] ? intval($option['minnum']) : '';
$checkoption[$option['identifier']]['maxlength'] = $option['maxlength'] ? intval($option['maxlength']) : '';
}
}
function threadtype_optiondata() {
global $db, $tablepre, $tid, $pid, $tradetype, $_DTYPE, $optiondata, $optionlist, $thread;
$optiondata = array();
if(!$tradetype) {
$id = $tid;
$field = 'tid';
$table = 'typeoptionvars';
} else {
$id = $pid;
$field = 'pid';
$table = 'tradeoptionvars';
}
if($id) {
$query = $db->query("SELECT optionid, value FROM {$tablepre}$table WHERE $field='$id'");
while($option = $db->fetch_array($query)) {
$optiondata[$option['optionid']] = $option['value'];
}
foreach($_DTYPE as $optionid => $option) {
$optionlist[$optionid]['title'] = $_DTYPE[$optionid]['title'];
$optionlist[$optionid]['type'] = $_DTYPE[$optionid]['type'];
$optionlist[$optionid]['identifier'] = $_DTYPE[$optionid]['identifier'];
$optionlist[$optionid]['choices'] = $_DTYPE[$optionid]['choices'];
$optionlist[$optionid]['required'] = $_DTYPE[$optionid]['required'];
$optionlist[$optionid]['unchangeable'] = $_DTYPE[$optionid]['unchangeable'] ? 'disabled' : '';
if($_DTYPE[$optionid]['type'] == 'radio') {
$optionlist[$optionid]['value'] = array($optiondata[$optionid] => 'checked="checked"');
} elseif($_DTYPE[$optionid]['type'] == 'select') {
$optionlist[$optionid]['value'] = array($optiondata[$optionid] => 'selected="selected"');
} elseif($_DTYPE[$optionid]['type'] == 'checkbox') {
foreach(explode("\t", $optiondata[$optionid]) as $value) {
$optionlist[$optionid]['value'][$value] = array($value => 'checked="checked"');
}
} else {
$optionlist[$optionid]['value'] = $optiondata[$optionid];
}
if(!isset($optiondata[$optionid])) {
$db->query("INSERT INTO {$tablepre}$table (typeid, $field, optionid)
VALUES ('$thread[typeid]', '$id', '$optionid')");
}
}
}
}
function threadtype_validator($typeoption) {
global $checkoption;
$optiondata = array();
foreach($typeoption as $var => $option) {
if($checkoption[$var]['required'] && !$typeoption[$var]) {
showmessage('threadtype_required_invalid');
} elseif($typeoption[$var] && ($checkoption[$var]['type'] == 'number' && !is_numeric($typeoption[$var]) || $checkoption[$var]['type'] == 'email' && !isemail($typeoption[$var]))){
showmessage('threadtype_format_invalid');
} elseif($typeoption[$var] && $checkoption[$var]['maxlength'] && strlen($typeoption[$var]) > $checkoption[$var]['maxlength']) {
showmessage('threadtype_toolong_invalid');
} elseif($typeoption[$var] && (($checkoption[$var]['maxnum'] && $typeoption[$var] >= $checkoption[$var]['maxnum']) || ($checkoption[$var]['minnum'] && $typeoption[$var] < $checkoption[$var]['minnum']))) {
showmessage('threadtype_num_invalid');
} elseif($typeoption[$var] && $checkoption[$var]['unchangeable']) {
showmessage('threadtype_unchangeable_invalid');
}
$option = $checkoption[$var]['type'] == 'checkbox' ? implode("\t", dhtmlspecialchars($option)) : dhtmlspecialchars(censor(trim($option)));
$optiondata[$checkoption[$var]['optionid']] = $option;
}
return $optiondata;
}
function videodelete($ids, $writelog = FALSE) {
global $db, $tablepre, $vsiteid, $vkey;
$ids = implode("','", (array)$ids);
$query = $db->query("SELECT t.tid, v.vid FROM {$tablepre}threads t LEFT JOIN {$tablepre}videos v ON t.tid=v.tid WHERE t.tid IN('$ids') AND t.special='6'");
$data = $datas = array();
while($data = $db->fetch_array($query)) {
$datas[] = $data['vid'];
}
$ids = implode("','", (array)$datas);
$vids = implode(",", (array)$datas);
$db->query("DELETE FROM {$tablepre}videos WHERE tid IN ('$ids')");
$db->query("DELETE FROM {$tablepre}videotags WHERE tid IN ('$ids')");
if($vids && $writelog) {
$fp = @fopen(DISCUZ_ROOT.'./forumdata/videodelete.log', 'a+');
@flock($fp, 3);
@fwrite($fp, $vids.',');
@fclose($fp);
$code = urlencode(authcode("vid=$vids", '', $vkey));
dfopen("http://union.bokecc.com/discuz2/delete.bo?siteid=$vsiteid&code=$code");
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/post.func.php | PHP | asf20 | 19,406 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: space.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$modulesettings = array(
'userinfo' => array('1', 0, 1),
'calendar' => array('1', 0),
'myblogs' => array('', 1),
'mythreads' => array('', 1),
'myreplies' => array('', 1),
'myrewards' => array('', 1),
'mytrades' => array('', 1),
'myvideos' => array('1', 2),
'mycounters' => array('1', 2),
'myfriends' => array('1', 2),
'myfavforums' => array('1', 2),
'myfavthreads' => array('1', 2)
);
$listmodule = array(
'myblogs' => 1,
'mythreads' => 2,
'myreplies' => 3,
'myrewards' => 4,
'mytrades' => 5,
'myvideos' => 6,
'myfavforums' => 7,
'myfavthreads' => 8
);
function getspacesettings($uid) {
global $db, $tablepre, $discuz_uid;
$query = $db->query("SELECT * FROM {$tablepre}memberspaces WHERE uid='$uid'");
if($spacesettings = $db->fetch_array($query)) {
$spacesettings['style'] = empty($spacesettings['style']) ? 'default' : str_replace('/', '', $spacesettings['style']);
if(!file_exists(DISCUZ_ROOT.'./mspace/'.$spacesettings['style'].'/style.ini')) {
$spacesettings['style'] = 'default';
}
} else {
$spacesettings['style'] = 'default';
$spacesettings['layout'] = "[userinfo][calendar][myreplies][myfavforums]\t[myblogs][mythreads]\t";
$spacesettings['side'] = 1;
$db->query("INSERT INTO {$tablepre}memberspaces (uid, style, description, layout, side) VALUES ('$uid', '$spacesettings[style]', '', '$spacesettings[layout]', '$spacesettings[side]')");
}
return $spacesettings;
}
function spacecutstr($str, $length) {
global $_DCACHE;
include_once DISCUZ_ROOT.'./forumdata/cache/cache_post.php';
$bbcodes = 'b|i|u|color|size|font|align|list|indent|url|email|code|free|table|tr|td|img|swf|payto|float'.($_DCACHE['bbcodes_display'] ? '|'.implode('|', array_keys($_DCACHE['bbcodes_display'])) : '');
$str = dhtmlspecialchars(cutstr(strip_tags(preg_replace(array(
"/\[hide=?\d*\](.+?)\[\/hide\]/is",
"/\[quote](.*)\[\/quote]/siU",
"/\[($bbcodes)=?.*\]/iU",
"/\[\/($bbcodes)\]/i",
"/\[attach\](\d+)\[\/attach\]/i",
"/\[media=(\w{1,4}),(\d{1,4}),(\d{1,4}),(\d)\]\s*([^\[\<\r\n]+?)\s*\[\/media\]/i",
), array(
'',
'',
'',
'',
'',
"\\5"
), $str)), $length));
$find = array("/http:\/\/[a-z0-9\/\-_+=.~!%@?#%&;:$\\()|]+?\.(jpg|gif|png|bmp)/is", "/(\n|\r|\r\n){2,}/", "/\s{2,}/");
$replace = array("<img onload=\"if(this.width>320) {this.resized=true;this.width=320;}\" src=\"\\0\">", "\r\n", '');
$str = preg_replace($find, $replace, $str);
return trim(nl2br($str));
}
function updatespacecache($uid, $module, $list = FALSE) {
global $_DCOOKIE, $db, $mod, $tablepre, $timestamp, $tpp, $page, $multipage, $starttime, $endtime, $spacedata, $lastvisit, $videoopen, $tradetypeid;
if(!file_exists(DISCUZ_ROOT.'./forumdata/cache/cache_spacesettings.php')) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatespacesettings();
}
require DISCUZ_ROOT.'./forumdata/cache/cache_spacesettings.php';
if($list) {
$tpp = $mod != 'mytrades' ? $tpp : 15;
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$parms['items'] = "$start_limit, $tpp";
} else {
$parms['items'] = intval($spacedata['limit'.$module]);
}
$parms['list'] = $list;
$parms['conditions'] = $parms['extraquery'] = '';
$parms['cols'] = '*';
$user_func = 'module_'.$module;
$user_func($parms);
$tids = $datalist = array();
$query = $db->query("SELECT $parms[cols] FROM {$tablepre}$parms[table] $parms[conditions] LIMIT $parms[items]");
while($data = $db->fetch_array($query)) {
if(!empty($data['message'])) {
$data['message'] = spacecutstr($data['message'], $spacedata['textlength']);
$videoopen && $data['message'] = videocode($data['message'], $data['tid'], $data['pid']);
}
if($data['tid'] && $lastvisit < $data['lastpost'] && (empty($_DCOOKIE['oldtopics']) || strpos($_DCOOKIE['oldtopics'], 'D'.$data['tid'].'D') === FALSE)) {
$data['subject'] .= ' <a href="redirect.php?tid='.$data['tid'].'&goto=newpost#newpost" target="_blank"><img src="'.IMGDIR.'/firstnew.gif" border="0" alt="" /></a>';
}
if($parms['extraquery']) {
$tids[] = $data['tid'];
$datalist[$data['tid']] = $data;
} else {
$datalist[] = $data;
}
}
if($tids) {
$query = $db->query($parms['extraquery'].'('.implodeids($tids).')');
while($data = $db->fetch_array($query)) {
$datalist[$data['tid']] = array_merge($datalist[$data['tid']], $data);
}
}
if(!$list) {
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$uid', '$module', '".addslashes(serialize($datalist))."', '".($timestamp + $spacedata['cachelife'])."')");
} else {
$query = $db->query("SELECT count(*) FROM {$tablepre}$parms[table] $parms[conditions]");
$num = $db->result($query, 0);
$module = empty($parms['pagemodule']) ? $module : $parms['pagemodule'];
$multipage = spacemulti($num, $tpp, $page, "space.php?uid=$uid&mod=$module".($starttime ? "&starttime=$starttime" : '').($endtime ? "&endtime=$endtime" : '').(isset($tradetypeid) ? "&tradetypeid=$tradetypeid" : ''));
}
return $datalist;
}
function spacemulti($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $simple = 0, $onclick = '') {
$multipage = '';
$mpurl .= strpos($mpurl, '?') ? '&' : '?';
$onclick = $onclick ? ' onclick="'.$onclick.'(event)"' : '';
if($num > $perpage) {
$offset = 2;
$realpages = @ceil($num / $perpage);
$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
if($page > $pages) {
$from = 1;
$to = $pages;
} else {
$from = $curpage - $offset;
$to = $from + $page - 1;
if($from < 1) {
$to = $curpage + 1 - $from;
$from = 1;
if($to - $from < $page) {
$to = $page;
}
} elseif($to > $pages) {
$from = $pages - $page + 1;
$to = $pages;
}
}
$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="p_redirect"'.$onclick.'>|‹</a>' : '').
($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="p_redirect">‹‹</a>' : '');
for($i = $from; $i <= $to; $i++) {
$multipage .= $i == $curpage ? '<a class="p_curpage">'.$i.'</a>' :
'<a href="'.$mpurl.'page='.$i.'" class="p_num"'.$onclick.'>'.$i.'</a>';
}
$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="p_redirect"'.$onclick.'>››</a>' : '').
($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="p_redirect"'.$onclick.'>›|</a>' : '').
($curpage == $maxpages ? '<a class="p_redirect" href="misc.php?action=maxpages&pages='.$maxpages.'">›?</a>' : '').
(!$simple && $pages > $page ? '<a class="p_pages" style="padding: 0px"><input class="p_input" type="text" name="custompage" onKeyDown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}"></a>' : '');
$multipage = $multipage ? '<div class="p_bar">'.(!$simple ? '<a class="p_total"> '.$num.' </a><a class="p_pages"> '.$curpage.'/'.$realpages.' </a>' : '').$multipage.'</div>' : '';
}
return $multipage;
}
function calendar() {
global $db, $tablepre, $uid, $starttime, $timestamp, $timeoffset, $dateformat;
$starttime = isset($starttime) ? intval($starttime) : 0;
$starttime = $starttime ? $starttime : $timestamp;
$pendtime = $starttime - (gmdate('j', $starttime + $timeoffset * 3600) - 1) * 86400 - ($starttime + $timeoffset * 3600) % 86400;
$pstarttime = $pendtime - gmdate('t', $pendtime + $timeoffset * 3600 - 1) * 86400;
$nstarttime = $pendtime + gmdate('t', $pendtime + $timeoffset * 3600 + 1) * 86400;
$nendtime = $nstarttime + gmdate('t', $nstarttime + $timeoffset * 3600 + 1) * 86400;
list($skip, $dim) = explode('-', gmdate('w-t', $pendtime + $timeoffset * 3600 + 1));
$rows = ceil(($skip + $dim) / 7);
$blogs = array();
$query = $db->query("SELECT dateline FROM {$tablepre}threads WHERE blog='1' AND authorid='$uid' AND dateline BETWEEN '$pendtime' AND '$nstarttime' AND displayorder>='0'");
while($blog = $db->fetch_array($query)) {
$day = gmdate('j', $blog['dateline'] + $timeoffset * 3600);
!isset($blogs[$day]) ? $blogs[$day] = array('num' => 1, 'dateline' => $blog['dateline'] - $blog['dateline'] % 86400) : $blogs[$day]['num']++;
}
$cal = '';
for($row = 0; $row < $rows; $row++) {
$cal .= '<tr class="row" align="center">';
for($col = 0; $col < 7; $col++) {
$cur = $row * 7 + $col - $skip + 1;
$curtd = $row * 7 + $col < $skip || $cur > $dim ? ' ' : $cur;
if(!isset($blogs[$cur])) {
$cal .= '<td>'.$curtd.'</td>';
} else {
$cal .= '<td><a href="space.php?'.$uid.'/myblogs/'.$blogs[$cur]['dateline'].'/'.($blogs[$cur]['dateline'] + 86400).'" title=" '.$blogs[$cur]['num'].' ">'.$cur.'</a></td>';
}
}
$cal .= '</tr>';
}
$calendar = array('curtime' => gmdate('Y-m', $starttime + $timeoffset * 3600), 'pstarttime' => $pstarttime, 'pendtime' => $pendtime, 'nstarttime' => $nstarttime, 'nendtime' => $nendtime, 'html' => $cal);
viewcalendar($calendar);
}
function spacecaches($uid, $modulelist = '') {
global $db, $tablepre, $timestamp;
$moduledata = array();
if(is_array($modulelist)) {
$allmodules = array(
'mythreads',
'myreplies',
'myrewards',
'mytrades',
'myvideos',
'myfriends',
'myfavforums',
'myfavthreads',
'myblogs',
'hotblog',
'lastpostblog',
);
$modulelist = empty($modulelist) ? $allmodules : array_intersect($modulelist, $allmodules);
$query = $db->query("SELECT * FROM {$tablepre}spacecaches WHERE uid='$uid'");
} else {
$query = $db->query("SELECT * FROM {$tablepre}spacecaches WHERE uid='$uid' AND variable='$modulelist'");
$modulelist = $allmodules = array($modulelist);
}
while($module = $db->fetch_array($query)) {
$moduledata[$module['variable']]['expiration'] = $module['expiration'];
$moduledata[$module['variable']]['value'] = unserialize($module['value']);
}
foreach($allmodules as $module) {
if(in_array($module, $modulelist) && (empty($moduledata[$module]) || $timestamp > $moduledata[$module]['expiration'])) {
$moduledata[$module]['value'] = updatespacecache($uid, $module);
}
if(!empty($modulelist) && !in_array($module, $modulelist)) {
unset($moduledata[$module]);
}
}
return $moduledata;
}
function module_mythreads(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'mythreads m';
if(!$parms['list']) {
$parms['cols'] = 't.tid, t.subject, t.special, t.price, t.fid, t.views, t.replies, t.author, t.authorid, t.lastpost, t.lastposter, t.attachment, p.pid, p.message';
$parms['conditions'] = "INNER JOIN {$tablepre}posts p ON p.tid=m.tid AND p.first='1'
INNER JOIN {$tablepre}threads t ON t.blog='0' AND t.authorid='$uid' AND t.author!='' AND t.price='0' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]'
WHERE m.uid='$uid' AND m.tid=t.tid ORDER BY t.lastpost DESC";
} else {
$parms['cols'] = 't.tid, t.subject, t.special, t.fid, t.views, t.replies, t.author, t.authorid, t.lastpost, t.lastposter, t.attachment';
$parms['conditions'] = "INNER JOIN {$tablepre}threads t ON t.blog='0' AND t.authorid='$uid' AND t.author!='' AND t.price='0' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]'
WHERE m.uid='$uid' AND m.tid=t.tid ORDER BY t.lastpost DESC";
}
}
function module_myreplies(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'myposts m';
$parms['cols'] = 't.tid, t.subject, t.special, t.price, t.fid, t.views, t.replies, t.author, t.authorid, t.lastpost, t.lastposter, t.attachment, p.pid'.(!$parms['list'] ? ', p.message' : '');
$parms['conditions'] = "INNER JOIN {$tablepre}posts p ON p.pid=m.pid AND p.anonymous='0'
INNER JOIN {$tablepre}threads t ON t.tid=m.tid AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]'
WHERE m.uid='$uid' ORDER BY m.dateline DESC";
}
function module_myrewards(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'threads t';
if(!$parms['list']) {
$parms['cols'] = 't.tid, t.fid, t.views, t.replies, t.price, t.subject, p.pid, p.message';
$parms['conditions'] = "INNER JOIN {$tablepre}posts p ON p.tid=t.tid AND p.first='1'
WHERE t.authorid='$uid' AND t.author!='' AND t.special='3' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]' ORDER BY t.lastpost DESC";
} else {
$parms['cols'] = 't.tid, t.fid, t.views, t.replies, t.price, t.subject';
$parms['conditions'] = "WHERE t.authorid='$uid' AND t.author!='' AND t.special='3' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]' ORDER BY t.lastpost DESC";
}
$parms['extraquery'] = "SELECT r.tid, r.answererid, m.username FROM {$tablepre}rewardlog r LEFT JOIN {$tablepre}members m ON m.uid=r.answererid WHERE r.authorid='$uid' AND r.tid IN ";
}
function module_mytrades(&$parms) {
global $uid, $tablepre, $tradetypeid;
$parms['table'] = 'trades';
$parms['cols'] = '*';
if($tradetypeid == 'all') {
$typeadd = '';
} elseif($tradetypeid == 'stick') {
$typeadd = 'AND displayorder>0';
} elseif($tradetypeid == '') {
$typeadd = 'AND displayorder>0';
$parms['items'] = 9;
} else {
$typeadd = 'AND typeid=\''.intval($tradetypeid).'\'';
}
$parms['conditions'] = "WHERE sellerid='$uid' $typeadd ORDER BY dateline DESC";
}
function module_myvideos(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'videos v, '.$tablepre.'members m';
$parms['cols'] = 'm.username, v.*';
$parms['conditions'] = "WHERE m.uid='$uid' AND m.uid=v.uid ORDER BY v.dateline DESC";
}
function module_mytradetypes(&$parms) {
global $uid;
$parms['table'] = 'trades';
$parms['cols'] = 'typeid';
$parms['conditions'] = "WHERE sellerid='$uid' GROUP BY typeid";
$parms['items'] = '65535';
}
function module_mycounters(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'threads t';
$parms['cols'] = 't.tid, t.fid, t.views, t.replies, t.price, t.subject';
$parms['conditions'] = "WHERE t.authorid='$uid' AND t.author!='' AND t.special='2' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]' ORDER BY t.lastpost DESC";
$parms['pagemodule'] = 'mytrades';
}
function format_expiration(&$trade) {
global $timestamp;
if($trade['expiration']) {
$trade['expiration'] = ($trade['expiration'] - $timestamp) / 86400;
if($trade['expiration'] > 0) {
$trade['expirationhour'] = floor(($trade['expiration'] - floor($trade['expiration'])) * 24);
$trade['expiration'] = floor($trade['expiration']);
} else {
$trade['expiration'] = -1;
}
}
}
function module_myfriends(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'members m';
$parms['cols'] = 'm.uid, m.username, mf.spacename';
$parms['conditions'] = "LEFT JOIN {$tablepre}buddys b ON m.uid=b.buddyid
LEFT JOIN {$tablepre}memberfields mf ON m.uid=mf.uid
WHERE b.uid='$uid'";
}
function module_myfavforums(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'forums f';
$parms['cols'] = 'f.fid, f.name, f.threads, f.posts, f.todayposts';
$parms['conditions'] = ",{$tablepre}favorites fav
WHERE fav.fid=f.fid AND fav.uid='$uid' AND fav.fid IN ($parms[infids])";
}
function module_myfavthreads(&$parms) {
global $uid, $tablepre;
$parms['table'] = 'threads t';
$parms['cols'] = 't.tid, t.subject, t.special, t.price, t.fid, t.views, t.replies, t.lastposter, t.lastpost';
$parms['conditions'] = ",{$tablepre}favorites fav
WHERE fav.tid=t.tid AND fav.uid='$uid' AND t.fid IN ($parms[infids]) AND t.displayorder>='0' AND t.readperm<='$parms[readaccess]' ORDER BY t.lastpost DESC";
}
function module_myblogs(&$parms) {
global $uid, $tablepre, $starttime, $endtime;
$starttimeadd = $starttime ? "AND t.dateline>='$starttime'" : '';
$endtimeadd = $endtime ? "AND t.dateline<'$endtime'" : '';
$parms['table'] = 'threads t';
$parms['cols'] = 't.tid, t.subject, t.special, t.price, t.fid, t.views, t.replies, t.authorid, t.dateline, t.lastpost, t.lastposter, t.attachment, p.pid, p.message';
$parms['conditions'] = "INNER JOIN {$tablepre}posts p ON p.tid=t.tid AND p.first='1' AND p.anonymous='0'
WHERE t.blog='1' AND t.authorid='$uid' $starttimeadd $endtimeadd ORDER BY t.dateline DESC";
}
function module_hotblog(&$parms) {
global $uid;
$parms['table'] = 'threads';
$parms['cols'] = 'tid, subject, views, replies';
$parms['conditions'] = "WHERE blog='1' AND authorid='$uid' AND displayorder>='0' ORDER BY views DESC";
$parms['items'] = 5;
}
function module_lastpostblog(&$parms) {
global $uid;
$parms['table'] = 'threads';
$parms['cols'] = 'tid, subject, views, replies';
$parms['conditions'] = "WHERE blog='1' AND authorid='$uid' AND displayorder>='0' ORDER BY lastpost DESC";
$parms['items'] = 5;
}
?> | zyyhong | trunk/jiaju001/bbs/include/space.func.php | PHP | asf20 | 17,359 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: counter.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$visitor = array();
$visitor['agent'] = $_SERVER['HTTP_USER_AGENT'];
list($visitor['month'], $visitor['week'], $visitor['hour']) = explode("\t", gmdate("Ym\tw\tH", $timestamp + $_DCACHE['settings']['timeoffset'] * 3600));
if(!$sessionexists) {
if(strpos($visitor['agent'], 'Netscape')) {
$visitor['browser'] = 'Netscape';
} elseif(strpos($visitor['agent'], 'Lynx')) {
$visitor['browser'] = 'Lynx';
} elseif(strpos($visitor['agent'], 'Opera')) {
$visitor['browser'] = 'Opera';
} elseif(strpos($visitor['agent'], 'Konqueror')) {
$visitor['browser'] = 'Konqueror';
} elseif(strpos($visitor['agent'], 'MSIE')) {
$visitor['browser'] = 'MSIE';
} elseif(substr($visitor['agent'], 0, 7) == 'Mozilla') {
$visitor['browser'] = 'Mozilla';
} else {
$visitor['browser'] = 'Other';
}
if(strpos($visitor['agent'], 'Win')) {
$visitor['os'] = 'Windows';
} elseif(strpos($visitor['agent'], 'Mac')) {
$visitor['os'] = 'Mac';
} elseif(strpos($visitor['agent'], 'Linux')) {
$visitor['os'] = 'Linux';
} elseif(strpos($visitor['agent'], 'FreeBSD')) {
$visitor['os'] = 'FreeBSD';
} elseif(strpos($visitor['agent'], 'SunOS')) {
$visitor['os'] = 'SunOS';
} elseif(strpos($visitor['agent'], 'OS/2')) {
$visitor['os'] = 'OS/2';
} elseif(strpos($visitor['agent'], 'AIX')) {
$visitor['os'] = 'AIX';
} elseif(preg_match("/(Bot|Crawl|Spider)/i", $visitor['agent'])) {
$visitor['os'] = 'Spiders';
} else {
$visitor['os'] = 'Other';
}
$visitorsadd = "OR (type='browser' AND variable='$visitor[browser]') OR (type='os' AND variable='$visitor[os]')".
($discuz_user ? " OR (type='total' AND variable='members')" : " OR (type='total' AND variable='guests')");
$updatedrows = 7;
} else {
$visitorsadd = '';
$updatedrows = 4;
}
$db->query("UPDATE {$tablepre}stats SET count=count+1 WHERE (type='total' AND variable='hits') $visitorsadd OR (type='month' AND variable='$visitor[month]') OR (type='week' AND variable='$visitor[week]') OR (type='hour' AND variable='$visitor[hour]')");
if($updatedrows > $db->affected_rows()) {
$db->query("INSERT INTO {$tablepre}stats (type, variable, count)
VALUES ('month', '$visitor[month]', '1')", 'SILENT');
}
?> | zyyhong | trunk/jiaju001/bbs/include/counter.inc.php | PHP | asf20 | 2,473 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_trade.inc.php 10132 2007-08-24 03:07:18Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(empty($do) || $do == 'tradeinfo') {
if($do == 'tradeinfo') {
$tradelistadd = "pid = '$pid'";
$tradelistlimit = '';
} else {
$tradenum = $db->result($db->query("SELECT count(*) FROM {$tablepre}trades WHERE tid='$tid'"), 0);
$tradelistadd = 'displayorder>0';
$tradelistlimit = '';
!$tradenum && $allowpostreply = FALSE;
}
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE tid='$tid' AND $tradelistadd ORDER BY displayorder $tradelistlimit");
$trades = array();$tradelist = 0;
if(empty($do)) {
$sellerid = 0;
$listcount = $db->num_rows($query);
$tradelist = $tradenum - $listcount;
}
while($trade = $db->fetch_array($query)) {
if($trade['expiration']) {
$trade['expiration'] = ($trade['expiration'] - $timestamp) / 86400;
if($trade['expiration'] > 0) {
$trade['expirationhour'] = floor(($trade['expiration'] - floor($trade['expiration'])) * 24);
$trade['expiration'] = floor($trade['expiration']);
} else {
$trade['expiration'] = -1;
}
}
$tradesaids[] = $trade['aid'];
$tradespids[] = $trade['pid'];
$trades[$trade['pid']] = $trade;
}
$tradespids = implodeids($tradespids);
unset($trade);
if($tradespids) {
$query = $db->query("SELECT a.* FROM {$tablepre}attachments a WHERE a.pid IN ($tradespids)");
while($attach = $db->fetch_array($query)) {
if($attach['isimage'] && is_array($tradesaids) && in_array($attach['aid'], $tradesaids)) {
$trades[$attach['pid']]['attachurl'] = ($attach['remote'] ? $ftp['attachurl'] : $attachurl).'/'.$attach['attachment'];
$trades[$attach['pid']]['thumb'] = $trades[$attach['pid']]['attachurl'].($attach['thumb'] ? '.thumb.jpg' : '');
}
}
}
if($do == 'tradeinfo') {
$subjectpos = strrpos($navigation, '» ');
$subject = substr($navigation, $subjectpos + 8);
$navigation = substr($navigation, 0, $subjectpos).'» <a href="viewthread.php?tid='.$tid.'">'.$subject.'</a>';
$trade = $trades[$pid];
unset($trades);
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.customstatus, mf.spacename, mf.buyercredit, mf.sellercredit $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE pid='$pid'");
$post = $db->fetch_array($query);
$postlist[$post['pid']] = viewthread_procpost($post);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages, array($trade['aid']));
}
$post = $postlist[$pid];
$post['buyerrank'] = 0;
if($post['buyercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($post['buyercredit'] <= $credit) {
$post['buyerrank'] = $level;
break;
}
}
}
$post['sellerrank'] = 0;
if($post['sellercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($post['sellercredit'] <= $credit) {
$post['sellerrank'] = $level;
break;
}
}
}
$navtitle = $trade['subject'].' - ';
$tradetypeid = $trade['typeid'];
$typetemplate = '';
$optiondata = $optionlist = array();
if($tradetypeid && isset($tradetypes[$tradetypeid])) {
if(@include_once DISCUZ_ROOT.'./forumdata/cache/threadtype_'.$tradetypeid.'.php') {
$query = $db->query("SELECT optionid, value FROM {$tablepre}tradeoptionvars WHERE pid='$pid'");
while($option = $db->fetch_array($query)) {
$optiondata[$option['optionid']] = $option['value'];
}
foreach($_DTYPE as $optionid => $option) {
$optionlist[$option['identifier']]['title'] = $_DTYPE[$optionid]['title'];
if($_DTYPE[$optionid]['type'] == 'checkbox') {
$optionlist[$option['identifier']]['value'] = '';
foreach(explode("\t", $optiondata[$optionid]) as $choiceid) {
$optionlist[$option['identifier']]['value'] .= $_DTYPE[$optionid]['choices'][$choiceid].' ';
}
} elseif(in_array($_DTYPE[$optionid]['type'], array('radio', 'select'))) {
$optionlist[$option['identifier']]['value'] = $_DTYPE[$optionid]['choices'][$optiondata[$optionid]];
} elseif($_DTYPE[$optionid]['type'] == 'image') {
$maxwidth = $_DTYPE[$optionid]['maxwidth'] ? 'width="'.$_DTYPE[$optionid]['maxwidth'].'"' : '';
$maxheight = $_DTYPE[$optionid]['maxheight'] ? 'height="'.$_DTYPE[$optionid]['maxheight'].'"' : '';
$optionlist[$option['identifier']]['value'] = $optiondata[$optionid] ? "<a href=\"$optiondata[$optionid]\" target=\"_blank\"><img src=\"$optiondata[$optionid]\" $maxwidth $maxheight border=\"0\"></a>" : '';
} elseif($_DTYPE[$optionid]['type'] == 'url') {
$optionlist[$option['identifier']]['value'] = $optiondata[$optionid] ? "<a href=\"$optiondata[$optionid]\" target=\"_blank\">$optiondata[$optionid]</a>" : '';
} else {
$optionlist[$option['identifier']]['value'] = $optiondata[$optionid];
}
}
$typetemplate = $_DTYPETEMPLATE ? preg_replace(array("/\[(.+?)value\]/ies", "/{(.+?)}/ies"), array("showoption('\\1', 'value')", "showoption('\\1', 'title')"), $_DTYPETEMPLATE) : '';
}
$post['subject'] = '['.$tradetypes[$tradetypeid].'] '.$post['subject'];
}
include template('trade_info');
} else {
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.customstatus, mf.spacename, mf.buyercredit, mf.sellercredit $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE p.tid='$tid' AND first=1 LIMIT 1");
$post = $db->fetch_array($query);
$tmp = explode("\t\t\t", $post['message']);
$post['message'] = count($tmp) == 2 ? $tmp[0] : '';
$postlist[$post['pid']] = viewthread_procpost($post);
viewthread_parsetags();
$postlist[$post['pid']]['counterdesc'] = $postlist[$post['pid']]['message'];
$post = $postlist[$post['pid']];
$post['buyerrank'] = 0;
if($post['buyercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($post['buyercredit'] <= $credit) {
$post['buyerrank'] = $level;
break;
}
}
}
$post['sellerrank'] = 0;
if($post['sellercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($post['sellercredit'] <= $credit) {
$post['sellerrank'] = $level;
break;
}
}
}
include template('viewthread_trade');
}
} elseif($do == 'viewtradelist') {
$tradepp = 10;
$start_limit = ($page - 1) * $tradepp;
$query = $db->query("SELECT typeid FROM {$tablepre}trades WHERE tid='$tid' AND displayorder<=0");
$trades = $threadtradetypes = array();
$showtradetypemenu = FALSE;
while($tradetype = $db->fetch_array($query)) {
$threadtradetypes[$tradetype['typeid']] = $tradetype['typeid'];
$tradetype['typeid'] && !$showtradetypemenu && $showtradetypemenu = TRUE;
}
$typeadd = isset($tradetypeid) ? ' AND typeid=\''.intval($tradetypeid).'\'' : '';
$listcount = $db->result($db->query("SELECT count(*) FROM {$tablepre}trades WHERE tid='$tid' AND displayorder<=0 $typeadd"), 0);
$multipage = multi($listcount, $tradepp, $page, "viewthread.php?do=viewtradelist&tid=$tid".(isset($tradetypeid) ? "&tradetypeid=$tradetypeid" : '').(isset($highlight) ? "&highlight=".rawurlencode($highlight) : ''));
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE tid='$tid' AND displayorder<=0 $typeadd ORDER BY displayorder DESC LIMIT $start_limit, $tradepp");
while($trade = $db->fetch_array($query)) {
if($trade['expiration']) {
$trade['expiration'] = ($trade['expiration'] - $timestamp) / 86400;
if($trade['expiration'] > 0) {
$trade['expirationhour'] = floor(($trade['expiration'] - floor($trade['expiration'])) * 24);
$trade['expiration'] = floor($trade['expiration']);
} else {
$trade['expiration'] = -1;
}
}
$trades[$trade['pid']] = $trade;
}
include template('viewthread_trade_list');
} elseif($do == 'viewfirstpost') {
$multipage = '';
$query = $db->query("SELECT p.*,m.username,m.adminid,m.groupid,m.credits FROM {$tablepre}posts p LEFT JOIN {$tablepre}members m ON m.uid=p.authorid WHERE tid='$tid' AND p.invisible='0' AND p.first='1' LIMIT 1");
$post = $db->fetch_array($query);
$tmp = explode("\t\t\t", $post['message']);
$post['message'] = count($tmp) == 2 ? $tmp[1] : $tmp[0];
$postlist[$post['pid']] = viewthread_procpost($post, 1);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$thread = $postlist[$post['pid']];
include template('viewthread_trade_post');
} elseif(in_array($do, array('viewall', 'viewpost', 'viewtrade'))) {
$sqladd = $do == 'viewall' ? "WHERE p.tid='$tid' AND p.invisible='0' AND p.first='0'" :
($do == 'viewpost' ? "LEFT JOIN {$tablepre}trades tr ON p.pid=tr.pid WHERE p.tid='$tid' AND p.invisible='0' AND tr.tid IS null AND p.first='0'" :
"INNER JOIN {$tablepre}trades tr ON p.pid=tr.pid WHERE p.tid='$tid' AND p.invisible='0'");
$query = $db->query("SELECT count(*) FROM {$tablepre}posts p $sqladd");
$repostnum = $db->result($query, 0);
$ppp = $forum['threadcaches'] && !$discuz_uid ? $_DCACHE['settings']['postperpage'] : $ppp;
$start_limit = $numpost = ($page - 1) * $ppp;
if($start_limit > $repostnum) {
$start_limit = $numpost = 0;
$page = 1;
}
$multipage = multi($repostnum, $ppp, $page, "viewthread.php?tid=$tid&do=$do&extra=$extra".(isset($highlight) ? "&highlight=".rawurlencode($highlight) : ''));
$query = $db->query("SELECT p.*,m.username,m.adminid,m.groupid,m.credits FROM {$tablepre}posts p LEFT JOIN {$tablepre}members m ON m.uid=p.authorid $sqladd ORDER BY p.dateline LIMIT $start_limit, $ppp");
$tradespids = array();
while($post = $db->fetch_array($query)) {
$post['first'] = 0;
$post = viewthread_procpost($post, 1);
$postlist[$post['pid']] = $post;
$tradespids[] = $post['pid'];
}
if(($do == 'viewtrade' || $do == 'viewall') && $tradespids) {
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE pid IN (".implodeids($tradespids).")");
while($trade = $db->fetch_array($query)) {
if($trade['expiration']) {
$trade['expiration'] = ($trade['expiration'] - $timestamp) / 86400;
if($trade['expiration'] > 0) {
$trade['expirationhour'] = floor(($trade['expiration'] - floor($trade['expiration'])) * 24);
$trade['expiration'] = floor($trade['expiration']);
} else {
$trade['expiration'] = -1;
}
}
$trades[$trade['pid']] = $trade;
$tradesaids[] = $trade['aid'];
}
}
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages, $tradesaids);
}
if($tradespids) {
$tradespids = implodeids($tradespids);
$query = $db->query("SELECT a.* FROM {$tablepre}attachments a WHERE a.pid IN ($tradespids)");
while($attach = $db->fetch_array($query)) {
if($attach['isimage'] && is_array($tradesaids) && in_array($attach['aid'], $tradesaids)) {
$trades[$attach['pid']]['attachurl'] = ($attach['remote'] ? $ftp['attachurl'] : $attachurl).'/'.$attach['attachment'];
$trades[$attach['pid']]['thumb'] = $trades[$attach['pid']]['attachurl'].($attach['thumb'] ? '.thumb.jpg' : '');
}
}
}
include template('viewthread_trade_post');
} elseif($do == 'viewrelatedtrade') {
$multipage = '';
$relatedtrades = !empty($insenz['relatedtrades']) ? stripslashes($insenz['relatedtrades']) : '';
include template('viewthread_trade_post');
}
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_trade.inc.php | PHP | asf20 | 12,879 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: chinese.class.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
define('CODETABLE_DIR', DISCUZ_ROOT.'./include/tables/');
class Chinese {
var $table = '';
var $iconv_enabled = false;
var $unicode_table = array();
var $config = array
(
'SourceLang' => '',
'TargetLang' => '',
'GBtoUnicode_table' => 'gb-unicode.table',
'BIG5toUnicode_table' => 'big5-unicode.table',
);
function Chinese($SourceLang, $TargetLang, $ForceTable = FALSE) {
$this->config['SourceLang'] = $this->_lang($SourceLang);
$this->config['TargetLang'] = $this->_lang($TargetLang);
if(function_exists('iconv') && $this->config['TargetLang'] != 'BIG5' && !$ForceTable) {
$this->iconv_enabled = true;
} else {
$this->iconv_enabled = false;
$this->OpenTable();
}
}
function _lang($LangCode) {
$LangCode = strtoupper($LangCode);
if(substr($LangCode, 0, 2) == 'GB') {
return 'GBK';
} elseif(substr($LangCode, 0, 3) == 'BIG') {
return 'BIG5';
} elseif(substr($LangCode, 0, 3) == 'UTF') {
return 'UTF-8';
} elseif(substr($LangCode, 0, 3) == 'UNI') {
return 'UNICODE';
}
}
function _hex2bin($hexdata) {
for($i=0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
function OpenTable() {
$this->unicode_table = array();
if($this->config['SourceLang'] == 'GBK' || $this->config['TargetLang'] == 'GBK') {
$this->table = CODETABLE_DIR.$this->config['GBtoUnicode_table'];
} elseif($this->config['SourceLang'] == 'BIG5' || $this->config['TargetLang'] == 'BIG5') {
$this->table = CODETABLE_DIR.$this->config['BIG5toUnicode_table'];
}
$fp = fopen($this->table, 'rb');
$tabletmp = fread($fp, filesize($this->table));
for($i = 0; $i < strlen($tabletmp); $i += 4) {
$tmp = unpack('nkey/nvalue', substr($tabletmp, $i, 4));
if($this->config['TargetLang'] == 'UTF-8') {
$this->unicode_table[$tmp['key']] = '0x'.dechex($tmp['value']);
} elseif($this->config['SourceLang'] == 'UTF-8') {
$this->unicode_table[$tmp['value']] = '0x'.dechex($tmp['key']);
} elseif($this->config['TargetLang'] == 'UNICODE') {
$this->unicode_table[$tmp['key']] = dechex($tmp['value']);
}
}
}
function CHSUtoUTF8($c) {
$str = '';
if($c < 0x80) {
$str .= $c;
} elseif($c < 0x800) {
$str .= (0xC0 | $c >> 6);
$str .= (0x80 | $c & 0x3F);
} elseif($c < 0x10000) {
$str .= (0xE0 | $c >> 12);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .=( 0x80 | $c & 0x3F);
} elseif($c < 0x200000) {
$str .= (0xF0 | $c >> 18);
$str .= (0x80 | $c >> 12 & 0x3F);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
return $str;
}
function Convert($SourceText) {
if($this->config['SourceLang'] == $this->config['TargetLang']) {
return $SourceText;
} elseif($this->iconv_enabled) {
if($this->config['TargetLang'] <> 'UNICODE') {
return iconv($this->config['SourceLang'], $this->config['TargetLang'], $SourceText);
} else {
$return = '';
while($SourceText != '') {
if(ord(substr($SourceText, 0, 1)) > 127) {
$return .= "&#x".dechex($this->Utf8_Unicode(iconv($this->config['SourceLang'],"UTF-8", substr($SourceText, 0, 2)))).";";
$SourceText = substr($SourceText, 2, strlen($SourceText));
} else {
$return .= substr($SourceText, 0, 1);
$SourceText = substr($SourceText, 1, strlen($SourceText));
}
}
return $return;
}
} elseif($this->config['TargetLang'] == 'UNICODE') {
$utf = '';
while($SourceText != '') {
if(ord(substr($SourceText, 0, 1)) > 127) {
if($this->config['SourceLang'] == 'GBK') {
$utf .= '&#x'.$this->unicode_table[hexdec(bin2hex(substr($SourceText, 0, 2))) - 0x8080].';';
} elseif($this->config['SourceLang'] == 'BIG5') {
$utf .= '&#x'.$this->unicode_table[hexdec(bin2hex(substr($SourceText, 0, 2)))].';';
}
$SourceText = substr($SourceText, 2, strlen($SourceText));
} else {
$utf .= substr($SourceText, 0, 1);
$SourceText = substr($SourceText, 1, strlen($SourceText));
}
}
return $utf;
} else {
$ret = '';
if($this->config['SourceLang'] == 'UTF-8') {
$out = '';
$len = strlen($SourceText);
$i = 0;
while($i < $len) {
$c = ord(substr($SourceText, $i++, 1));
switch($c >> 4) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
$out .= substr($SourceText, $i - 1, 1);
break;
case 12: case 13:
$char2 = ord(substr($SourceText, $i++, 1));
$char3 = $this->unicode_table[(($c & 0x1F) << 6) | ($char2 & 0x3F)];
if($this->config['TargetLang'] == 'GBK') {
$out .= $this->_hex2bin(dechex($char3 + 0x8080));
} elseif($this->config['TargetLang'] == 'BIG5') {
$out .= $this->_hex2bin($char3);
}
break;
case 14:
$char2 = ord(substr($SourceText, $i++, 1));
$char3 = ord(substr($SourceText, $i++, 1));
$char4 = $this->unicode_table[(($c & 0x0F) << 12) | (($char2 & 0x3F) << 6) | (($char3 & 0x3F) << 0)];
if($this->config['TargetLang'] == 'GBK') {
$out .= $this->_hex2bin(dechex($char4 + 0x8080));
} elseif($this->config['TargetLang'] == 'BIG5') {
$out .= $this->_hex2bin($char4);
}
break;
}
}
return $out;
} else {
while($SourceText != '') {
if(ord(substr($SourceText, 0, 1)) > 127) {
if($this->config['SourceLang'] == 'BIG5') {
$utf8 = $this->CHSUtoUTF8(hexdec($this->unicode_table[hexdec(bin2hex(substr($SourceText, 0, 2)))]));
} elseif($this->config['SourceLang'] == 'GBK') {
$utf8=$this->CHSUtoUTF8(hexdec($this->unicode_table[hexdec(bin2hex(substr($SourceText, 0, 2))) - 0x8080]));
}
for($i = 0; $i < strlen($utf8); $i += 3) {
$ret .= chr(substr($utf8, $i, 3));
}
$SourceText = substr($SourceText, 2, strlen($SourceText));
} else {
$ret .= substr($SourceText, 0, 1);
$SourceText = substr($SourceText, 1, strlen($SourceText));
}
}
//$this->unicode_table = array();
$SourceText = '';
return $ret;
}
}
}
function Utf8_Unicode($char) {
switch(strlen($char)) {
case 1:
return ord($char);
case 2:
$n = (ord($char[0]) & 0x3f) << 6;
$n += ord($char[1]) & 0x3f;
return $n;
case 3:
$n = (ord($char[0]) & 0x1f) << 12;
$n += (ord($char[1]) & 0x3f) << 6;
$n += ord($char[2]) & 0x3f;
return $n;
case 4:
$n = (ord($char[0]) & 0x0f) << 18;
$n += (ord($char[1]) & 0x3f) << 12;
$n += (ord($char[2]) & 0x3f) << 6;
$n += ord($char[3]) & 0x3f;
return $n;
}
}
}
?>
| zyyhong | trunk/jiaju001/bbs/include/chinese.class.php | PHP | asf20 | 7,047 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: insenz_cron.func.php 10586 2007-09-07 07:14:10Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function insenz_runcron() {
global $timestamp, $db, $tablepre, $_DCACHE;
$lockfile = DISCUZ_ROOT.'./forumdata/insenzcron_'.gmdate('ymdH', $timestamp + 8 * 3600).'.lock';
if(is_writable($lockfile) && filemtime($lockfile) > $timestamp - 180) {
return NULL;
} else {
@touch($lockfile);
}
@set_time_limit(1000);
@ignore_user_abort(TRUE);
$globalstick = $floatthreads = 0;
$query = $db->query("SELECT c.id, c.type, c.fid AS virtualfid, c.tid, c.status, c.begintime, c.starttime, c.endtime, t.fid, t.authorid, t.author, t.subject, t.lastpost, t.displayorder FROM {$tablepre}campaigns c LEFT JOIN {$tablepre}threads t ON t.tid=c.tid WHERE c.nextrun<='$timestamp'");
while($c = $db->fetch_array($query)) {
$moderated = in_array($c['displayorder'], array(-11, -12, 1, 2)) ? 1 : 0;
$moderatedadd = $moderated ? ", moderated=1" : '';
if($c['status'] == 1) {
if($c['type'] != 4) {
$db->query("UPDATE {$tablepre}threads SET displayorder=-displayorder-10 $moderatedadd WHERE tid='$c[tid]'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}campaigns SET status=2, starttime='$timestamp', nextrun=endtime+starttime-begintime WHERE id='$c[id]' AND type='$c[type]'", 'UNBUFFERED');
$lastpost = "$c[tid]\t$c[subject]\t$c[lastpost]\t$c[author]";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+1, todayposts=todayposts+1 WHERE fid='$c[fid]'", 'UNBUFFERED');
if($moderated) {
$expiration = $c['endtime'] + $c['starttime'] - $c['begintime'];
$db->query("INSERT INTO {$tablepre}threadsmod (tid, uid, username, dateline, action, expiration, status) VALUES ('$c[tid]', '".$_DCACHE[settings][insenz][uid]."', '".$_DCACHE[settings][insenz][username]."', '$timestamp', 'EST', '$expiration', '0')", 'UNBUFFERED');
}
if($c['displayorder'] < -13) {
$floatthreads = 1;
} elseif($c['displayorder'] < -11) {
$globalstick = 1;
}
require_once DISCUZ_ROOT.'./include/post.func.php';
updatepostcredits('+', $c['authorid'], $_DCACHE['settings']['creditspolicy']['post']);
} else {
$db->query("UPDATE {$tablepre}campaigns SET status=2, starttime='$timestamp', nextrun=endtime+starttime-begintime WHERE id='$c[id]' AND type=4", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}forums SET status='1' WHERE fid='$c[virtualfid]'");
}
} elseif($c['status'] == 2) {
if($c['type'] != 4) {
if($c['displayorder'] > 0) {
$db->query("UPDATE {$tablepre}threads SET displayorder=0 $moderatedadd WHERE tid='$c[tid]'", 'UNBUFFERED');
if($moderated) {
$db->query("INSERT INTO {$tablepre}threadsmod (tid, uid, username, dateline, action, expiration, status) VALUES ('$c[tid]', '".$_DCACHE[settings][insenz][uid]."', '".$_DCACHE[settings][insenz][username]."', '$timestamp', 'UES', '0', '0')", 'UNBUFFERED');
}
if($c['displayorder'] > 3) {
$floatthreads = 1;
} elseif($c['displayorder'] > 1) {
$globalstick = 1;
}
}
} else {
$db->query("UPDATE {$tablepre}forums SET status='0' WHERE fid='$c[virtualfid]'");
}
$db->query("UPDATE {$tablepre}campaigns SET status=3, nextrun=expiration WHERE id='$c[id]' AND type='$c[type]'", 'UNBUFFERED');
} elseif($c['status'] == 3) {
if($c['type'] != 4) {
$db->query("UPDATE {$tablepre}threads SET digest=0 WHERE tid='$c[tid]'", 'UNBUFFERED');
}
$db->query("DELETE FROM {$tablepre}campaigns WHERE id='$c[id]' AND type='$c[type]'", 'UNBUFFERED');
}
}
require_once DISCUZ_ROOT.'./include/cache.func.php';
$query = $db->query("SELECT nextrun FROM {$tablepre}campaigns WHERE nextrun>'$timestamp' ORDER BY nextrun LIMIT 1");
$_DCACHE['settings']['insenz']['cronnextrun'] = $db->result($query, 0);
updatesettings();
$globalstick && updatecache('globalstick');
$floatthreads && updatecache('floatthreads');
@unlink($lockfile);
}
function insenz_onlinestats() {
global $timestamp, $db, $tablepre, $_DCACHE;
require_once DISCUZ_ROOT.'./include/cache.func.php';
$_DCACHE['settings']['insenz']['statsnextrun'] = $timestamp + 3600;
updatesettings();
$onlinenum = $db->result($db->query("SELECT COUNT(*) FROM {$tablepre}sessions WHERE lastactivity>=($timestamp-900)"), 0);
$db->query("REPLACE INTO {$tablepre}statvars (type, variable, value) VALUES ('houronlines', '".gmdate('ymdH', $timestamp + 8 * 3600)."', '$onlinenum')");
}
?> | zyyhong | trunk/jiaju001/bbs/include/insenz_cron.func.php | PHP | asf20 | 4,692 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: moderation.inc.php 10463 2007-09-03 01:23:37Z tiger $
*/
if(!defined('IN_DISCUZ') || CURSCRIPT != 'topicadmin') {
exit('Access Denied');
}
if($action != 'moderate') {
$operation = $action;
$action = 'moderate';
$moderate = array($tid);
}
if(!in_array($operation, array('delete', 'move', 'copy', 'highlight', 'type', 'close', 'stick', 'digest', 'supe_push', 'removereward', 'bump', 'recommend')) || (!$allowdelpost && !$iscircleadmin && $operation == 'delete') || (!$allowstickthread && $operation == 'stick')) {
showmessage('admin_moderate_invalid');
}
$threadlist = $loglist = array();
if($tids = implodeids($moderate)) {
$sgidadd = $iscircleadmin ? "AND sgid='$gid'" : '';
$query = $db->query("SELECT * FROM {$tablepre}threads WHERE tid IN ($tids) AND fid='$fid' AND displayorder>='0' AND digest>='0' $sgidadd LIMIT $tpp");
while($thread = $db->fetch_array($query)) {
$thread['lastposterenc'] = rawurlencode($thread['lastposter']);
$thread['dblastpost'] = $thread['lastpost'];
$thread['lastpost'] = gmdate("$dateformat $timeformat", $thread['lastpost'] + $timeoffset * 3600);
$threadlist[$thread['tid']] = $thread;
$tid = empty($tid) ? $thread['tid'] : $tid;
}
}
if(empty($threadlist)) {
showmessage('admin_moderate_invalid');
}
$modpostsnum = count($threadlist);
$single = $modpostsnum == 1 ? TRUE : FALSE;
$referer = "forumdisplay.php?fid=$fid";
if(!submitcheck('modsubmit')) {
if($operation == 'move') {
require_once DISCUZ_ROOT.'./include/forum.func.php';
$forumselect = forumselect();
} elseif($operation == 'highlight') {
$stylecheck = array();
$colorcheck = array(0 => 'checked="checked"');
if($single) {
$string = sprintf('%02d', $threadlist[$tid]['highlight']);
$stylestr = sprintf('%03b', $string[0]);
for($i = 1; $i <= 3; $i++) {
$stylecheck[$i] = $stylestr[$i - 1] ? 'checked="checked"' : '';
}
$colorcheck = array($string[1] => 'checked="checked"');
}
} elseif($operation == 'type') {
$typeselect = typeselect('', 1);
}
if(in_array($operation, array('stick', 'digest', 'highlight', 'close', 'supe_push', 'recommend'))) {
$expirationmin = gmdate($dateformat, $timestamp + 86400 + $timeoffset * 3600);
$expirationmax = gmdate($dateformat, $timestamp + 86400 * 180 + $timeoffset * 3600);
$expirationdefault = '';
$stickcheck = $digestcheck = $closecheck = $supe_pushstatus = array();
if($single) {
empty($threadlist[$tid]['displayorder']) ? $stickcheck[1] ='checked="checked"' : $stickcheck[$threadlist[$tid]['displayorder']] = 'checked="checked"';
empty($threadlist[$tid]['digest']) ? $digestcheck[1] = 'checked="checked"' : $digestcheck[$threadlist[$tid]['digest']] = 'checked="checked"';
empty($threadlist[$tid]['supe_pushstatus']) ? $supe_pushstatus[2] = 'checked="checked"' : $supe_pushstatus[$threadlist[$tid]['supe_pushstatus']] = 'checked="checked"';
empty($threadlist[$tid]['closed']) ? $closecheck[0] = 'checked="checked"' : $closecheck[1] = 'checked="checked"';
if($threadlist[$tid]['moderated']) {
switch($operation) {
case 'stick': $actionarray = array('EST'); break;
case 'digest': $actionarray = array('EDI'); break;
case 'highlight': $actionarray = array('EHL'); break;
case 'close': $actionarray = array('ECL', 'EOP'); break;
case 'supe_push': $actionarray = array('PTS', 'RFS'); break;
default: $actionarray = array();
}
$query = $db->query("SELECT * FROM {$tablepre}threadsmod WHERE tid='{$threadlist[0][tid]}' ORDER BY dateline DESC");
while($log = $db->fetch_array($query)) {
$log['dateline'] = gmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$log['expiration'] = !empty($log['expiration']) ? gmdate("$dateformat", $log['expiration'] + $timeoffset * 3600) : '';
if($log['status'] && in_array($log['action'], $actionarray)) {
$expirationdefault = $log['expiration'];
}
$log['status'] = empty($log['status']) ? 'style="text-decoration: line-through" disabled' : '';
$loglist[] = $log;
}
if(!empty($loglist)) {
include_once language('modactions');
}
}
}
}
include template('topicadmin_moderate');
} else {
$moderatetids = implodeids(array_keys($threadlist));
checkreasonpm();
if($operation == 'delete') {
$stickmodify = 0;
foreach($threadlist as $thread) {
if($thread['digest']) {
updatecredits($thread['authorid'], $digestcredits, -$thread['digest'], 'digestposts=digestposts-1');
}
if(in_array($thread['displayorder'], array(2, 3))) {
$stickmodify = 1;
}
}
$losslessdel = $losslessdel > 0 ? $timestamp - $losslessdel * 86400 : 0;
//Update members' credits and post counter
$uidarray = $tuidarray = $ruidarray = array();
$query = $db->query("SELECT first, authorid, dateline FROM {$tablepre}posts WHERE tid IN ($moderatetids)");
while($post = $db->fetch_array($query)) {
if($post['dateline'] < $losslessdel) {
$uidarray[] = $post['authorid'];
} else {
if($post['first']) {
$tuidarray[] = $post['authorid'];
} else {
$ruidarray[] = $post['authorid'];
}
}
}
if($uidarray) {
updatepostcredits('-', $uidarray, array());
}
if($tuidarray) {
updatepostcredits('-', $tuidarray, $postcredits);
}
if($ruidarray) {
updatepostcredits('-', $ruidarray, $replycredits);
}
$modaction = 'DEL';
if($forum['recyclebin']) {
$db->query("UPDATE {$tablepre}threads SET displayorder='-1', digest='0', moderated='1' WHERE tid IN ($moderatetids)");
$db->query("UPDATE {$tablepre}posts SET invisible='-1' WHERE tid IN ($moderatetids)");
} else {
$auidarray = array();
$query = $db->query("SELECT uid, attachment, dateline, thumb, remote FROM {$tablepre}attachments WHERE tid IN ($moderatetids)");
while($attach = $db->fetch_array($query)) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
if($attach['dateline'] > $losslessdel) {
$auidarray[$attach['uid']] = !empty($auidarray[$attach['uid']]) ? $auidarray[$attach['uid']] + 1 : 1;
}
}
if($auidarray) {
updateattachcredits('-', $auidarray, $postattachcredits);
}
$videoopen && videodelete($moderate, TRUE);
foreach(array('threads', 'threadsmod', 'relatedthreads', 'posts', 'polls', 'polloptions', 'trades', 'activities', 'activityapplies', 'debates', 'videos', 'debateposts', 'attachments', 'favorites', 'mythreads', 'myposts', 'subscriptions', 'typeoptionvars', 'forumrecommend') as $value) {
$db->query("DELETE FROM {$tablepre}$value WHERE tid IN ($moderatetids)", 'UNBUFFERED');
}
}
if($globalstick && $stickmodify) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
updateforumcount($fid);
} else {
if(isset($expiration) && !empty($expiration) && in_array($operation, array('stick', 'digest', 'highlight', 'close'))) {
$expiration = strtotime($expiration) - $timeoffset * 3600 + date('Z');
if(gmdate('Ymd', $expiration + $timeoffset * 3600) <= gmdate('Ymd', $timestamp + $timeoffset * 3600) || ($expiration > $timestamp + 86400 * 180)) {
showmessage('admin_expiration_invalid');
}
} else {
$expiration = 0;
}
if($operation == 'stick' || $operation == 'digest') {
$level = intval($level);
if($level < 0 || $level > 3 || ( $operation == 'stick' && $level > $allowstickthread)) {
showmessage('undefined_action');
}
$expiration = $level ? $expiration : 0;
if($operation == 'stick') {
$db->query("UPDATE {$tablepre}threads SET displayorder='$level', moderated='1' WHERE tid IN ($moderatetids)");
$stickmodify = 0;
foreach($threadlist as $thread) {
$stickmodify = (in_array($thread['displayorder'], array(2, 3)) || in_array($level, array(2, 3))) && $level != $thread['displayorder'] ? 1 : $stickmodify;
}
if($globalstick && $stickmodify) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
$modaction = $level ? ($expiration ? 'EST' : 'STK') : 'UST';
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('STK', 'UST', 'EST', 'UES')", 'UNBUTTERED');
} elseif($operation == 'digest') {
$db->query("UPDATE {$tablepre}threads SET digest='$level', moderated='1' WHERE tid IN ($moderatetids)");
foreach($threadlist as $thread) {
if($thread['digest'] != $level) {
$digestpostsadd = ($thread['digest'] > 0 && $level == 0) || ($thread['digest'] == 0 && $level > 0) ? 'digestposts=digestposts'.($level == 0 ? '-' : '+').'1' : '';
updatecredits($thread['authorid'], $digestcredits, $level - $thread['digest'], $digestpostsadd);
}
}
$modaction = $level ? ($expiration ? 'EDI' : 'DIG') : 'UDG';
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('DIG', 'UDI', 'EDI', 'UED')", 'UNBUTTERED');
}
} elseif($operation == 'close') {
$modaction = empty($close) ? ($expiration ? 'EOP' : 'OPN'): ($expiration ? 'ECL' : 'CLS');
$close = ($modaction == 'ECL' || $modaction == 'CLS') ? 1 : 0;
$db->query("UPDATE {$tablepre}threads SET closed='$close', moderated='1' WHERE tid IN ($moderatetids)");
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('CLS','OPN', 'ECL', 'UCL', 'EOP', 'UEO')", 'UNBUTTERED');
} elseif($operation == 'move') {
$query = $db->query("SELECT fid, name, modnewposts, allowpostspecial FROM {$tablepre}forums WHERE fid='$moveto' AND status>0 AND type<>'group'");
if(!$toforum = $db->fetch_array($query)) {
showmessage('admin_move_invalid');
} elseif($fid == $toforum['fid']) {
showmessage('admin_move_illegal');
} else {
$moveto = $toforum['fid'];
$modnewthreads = (!$allowdirectpost || $allowdirectpost == 1) && $toforum['modnewposts'] ? 1 : 0;
$modnewreplies = (!$allowdirectpost || $allowdirectpost == 2) && $toforum['modnewposts'] ? 1 : 0;
if($modnewthreads || $modnewreplies) {
showmessage('admin_move_have_mod');
}
}
if($adminid == 3) {
if($accessmasks) {
$accessadd1 = ', a.allowview, a.allowpost, a.allowreply, a.allowgetattach, a.allowpostattach';
$accessadd2 = "LEFT JOIN {$tablepre}access a ON a.uid='$discuz_uid' AND a.fid='$moveto'";
}
$query = $db->query("SELECT ff.postperm, m.uid AS istargetmod $accessadd1
FROM {$tablepre}forumfields ff
$accessadd2
LEFT JOIN {$tablepre}moderators m ON m.fid='$moveto' AND m.uid='$discuz_uid'
WHERE ff.fid='$moveto'");
$priv = $db->fetch_array($query);
if((($priv['postperm'] && !in_array($groupid, explode("\t", $priv['postperm']))) || ($accessmasks && ($priv['allowview'] || $priv['allowreply'] || $priv['allowgetattach'] || $priv['allowpostattach']) && !$priv['allowpost'])) && !$priv['istargetmod']) {
showmessage('admin_move_nopermission');
}
}
$moderate = array();
$stickmodify = 0;
foreach($threadlist as $tid => $thread) {
if(!$thread['special'] || substr(sprintf('%04b', $toforum['allowpostspecial']), -$thread['special'], 1)) {
$moderate[] = $tid;
if(in_array($thread['displayorder'], array(2, 3))) {
$stickmodify = 1;
}
if($type == 'redirect') {
$db->query("INSERT INTO {$tablepre}threads (fid, readperm, iconid, author, authorid, subject, dateline, lastpost, lastposter, views, replies, displayorder, digest, closed, special, attachment)
VALUES ('$thread[fid]', '$thread[readperm]', '$thread[iconid]', '".addslashes($thread['author'])."', '$thread[authorid]', '".addslashes($thread['subject'])."', '$thread[dateline]', '$thread[dblastpost]', '$thread[lastposter]', '0', '0', '0', '0', '$thread[tid]', '0', '0')");
}
}
}
if(!$moderatetids = implode(',', $moderate)) {
showmessage('admin_moderate_invalid');
}
$displayorderadd = $adminid == 3 ? ', displayorder=\'0\'' : '';
$db->query("UPDATE {$tablepre}threads SET fid='$moveto', moderated='1' $displayorderadd WHERE tid IN ($moderatetids)");
$db->query("UPDATE {$tablepre}posts SET fid='$moveto' WHERE tid IN ($moderatetids)");
if($globalstick && $stickmodify) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
$modaction = 'MOV';
updateforumcount($moveto);
updateforumcount($fid);
} elseif($operation == 'highlight') {
$stylebin = '';
for($i = 1; $i <= 3; $i++) {
$stylebin .= empty($highlight_style[$i]) ? '0' : '1';
}
$highlight_style = bindec($stylebin);
if($highlight_style < 0 || $highlight_style > 7 || $highlight_color < 0 || $highlight_color > 8) {
showmessage('undefined_action', NULL, 'HALTED');
}
$db->query("UPDATE {$tablepre}threads SET highlight='$highlight_style$highlight_color', moderated='1' WHERE tid IN ($moderatetids)", 'UNBUFFERED');
$modaction = ($highlight_style + $highlight_color) ? ($expiration ? 'EHL' : 'HLT') : 'UHL';
$expiration = $modaction == 'UHL' ? 0 : $expiration;
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('HLT', 'UHL', 'EHL', 'UEH')", 'UNBUTTERED');
} elseif($operation == 'type') {
if(!isset($forum['threadtypes']['types'][$typeid]) && !($typeid == 0 && !$forum['threadtypes']['required'])) {
showmessage('admin_move_invalid');
}
$db->query("UPDATE {$tablepre}threads SET typeid='$typeid', moderated='1' WHERE tid IN ($moderatetids)");
$modaction = 'TYP';
} elseif($operation == 'bump') {
if($isbump) {
$modaction = 'BMP';
$thread = $threadlist;
$thread = array_pop($thread);
$thread['subject'] = addslashes($thread['subject']);
$thread['lastposter'] = addslashes($thread['lastposter']);
$db->query("UPDATE {$tablepre}threads SET lastpost='$timestamp', moderated='1' WHERE tid IN ($moderatetids)");
$db->query("UPDATE {$tablepre}forums SET lastpost='$thread[tid]\t$thread[subject]\t$timestamp\t$thread[lastposter]' WHERE fid='$fid'");
} else {
$modaction = 'DWN';
$downtime = $timestamp - 86400 * 730;
$db->query("UPDATE {$tablepre}threads SET lastpost='$downtime', moderated='1' WHERE tid IN ($moderatetids)");
}
$forum['threadcaches'] && deletethreadcaches($thread['tid']);
} elseif($operation == 'supe_push') {
if(!$supe['status']) {
showmessage('supe_pushsetting_noopen');
}
if(!$supe_allowpushthread) {
showmessage('admin_nopermission');
}
if($forum['supe_pushsetting']['status'] != '2') {
showmessage('supe_pushsetting_nohand');
}
$supe_pushstatus = in_array($supe_pushstatus, array('2', '-2')) ? $supe_pushstatus : '2';
$db->query("UPDATE {$tablepre}threads SET supe_pushstatus='$supe_pushstatus' WHERE tid IN ($moderatetids)");
$modaction = $supe_pushstatus == '2' ? 'PTS' : ($supe_pushstatus == '-2' ? 'RFS' : '');
} elseif($operation == 'recommend') {
$db->query("UPDATE {$tablepre}threads SET moderated='1' WHERE tid IN ($moderatetids)");
$modaction = $isrecommend ? 'REC' : 'URE';
$thread = daddslashes($thread, 1);
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('REC')", 'UNBUTTERED');
if($isrecommend) {
$recommendexpire = $recommendexpire ? intval($recommendexpire) : 0;
$addthread = $comma = '';
foreach($threadlist as $thread) {
$addthread .= $comma."('$thread[fid]', '$thread[tid]', '0', '".addslashes($thread['subject'])."', '".addslashes($thread['author'])."', '$thread[authorid]', '$discuz_uid', '".($timestamp + $recommendexpire)."')";
$comma = ', ';
}
if($addthread) {
$db->query("REPLACE INTO {$tablepre}forumrecommend (fid, tid, displayorder, subject, author, authorid, moderatorid, expiration) VALUES $addthread");
}
} else {
$db->query("DELETE FROM {$tablepre}forumrecommend WHERE fid='$fid' AND tid IN ($moderatetids)");
}
}
}
$resultarray = array(
'redirect' => (preg_match("/^topicadmin/", ($redirect = dreferer("forumdisplay.php?fid=$fid"))) ? "forumdisplay.php?fid=$fid" : $redirect),
'reasonpm' => ($sendreasonpm ? array('data' => $threadlist, 'var' => 'thread', 'item' => ($operation == 'move' ? 'reason_move' : 'reason_moderate')) : array()),
'modtids' => ($operation == 'delete' && !$forum['recyclebin']) ? 0 : $moderatetids,
'modlog' => $threadlist,
'expiration'=> $expiration
);
if($iscircleadmin && $supe_referer) {
$resultarray['redirect'] = $supe_referer;
}
if(in_array($operation, array('stick', 'digest', 'highlight')) && !empty($next) && $next != $operation && in_array($next, array('stick', 'digest', 'highlight'))) {
if(count($moderate) == 1) {
$resultarray['redirect'] = "topicadmin.php?tid=$moderate[0]&fid=$fid&action=$next";
} else {
$resultarray['redirect'] = "topicadmin.php?action=moderate&fid=$fid&operation=$next";
if(is_array($moderate)) {
foreach($moderate as $modtid) {
$resultarray['redirect'] .= "&moderate[]=$modtid";
}
}
}
$resultarray['message'] = 'admin_succeed_next';
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/moderation.inc.php | PHP | asf20 | 17,596 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: category.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$sql = $accessmasks ? "SELECT f.fid, f.fup, f.type, f.name, f.threads, f.posts, f.todayposts, f.lastpost, f.inheritedmod, ff.description, ff.moderators, ff.icon, ff.viewperm, a.allowview FROM {$tablepre}forums f
LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid
LEFT JOIN {$tablepre}access a ON a.uid='$discuz_uid' AND a.fid=f.fid
WHERE f.status>0 AND (f.fid='$gid' OR (f.fup='$gid' AND f.type='forum')) ORDER BY f.type, f.displayorder"
: "SELECT f.fid, f.fup, f.type, f.name, f.threads, f.posts, f.todayposts, f.lastpost, f.inheritedmod, ff.description, ff.moderators, ff.icon, ff.viewperm FROM {$tablepre}forums f
LEFT JOIN {$tablepre}forumfields ff USING(fid)
WHERE f.status>0 AND (f.fid='$gid' OR (f.fup='$gid' AND f.type='forum')) ORDER BY f.type, f.displayorder";
$query = $db->query($sql);
if($db->num_rows($query) < 2) {
showmessage('forum_nonexistence', NULL, 'HALTED');
}
while($forum = $db->fetch_array($query)) {
if($forum['type'] != 'group') {
$threads += $forum['threads'];
$posts += $forum['posts'];
$todayposts += $forum['todayposts'];
if(forum($forum)) {
$forum['orderid'] = $catlist[$forum['fup']]['forumscount'] ++;
$forum['subforums'] = '';
$forumlist[$forum['fid']] = $forum;
$catlist[$forum['fup']]['forums'][] = $forum['fid'];
$fids .= ','.$forum['fid'];
}
} else {
$forum['collapseimg'] = 'collapsed_no.gif';
$collapse['category_'.$forum['fid']] = '';
if($forum['moderators']) {
$forum['moderators'] = moddisplay($forum['moderators'], 'flat');
}
$forum['forumscount'] = 0;
$forum['forumcolumns'] = 0;
$catlist[$forum['fid']] = $forum;
$navigation = '» '.$forum['name'];
$navtitle = strip_tags($forum['name']).' - ';
}
}
$query = $db->query("SELECT fid, fup, name, threads, posts, todayposts FROM {$tablepre}forums WHERE status>0 AND fup IN ($fids) AND type='sub'");
while($forum = $db->fetch_array($query)) {
if($subforumsindex && $forumlist[$forum['fup']]['permission'] == 2) {
$forumlist[$forum['fup']]['subforums'] .= '<a href="forumdisplay.php?fid='.$forum['fid'].'"><u>'.$forum['name'].'</u></a> ';
}
$forumlist[$forum['fup']]['threads'] += $forum['threads'];
$forumlist[$forum['fup']]['posts'] += $forum['posts'];
$forumlist[$forum['fup']]['todayposts'] += $forum['todayposts'];
}
?> | zyyhong | trunk/jiaju001/bbs/include/category.inc.php | PHP | asf20 | 2,619 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: global.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function authcode($string, $operation, $key = '') {
$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
$key_length = strlen($key);
$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
$string_length = strlen($string);
$rndkey = $box = array();
$result = '';
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($key[$i % $key_length]);
$box[$i] = $i;
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
return substr($result, 8);
} else {
return '';
}
} else {
return str_replace('=', '', base64_encode($result));
}
}
function clearcookies() {
global $discuz_uid, $discuz_user, $discuz_pw, $discuz_secques, $adminid, $credits;
dsetcookie('sid', '', -86400 * 365);
dsetcookie('auth', '', -86400 * 365);
dsetcookie('visitedfid', '', -86400 * 365);
dsetcookie('onlinedetail', '', -86400 * 365, 0);
$discuz_uid = $adminid = $credits = 0;
$discuz_user = $discuz_pw = $discuz_secques = '';
}
function checklowerlimit($creditsarray, $coef = 1) {
if(is_array($creditsarray)) {
global $extcredits, $id;
foreach($creditsarray as $id => $addcredits) {
$addcredits = $addcredits * $coef;
if($addcredits < 0 && ($GLOBALS['extcredits'.$id] < $extcredits[$id]['lowerlimit'] || (($GLOBALS['extcredits'.$id] + $addcredits) < $extcredits[$id]['lowerlimit']))) {
if($coef == 1) {
showmessage('credits_policy_lowerlimit');
} else {
showmessage('credits_policy_num_lowerlimit');
}
}
}
}
}
function cutstr($string, $length, $dot = ' ...') {
global $charset;
if(strlen($string) <= $length) {
return $string;
}
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
$strcut = '';
if(strtolower($charset) == 'utf-8') {
$n = $tn = $noc = 0;
while($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
} else {
for($i = 0; $i < $length; $i++) {
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
$strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
return $strcut.$dot;
}
function daddslashes($string, $force = 0) {
!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
if(!MAGIC_QUOTES_GPC || $force) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = daddslashes($val, $force);
}
} else {
$string = addslashes($string);
}
}
return $string;
}
function datecheck($ymd, $sep='-') {
if(!empty($ymd)) {
list($year, $month, $day) = explode($sep, $ymd);
return checkdate($month, $day, $year);
} else {
return FALSE;
}
}
function debuginfo() {
if($GLOBALS['debug']) {
global $db, $discuz_starttime, $debuginfo;
$mtime = explode(' ', microtime());
$debuginfo = array('time' => number_format(($mtime[1] + $mtime[0] - $discuz_starttime), 6), 'queries' => $db->querynum);
return TRUE;
} else {
return FALSE;
}
}
function dexit($message = '') {
echo $message;
output();
exit();
}
function dhtmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val);
}
} else {
$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string));
}
return $string;
}
function dheader($string, $replace = true, $http_response_code = 0) {
$string = str_replace(array("\r", "\n"), array('', ''), $string);
if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
@header($string, $replace);
} else {
@header($string, $replace, $http_response_code);
}
if(preg_match('/^\s*location:/is', $string)) {
exit();
}
}
function disuploadedfile($file) {
return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}
function dreferer($default = '') {
global $referer, $indexname;
$default = empty($default) ? $indexname : '';
if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
$referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
$referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
} else {
$referer = dhtmlspecialchars($referer);
}
if(!preg_match("/(\.php|[a-z]+(\-\d+)+\.html)/", $referer) || strpos($referer, 'logging.php')) {
$referer = $default;
}
return $referer;
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
setcookie(($prefix ? $cookiepre : '').$var, $value,
$life ? $timestamp + $life : 0, $cookiepath,
$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function dunlink($filename, $havethumb = 0, $remote = 0) {
global $authkey, $ftp, $attachdir;
if($remote) {
require_once DISCUZ_ROOT.'./include/ftp.func.php';
if(!$ftp['connid']) {
if(!($ftp['connid'] = dftp_connect($ftp['host'], $ftp['username'], authcode($ftp['password'], 'DECODE', md5($authkey)), $ftp['attachdir'], $ftp['port'], $ftp['ssl']))) {
return;
}
}
dftp_delete($ftp['connid'], $filename);
$havethumb && dftp_delete($ftp['connid'], $filename.'.thumb.jpg');
} else {
@unlink($attachdir.'/'.$filename);
$havethumb && @unlink($attachdir.'/'.$filename.'.thumb.jpg');
}
}
function emailconv($email, $tolink = 1) {
$email = str_replace(array('@', '.'), array('@', '.'), $email);
return $tolink ? '<a href="mailto: '.$email.'">'.$email.'</a>': $email;
}
function errorlog($type, $message, $halt = 1) {
global $timestamp, $discuz_userss, $onlineip, $_SERVER;
$user = empty($discuz_userss) ? '' : $discuz_userss.'<br />';
$user .= $onlineip.'|'.$_SERVER['REMOTE_ADDR'];
writelog('errorlog', dhtmlspecialchars("$timestamp\t$type\t$user\t".str_replace(array("\r", "\n"), array(' ', ' '), trim($message))));
if($halt) {
exit();
}
}
function getrobot() {
if(!defined('IS_ROBOT')) {
$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
if(preg_match("/($kw_browsers)/", $_SERVER['HTTP_USER_AGENT'])) {
define('IS_ROBOT', FALSE);
} elseif(preg_match("/($kw_spiders)/", $_SERVER['HTTP_USER_AGENT'])) {
define('IS_ROBOT', TRUE);
} else {
define('IS_ROBOT', FALSE);
}
}
return IS_ROBOT;
}
function fileext($filename) {
return trim(substr(strrchr($filename, '.'), 1, 10));
}
function formhash($specialadd = '') {
global $discuz_user, $discuz_uid, $discuz_pw, $timestamp, $discuz_auth_key;
$hashadd = defined('IN_ADMINCP') ? 'Only For Discuz! Admin Control Panel' : '';
return substr(md5(substr($timestamp, 0, -7).$discuz_user.$discuz_uid.$discuz_pw.$discuz_auth_key.$hashadd.$specialadd), 8, 8);
}
function forumperm($permstr) {
global $groupid, $extgroupids;
$groupidarray = array($groupid);
foreach(explode("\t", $extgroupids) as $extgroupid) {
if($extgroupid = intval(trim($extgroupid))) {
$groupidarray[] = $extgroupid;
}
}
return preg_match("/(^|\t)(".implode('|', $groupidarray).")(\t|$)/", $permstr);
}
function forumformulaperm($formula, $return = 0) {
global $_DSESSION, $extcredits, $formulamessage, $usermsg, $forum;
if(!$formula || $_DSESSION['adminid'] == 1 || $forum['ismoderator']) {
return;
}
$formula = unserialize($formula);$formula = $formula[1];
if(!$formula) {
return;
}
@eval("\$formulaperm = ($formula) ? TRUE : FALSE;");
if(!$formulaperm) {
if($return) {
return FALSE;
}
include_once language('misc');
$search = array('$_DSESSION[\'digestposts\']', '$_DSESSION[\'posts\']', '$_DSESSION[\'oltime\']', '$_DSESSION[\'pageviews\']');
$replace = array($language['formulaperm_digestposts'], $language['formulaperm_posts'], $language['formulaperm_oltime'], $language['formulaperm_pageviews']);
for($i = 1; $i <= 8; $i++) {
$search[] = '$_DSESSION[\'extcredits'.$i.'\']';
$replace[] = $extcredits[$i]['title'] ? $extcredits[$i]['title'] : $language['formulaperm_extcredits'].$i;
}
$i = 0;$usermsg = '';
foreach($search as $s) {
$usermsg .= strexists($formula, $s) ? $replace[$i].' = '.(@eval('return intval('.$s.');')).' ' : '';
$i++;
}
$search = array_merge($search, array('and', 'or', '>=', '<='));
$replace = array_merge($replace, array(' '.$language['formulaperm_and'].' ', ' '.$language['formulaperm_or'].' ', '≥', '≤'));
$formulamessage = str_replace($search, $replace, $formula);
showmessage('forum_permforum_nopermission', NULL, 'NOPERM');
}
return TRUE;
}
function getgroupid($uid, $group, &$member) {
global $creditsformula, $db, $tablepre;
if(!empty($creditsformula)) {
$updatearray = array();
eval("\$credits = round($creditsformula);");
if($credits != $member['credits']) {
$updatearray[] = "credits='$credits'";
$member['credits'] = $credits;
}
if($group['type'] == 'member' && !($member['credits'] >= $group['creditshigher'] && $member['credits'] < $group['creditslower'])) {
$query = $db->query("SELECT groupid FROM {$tablepre}usergroups WHERE type='member' AND $member[credits]>=creditshigher AND $member[credits]<creditslower LIMIT 1");
if($db->num_rows($query)) {
$member['groupid'] = $db->result($query, 0);
$updatearray[] = "groupid='$member[groupid]'";
}
}
if($updatearray) {
$db->query("UPDATE {$tablepre}members SET ".implode(', ', $updatearray)." WHERE uid='$uid'");
}
}
return $member['groupid'];
}
function groupexpiry($terms) {
$terms = is_array($terms) ? $terms : unserialize($terms);
$groupexpiry = isset($terms['main']['time']) ? intval($terms['main']['time']) : 0;
if(is_array($terms['ext'])) {
foreach($terms['ext'] as $expiry) {
if((!$groupexpiry && $expiry) || $expiry < $groupexpiry) {
$groupexpiry = $expiry;
}
}
}
return $groupexpiry;
}
function ipaccess($ip, $accesslist) {
return preg_match("/^(".str_replace(array("\r\n", ' '), array('|', ''), preg_quote($accesslist, '/')).")/", $ip);
}
function ipbanned($onlineip) {
global $ipaccess, $timestamp, $cachelost;
if($ipaccess && !ipaccess($onlineip, $ipaccess)) {
return TRUE;
}
$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/cache_ipbanned.php') ? '' : ' ipbanned';
if(empty($_DCACHE['ipbanned'])) {
return FALSE;
} else {
if($_DCACHE['ipbanned']['expiration'] < $timestamp) {
@unlink(DISCUZ_ROOT.'./forumdata/cache/cache_ipbanned.php');
}
return preg_match("/^(".$_DCACHE['ipbanned']['regexp'].")$/", $onlineip);
}
}
function isemail($email) {
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
function language($file, $templateid = 0, $tpldir = '') {
$tpldir = $tpldir ? $tpldir : TPLDIR;
$templateid = $templateid ? $templateid : TEMPLATEID;
$languagepack = DISCUZ_ROOT.'./'.$tpldir.'/'.$file.'.lang.php';
if(file_exists($languagepack)) {
return $languagepack;
} elseif($templateid != 1 && $tpldir != './templates/default') {
return language($file, 1, './templates/default');
} else {
return FALSE;
}
}
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
global $maxpage;
$ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".dhtmlspecialchars($_GET['ajaxtarget'])."\" " : '';
$multipage = '';
$mpurl .= strpos($mpurl, '?') ? '&' : '?';
$realpages = 1;
if($num > $perpage) {
$offset = 2;
$realpages = @ceil($num / $perpage);
$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
if($page > $pages) {
$from = 1;
$to = $pages;
} else {
$from = $curpage - $offset;
$to = $from + $page - 1;
if($from < 1) {
$to = $curpage + 1 - $from;
$from = 1;
if($to - $from < $page) {
$to = $page;
}
} elseif($to > $pages) {
$from = $pages - $page + 1;
$to = $pages;
}
}
$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev"'.$ajaxtarget.'>‹‹</a>' : '');
for($i = $from; $i <= $to; $i++) {
$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
'<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>';
}
$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>››</a>' : '').
($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
(!$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" /></kbd>' : '');
$multipage = $multipage ? '<div class="pages">'.(!$simple ? '<em> '.$num.' </em>' : '').$multipage.'</div>' : '';
}
$maxpage = $realpages;
return $multipage;
}
function output() {
if(defined('DISCUZ_OUTPUTED')) {
return;
}
define('DISCUZ_OUTPUTED', 1);
global $sid, $transsidstatus, $rewritestatus, $ftp, $advlist, $insenz, $queryfloat, $thread, $inajax;
if(($advlist || !empty($insenz['hardadstatus']) || $queryfloat) && !defined('IN_ADMINCP') && !(CURSCRIPT == 'viewthread' && $thread['digest'] == '-1') && !$inajax) {
include template('adv');
}
if(($transsidstatus = empty($GLOBALS['_DCOOKIE']['sid']) && $transsidstatus) || $rewritestatus) {
if($transsidstatus) {
$searcharray = array
(
"/\<a(\s*[^\>]+\s*)href\=([\"|\']?)([^\"\'\s]+)/ies",
"/(\<form.+?\>)/is"
);
$replacearray = array
(
"transsid('\\3','<a\\1href=\\2')",
"\\1\n<input type=\"hidden\" name=\"sid\" value=\"$sid\" />"
);
} else {
$searcharray = $replacearray = array();
if($rewritestatus & 1) {
$searcharray[] = "/\<a href\=\"forumdisplay\.php\?fid\=(\d+)(&page\=(\d+))?\"([^\>]*)\>/e";
$replacearray[] = "rewrite_forum('\\1', '\\3', '\\4')";
}
if($rewritestatus & 2) {
$searcharray[] = "/\<a href\=\"viewthread\.php\?tid\=(\d+)(&extra\=page\%3D(\d+))?(&page\=(\d+))?\"([^\>]*)\>/e";
$replacearray[] = "rewrite_thread('\\1', '\\5', '\\3', '\\6')";
}
if($rewritestatus & 4) {
$searcharray[] = "/\<a href\=\"space\.php\?(uid\=(\d+)|username\=([^&]+?))\"([^\>]*)\>/e";
$replacearray[] = "rewrite_space('\\2', '\\3', '\\4')";
}
if($rewritestatus & 8) {
$searcharray[] = "/\<a href\=\"tag\.php\?name\=([^&]+?)\"([^\>]*)\>/e";
$replacearray[] = "rewrite_tag('\\1', '\\2')";
}
}
$content = preg_replace($searcharray, $replacearray, ob_get_contents());
ob_end_clean();
$GLOBALS['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
echo $content;
}
if($ftp['connid']) {
@ftp_close($ftp['connid']);
}
$ftp = array();
if(defined('CACHE_FILE') && CACHE_FILE && !defined('CACHE_FORBIDDEN')) {
global $cachethreaddir;
if(diskfreespace(DISCUZ_ROOT.'./'.$cachethreaddir) > 1000000) {
if($fp = @fopen(CACHE_FILE, 'w')) {
flock($fp, LOCK_EX);
fwrite($fp, empty($content) ? ob_get_contents() : $content);
}
@fclose($fp);
chmod(CACHE_FILE, 0777);
}
}
}
function rewrite_thread($tid, $page = 0, $prevpage = 0, $extra = '') {
return '<a href="thread-'.$tid.'-'.($page ? $page : 1).'-'.($prevpage && !IS_ROBOT ? $prevpage : 1).'.html"'.stripslashes($extra).'>';
}
function rewrite_forum($fid, $page = 0, $extra = '') {
return '<a href="forum-'.$fid.'-'.($page ? $page : 1).'.html"'.stripslashes($extra).'>';
}
function rewrite_space($uid, $username, $extra = '') {
$GLOBALS['rewritecompatible'] && $username = rawurlencode($username);
return '<a href="space-'.($uid ? 'uid-'.$uid : 'username-'.$username).'.html"'.stripslashes($extra).'>';
}
function rewrite_tag($name, $extra = '') {
$GLOBALS['rewritecompatible'] && $name = rawurlencode($name);
return '<a href="tag-'.$name.'.html"'.stripslashes($extra).'>';
}
function periodscheck($periods, $showmessage = 1) {
global $timestamp, $disableperiodctrl, $_DCACHE, $banperiods;
if(!$disableperiodctrl && $_DCACHE['settings'][$periods]) {
$now = gmdate('G.i', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600);
foreach(explode("\r\n", str_replace(':', '.', $_DCACHE['settings'][$periods])) as $period) {
list($periodbegin, $periodend) = explode('-', $period);
if(($periodbegin > $periodend && ($now >= $periodbegin || $now < $periodend)) || ($periodbegin < $periodend && $now >= $periodbegin && $now < $periodend)) {
$banperiods = str_replace("\r\n", ', ', $_DCACHE['settings'][$periods]);
if($showmessage) {
showmessage('period_nopermission', NULL, 'NOPERM');
} else {
return TRUE;
}
}
}
}
return FALSE;
}
function quescrypt($questionid, $answer) {
return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : '';
}
function random($length, $numeric = 0) {
PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
if($numeric) {
$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
} else {
$hash = '';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
function removedir($dirname, $keepdir = FALSE) {
$dirname = wipespecial($dirname);
if(!is_dir($dirname)) {
return FALSE;
}
$handle = opendir($dirname);
while(($file = readdir($handle)) !== FALSE) {
if($file != '.' && $file != '..') {
$dir = $dirname . DIRECTORY_SEPARATOR . $file;
is_dir($dir) ? removedir($dir) : unlink($dir);
}
}
closedir($handle);
return !$keepdir ? (@rmdir($dirname) ? TRUE : FALSE) : TRUE;
}
function sendmail($email_to, $email_subject, $email_message, $email_from = '') {
extract($GLOBALS, EXTR_SKIP);
require DISCUZ_ROOT.'./include/sendmail.inc.php';
}
function sendpm($toid, $subject, $message, $fromid = '', $from = '') {
extract($GLOBALS, EXTR_SKIP);
include language('pms');
if(isset($language[$subject])) {
eval("\$subject = addslashes(\"".$language[$subject]."\");");
}
if(isset($language[$message])) {
eval("\$message = addslashes(\"".$language[$message]."\");");
}
if(!$fromid && !$from) {
$fromid = $discuz_uid;
$from = $discuz_user;
}
$pmids = array();
foreach(explode(',', $toid) as $uid) {
if(is_numeric($uid)) {
$query = $db->query("INSERT INTO {$tablepre}pms (msgfrom, msgfromid, msgtoid, folder, new, subject, dateline, message)
VALUES ('$from', '$fromid', '$uid', 'inbox', '1', '$subject', '$timestamp', '$message')");
if($query) {
$pmids[] = $uid;
}
}
}
if($toid = implodeids($pmids)) {
$db->query("UPDATE {$tablepre}members SET newpm='1' WHERE uid IN ($toid)");
}
}
function showmessage($message, $url_forward = '', $extra = '') {
extract($GLOBALS, EXTR_SKIP);
global $extrahead, $discuz_action, $debuginfo, $seccode, $fid, $tid, $supe_fromsupesite, $supe_jumpurl, $supe, $charset, $show_message, $inajax, $_DCACHE, $advlist;
define('CACHE_FORBIDDEN', TRUE);
$supe_messagetpl = $supe_error = '';
$show_message = $message;
$msgforward = unserialize($_DCACHE['settings']['msgforward']);
$msgforward['refreshtime'] = intval($msgforward['refreshtime']);
$url_forward = empty($url_forward) ? '' : (empty($_DCOOKIE['sid']) && $transsidstatus ? transsid($url_forward) : $url_forward);
if($supe_fromsupesite && $supe['status']) {
$supe_messagetpl = 'supesite_';
$extra = '';
$supe_error = $url_forward ? false : true;
$url_forward = !empty($supe_jumpurl) && !$supe_error ? urldecode($supe_jumpurl) : $url_forward;
} elseif($url_forward && empty($inajax) && $msgforward['quick'] && $msgforward['messages'] && @in_array($message, $msgforward['messages'])) {
updatesession();
dheader("location: ".str_replace('&', '&', $url_forward));
}
if(in_array($extra, array('HALTED', 'NOPERM'))) {
$fid = $tid = 0;
$discuz_action = 254;
} else {
$discuz_action = 255;
}
include language('messages');
if(isset($language[$message])) {
$pre = $supe_fromsupesite ? 'supe_' : ($inajax ? 'ajax_' : '');
eval("\$show_message = \"".(isset($language[$pre.$message]) ? $language[$pre.$message] : $language[$message])."\";");
unset($pre);
}
$extrahead .= $url_forward ? '<meta http-equiv="refresh" content="'.$msgforward['refreshtime'].' url='.$url_forward.'">' : '';
if($advlist = array_merge($globaladvs ? $globaladvs['type'] : array(), $redirectadvs ? $redirectadvs['type'] : array())) {
$advitems = ($globaladvs ? $globaladvs['items'] : array()) + ($redirectadvs ? $redirectadvs['items'] : array());
foreach($advlist AS $type => $redirectadvs) {
$advlist[$type] = $advitems[$redirectadvs[array_rand($redirectadvs)]];
}
}
if($extra == 'NOPERM' && !$passport_status) {
//get secure code checking status (pos. -2)
if($seccodecheck = substr(sprintf('%05b', $seccodestatus), -2, 1)) {
$seccode = random(6, 1) + $seccode{0} * 1000000;
}
include template('nopermission');
} else {
include template($supe_messagetpl.'showmessage');
}
dexit();
}
function showstars($num) {
global $starthreshold;
$alt = 'alt="Rank: '.$num.'"';
if(empty($starthreshold)) {
for($i = 0; $i < $num; $i++) {
echo '<img src="'.IMGDIR.'/star_level1.gif" '.$alt.' />';
}
} else {
for($i = 3; $i > 0; $i--) {
$numlevel = intval($num / pow($starthreshold, ($i - 1)));
$num = ($num % pow($starthreshold, ($i - 1)));
for($j = 0; $j < $numlevel; $j++) {
echo '<img src="'.IMGDIR.'/star_level'.$i.'.gif" '.$alt.' />';
}
}
}
}
function site() {
return $_SERVER['HTTP_HOST'];
}
function strexists($haystack, $needle) {
return !(strpos($haystack, $needle) === FALSE);
}
function seccodeconvert(&$seccode) {
global $seccodedata, $charset;
$seccode = substr($seccode, -6);
if($seccodedata['type'] == 1) {
include_once language('seccode');
$len = strtoupper($charset) == 'GBK' ? 2 : 3;
$code = array(substr($seccode, 0, 3), substr($seccode, 3, 3));
$seccode = '';
for($i = 0; $i < 2; $i++) {
$seccode .= substr($lang['chn'], $code[$i] * $len, $len);
}
} else {
$s = sprintf('%04s', base_convert($seccode, 10, 24));
$seccode = '';
$seccodeunits = 'BCEFGHJKMPQRTVWXY2346789';
for($i = 0; $i < 4; $i++) {
$unit = ord($s{$i});
$seccode .= ($unit >= 0x30 && $unit <= 0x39) ? $seccodeunits[$unit - 0x30] : $seccodeunits[$unit - 0x57];
}
}
}
function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0) {
if(empty($GLOBALS[$var])) {
return FALSE;
} else {
global $_SERVER, $seccode, $seccodeverify, $secanswer, $_DCACHE;
if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && $GLOBALS['formhash'] == formhash() && (empty($_SERVER['HTTP_REFERER']) ||
preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
if($seccodecheck) {
$tmp = $seccode{0};
seccodeconvert($seccode);
if(strtoupper($seccodeverify) != $seccode) {
showmessage('submit_seccode_invalid');
}
$seccode = random(6, 1) + $tmp * 1000000;
}
if($secqaacheck) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
if(md5($secanswer) != $_DCACHE['secqaa'][substr($seccode, 0, 1)]['answer']) {
showmessage('submit_secqaa_invalid');
}
$seccode = random(1, 1) * 1000000 + substr($seccode, -6);
}
return TRUE;
} else {
showmessage('submit_invalid');
}
}
}
function supe_submitcheck($allowget = 0, $timespan = 300) {
global $supe_seccode, $timestamp, $_DCOOKIE, $supe, $supe_fromsupesite;
$supe_hash = isset($_GET['supe_hash']) || isset($_POST['supe_hash']) ?
(isset($_GET['supe_hash']) ? $_GET['supe_hash'] : $_POST['supe_hash']) :
(isset($_DCOOKIE['supe_hash']) ? $_DCOOKIE['supe_hash'] : '');
if($supe_fromsupesite && $supe['status'] && ($allowget || $_SERVER['REQUEST_METHOD'] == 'POST') && $supe_hash && !empty($supe_seccode)) {
list($check_timestamp, $check_seccode) = explode("\t", authcode($supe_hash, 'DECODE'));
if($timestamp - $check_timestamp <= $timespan && $check_seccode == $supe_seccode) {
return TRUE;
}
showmessage('submit_invalid');
}
return FALSE;
}
function template($file, $templateid = 0, $tpldir = '') {
global $tplrefresh, $inajax;
$file .= $inajax && ($file == 'header' || $file == 'footer') ? '_ajax' : '';
$tpldir = $tpldir ? $tpldir : TPLDIR;
$templateid = $templateid ? $templateid : TEMPLATEID;
$tplfile = DISCUZ_ROOT.'./'.$tpldir.'/'.$file.'.htm';
$objfile = DISCUZ_ROOT.'./forumdata/templates/'.$templateid.'_'.$file.'.tpl.php';
if(TEMPLATEID != 1 && $templateid != 1 && !file_exists($tplfile)) {
return template($file, 1, './templates/default/');
}
if($tplrefresh == 1 || ($tplrefresh > 1 && substr($GLOBALS['timestamp'], -1) > $tplrefresh)) {
if(@filemtime($tplfile) > @filemtime($objfile)) {
require_once DISCUZ_ROOT.'./include/template.func.php';
parse_template($file, $templateid, $tpldir);
}
}
return $objfile;
}
function transsid($url, $tag = '', $wml = 0) {
global $sid;
$tag = stripslashes($tag);
if(!$tag || (!preg_match("/^(http:\/\/|mailto:|#|javascript)/i", $url) && !strpos($url, 'sid='))) {
if($pos = strpos($url, '#')) {
$urlret = substr($url, $pos);
$url = substr($url, 0, $pos);
} else {
$urlret = '';
}
$url .= (strpos($url, '?') ? ($wml ? '&' : '&') : '?').'sid='.$sid.$urlret;
}
return $tag.$url;
}
function typeselect($curtypeid = 0, $special = '', $onchange = '', $modelid = 0) {
global $fid, $sid, $extra;
$onchange = $onchange ? $onchange : "onchange=\"ajaxget('post.php?action=threadtypes&typeid='+this.options[this.selectedIndex].value+'&fid=$fid&sid=$sid', 'threadtypes', 'threadtypeswait')\"";
if($threadtypes = $GLOBALS['forum']['threadtypes']) {
$html = '<select name="typeid" '.(!$special ? $onchange : '').'><option value="0"> </option>';
foreach($threadtypes['types'] as $typeid => $name) {
if(!$special || $special == 'disabled' || !$threadtypes['special'][$typeid]) {
$typehtml = '<option value="'.$typeid.'" '.($curtypeid == $typeid ? 'selected="selected"' : '').' '.($threadtypes['special'][$typeid] ? 'class="special"' : '').'>'.strip_tags($name).'</option>';
$html .= $modelid ? ($threadtypes['modelid'][$typeid] == $modelid ? $typehtml : '') : $typehtml;
}
}
$html .= '</select><span id="threadtypeswait"></span>'.($special === 'disabled' ? '<input type="hidden" name="typeid" value="'.$curtypeid.'" />' : '');
return $html;
} else {
return '';
}
}
function updatecredits($uids, $creditsarray, $coef = 1, $extrasql = '') {
if($uids && ((!empty($creditsarray) && is_array($creditsarray)) || $extrasql)) {
global $db, $tablepre;
$creditsadd = $comma = '';
foreach($creditsarray as $id => $addcredits) {
$creditsadd .= $comma.'extcredits'.$id.'=extcredits'.$id.'+('.intval($addcredits).')*('.$coef.')';
$comma = ', ';
}
if($creditsadd || $extrasql) {
$db->query("UPDATE {$tablepre}members SET $creditsadd ".($creditsadd && $extrasql ? ', ' : '')." $extrasql WHERE uid IN ('$uids')", 'UNBUFFERED');
}
}
}
function updatesession() {
if(!empty($GLOBALS['sessionupdated'])) {
return TRUE;
}
global $db, $tablepre, $sessionexists, $sessionupdated, $sid, $onlineip, $discuz_uid, $discuz_user, $timestamp, $lastactivity, $seccode,
$pvfrequence, $spageviews, $lastolupdate, $oltimespan, $onlinehold, $groupid, $styleid, $invisible, $discuz_action, $fid, $tid, $bloguid;
$fid = intval($fid);
$tid = intval($tid);
if($oltimespan && $discuz_uid && $lastactivity && $timestamp - ($lastolupdate ? $lastolupdate : $lastactivity) > $oltimespan * 60) {
$lastolupdate = $timestamp;
$db->query("UPDATE {$tablepre}onlinetime SET total=total+'$oltimespan', thismonth=thismonth+'$oltimespan', lastupdate='$timestamp' WHERE uid='$discuz_uid' AND lastupdate<='".($timestamp - $oltimespan * 60)."'");
if(!$db->affected_rows()) {
$db->query("INSERT INTO {$tablepre}onlinetime (uid, thismonth, total, lastupdate)
VALUES ('$discuz_uid', '$oltimespan', '$oltimespan', '$timestamp')", 'SILENT');
}
} else {
$lastolupdate = intval($lastolupdate);
}
if($sessionexists == 1) {
if($pvfrequence && $discuz_uid) {
if($spageviews >= $pvfrequence) {
$pageviewsadd = ', pageviews=\'0\'';
$db->query("UPDATE {$tablepre}members SET pageviews=pageviews+'$spageviews' WHERE uid='$discuz_uid'", 'UNBUFFERED');
} else {
$pageviewsadd = ', pageviews=pageviews+1';
}
} else {
$pageviewsadd = '';
}
$db->query("UPDATE {$tablepre}sessions SET uid='$discuz_uid', username='$discuz_user', groupid='$groupid', styleid='$styleid', invisible='$invisible', action='$discuz_action', lastactivity='$timestamp', lastolupdate='$lastolupdate', seccode='$seccode', fid='$fid', tid='$tid', bloguid='$bloguid' $pageviewsadd WHERE sid='$sid'");
} else {
$ips = explode('.', $onlineip);
$db->query("DELETE FROM {$tablepre}sessions WHERE sid='$sid' OR lastactivity<($timestamp-$onlinehold) OR ('$discuz_uid'<>'0' AND uid='$discuz_uid') OR (uid='0' AND ip1='$ips[0]' AND ip2='$ips[1]' AND ip3='$ips[2]' AND ip4='$ips[3]' AND lastactivity>$timestamp-60)");
$db->query("INSERT INTO {$tablepre}sessions (sid, ip1, ip2, ip3, ip4, uid, username, groupid, styleid, invisible, action, lastactivity, lastolupdate, seccode, fid, tid, bloguid)
VALUES ('$sid', '$ips[0]', '$ips[1]', '$ips[2]', '$ips[3]', '$discuz_uid', '$discuz_user', '$groupid', '$styleid', '$invisible', '$discuz_action', '$timestamp', '$lastolupdate', '$seccode', '$fid', '$tid', '$bloguid')", 'SILENT');
if($discuz_uid && $timestamp - $lastactivity > 21600) {
if($oltimespan && $timestamp - $lastactivity > 86400) {
$query = $db->query("SELECT total FROM {$tablepre}onlinetime WHERE uid='$discuz_uid'");
$oltimeadd = ', oltime='.round(intval($db->result($query, 0)) / 60);
} else {
$oltimeadd = '';
}
$db->query("UPDATE {$tablepre}members SET lastip='$onlineip', lastvisit=lastactivity, lastactivity='$timestamp' $oltimeadd WHERE uid='$discuz_uid'", 'UNBUFFERED');
}
}
$sessionupdated = 1;
}
function updatemodworks($modaction, $posts = 1) {
global $modworkstatus, $db, $tablepre, $discuz_uid, $timestamp, $_DCACHE;
$today = gmdate('Y-m-d', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600);
if($modworkstatus && $modaction && $posts) {
$db->query("UPDATE {$tablepre}modworks SET count=count+1, posts=posts+'$posts' WHERE uid='$discuz_uid' AND modaction='$modaction' AND dateline='$today'");
if(!$db->affected_rows()) {
$db->query("INSERT INTO {$tablepre}modworks (uid, modaction, dateline, count, posts) VALUES ('$discuz_uid', '$modaction', '$today', 1, '$posts')");
}
}
}
function writelog($file, $log) {
global $timestamp, $_DCACHE;
$yearmonth = gmdate('Ym', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600);
$logdir = DISCUZ_ROOT.'./forumdata/logs/';
$logfile = $logdir.$yearmonth.'_'.$file.'.php';
if(@filesize($logfile) > 2048000) {
$dir = opendir($logdir);
$length = strlen($file);
$maxid = $id = 0;
while($entry = readdir($dir)) {
if(strexists($entry, $yearmonth.'_'.$file)) {
$id = intval(substr($entry, $length + 8, -4));
$id > $maxid && $maxid = $id;
}
}
closedir($dir);
$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
@rename($logfile, $logfilebak);
}
if($fp = @fopen($logfile, 'a')) {
@flock($fp, 2);
$log = is_array($log) ? $log : array($log);
foreach($log as $tmp) {
fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
}
fclose($fp);
}
}
function implodeids($array) {
if(!empty($array)) {
return "'".implode("','", is_array($array) ? $array : array($array))."'";
} else {
return '';
}
}
function wipespecial($str) {
return str_replace(array('..', "\n", "\r"), array('', '', ''), $str);
}
function supe_dbconnect() {
global $supe, $db;
if(!$supe['status']) {
return FALSE;
} elseif(empty($supe['dbmode'])) {
$supe['db'] = $db;
} elseif(empty($supe['db'])) {
$supe['db'] = new dbstuff;
$supe['link'] = $supe['db']->connect($supe['dbhost'], $supe['dbuser'], $supe['dbpw'], $supe['dbname'], $supe['pconnect'], FALSE);
$supe['status'] = $supe['link'] ? $supe['link'] : FALSE;
}
}
function checkmd5($md5, $verified, $salt = '') {
if(md5($md5.$salt) == $verified) {
$result = !empty($salt) ? 1 : 2;
} elseif(empty($salt)) {
$result = $md5 == $verified ? 3 : ((strlen($verified) == 16 && substr($md5, 8, 16) == $verified) ? 4 : 0);
} else {
$result = 0;
}
return $result;
}
function dfopen($url, $limit = 500000, $post = '', $cookie = '', $bysocket = FALSE) {
global $version, $boardurl;
if(ini_get('allow_url_fopen') && !$bysocket && !$post) {
$fp = @fopen($url, 'r');
$s = @fread($fp, $limit);
@fclose($fp);
return $s;
}
$return = '';
$matches = parse_url($url);
$host = $matches['host'];
$script = $matches['path'].'?'.$matches['query'].'#'.$matches['fragment'];
$port = !empty($matches['port']) ? $matches['port'] : 80;
if($post) {
$out = "POST $script HTTP/1.1\r\n";
$out .= "Accept: */*\r\n";
$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Accept-Encoding: none\r\n";
$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
$out .= "Host: $host\r\n";
$out .= 'Content-Length: '.strlen($post)."\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cache-Control: no-cache\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
$out .= $post;
} else {
$out = "GET $script HTTP/1.1\r\n";
$out .= "Accept: */*\r\n";
$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "Accept-Encoding:\r\n";
$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
}
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if(!$fp) {
return "";
} else {
@fwrite($fp, $out);
while(!feof($fp) && $limit > -1) {
$limit -= 524;
$return .= @fread($fp, 524);
}
@fclose($fp);
$return = preg_replace("/\r\n\r\n/", "\n\n", $return, 1);
$strpos = strpos($return, "\n\n");
$strpos = $strpos !== FALSE ? $strpos + 2 : 0;
$return = substr($return, $strpos);
return $return;
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/global.func.php | PHP | asf20 | 36,905 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: ftp.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function dftp_connect($ftphost, $ftpuser, $ftppass, $ftppath, $ftpport = 21, $ftpssl = 0, $silent = 0) {
global $ftp;
@set_time_limit(0);
$ftphost = wipespecial($ftphost);
$ftpport = intval($ftpport);
$ftpssl = intval($ftpssl);
$ftp['timeout'] = intval($ftp['timeout']);
$func = $ftpssl && function_exists('ftp_ssl_connect') ? 'ftp_ssl_connect' : 'ftp_connect';
if($func == 'ftp_connect' && !function_exists('ftp_connect')) {
if($silent) {
return -4;
} else {
errorlog('FTP', "FTP not supported.", 0);
}
}
if($ftp_conn_id = @$func($ftphost, $ftpport, 20)) {
if($ftp['timeout'] && function_exists('ftp_set_option')) {
@ftp_set_option($ftp_conn_id, FTP_TIMEOUT_SEC, $ftp['timeout']);
}
if(dftp_login($ftp_conn_id, $ftpuser, $ftppass)) {
if($ftp['pasv']) {
dftp_pasv($ftp_conn_id, TRUE);
}
if(dftp_chdir($ftp_conn_id, $ftppath)) {
return $ftp_conn_id;
} else {
if($silent) {
return -3;
} else {
errorlog('FTP', "Chdir '$ftppath' error.", 0);
}
}
} else {
if($silent) {
return -2;
} else {
errorlog('FTP', '530 Not logged in.', 0);
}
}
} else {
if($silent) {
return -1;
} else {
errorlog('FTP', "Couldn't connect to $ftphost:$ftpport.", 0);
}
}
dftp_close($ftp_conn_id);
return -1;
}
function dftp_mkdir($ftp_stream, $directory) {
$directory = wipespecial($directory);
return @ftp_mkdir($ftp_stream, $directory);
}
function dftp_rmdir($ftp_stream, $directory) {
$directory = wipespecial($directory);
return @ftp_rmdir($ftp_stream, $directory);
}
function dftp_put($ftp_stream, $remote_file, $local_file, $mode, $startpos = 0 ) {
$remote_file = wipespecial($remote_file);
$local_file = wipespecial($local_file);
$mode = intval($mode);
$startpos = intval($startpos);
return @ftp_put($ftp_stream, $remote_file, $local_file, $mode, $startpos);
}
function dftp_size($ftp_stream, $remote_file) {
$remote_file = wipespecial($remote_file);
return @ftp_size($ftp_stream, $remote_file);
}
function dftp_close($ftp_stream) {
return @ftp_close($ftp_stream);
}
function dftp_delete($ftp_stream, $path) {
$path = wipespecial($path);
return @ftp_delete($ftp_stream, $path);
}
function dftp_get($ftp_stream, $local_file, $remote_file, $mode, $resumepos = 0) {
$remote_file = wipespecial($remote_file);
$local_file = wipespecial($local_file);
$mode = intval($mode);
$resumepos = intval($resumepos);
return @ftp_get($ftp_stream, $local_file, $remote_file, $mode, $resumepos);
}
function dftp_login($ftp_stream, $username, $password) {
$username = wipespecial($username);
$password = str_replace(array("\n", "\r"), array('', ''), $password);
return @ftp_login($ftp_stream, $username, $password);
}
function dftp_pasv($ftp_stream, $pasv) {
$pasv = intval($pasv);
return @ftp_pasv($ftp_stream, $pasv);
}
function dftp_chdir($ftp_stream, $directory) {
$directory = wipespecial($directory);
return @ftp_chdir($ftp_stream, $directory);
}
function dftp_site($ftp_stream, $cmd) {
$cmd = wipespecial($cmd);
return @ftp_site($ftp_stream, $cmd);
}
function dftp_chmod($ftp_stream, $mode, $filename) {
$mode = intval($mode);
$filename = wipespecial($filename);
if(function_exists('ftp_chmod')) {
return @ftp_chmod($ftp_stream, $mode, $filename);
} else {
return dftp_site($ftp_stream, 'CHMOD '.$mode.' '.$filename);
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/ftp.func.php | PHP | asf20 | 3,711 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: discuzcode.func.php 10561 2007-09-05 08:24:49Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
include template('discuzcode');
$discuzcodes = array(
'pcodecount' => -1,
'codecount' => 0,
'codehtml' => '',
'searcharray' => array(),
'replacearray' => array(),
'seoarray' => array(
0 => '',
1 => $_SERVER['HTTP_HOST'],
2 => $bbname,
3 => $seotitle,
4 => $seokeywords,
5 => $seodescription
)
);
if(!isset($_DCACHE['bbcodes']) || !is_array($_DCACHE['bbcodes']) || !is_array($_DCACHE['smilies'])) {
@include DISCUZ_ROOT.'./forumdata/cache/cache_bbcodes.php';
}
foreach($_DCACHE['smilies']['replacearray'] AS $key => $smiley) {
$_DCACHE['smilies']['replacearray'][$key] = '<img src="images/smilies/'.$_DCACHE['smileytypes'][$_DCACHE['smilies']['typearray'][$key]]['directory'].'/'.$smiley.'" smilieid="'.$key.'" border="0" alt="" />';
}
mt_srand((double)microtime() * 1000000);
function attachtag($pid, $aid, &$postlist) {
global $attachrefcheck, $thumbstatus, $extcredits, $creditstrans, $ftp, $exthtml;
$attach = $postlist[$pid]['attachments'][$aid];
if($attach['attachimg']) {
$attachrefcheck = ($attachrefcheck || $attach['remote']) && !($attach['remote'] && substr($ftp['attachurl'], 0, 3) == 'ftp' && !$ftp['hideurl']);
}
return attachinpost($attach);
}
function censor($message) {
global $_DCACHE;
require_once(DISCUZ_ROOT.'/forumdata/cache/cache_censor.php');
if($_DCACHE['censor']['banned'] && preg_match($_DCACHE['censor']['banned'], $message)) {
showmessage('word_banned');
} else {
return empty($_DCACHE['censor']['filter']) ? $message :
@preg_replace($_DCACHE['censor']['filter']['find'], $_DCACHE['censor']['filter']['replace'], $message);
}
}
function censormod($message) {
global $_DCACHE;
require_once(DISCUZ_ROOT.'/forumdata/cache/cache_censor.php');
return $_DCACHE['censor']['mod'] && preg_match($_DCACHE['censor']['mod'], $message);
}
function creditshide($creditsrequire, $message, $pid) {
global $hideattach;
if($GLOBALS['credits'] < $creditsrequire && !$GLOBALS['forum']['ismoderator']) {
$hideattach[$pid] = 1;
return tpl_hide_credits_hidden($creditsrequire);
} else {
$hideattach[$pid] = 0;
return tpl_hide_credits($creditsrequire, str_replace('\\"', '"', $message));
}
}
function codedisp($code) {
global $discuzcodes;
$discuzcodes['pcodecount']++;
$code = htmlspecialchars(str_replace('\\"', '"', preg_replace("/^[\n\r]*(.+?)[\n\r]*$/is", "\\1", $code)));
$discuzcodes['codehtml'][$discuzcodes['pcodecount']] = tpl_codedisp($discuzcodes, $code);
$discuzcodes['codecount']++;
return "[\tDISCUZ_CODE_$discuzcodes[pcodecount]\t]";
}
function karmaimg($rate, $ratetimes) {
$karmaimg = '';
if($rate && $ratetimes) {
$image = $rate > 0 ? 'agree.gif' : 'disagree.gif';
for($i = 0; $i < ceil(abs($rate) / $ratetimes); $i++) {
$karmaimg .= '<img src="'.IMGDIR.'/'.$image.'" border="0" alt="" />';
}
}
return $karmaimg;
}
function parsetable($width, $bgcolor, $message) {
if(!preg_match("/^\[tr(?:=([\(\)%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/", $message) && !preg_match("/^<tr[^>]*?>\s*<td[^>]*?>/", $message)) {
return str_replace('\\"', '"', preg_replace("/\[tr(?:=([\(\)%,#\w]+))?\]|\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]|\[\/td\]|\[\/tr\]/", '', $message));
}
$width = substr($width, -1) == '%' ? (substr($width, 0, -1) <= 98 ? intval($width).'%' : '98%') : ($width <= 560 ? intval($width).'px' : '98%');
return '<table cellspacing="0" class="t_table" '.
($width == '' ? NULL : 'style="width:'.$width.'"').
($bgcolor ? ' bgcolor="'.$bgcolor.'">' : '>').
str_replace('\\"', '"', preg_replace(array(
"/\[tr(?:=([\(\)%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",
"/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",
"/\[\/td\]\s*\[\/tr\]/i"
), array(
"parsetrtd('\\1', '\\2', '\\3', '\\4')",
"parsetrtd('td', '\\1', '\\2', '\\3')",
'</td></tr>'
), $message)
).'</table>';
}
function parsetrtd($bgcolor, $colspan, $rowspan, $width) {
return ($bgcolor == 'td' ? '</td>' : '<tr'.($bgcolor ? ' bgcolor="'.$bgcolor.'"' : '').'>').'<td'.($colspan > 1 ? ' colspan="'.$colspan.'"' : '').($rowspan > 1 ? ' rowspan="'.$rowspan.'"' : '').($width ? ' width="'.$width.'"' : '').'>';
}
function parsemedia($type, $width, $height, $autostart, $url) {
if(in_array($type, array('ra', 'rm', 'wma', 'wmv', 'mp3', 'mov'))) {
$url = str_replace(array('<', '>'), '', str_replace('\\"', '\"', $url));
$mediaid = 'media_'.random(3);
switch($type) {
case 'ra' : return '<object classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA" width="'.$width.'" height="32"><param name="autostart" value="'.$autostart.'" /><param name="src" value="'.$url.'" /><param name="controls" value="controlpanel" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="ControlPanel" '.($autostart ? 'autostart="true"' : '').' console="'.$mediaid.'_" width="'.$width.'" height="32"></embed></object>';break;
case 'rm' : return '<object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.$autostart.'" /><param name="src" value="'.$url.'" /><param name="controls" value="imagewindow" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="IMAGEWINDOW" console="'.$mediaid.'_" width="'.$width.'" height="'.$height.'"></embed></object><br /><object classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA" width="'.$width.'" height="32"><param name="src" value="'.$url.'" /><param name="controls" value="controlpanel" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="ControlPanel" '.($autostart ? 'autostart="true"' : '').' console="'.$mediaid.'_" width="'.$width.'" height="32"></embed></object>';break;
case 'wma' : return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="64"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="audio/x-ms-wma" width="'.$width.'" height="64"></embed></object>';break;
case 'wmv' : return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="video/x-ms-wmv" width="'.$width.'" height="'.$height.'"></embed></object>';break;
case 'mp3' : return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="64"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="application/x-mplayer2" width="'.$width.'" height="64"></embed></object>';break;
case 'mov' : return '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.($autostart ? 'true' : 'false').'" /><param name="src" value="'.$url.'" /><embed controller="true" width="'.$width.'" height="'.$height.'" src="'.$url.'" autostart="'.($autostart ? 'true' : 'false').'"></embed></object>';break;
}
}
return;
}
function discuzcode($message, $smileyoff, $bbcodeoff, $htmlon = 0, $allowsmilies = 1, $allowbbcode = 1, $allowimgcode = 1, $allowhtml = 0, $jammer = 0, $parsetype = '0', $authorid = '0', $allowmediacode = '0', $pid = 0) {
global $discuzcodes, $credits, $tid, $discuz_uid, $highlight, $maxsmilies, $db, $tablepre, $hideattach;
if($parsetype != 1 && !$bbcodeoff && $allowbbcode) {
$message = preg_replace("/\s*\[code\](.+?)\[\/code\]\s*/ies", "codedisp('\\1')", $message);
}
if(!$htmlon && !$allowhtml) {
$message = $jammer ? preg_replace("/\r\n|\n|\r/e", "jammer()", dhtmlspecialchars($message)) : dhtmlspecialchars($message);
}
if(!$smileyoff && $allowsmilies && !empty($GLOBALS['_DCACHE']['smilies']) && is_array($GLOBALS['_DCACHE']['smilies'])) {
$message = preg_replace($GLOBALS['_DCACHE']['smilies']['searcharray'], $GLOBALS['_DCACHE']['smilies']['replacearray'], $message, $maxsmilies);
}
if(!$bbcodeoff && $allowbbcode) {
if(empty($discuzcodes['searcharray'])) {
$discuzcodes['searcharray']['bbcode_regexp'] = array(
"/\[url\]\s*(www.|https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|bctp:\/\/|ed2k:\/\/|thunder:\/\/|synacast:\/\/){1}([^\[\"']+?)\s*\[\/url\]/ie",
"/\[url=www.([^\[\"']+?)\](.+?)\[\/url\]/is",
"/\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/([^\[\"']+?)\](.+?)\[\/url\]/is",
"/\[email\]\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*\[\/email\]/i",
"/\[email=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\](.+?)\[\/email\]/is",
"/\[color=([#\w]+?)\]/i",
"/\[size=(\d+?)\]/i",
"/\[size=(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%)+?)\]/i",
"/\[font=([^\[\<]+?)\]/i",
"/\[align=(left|center|right)\]/i",
"/\[float=(left|right)\]/i"
);
$discuzcodes['replacearray']['bbcode_regexp'] = array(
"cuturl('\\1\\2')",
"<a href=\"http://www.\\1\" target=\"_blank\">\\2</a>",
"<a href=\"\\1://\\2\" target=\"_blank\">\\3</a>",
"<a href=\"mailto:\\1@\\2\">\\1@\\2</a>",
"<a href=\"mailto:\\1@\\2\">\\3</a>",
"<font color=\"\\1\">",
"<font size=\"\\1\">",
"<font style=\"font-size: \\1\">",
"<font face=\"\\1 \">",
"<p align=\"\\1\">",
"<span style=\"float: \\1;\">"
);
$discuzcodes['searcharray']['bbcode_regexp'][] = "/\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*(.+?)\s*\[\/table\]/ies";
$discuzcodes['replacearray']['bbcode_regexp'][] = "parsetable('\\1', '\\2', '\\3')";
$discuzcodes['searcharray']['bbcode_regexp'][] = "/\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*(.+?)\s*\[\/table\]/ies";
$discuzcodes['replacearray']['bbcode_regexp'][] = "parsetable('\\1', '\\2', '\\3')";
if($parsetype != 1) {
$discuzcodes['searcharray']['bbcode_regexp'][] = "/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is";
$discuzcodes['searcharray']['bbcode_regexp'][] = "/\s*\[free\][\n\r]*(.+?)[\n\r]*\[\/free\]\s*/is";
$discuzcodes['replacearray']['bbcode_regexp'][] = tpl_quote();
$discuzcodes['replacearray']['bbcode_regexp'][] = tpl_free();
}
$discuzcodes['searcharray']['bbcode_regexp'] = array_merge($discuzcodes['searcharray']['bbcode_regexp'], $discuzcodes['searcharray']['bbcode_regexp']);
$discuzcodes['replacearray']['bbcode_regexp'] = array_merge($discuzcodes['replacearray']['bbcode_regexp'], $discuzcodes['replacearray']['bbcode_regexp']);
$discuzcodes['searcharray']['bbcode_str'] = array(
'[/color]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]',
'[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
'[list=A]', '[*]', '[/list]', '[indent]', '[/indent]', '[/float]'
);
$discuzcodes['replacearray']['bbcode_str'] = array(
'</font>', '</font>', '</font>', '</p>', '<strong>', '</strong>', '<i>',
'</i>', '<u>', '</u>', '<ul>', '<ul type="1">', '<ul type="a">',
'<ul type="A">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
);
}
$discuzcodes['searcharray']['bbcode_regexp'][] = "/\[media=(\w{1,4}),(\d{1,4}),(\d{1,4}),(\d)\]\s*([^\[\<\r\n]+?)\s*\[\/media\]/ies";
if($allowmediacode) {
$discuzcodes['replacearray']['bbcode_regexp'][] = "parsemedia('\\1', \\2, \\3, \\4, '\\5')";
} else {
$discuzcodes['replacearray']['bbcode_regexp'][] = "bbcodeurl('\\5', '<a href=\"%s\" target=\"_blank\">%s</a>')";
}
@$message = str_replace($discuzcodes['searcharray']['bbcode_str'], $discuzcodes['replacearray']['bbcode_str'],
preg_replace(
($parsetype != 1 && $allowbbcode == 2 && $GLOBALS['_DCACHE']['bbcodes'] ? array_merge($discuzcodes['searcharray']['bbcode_regexp'], $GLOBALS['_DCACHE']['bbcodes']['searcharray']) : $discuzcodes['searcharray']['bbcode_regexp']),
($parsetype != 1 && $allowbbcode == 2 && $GLOBALS['_DCACHE']['bbcodes'] ? array_merge($discuzcodes['replacearray']['bbcode_regexp'], $GLOBALS['_DCACHE']['bbcodes']['replacearray']) : $discuzcodes['replacearray']['bbcode_regexp']),
$message));
if($parsetype != 1 && preg_match("/\[hide=?\d*\].+?\[\/hide\]/is", $message)) {
if(stristr($message, '[hide]')) {
$query = $db->query("SELECT pid FROM {$tablepre}posts WHERE tid='$tid' AND ".($discuz_uid ? "authorid='$discuz_uid'" : "authorid=0 AND useip='$GLOBALS[onlineip]'")." LIMIT 1");
if($GLOBALS['forum']['ismoderator'] || $apid = $db->result($query, 0)) {
$message = preg_replace("/\[hide\]\s*(.+?)\s*\[\/hide\]/is", tpl_hide_reply(), $message);
$hideattach[$apid] = 0;
} else {
$message = preg_replace("/\[hide\](.+?)\[\/hide\]/is", tpl_hide_reply_hidden(), $message);
$hideattach[$pid] = 1;
}
}
$message = preg_replace("/\[hide=(\d+)\]\s*(.+?)\s*\[\/hide\]/ies", "creditshide(\\1,'\\2', $pid)", $message);
}
}
if(!$bbcodeoff) {
$message = preg_replace(array(
($parsetype != 1 ? "/\[swf\]\s*([^\[\<\r\n]+?)\s*\[\/swf\]/ies" : "//"),
"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",
"/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies"
), $allowimgcode ? array(
($parsetype != 1 ? "bbcodeurl('\\1', ' <img src=\"images/attachicons/flash.gif\" align=\"absmiddle\" alt=\"\" /> <a href=\"%s\" target=\"_blank\">Flash: %s</a> ')" : ""),
"bbcodeurl('\\1', '<img src=\"%s\" border=\"0\" onclick=\"zoom(this)\" onload=\"attachimg(this, \'load\')\" alt=\"\" />')",
"bbcodeurl('\\3', '<img width=\"\\1\" height=\"\\2\" src=\"%s\" border=\"0\" alt=\"\" />')"
) : array(
($parsetype != 1 ? "bbcodeurl('\\1', ' <img src=\"images/attachicons/flash.gif\" align=\"absmiddle\" alt=\"\" /> <a href=\"%s\" target=\"_blank\">Flash: %s</a> ')" : ""),
"bbcodeurl('\\1', '<a href=\"%s\" target=\"_blank\">%s</a>')",
"bbcodeurl('\\3', '<a href=\"%s\" target=\"_blank\">%s</a>')"
), $message);
}
for($i = 0; $i <= $discuzcodes['pcodecount']; $i++) {
$message = str_replace("[\tDISCUZ_CODE_$i\t]", $discuzcodes['codehtml'][$i], $message);
}
if($highlight) {
$highlightarray = explode('+', $highlight);
$message = preg_replace('#(^|>)([^<]+)(?=<|$)#sUe', "highlight('\\2', \$highlightarray, '\\1', 0)", $message);
}
return $htmlon || $allowhtml ? $message : nl2br(str_replace(array("\t", ' ', ' '), array(' ', ' ', ' '), $message));
}
if($videoopen) {
function videocode($message, $tid, $pid) {
global $vsiteid, $vsiteurl, $boardurl;
$vsiteurl = urlencode($vsiteurl);
$playurl = "http://union.bokecc.com/flash/discuz2/player.swf?siteid=$vsiteid&vid=\\2&tid=$tid&pid=$pid&autoStart=\\1&referer=".urlencode($boardurl."redirect.php?goto=findpost&pid=$pid&ptid=$tid");
$flashplayer = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="object_flash_player" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" height="373" width="438">';
$flashplayer .= '<param name="movie" value="'.$playurl.'">';
$flashplayer .= '<param name="quality" value="high">';
$flashplayer .= '<param name="allowScriptAccess" value="always">';
$flashplayer .= '<param name="allowFullScreen" value="true">';
$flashplayer .= '<embed src="'.$playurl.'" allowScriptAccess="always" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowfullscreen="true" height="373" width="438">';
$flashplayer .= '</object>';
return preg_replace("/\[video=(\d)\](\w+)\[\/video\]/", "$flashplayer", $message);
}
}
function cuturl($url) {
$length = 65;
$urllink = "<a href=\"".(substr(strtolower($url), 0, 4) == 'www.' ? "http://$url" : $url).'" target="_blank">';
if(strlen($url) > $length) {
$url = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
}
$urllink .= $url.'</a>';
return $urllink;
}
function bbcodeurl($url, $tags) {
if(!preg_match("/<.+?>/s", $url)) {
if(!in_array(strtolower(substr($url, 0, 6)), array('http:/', 'https:', 'ftp://', 'rtsp:/', 'mms://'))) {
$url = 'http://'.$url;
}
return str_replace(array('submit', 'logging.php'), array('', ''), sprintf($tags, $url, addslashes($url)));
} else {
return ' '.$url;
}
}
function jammer() {
$randomstr = '';
for($i = 0; $i < mt_rand(5, 15); $i++) {
$randomstr .= chr(mt_rand(32, 59)).' '.chr(mt_rand(63, 126));
}
$seo = !$GLOBALS['tagstatus'] ? $GLOBALS['discuzcodes']['seoarray'][mt_rand(0, 5)] : '';
return mt_rand(0, 1) ? '<font style="font-size:0px;color:'.TABLEBG.'">'.$seo.$randomstr.'</font>'."\r\n" :
"\r\n".'<span style="display:none">'.$randomstr.$seo.'</span>';
}
function highlight($text, $words, $prepend, $type = 1) {
$text = str_replace('\"', '"', $text);
foreach($words AS $key => $replaceword) {
if($type) {
global $_DCACHE;
if($_DCACHE['tags'][$key] && @strexists($text, $replaceword)) {
$text = str_replace($replaceword, '<span href="tag.php?name='.rawurlencode($replaceword).'" onclick="tagshow(event)" class="t_tag">'.$replaceword.'</span>', $text);
unset($_DCACHE['tags'][$key]);
}
} else {
$text = str_replace($replaceword, '<strong><font color="#FF0000">'.$replaceword.'</font></strong>', $text);
}
}
return "$prepend$text";
}
?> | zyyhong | trunk/jiaju001/bbs/include/discuzcode.func.php | PHP | asf20 | 17,995 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_video.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($iscircle) {
$allowvote = ($circle['allowshare'] && ($circle['ispublic'] == 1 || ($circle['ispublic'] == 2 && $circle['password'] == $_DCOOKIE['gidpw'.$gid]))) || $incircle;
}
$query = $db->query("SELECT * FROM {$tablepre}videos WHERE tid='$tid' LIMIT 1");
$videodata = $db->fetch_array($query);
$vid = $videodata['vid'];
$vautoplay = $videodata['vautoplay'];
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.customstatus, mf.spacename $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE p.tid='$tid' AND first=1 LIMIT 1");
$post = $db->fetch_array($query);
$pid = $post['pid'];
$postlist[$post['pid']] = viewthread_procpost($post);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$post = $postlist[$post['pid']];
include template('viewthread_video');
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_video.inc.php | PHP | asf20 | 1,721 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cache.func.php 19193 2009-08-17 02:59:31Z cnteacher $
*/
define('DISCUZ_KERNEL_VERSION', '6.0.0');
define('DISCUZ_KERNEL_RELEASE', '20070904');
if(isset($_GET['kernel_version'])) {
exit('Crossday Discuz! Board<br />Developed by Comsenz Inc.<br /><br />Version: '.DISCUZ_KERNEL_VERSION.'<br />Release: '.DISCUZ_KERNEL_RELEASE);
} elseif(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function updatecache($cachename = '') {
global $db, $bbname, $tablepre, $maxbdays;
static $cachescript = array
(
'settings' => array('settings'),
'forums' => array('forums'),
'icons' => array('icons'),
'ranks' => array('ranks'),
'usergroups' => array('usergroups'),
'jswizard' => array('jswizard'),
'medals' => array('medals'),
'magics' => array('magics'),
'topicadmin' => array('modreasons'),
'archiver' => array('advs_archiver'),
'register' => array('advs_register'),
'faqs' => array('faqs'),
'secqaa' => array('secqaa'),
'updatecircles' => array('supe_updatecircles'),
'censor' => array('censor'),
'ipbanned' => array('ipbanned'),
'google' => array('google'),
'index' => array('announcements', 'onlinelist', 'forumlinks', 'advs_index', 'supe_updateusers', 'supe_updateitems', 'tags_index'),
'forumdisplay' => array('announcements_forum', 'pmlist', 'globalstick', 'floatthreads', 'forums', 'icons', 'onlinelist', 'advs_forumdisplay'),
'viewthread' => array('forums', 'pmlist', 'usergroups', 'ranks', 'bbcodes', 'smilies', 'smileytypes', 'advs_viewthread', 'tags_viewthread', 'custominfo'),
'post' => array('bbcodes_display', 'bbcodes', 'smilies_display', 'smilies', 'smileytypes', 'icons'),
'blog' => array('usergroups', 'ranks', 'bbcodes', 'smilies', 'smileytypes'),
'profilefields' => array('fields_required', 'fields_optional'),
'viewpro' => array('fields_required', 'fields_optional', 'custominfo'),
'bbcodes' => array('bbcodes', 'smilies', 'smileytypes'),
);
if($maxbdays) {
$cachescript['birthdays'] = array('birthdays');
$cachescript['index'][] = 'birthdays_index';
}
$updatelist = empty($cachename) ? array_values($cachescript) : (is_array($cachename) ? array('0' => $cachename) : array(array('0' => $cachename)));
$updated = array();
foreach($updatelist as $value) {
foreach($value as $cname) {
if(empty($updated) || !in_array($cname, $updated)) {
$updated[] = $cname;
getcachearray($cname);
}
}
}
foreach($cachescript as $script => $cachenames) {
if(empty($cachename) || (!is_array($cachename) && in_array($cachename, $cachenames)) || (is_array($cachename) && array_intersect($cachename, $cachenames))) {
$cachedata = '';
$query = $db->query("SELECT data FROM {$tablepre}caches WHERE cachename in(".implodeids($cachenames).")");
while($data = $db->fetch_array($query)) {
$cachedata .= $data['data'];
}
writetocache($script, $cachenames, $cachedata);
}
}
if(!$cachename || $cachename == 'styles') {
$stylevars = array();
$defaultstyleid = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable = 'styleid'");
$query = $db->query("SELECT sv.* FROM {$tablepre}stylevars sv LEFT JOIN {$tablepre}styles s ON s.styleid = sv.styleid AND (s.available=1 OR s.styleid='$defaultstyleid')");
while($var = $db->fetch_array($query)) {
$stylevars[$var['styleid']][$var['variable']] = $var['substitute'];
}
$query = $db->query("SELECT s.*, t.directory AS tpldir FROM {$tablepre}styles s LEFT JOIN {$tablepre}templates t ON s.templateid=t.templateid WHERE s.available=1 OR s.styleid='$defaultstyleid'");
while($data = $db->fetch_array($query)) {
$data = array_merge($data, $stylevars[$data['styleid']]);
$data['bgcode'] = setcssbackground($data, 'bgcolor');
$data['catbgcode'] = setcssbackground($data, 'catcolor');
$data['headerbgcode'] = setcssbackground($data, 'headercolor');
$data['headermenubgcode'] = setcssbackground($data, 'headermenu');
$data['portalboxbgcode'] = setcssbackground($data, 'portalboxbgcode');
if(strstr($data['boardimg'], ',')) {
$flash = explode(",", $data['boardimg']);
$flash[0] = trim($flash[0]);
$flash[0] = preg_match('/^http:\/\//i', $flash[0]) ? $flash[0] : $data['imgdir'].'/'.$flash[0];
$data['boardlogo'] = "<embed src=\"".$flash[0]."\" width=\"".trim($flash[1])."\" height=\"".trim($flash[2])."\" type=\"application/x-shockwave-flash\"></embed>";
} else {
$data['boardimg'] = preg_match('/^http:\/\//i', $data['boardimg']) ? $data['boardimg'] : $data['imgdir'].'/'.$data['boardimg'];
$data['boardlogo'] = "<img src=\"$data[boardimg]\" alt=\"$bbname\" border=\"0\" />";
}
$data['bold'] = $data['nobold'] ? 'normal' : 'bold';
$data['postminheight'] = $GLOBALS['postminheight'];
$data['maxsigrows'] = $GLOBALS['maxsigrows'];
writetocache($data['styleid'], '', getcachevars($data, 'CONST'), 'style_');
writetocsscache($data);
}
}
if(!$cachename || $cachename == 'usergroups') {
$query = $db->query("SELECT * FROM {$tablepre}usergroups u
LEFT JOIN {$tablepre}admingroups a ON u.groupid=a.admingid");
while($data = $db->fetch_array($query)) {
$ratearray = array();
if($data['raterange']) {
foreach(explode("\n", $data['raterange']) as $rating) {
$rating = explode("\t", $rating);
$ratearray[$rating[0]] = array('min' => $rating[1], 'max' => $rating[2], 'mrpd' => $rating[3]);
}
}
$data['raterange'] = $ratearray;
$data['grouptitle'] = $data['color'] ? '<font color="'.$data['color'].'">'.$data['grouptitle'].'</font>' : $data['grouptitle'];
$data['grouptype'] = $data['type'];
$data['grouppublic'] = $data['system'] != 'private';
$data['groupcreditshigher'] = $data['creditshigher'];
$data['groupcreditslower'] = $data['creditslower'];
unset($data['type'], $data['system'], $data['creditshigher'], $data['creditslower'], $data['color'], $data['groupavatar'], $data['admingid']);
foreach($data as $key => $val) {
if(!isset($data[$key])) {
unset($data[$key]);
}
}
writetocache($data['groupid'], '', getcachevars($data), 'usergroup_');
}
}
if(!$cachename || $cachename == 'admingroups') {
$query = $db->query("SELECT * FROM {$tablepre}admingroups");
while($data = $db->fetch_array($query)) {
writetocache($data['admingid'], '', getcachevars($data), 'admingroup_');
}
}
if(!$cachename || $cachename == 'plugins') {
$query = $db->query("SELECT pluginid, available, adminid, name, identifier, datatables, directory, copyright, modules FROM {$tablepre}plugins");
while($plugin = $db->fetch_array($query)) {
$data = array_merge($plugin, array('modules' => array()), array('vars' => array()));
$plugin['modules'] = unserialize($plugin['modules']);
if(is_array($plugin['modules'])) {
foreach($plugin['modules'] as $module) {
$data['modules'][$module['name']] = $module;
}
}
$queryvars = $db->query("SELECT variable, value FROM {$tablepre}pluginvars WHERE pluginid='$plugin[pluginid]'");
while($var = $db->fetch_array($queryvars)) {
$data['vars'][$var['variable']] = $var['value'];
}
writetocache($plugin['identifier'], '', "\$_DPLUGIN['$plugin[identifier]'] = ".arrayeval($data), 'plugin_');
}
}
if(!$cachename || $cachename == 'threadtypes') {
$typelist = $templatedata = array();
$query = $db->query("SELECT t.typeid, tt.optionid, tt.title, tt.type, tt.rules, tt.identifier, tt.description, tv.required, tv.unchangeable, tv.search
FROM {$tablepre}threadtypes t
LEFT JOIN {$tablepre}typevars tv ON t.typeid=tv.typeid
LEFT JOIN {$tablepre}typeoptions tt ON tv.optionid=tt.optionid
WHERE t.special='1' AND tv.available='1'
ORDER BY tv.displayorder");
while($data = $db->fetch_array($query)) {
$data['rules'] = unserialize($data['rules']);
$typeid = $data['typeid'];
$optionid = $data['optionid'];
$typelist[$typeid][$optionid] = array(
'title' => dhtmlspecialchars($data['title']),
'type' => dhtmlspecialchars($data['type']),
'identifier' => dhtmlspecialchars($data['identifier']),
'description' => dhtmlspecialchars($data['description']),
'required' => intval($data['required']),
'unchangeable' => intval($data['unchangeable']),
'search' => intval($data['search'])
);
if(in_array($data['type'], array('select', 'checkbox', 'radio'))) {
if($data['rules']['choices']) {
$choices = array();
foreach(explode("\n", $data['rules']['choices']) as $item) {
list($index, $choice) = explode('=', $item);
$choices[trim($index)] = trim($choice);
}
$typelist[$typeid][$optionid]['choices'] = $choices;
} else {
$typelist[$typeid][$optionid]['choices'] = array();
}
} elseif(in_array($data['type'], array('text', 'textarea'))) {
$typelist[$typeid][$optionid]['maxlength'] = intval($data['rules']['maxlength']);
} elseif($data['type'] == 'image') {
$typelist[$typeid][$optionid]['maxwidth'] = intval($data['rules']['maxwidth']);
$typelist[$typeid][$optionid]['maxheight'] = intval($data['rules']['maxheight']);
} elseif($data['type'] == 'number') {
$typelist[$typeid][$optionid]['maxnum'] = intval($data['rules']['maxnum']);
$typelist[$typeid][$optionid]['minnum'] = intval($data['rules']['minnum']);
}
}
$query = $db->query("SELECT typeid, description, template FROM {$tablepre}threadtypes WHERE special='1'");
while($data = $db->fetch_array($query)) {
$templatedata[$data['typeid']] = $data['template'];
$threaddesc[$data['typeid']] = dhtmlspecialchars($data['description']);
}
foreach($typelist as $typeid => $option) {
writetocache($typeid, '', "\$_DTYPE = ".arrayeval($option).";\n\n\$_DTYPETEMPLATE = \"".addslashes($templatedata[$typeid])."\";\n\n\$_DTYPEDESC = \"".addslashes($threaddesc[$typeid])."\";\n", 'threadtype_');
}
}
if(empty($cachename) || in_array($cachename, array('forums', 'usergroups', 'settings'))) {
updatespacesettings();
}
}
function setcssbackground(&$data, $code) {
$codes = explode(' ', $data[$code]);
$css = $codevalue = '';
for($i = 0; $i <= 1; $i++) {
if($codes[$i] != '') {
if($codes[$i]{0} == '#') {
$css .= strtoupper($codes[$i]).' ';
$codevalue = strtoupper($codes[$i]);
} elseif(preg_match('/^http:\/\//i', $codes[$i])) {
$css .= 'url(\"'.$codes[$i].'\") ';
} else {
$css .= 'url("'.$data['imgdir'].'/'.$codes[$i].'") ';
}
}
}
$data[$code] = $codevalue;
return 'background: '.trim($css);
}
function updatespacesettings() {
global $db, $tablepre, $initcredits;
$initcreditarray = explode(',', $initcredits);
$tmp = array();
for($i = 1;$i <= 8;$i++) {
$tmp['extcredits'.$i] = $initcreditarray[$i];
}
$lowercredits = intval($initcredits);
$groupinfo = $db->fetch_first("SELECT groupid, readaccess FROM {$tablepre}usergroups WHERE creditshigher<=$lowercredits AND creditslower>$lowercredits ORDER BY creditshigher LIMIT 1");
$fids = 0;
$query = $db->query("SELECT ff.fid, ff.viewperm, ff.formulaperm FROM {$tablepre}forumfields ff,{$tablepre}forums f WHERE f.fid=ff.fid AND f.status>'0' AND ff.password=''");
while($forum = $db->fetch_array($query)) {
if((empty($forum['viewperm']) || in_array($groupinfo['groupid'], explode("\t", $forum['viewperm'])))) {
$fids .= ','.$forum['fid'];
}
}
$spacesettings = array('parms' => array('infids' => $fids, 'groupid' => $groupinfo['groupid'], 'readaccess' => $groupinfo['readaccess']));
writetocache('spacesettings', '', getcachevars($spacesettings));
}
function updatesettings() {
global $_DCACHE;
if(isset($_DCACHE['settings']) && is_array($_DCACHE['settings'])) {
writetocache('settings', '', '$_DCACHE[\'settings\'] = '.arrayeval($_DCACHE['settings']).";\n\n");
}
}
function writetocache($script, $cachenames, $cachedata = '', $prefix = 'cache_') {
global $authkey;
if(is_array($cachenames) && !$cachedata) {
foreach($cachenames as $name) {
$cachedata .= getcachearray($name, $script);
}
}
$dir = DISCUZ_ROOT.'./forumdata/cache/';
if(!is_dir($dir)) {
@mkdir($dir, 0777);
}
if($fp = @fopen("$dir$prefix$script.php", 'wb')) {
fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!".
"\n//Created: ".date("M j, Y, G:i").
"\n//Identify: ".md5($prefix.$script.'.php'.$cachedata.$authkey)."\n\n$cachedata?>");
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
}
function writetocsscache($data) {
$cssdata = '';
foreach(array('css', 'css_append') as $css) {
$cssfile = DISCUZ_ROOT.'./'.$data['tpldir'].'/'.$css.'.htm';
!file_exists($cssfile) && $cssfile = DISCUZ_ROOT.'./templates/default/'.$css.'.htm';
$fp = fopen($cssfile, 'r');
$cssdata .= fread($fp, filesize($cssfile))."\n\n";
fclose($fp);
}
$cssdata = preg_replace("/\{([A-Z0-9]+)\}/e", '\$data[strtolower(\'\1\')]', $cssdata);
$cssdata = preg_replace("/<\?.+?\?>\s*/", '', $cssdata);
$cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url(\"$data[imgdir]", "url(\"../../$data[imgdir]", $cssdata) : $cssdata;
$cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url($data[imgdir]", "url(../../$data[imgdir]", $cssdata) : $cssdata;
$extra = substr($css, 3);
if(@$fp = fopen(DISCUZ_ROOT.'./forumdata/cache/style_'.$data['styleid'].'.css', 'w')) {
fwrite($fp, $cssdata);
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
}
function getcachearray($cachename, $script = '') {
global $db, $timestamp, $tablepre, $timeoffset, $maxbdays, $smcols, $smrows, $charset, $supe;
$cols = '*';
$conditions = '';
switch($cachename) {
case 'settings':
$table = 'settings';
$conditions = "WHERE variable NOT IN ('siteuniqueid', 'mastermobile', 'bbrules', 'bbrulestxt', 'closedreason', 'creditsnotify', 'backupdir', 'custombackup', 'jswizard', 'maxonlines', 'modreasons', 'newsletter', 'welcomemsg', 'welcomemsgtxt', 'postno', 'postnocustom', 'customauthorinfo') AND SUBSTRING(variable, 1, 9)<>'jswizard_'";
break;
case 'custominfo':
$table = 'settings';
$conditions = "WHERE variable IN ('extcredits', 'customauthorinfo', 'postno', 'postnocustom', 'maxavatarpixel')";
break;
case 'jswizard':
$table = 'settings';
$conditions = "WHERE variable LIKE 'jswizard_%'";
break;
case 'usergroups':
$table = 'usergroups';
$cols = 'groupid, type, grouptitle, creditshigher, creditslower, stars, color, groupavatar, readaccess, allowavatar, allowcusbbcode, allowuseblog';
$conditions = "ORDER BY creditslower";
break;
case 'ranks':
$table = 'ranks';
$cols = 'ranktitle, postshigher, stars, color';
$conditions = "ORDER BY postshigher DESC";
break;
case 'announcements':
$table = 'announcements';
$cols = 'id, subject, type, starttime, endtime, displayorder, groups, message';
$conditions = "WHERE starttime<='$timestamp' AND (endtime>='$timestamp' OR endtime='0') ORDER BY displayorder, starttime DESC, id DESC";
break;
case 'announcements_forum':
$table = 'announcements a';
$cols = 'a.id, a.author, m.uid AS authorid, a.subject, a.message, a.type, a.starttime, a.displayorder';
$conditions = "LEFT JOIN {$tablepre}members m ON m.username=a.author WHERE a.type!=2 AND a.groups = '' AND a.starttime<='$timestamp' ORDER BY a.displayorder, a.starttime DESC, a.id DESC LIMIT 1";
break;
case 'pmlist':
$table = 'announcements a';
$cols = 'id as pmid, subject, starttime, endtime, groups';
$conditions = "WHERE type=2 AND starttime<='$timestamp' AND (endtime>='$timestamp' OR endtime='0') ORDER BY displayorder, starttime DESC, id DESC";
break;
case in_array($cachename, array('globalstick', 'floatthreads')):
$table = 'forums';
$cols = 'fid, type, fup';
$conditions = "WHERE status>0 AND type IN ('forum', 'sub') ORDER BY type";
break;
case 'forums':
$table = 'forums f';
$cols = 'f.fid, f.type, f.name, f.fup, f.simple, ff.viewperm, ff.formulaperm, a.uid';
$conditions = "LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid LEFT JOIN {$tablepre}access a ON a.fid=f.fid AND a.allowview='1' WHERE f.status>0 ORDER BY f.type, f.displayorder";
break;
case 'onlinelist':
$table = 'onlinelist';
$conditions = "ORDER BY displayorder";
break;
case 'forumlinks':
$table = 'forumlinks';
$conditions = "ORDER BY displayorder";
break;
case 'bbcodes':
$table = 'bbcodes';
$conditions = "WHERE available='1'";
break;
case 'bbcodes_display':
$table = 'bbcodes';
$cols = 'tag, icon, explanation, params, prompt';
$conditions = "WHERE available='1' AND icon!=''";
break;
case 'smilies':
$table = 'smilies s';
$cols = 's.id, s.code, s.url, t.typeid';
$conditions = "LEFT JOIN {$tablepre}imagetypes t ON t.typeid=s.typeid WHERE s.type='smiley' AND s.code<>'' AND t.typeid IS NOT NULL ORDER BY LENGTH(s.code) DESC";
break;
case 'smilies_display':
$table = 'imagetypes';
$cols = 'typeid, directory';
$conditions = "WHERE type='smiley' ORDER BY displayorder";
break;
case 'smileytypes':
$table = 'imagetypes';
$cols = 'typeid, name, directory';
$conditions = "WHERE type='smiley' ORDER BY displayorder";
break;
case 'icons':
$table = 'smilies';
$cols = 'id, url';
$conditions = "WHERE type='icon' ORDER BY displayorder";
break;
case 'fields_required':
$table = 'profilefields';
$cols = 'fieldid, invisible, title, description, required, unchangeable, selective, choices';
$conditions = "WHERE available='1' AND required='1' ORDER BY displayorder";
break;
case 'fields_optional':
$table = 'profilefields';
$cols = 'fieldid, invisible, title, description, required, unchangeable, selective, choices';
$conditions = "WHERE available='1' AND required='0' ORDER BY displayorder";
break;
case 'ipbanned':
$db->query("DELETE FROM {$tablepre}banned WHERE expiration<'$timestamp'");
$table = 'banned';
$cols = 'ip1, ip2, ip3, ip4, expiration';
break;
case 'google':
$table = 'settings';
$cols = 'value';
$conditions = "WHERE variable = 'google'";
break;
case 'censor':
$table = 'words';
$cols = 'find, replacement';
break;
case 'medals':
$table = 'medals';
$cols = 'medalid, name, image';
$conditions = "WHERE available='1'";
break;
case 'magics':
$table = 'magics';
$cols = 'magicid, available, identifier, name, description, weight, price';
break;
case 'birthdays_index':
$table = 'members';
$cols = 'uid, username, email, bday';
$conditions = "WHERE RIGHT(bday, 5)='".gmdate('m-d', $timestamp + $timeoffset * 3600)."' ORDER BY bday LIMIT $maxbdays";
break;
case 'birthdays':
$table = 'members';
$cols = 'uid';
$conditions = "WHERE RIGHT(bday, 5)='".gmdate('m-d', $timestamp + $timeoffset * 3600)."' ORDER BY bday";
break;
case 'modreasons':
$table = 'settings';
$cols = 'value';
$conditions = "WHERE variable='modreasons'";
break;
case 'faqs':
$table = 'faqs';
$cols = 'id, identifier, keyword';
$conditions = "WHERE identifier!='' AND keyword!=''";
break;
case substr($cachename, 0, 5) == 'tags_':
global $viewthreadtags, $hottags;
$taglimit = substr($cachename, 5) == 'viewthread' ? intval($viewthreadtags) : intval($hottags);
$table = 'tags';
$cols = 'tagname, total';
$conditions = "WHERE closed=0 ORDER BY total DESC LIMIT $taglimit";
break;
}
$data = array();
if(!in_array($cachename, array('secqaa', 'supe_updateusers', 'supe_updateitems', 'supe_updatecircles')) && substr($cachename, 0, 5) != 'advs_') {
if(empty($table) || empty($cols)) return '';
$query = $db->query("SELECT $cols FROM {$tablepre}$table $conditions");
}
switch($cachename) {
case 'settings':
while($setting = $db->fetch_array($query)) {
if($setting['variable'] == 'extcredits') {
if(is_array($setting['value'] = unserialize($setting['value']))) {
foreach($setting['value'] as $key => $value) {
if($value['available']) {
unset($setting['value'][$key]['available']);
} else {
unset($setting['value'][$key]);
}
}
}
} elseif($setting['variable'] == 'creditsformula') {
if(!preg_match("/^([\+\-\*\/\.\d\(\)]|((extcredits[1-8]|digestposts|posts|pageviews|oltime)([\+\-\*\/\(\)]|$)+))+$/", $setting['value']) || !is_null(@eval(preg_replace("/(digestposts|posts|pageviews|oltime|extcredits[1-8])/", "\$\\1", $setting['value']).';'))) {
$setting['value'] = '$member[\'extcredits1\']';
} else {
$setting['value'] = preg_replace("/(digestposts|posts|pageviews|oltime|extcredits[1-8])/", "\$member['\\1']", $setting['value']);
}
} elseif($setting['variable'] == 'maxsmilies') {
$setting['value'] = $setting['value'] <= 0 ? -1 : $setting['value'];
} elseif($setting['variable'] == 'threadsticky') {
$setting['value'] = explode(',', $setting['value']);
} elseif($setting['variable'] == 'attachdir') {
$setting['value'] = preg_replace("/\.asp|\\0/i", '0', $setting['value']);
$setting['value'] = str_replace('\\', '/', substr($setting['value'], 0, 2) == './' ? DISCUZ_ROOT.$setting['value'] : $setting['value']);
} elseif($setting['variable'] == 'onlinehold') {
$setting['value'] = $setting['value'] * 60;
} elseif($setting['variable'] == 'userdateformat') {
if(empty($setting['value'])) {
$setting['value'] = array();
} else {
$setting['value'] = dhtmlspecialchars(explode("\n", $setting['value']));
$setting['value'] = array_map('trim', $setting['value']);
}
} elseif(in_array($setting['variable'], array('creditspolicy', 'ftp', 'secqaa', 'supe', 'ec_credit', 'google', 'qihoo', 'insenz', 'spacedata'))) {
$setting['value'] = unserialize($setting['value']);
}
$GLOBALS[$setting['variable']] = $data[$setting['variable']] = $setting['value'];
}
$GLOBALS['version'] = $data['version'] = DISCUZ_KERNEL_VERSION;
$GLOBALS['totalmembers'] = $data['totalmembers'] = $db->result_first("SELECT COUNT(*) FROM {$tablepre}members");
$GLOBALS['lastmember'] = $data['lastmember'] = $db->result_first("SELECT username FROM {$tablepre}members ORDER BY uid DESC LIMIT 1");
$data['cachethreadon'] = $db->result_first("SELECT COUNT(*) FROM {$tablepre}forums WHERE status>0 AND threadcaches>0") ? 1 : 0;
$data['cronnextrun'] = $db->result_first("SELECT nextrun FROM {$tablepre}crons WHERE available>'0' AND nextrun>'0' ORDER BY nextrun LIMIT 1");
$data['ftp']['connid'] = 0;
$data['indexname'] = empty($data['indexname']) ? 'index.php' : $data['indexname'];
if(!$data['imagelib']) {
unset($data['imageimpath']);
}
$data['seccodedata'] = $data['seccodedata'] ? unserialize($data['seccodedata']) : array();
if($data['seccodedata']['type'] == 2) {
if(extension_loaded('ming')) {
unset($data['seccodedata']['background'], $data['seccodedata']['adulterate'],
$data['seccodedata']['ttf'], $data['seccodedata']['angle'],
$data['seccodedata']['color'], $data['seccodedata']['size'],
$data['seccodedata']['animator']);
} else {
$data['seccodedata']['type'] = 0;
}
}
$secqaacheck = sprintf('%03b', $data['secqaa']['status']);
$data['secqaa']['status'] = array(
1 => $secqaacheck{2},
2 => $secqaacheck{1},
3 => $secqaacheck{0}
);
if(!$data['secqaa']['status'][2] && !$data['secqaa']['status'][3]) {
unset($data['secqaa']['minposts']);
}
if($data['watermarktype'] == 2 && $data['watermarktext']) {
$data['watermarktext'] = unserialize($data['watermarktext']);
if($data['watermarktext']['text'] && strtoupper($charset) != 'UTF-8') {
require_once DISCUZ_ROOT.'include/chinese.class.php';
$c = new Chinese($charset, 'utf8');
$data['watermarktext']['text'] = $c->Convert($data['watermarktext']['text']);
}
$data['watermarktext']['text'] = bin2hex($data['watermarktext']['text']);
$data['watermarktext']['fontpath'] = 'images/fonts/'.$data['watermarktext']['fontpath'];
$data['watermarktext']['color'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $data['watermarktext']['color']);
$data['watermarktext']['shadowcolor'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $data['watermarktext']['shadowcolor']);
} else {
$data['watermarktext'] = array();
}
$tradetypes = implodeids(unserialize($data['tradetypes']));
$data['tradetypes'] = array();
if($tradetypes) {
$query = $db->query("SELECT typeid, name FROM {$tablepre}threadtypes WHERE typeid in ($tradetypes)");
while($type = $db->fetch_array($query)) {
$data['tradetypes'][$type['typeid']] = $type['name'];
}
}
$data['jsmenustatus'] = sprintf('%b', $data['jsmenustatus']);
for($i = 1; $i <= strlen($data['jsmenustatus']); $i++) {
if(substr($data['jsmenustatus'], -$i, 1)) $data['jsmenu'][$i] = TRUE;
}
unset($data['jsmenustatus']);
$data['stylejumpstatus'] = $data['stylejump'];
$data['stylejump'] = array();
$query = $db->query("SELECT styleid, name FROM {$tablepre}styles WHERE available='1'");
while($style = $db->fetch_array($query)) {
$data['stylejump'][$style['styleid']] = dhtmlspecialchars($style['name']);
}
$globaladvs = advertisement('all');
$data['globaladvs'] = $globaladvs['all'] ? $globaladvs['all'] : array();
$data['redirectadvs'] = $globaladvs['redirect'] ? $globaladvs['redirect'] : array();
$data['invitecredit'] = '';
if($data['inviteconfig'] = unserialize($data['inviteconfig'])) {
$data['invitecredit'] = $data['inviteconfig']['invitecredit'];
}
unset($data['inviteconfig']);
$data['videoopen'] = $data['videotype'] = $data['vsiteid'] = $data['vpassword'] = $data['vkey'] = $data['vsiteurl'] = '';
if($data['videoinfo'] = unserialize($data['videoinfo'])) {
$data['videoopen'] = intval($data['videoinfo']['open']);
$data['videotype'] = explode("\n", $data['videoinfo']['vtype']);
$data['vsiteid'] = $data['videoinfo']['vsiteid'];
$data['vpassword'] = $data['videoinfo']['vpassword'];
$data['vkey'] = $data['videoinfo']['vkey'];
$data['vsiteurl'] = $data['videoinfo']['url'];
}
unset($data['videoinfo']);
$exchcredits = array();
$allowexchangein = $allowexchangeout = FALSE;
foreach((array)$data['extcredits'] as $id => $credit) {
if(!empty($credit['ratio'])) {
$exchcredits[$id] = $credit;
$credit['allowexchangein'] && $allowexchangein = TRUE;
$credit['allowexchangeout'] && $allowexchangeout = TRUE;
}
}
$data['exchangestatus'] = $allowexchangein && $allowexchangeout;
$data['transferstatus'] = isset($data['extcredits'][$data['creditstrans']]);
foreach(array('supe_status', 'supe_tablepre', 'supe_siteurl', 'supe_sitename', 'supe_circlestatus') AS $variable) {
$data['supe'][substr($variable, 5)] = $data[$variable];
unset($data[$variable]);
}
if(!$data['supe']['status']) {
$data['supe'] = array('status' => 0);
} else {
if(!$data['supe']['items']['status']) {
$data['supe']['items'] = array('status' => 0);
}
if(!isset($data['supe']['attachurl']) && isset($supe['tablepre'])) {
$supe['status'] = 1;
supe_dbconnect();
$query = $supe['db']->query("SELECT * FROM {$supe[tablepre]}settings WHERE variable IN ('attachmentdir', 'attachmenturl')", 'SILENT');
$supe_settings = array();
while($supe_setting = $supe['db']->fetch_array($query)) {
$supe_settings[$supe_setting['variable']] = $supe_setting['value'];
}
if(substr($supe_settings['attachmentdir'], 0, 2) == './' && empty($supe_settings['attachmenturl'])) {
$supe_settings['attachmenturl'] = $supe['siteurl'].substr($supe_settings['attachmentdir'], 1);
}
$data['supe']['attachurl'] = $supe_settings['attachmenturl'];
$db->query("UPDATE {$tablepre}settings SET value='".addslashes(serialize($data['supe']))."' WHERE variable='supe'");
}
if(!$data['supe']['dbmode']) {
unset($data['supe']['dbhost'], $data['supe']['dbuser'], $data['supe']['dbpw'], $data['supe']['dbname']);
}
}
if($data['insenz']['status'] && $data['insenz']['authkey']) {
$softadstatus = intval($data['insenz']['softadstatus']);
$hardadstatus = is_array($data['insenz']['hardadstatus']) && $data['insenz']['jsurl'] ? implode(',', $data['insenz']['hardadstatus']) : '';
$relatedadstatus = intval($data['insenz']['relatedadstatus']);
$insenz_cronnextrun = intval($db->result_first("SELECT nextrun FROM {$tablepre}campaigns ORDER BY nextrun LIMIT 1"));
if(!$softadstatus && !$hardadstatus && !$relatedadstatus && !$data['insenz']['virtualforumstatus'] && !$insenz_cronnextrun) {
$data['insenz']['status'] = $data['insenz']['cronnextrun'] = 0;
$db->query("REPLACE INTO {$tablepre}settings (variable, value) VALUES ('insenz', '".addslashes(serialize($data['insenz']))."')");
$data['insenz'] = array();
} else {
$data['insenz'] = array(
'siteid' => $data['insenz']['siteid'],
'uid' => intval($data['insenz']['uid']),
'username' => addslashes($data['insenz']['username']),
'hardadstatus' => $hardadstatus,
'topicrelatedad' => $relatedadstatus && $data['insenz']['topicrelatedad'] ? $data['insenz']['topicrelatedad'] : '',
'traderelatedad' => $relatedadstatus && $data['insenz']['traderelatedad'] ? $data['insenz']['traderelatedad'] : '',
'relatedtrades' => $relatedadstatus && $data['insenz']['traderelatedad'] && $data['insenz']['relatedtrades'] ? $data['insenz']['relatedtrades'] : '',
'cronnextrun' => $insenz_cronnextrun,
'statsnextrun' => intval($data['insenz']['statsnextrun']),
'jsurl' => $data['insenz']['jsurl']
);
}
} else {
$data['insenz'] = array();
}
if(!empty($data['google']['status'])) {
$data['google'] = $data['google']['searchbox'];
} else {
$data['google'] = 0;
}
if($data['qihoo']['status']) {
$qihoo = $data['qihoo'];
$data['qihoo']['links'] = $data['qihoo']['relate'] = array();
foreach(explode("\n", trim($qihoo['keywords'])) AS $keyword) {
if($keyword = trim($keyword)) {
$data['qihoo']['links']['keywords'][] = '<a href="search.php?srchtype=qihoo&srchtxt='.rawurlencode($keyword).'&searchsubmit=yes" target="_blank">'.dhtmlspecialchars(trim($keyword)).'</a>';
}
}
foreach((array)$qihoo['topics'] AS $topic) {
if($topic['topic'] = trim($topic['topic'])) {
$data['qihoo']['links']['topics'][] = '<a href="topic.php?topic='.rawurlencode($topic['topic']).'&keyword='.rawurlencode($topic['keyword']).'&stype='.$topic['stype'].'&length='.$topic['length'].'&relate='.$topic['relate'].'" target="_blank">'.dhtmlspecialchars(trim($topic['topic'])).'</a>';
}
}
if(is_array($qihoo['relatedthreads'])) {
if($data['qihoo']['relate']['bbsnum'] = intval($qihoo['relatedthreads']['bbsnum'])) {
$data['qihoo']['relate']['position'] = intval($qihoo['relatedthreads']['position']);
$data['qihoo']['relate']['validity'] = intval($qihoo['relatedthreads']['validity']);
if($data['qihoo']['relate']['webnum'] = intval($qihoo['relatedthreads']['webnum'])) {
$data['qihoo']['relate']['banurl'] = $qihoo['relatedthreads']['banurl'] ? '/('.str_replace("\r\n", '|', $qihoo['relatedthreads']['banurl']).')/i' : '';
$data['qihoo']['relate']['type'] = implode('|', (array)$qihoo['relatedthreads']['type']);
$data['qihoo']['relate']['order'] = intval($qihoo['relatedthreads']['order']);
}
} else {
$data['qihoo']['relate'] = array();
}
}
unset($qihoo, $data['qihoo']['keywords'], $data['qihoo']['topics'], $data['qihoo']['relatedthreads']);
} else {
$data['qihoo'] = array();
}
$data['plugins'] = $data['pluginlinks'] = array();
$query = $db->query("SELECT available, name, identifier, directory, datatables, modules FROM {$tablepre}plugins");
while($plugin = $db->fetch_array($query)) {
$plugin['modules'] = unserialize($plugin['modules']);
if(is_array($plugin['modules'])) {
foreach($plugin['modules'] as $module) {
if($plugin['available'] && isset($module['name'])) {
switch($module['type']) {
case 1:
$data['plugins']['links'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"$module[url]\">$module[menu]</a>");
break;
case 2:
$data['plugins']['links'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"plugin.php?identifier=$plugin[identifier]&module=$module[name]\">$module[menu]</a>");
$data['pluginlinks'][$plugin['identifier']][$module['name']] = array('adminid' => $module['adminid'], 'directory' => $plugin['directory']);
break;
case 4:
$data['plugins']['include'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'script' => $plugin['directory'].$module['name']);
break;
case 5:
$data['plugins']['jsmenu'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"$module[url]\">$module[menu]</a>");
break;
case 6:
$data['plugins']['jsmenu'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"plugin.php?identifier=$plugin[identifier]&module=$module[name]\">$module[menu]</a>");
$data['pluginlinks'][$plugin['identifier']][$module['name']] = array('adminid' => $module['adminid'], 'directory' => $plugin['directory']);
break;
}
}
}
}
}
if(is_array($data['plugins']['links'])) {
usort($data['plugins']['links'], 'pluginmodulecmp');
foreach($data['plugins']['links'] as $key => $module) {
unset($data['plugins']['links'][$key]['displayorder']);
}
}
if(is_array($data['plugins']['include'])) {
usort($data['plugins']['include'], 'pluginmodulecmp');
foreach($data['plugins']['include'] as $key => $module) {
unset($data['plugins']['include'][$key]['displayorder']);
}
}
if(is_array($data['plugins']['jsmenu'])) {
usort($data['plugins']['jsmenu'], 'pluginmodulecmp');
foreach($data['plugins']['jsmenu'] as $key => $module) {
unset($data['plugins']['jsmenu'][$key]['displayorder']);
}
}
$data['hooks'] = array();
$query = $db->query("SELECT ph.title, ph.code, p.identifier FROM {$tablepre}plugins p
LEFT JOIN {$tablepre}pluginhooks ph ON ph.pluginid=p.pluginid AND ph.available='1'
WHERE p.available='1' ORDER BY p.identifier");
while($hook = $db->fetch_array($query)) {
if($hook['title'] && $hook['code']) {
$data['hooks'][$hook['identifier'].'_'.$hook['title']] = $hook['code'];
}
}
break;
case 'custominfo':
while($setting = $db->fetch_array($query)) {
$data[$setting['variable']] = $setting['value'];
}
$data['customauthorinfo'] = unserialize($data['customauthorinfo']);
$data['customauthorinfo'] = $data['customauthorinfo'][0];
$data['extcredits'] = unserialize($data['extcredits']);
include language('templates');
$authorinfoitems = array(
'uid' => '$post[uid]',
'posts' => '$post[posts]',
'digest' => '<a href="digest.php?authorid=$post[authorid]">$post[digestposts]</a>',
'credits' => '$post[credits]',
'readperm' => '$post[readaccess]',
'gender' => '$post[gender]',
'location' => '$post[location]',
'oltime' => '$post[oltime] '.$language['hours'],
'regtime' => '$post[regdate]',
'lastdate' => '$post[lastdate]',
);
if(!empty($data['extcredits'])) {
foreach($data['extcredits'] as $key => $value) {
if($value['available'] && $value['showinthread']) {
$authorinfoitems['extcredits'.$key] = array($value['title'], '$post[extcredits'.$key.'] {$extcredits['.$key.'][unit]}');
}
}
}
$data['fieldsadd'] = '';$data['profilefields'] = array();
$query = $db->query("SELECT * FROM {$tablepre}profilefields WHERE available='1' AND invisible='0' AND showinthread='1' ORDER BY displayorder");
while($field = $db->fetch_array($query)) {
$data['fieldsadd'] .= ', mf.field_'.$field['fieldid'];
if($field['selective']) {
foreach(explode("\n", $field['choices']) as $item) {
list($index, $choice) = explode('=', $item);
$data['profilefields'][$field['fieldid']][trim($index)] = trim($choice);
}
$authorinfoitems['field_'.$field['fieldid']] = array($field['title'], '{$profilefields['.$field['fieldid'].'][$post[field_'.$field['fieldid'].']]}');
} else {
$authorinfoitems['field_'.$field['fieldid']] = array($field['title'], '$post[field_'.$field['fieldid'].']');
}
}
$customauthorinfo = array();
if(is_array($data['customauthorinfo'])) {
foreach($data['customauthorinfo'] as $key => $value) {
if(array_key_exists($key, $authorinfoitems)) {
if(substr($key, 0, 10) == 'extcredits') {
$v = addcslashes('<dt>'.$authorinfoitems[$key][0].'</dt><dd>'.$authorinfoitems[$key][1].' </dd>', '"');
} elseif(substr($key, 0, 6) == 'field_') {
$v = addcslashes('<dt>'.$authorinfoitems[$key][0].'</dt><dd>'.$authorinfoitems[$key][1].' </dd>', '"');
} elseif($key == 'gender') {
$v = '".('.$authorinfoitems['gender'].' == 1 ? "'.addcslashes('<dt>'.$language['authorinfoitems_'.$key].'</dt><dd>'.$language['authorinfoitems_gender_male'].' </dd>', '"').'" : ('.$authorinfoitems['gender'].' == 2 ? "'.addcslashes('<dt>'.$language['authorinfoitems_'.$key].'</dt><dd>'.$language['authorinfoitems_gender_female'].' </dd>', '"').'" : ""))."';
} elseif($key == 'location') {
$v = '".('.$authorinfoitems[$key].' ? "'.addcslashes('<dt>'.$language['authorinfoitems_'.$key].'</dt><dd>'.$authorinfoitems[$key].' </dd>', '"').'" : "")."';
} else {
$v = addcslashes('<dt>'.$language['authorinfoitems_'.$key].'</dt><dd>'.$authorinfoitems[$key].' </dd>', '"');
}
if(isset($value['left'])) {
$customauthorinfo[1][] = $v;
}
if(isset($value['menu'])) {
$customauthorinfo[2][] = $v;
}
if(isset($value['special'])) {
$customauthorinfo[3][] = $v;
}
}
}
}
$GLOBALS['postminheight'] = ($data['maxavatarpixel'] > 300 ? 300 : $data['maxavatarpixel']) + count($customauthorinfo[1]) * 20;
$customauthorinfo[1] = @implode('', $customauthorinfo[1]);
$customauthorinfo[2] = @implode('', $customauthorinfo[2]);
$customauthorinfo[3] = @implode('', $customauthorinfo[3]);
$data['customauthorinfo'] = $customauthorinfo;
updatecache('styles');
$postnocustomnew[0] = $data['postno'] != '' ? (preg_match("/^[\x01-\x7f]+$/", $data['postno']) ? '<sup>'.$data['postno'].'</sup>' : $data['postno']) : '<sup>#</sup>';
$data['postnocustom'] = unserialize($data['postnocustom']);
if(is_array($data['postnocustom'])) {
foreach($data['postnocustom'] as $key => $value) {
$value = trim($value);
$postnocustomnew[$key + 1] = preg_match("/^[\x01-\x7f]+$/", $value) ? '<sup>'.$value.'</sup>' : $value;
}
}
unset($data['postno'], $data['postnocustom'], $data['extcredits'], $data['maxavatarpixel']);
$data['postno'] = $postnocustomnew;
break;
case 'jswizard':
while($jswizard = $db->fetch_array($query)) {
$key = substr($jswizard['variable'], 9);
$data[$key] = unserialize($jswizard['value']);
unset($data[$key]['type']);
unset($data[$key]['parameter']);
}
break;
case 'usergroups':
global $userstatusby;
while($group = $db->fetch_array($query)) {
$groupid = $group['groupid'];
$group['grouptitle'] = $group['color'] ? '<font color="'.$group['color'].'">'.$group['grouptitle'].'</font>' : $group['grouptitle'];
if($userstatusby == 1) {
$group['userstatusby'] = 1;
} elseif($userstatusby == 2) {
if($group['type'] != 'member') {
$group['userstatusby'] = 1;
} else {
$group['userstatusby'] = 2;
}
}
if($group['type'] != 'member') {
unset($group['creditshigher'], $group['creditslower']);
}
unset($group['groupid'], $group['color']);
$data[$groupid] = $group;
}
break;
case 'ranks':
global $userstatusby;
if($userstatusby == 2) {
while($rank = $db->fetch_array($query)) {
$rank['ranktitle'] = $rank['color'] ? '<font color="'.$rank['color'].'">'.$rank['ranktitle'].'</font>' : $rank['ranktitle'];
unset($rank['color']);
$data[] = $rank;
}
}
break;
case 'announcements':
$data = array();
while($datarow = $db->fetch_array($query)) {
if($datarow['type'] == 2) {
$datarow['pmid'] = $datarow['id'];
unset($datarow['id']);
unset($datarow['message']);
$datarow['subject'] = cutstr($datarow['subject'], 60);
}
$datarow['groups'] = empty($datarow['groups']) ? array() : explode(',', $datarow['groups']);
$data[] = $datarow;
}
break;
case 'announcements_forum':
if($data = $db->fetch_array($query)) {
$data['authorid'] = intval($data['authorid']);
if(empty($data['type'])) {
unset($data['message']);
}
} else {
$data = array();
}
break;
case 'pmlist':
$data = array();
while($datarow = $db->fetch_array($query)) {
$datarow['subject'] = cutstr($datarow['subject'], 60);
$datarow['groups'] = empty($datarow['groups']) ? array() : explode(',', $datarow['groups']);
$data[] = $datarow;
}
break;
case 'globalstick':
$fuparray = $threadarray = array();
while($forum = $db->fetch_array($query)) {
switch($forum['type']) {
case 'forum':
$fuparray[$forum['fid']] = $forum['fup'];
break;
case 'sub':
$fuparray[$forum['fid']] = $fuparray[$forum['fup']];
break;
}
}
$query = $db->query("SELECT tid, fid, displayorder FROM {$tablepre}threads WHERE displayorder IN (2, 3)");
while($thread = $db->fetch_array($query)) {
switch($thread['displayorder']) {
case 2:
$threadarray[$fuparray[$thread['fid']]][] = $thread['tid'];
break;
case 3:
$threadarray['global'][] = $thread['tid'];
break;
}
}
foreach(array_unique($fuparray) as $gid) {
if(!empty($threadarray[$gid])) {
$data['categories'][$gid] = array(
'tids' => implode(',', $threadarray[$gid]),
'count' => intval(@count($threadarray[$gid]))
);
}
}
$data['global'] = array(
'tids' => empty($threadarray['global']) ? 0 : implode(',', $threadarray['global']),
'count' => intval(@count($threadarray['global']))
);
break;
case 'floatthreads':
$fuparray = $threadarray = $forums = array();
while($forum = $db->fetch_array($query)) {
switch($forum['type']) {
case 'forum':
$fuparray[$forum['fid']] = $forum['fup'];
break;
case 'sub':
$fuparray[$forum['fid']] = $fuparray[$forum['fup']];
break;
}
}
$query = $db->query("SELECT tid, fid, displayorder FROM {$tablepre}threads WHERE displayorder IN (4, 5)");
while($thread = $db->fetch_array($query)) {
switch($thread['displayorder']) {
case 4:
$threadarray[$thread['fid']][] = $thread['tid'];
break;
case 5:
$threadarray[$fuparray[$thread['fid']]][] = $thread['tid'];
break;
}
$forums[] = $thread['fid'];
}
foreach(array_unique($fuparray) as $gid) {
if(!empty($threadarray[$gid])) {
$data['categories'][$gid] = implode(',', $threadarray[$gid]);
}
}
foreach(array_unique($forums) as $fid) {
if(!empty($threadarray[$fid])) {
$data['forums'][$fid] = implode(',', $threadarray[$fid]);
}
}
break;
case 'censor':
$banned = $mod = array();
$data = array('filter' => array(), 'banned' => '', 'mod' => '');
while($censor = $db->fetch_array($query)) {
$censor['find'] = preg_replace("/\\\{(\d+)\\\}/", ".{0,\\1}", preg_quote($censor['find'], '/'));
switch($censor['replacement']) {
case '{BANNED}':
$banned[] = $censor['find'];
break;
case '{MOD}':
$mod[] = $censor['find'];
break;
default:
$data['filter']['find'][] = '/'.$censor['find'].'/i';
$data['filter']['replace'][] = $censor['replacement'];
break;
}
}
if($banned) {
$data['banned'] = '/('.implode('|', $banned).')/i';
}
if($mod) {
$data['mod'] = '/('.implode('|', $mod).')/i';
}
break;
case 'forums':
while($forum = $db->fetch_array($query)) {
$forum['orderby'] = bindec((($forum['simple'] & 128) ? 1 : 0).(($forum['simple'] & 64) ? 1 : 0));
$forum['ascdesc'] = ($forum['simple'] & 32) ? 'ASC' : 'DESC';
if(!isset($forumlist[$forum['fid']])) {
$forum['name'] = strip_tags($forum['name']);
if($forum['uid']) {
$forum['users'] = "\t$forum[uid]\t";
}
unset($forum['uid']);
if($forum['fup']) {
$forumlist[$forum['fup']]['count']++;
}
$forumlist[$forum['fid']] = $forum;
} elseif($forum['uid']) {
if(!$forumlist[$forum['fid']]['users']) {
$forumlist[$forum['fid']]['users'] = "\t";
}
$forumlist[$forum['fid']]['users'] .= "$forum[uid]\t";
}
}
$orderbyary = array('lastpost', 'dateline', 'replies', 'views');
if(!empty($forumlist)) {
foreach($forumlist as $fid1 => $forum1) {
if(($forum1['type'] == 'group' && $forum1['count'])) {
$data[$fid1]['fid'] = $forum1['fid'];
$data[$fid1]['type'] = $forum1['type'];
$data[$fid1]['name'] = $forum1['name'];
$data[$fid1]['fup'] = $forum1['fup'];
$data[$fid1]['viewperm'] = $forum1['viewperm'];
$data[$fid1]['orderby'] = $orderbyary[$forum1['orderby']];
$data[$fid1]['ascdesc'] = $forum1['ascdesc'];
foreach($forumlist as $fid2 => $forum2) {
if($forum2['fup'] == $fid1 && $forum2['type'] == 'forum') {
$data[$fid2]['fid'] = $forum2['fid'];
$data[$fid2]['type'] = $forum2['type'];
$data[$fid2]['name'] = $forum2['name'];
$data[$fid2]['fup'] = $forum2['fup'];
$data[$fid2]['viewperm'] = $forum2['viewperm'];
$data[$fid2]['orderby'] = $orderbyary[$forum2['orderby']];
$data[$fid2]['ascdesc'] = $forum2['ascdesc'];
foreach($forumlist as $fid3 => $forum3) {
if($forum3['fup'] == $fid2 && $forum3['type'] == 'sub') {
$data[$fid3]['fid'] = $forum3['fid'];
$data[$fid3]['type'] = $forum3['type'];
$data[$fid3]['name'] = $forum3['name'];
$data[$fid3]['fup'] = $forum3['fup'];
$data[$fid3]['viewperm'] = $forum3['viewperm'];
$data[$fid3]['orderby'] = $orderbyary[$forum3['orderby']];
$data[$fid3]['ascdesc'] = $forum3['ascdesc'];
}
}
}
}
}
}
}
break;
case 'onlinelist':
$data['legend'] = '';
while($list = $db->fetch_array($query)) {
$data[$list['groupid']] = $list['url'];
$data['legend'] .= "<img src=\"images/common/$list[url]\" alt=\"\" /> $list[title] ";
if($list['groupid'] == 7) {
$data['guest'] = $list['title'];
}
}
break;
case 'forumlinks':
global $forumlinkstatus;
if($forumlinkstatus) {
$tightlink_text = $tightlink_logo = '';
while($flink = $db->fetch_array($query)) {
if($flink['description']) {
$forumlink['content'] = "<h5><a href=\"$flink[url]\" target=\"_blank\">$flink[name]</a></h5><p>$flink[description]</p>";
if($flink['logo']) {
$forumlink['type'] = 1;
$forumlink['logo'] = $flink['logo'];
} else {
$forumlink['type'] = 2;
}
$data[] = $forumlink;
} else {
if($flink['logo']) {
$tightlink_logo .= "<a href=\"$flink[url]\" target=\"_blank\"><img src=\"$flink[logo]\" border=\"0\" alt=\"$flink[name]\" /></a> ";
} else {
$tightlink_text .= "<a href=\"$flink[url]\" target=\"_blank\">[$flink[name]]</a> ";
}
}
}
if($tightlink_logo || $tightlink_text) {
$tightlink_logo .= $tightlink_logo ? '<br />' : '';
$data[] = array('type' => 3, 'content' => $tightlink_logo.$tightlink_text);
}
} else {
$data = array();
}
break;
case 'bbcodes':
$regexp = array (
1 => "/\[{bbtag}]([^\"]+?)\[\/{bbtag}\]/is",
2 => "/\[{bbtag}=(['\"]?)([^\"]+?)(['\"]?)\]([^\"]+?)\[\/{bbtag}\]/is",
3 => "/\[{bbtag}=(['\"]?)([^\"]+?)(['\"]?),(['\"]?)([^\"]+?)(['\"]?)\]([^\"]+?)\[\/{bbtag}\]/is"
);
while($bbcode = $db->fetch_array($query)) {
$search = str_replace('{bbtag}', $bbcode['tag'], $regexp[$bbcode['params']]);
$bbcode['replacement'] = preg_replace("/([\r\n])/", '', $bbcode['replacement']);
switch($bbcode['params']) {
case 2:
$bbcode['replacement'] = str_replace('{1}', '\\2', $bbcode['replacement']);
$bbcode['replacement'] = str_replace('{2}', '\\4', $bbcode['replacement']);
break;
case 3:
$bbcode['replacement'] = str_replace('{1}', '\\2', $bbcode['replacement']);
$bbcode['replacement'] = str_replace('{2}', '\\5', $bbcode['replacement']);
$bbcode['replacement'] = str_replace('{3}', '\\7', $bbcode['replacement']);
break;
default:
$bbcode['replacement'] = str_replace('{1}', '\\1', $bbcode['replacement']);
break;
}
if(preg_match("/\{(RANDOM|MD5)\}/", $bbcode['replacement'])) {
$search = str_replace('is', 'ies', $search);
$replace = '\''.str_replace('{RANDOM}', '_\'.random(6).\'', str_replace('{MD5}', '_\'.md5(\'\\1\').\'', $bbcode['replacement'])).'\'';
} else {
$replace = $bbcode['replacement'];
}
for($i = 0; $i < $bbcode['nest']; $i++) {
$data['searcharray'][] = $search;
$data['replacearray'][] = $replace;
}
}
break;
case 'bbcodes_display':
while($bbcode = $db->fetch_array($query)) {
$tag = $bbcode['tag'];
$bbcode['explanation'] = dhtmlspecialchars(trim($bbcode['explanation']));
$bbcode['prompt'] = addcslashes($bbcode['prompt'], '\\\'');
unset($bbcode['tag']);
$data[$tag] = $bbcode;
}
break;
case 'smilies':
$data = array('searcharray' => array(), 'replacearray' => array(), 'typearray' => array());
while($smiley = $db->fetch_array($query)) {
$data['searcharray'][$smiley['id']] = '/'.preg_quote(dhtmlspecialchars($smiley['code']), '/').'/';
$data['replacearray'][$smiley['id']] = $smiley['url'];
$data['typearray'][$smiley['id']] = $smiley['typeid'];
}
break;
case 'smilies_display':
while($type = $db->fetch_array($query)) {
$squery = $db->query("SELECT id, code, url FROM {$tablepre}smilies WHERE type='smiley' AND code<>'' AND typeid='$type[typeid]' ORDER BY displayorder");
if($db->num_rows($squery)) {
while($smiley = $db->fetch_array($squery)) {
if($size = @getimagesize('./images/smilies/'.$type['directory'].'/'.$smiley['url'])) {
$smiley['code'] = dhtmlspecialchars($smiley['code']);
$smileyid = $smiley['id'];
$s = smthumb($size, $GLOBALS['smthumb']);
$smiley['w'] = $s['w'];
$smiley['h'] = $s['h'];
$l = smthumb($size);
$smiley['lw'] = $l['w'];
unset($smiley['id'], $smiley['directory']);
$data[$type['typeid']][$smileyid] = $smiley;
}
}
}
}
break;
case 'smileytypes':
while($type = $db->fetch_array($query)) {
$typeid = $type['typeid'];
unset($type['typeid']);
$squery = $db->query("SELECT COUNT(*) FROM {$tablepre}smilies WHERE type='smiley' AND code<>'' AND typeid='$typeid'");
if($db->result($squery, 0)) {
$data[$typeid] = $type;
}
}
break;
case 'icons':
while($icon = $db->fetch_array($query)) {
$data[$icon['id']] = $icon['url'];
}
break;
case (in_array($cachename, array('fields_required', 'fields_optional'))):
while($field = $db->fetch_array($query)) {
$choices = array();
if($field['selective']) {
foreach(explode("\n", $field['choices']) as $item) {
list($index, $choice) = explode('=', $item);
$choices[trim($index)] = trim($choice);
}
$field['choices'] = $choices;
} else {
unset($field['choices']);
}
$data['field_'.$field['fieldid']] = $field;
}
break;
case 'ipbanned':
if($db->num_rows($query)) {
$data['expiration'] = 0;
$data['regexp'] = $separator = '';
}
while($banned = $db->fetch_array($query)) {
$data['expiration'] = !$data['expiration'] || $banned['expiration'] < $data['expiration'] ? $banned['expiration'] : $data['expiration'];
$data['regexp'] .= $separator.
($banned['ip1'] == '-1' ? '\\d+\\.' : $banned['ip1'].'\\.').
($banned['ip2'] == '-1' ? '\\d+\\.' : $banned['ip2'].'\\.').
($banned['ip3'] == '-1' ? '\\d+\\.' : $banned['ip3'].'\\.').
($banned['ip4'] == '-1' ? '\\d+' : $banned['ip4']);
$separator = '|';
}
break;
case 'google':
$data = unserialize($db->result($query, 0));
$lr = $data['lang'] ? 'lang_'.$data['lang'] : '';
$jsdata = 'var google_host="'.$_SERVER['HTTP_HOST'].'";var google_charset="'.$charset.'";var google_hl="'.$data['lang'].'";var google_lr="'.$lr.'";';
$cachedir = DISCUZ_ROOT.'./forumdata/cache/';
if(@$fp = fopen($cachedir.'google_var.js', 'w')) {
fwrite($fp, $jsdata);
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
break;
case 'medals':
while($medal = $db->fetch_array($query)) {
$data[$medal['medalid']] = array('name' => $medal['name'], 'image' => $medal['image']);
}
break;
case 'magics':
while($magic = $db->fetch_array($query)) {
$data[$magic['magicid']]['identifier'] = $magic['identifier'];
$data[$magic['magicid']]['available'] = $magic['available'];
$data[$magic['magicid']]['name'] = $magic['name'];
$data[$magic['magicid']]['description'] = $magic['description'];
$data[$magic['magicid']]['weight'] = $magic['weight'];
$data[$magic['magicid']]['price'] = $magic['price'];
}
break;
case 'birthdays_index':
$bdaymembers = array();
while($bdaymember = $db->fetch_array($query)) {
$birthyear = intval($bdaymember['bday']);
$bdaymembers[] = '<a href="space.php?uid='.$bdaymember['uid'].'" target="_blank" '.($birthyear ? 'title="'.$bdaymember['bday'].'"' : '').'>'.$bdaymember['username'].'</a>';
}
$data['todaysbdays'] = implode(', ', $bdaymembers);
break;
case 'birthdays':
$data['uids'] = $comma = '';
$data['num'] = 0;
while($bdaymember = $db->fetch_array($query)) {
$data['uids'] .= $comma.$bdaymember['uid'];
$comma = ',';
$data['num'] ++;
}
break;
case 'modreasons':
$modreasons = $db->result($query, 0);
$modreasons = str_replace(array("\r\n", "\r"), array("\n", "\n"), $modreasons);
$data = explode("\n", trim($modreasons));
break;
case substr($cachename, 0, 5) == 'advs_':
$data = advertisement(substr($cachename, 5));
break;
case 'faqs':
while($faqs = $db->fetch_array($query)) {
$data[$faqs['identifier']]['id'] = $faqs['id'];
$data[$faqs['identifier']]['keyword'] = $faqs['keyword'];
}
break;
case 'secqaa':
$secqaanum = $db->result_first("SELECT COUNT(*) FROM {$tablepre}itempool");
$start_limit = $secqaanum <= 10 ? 0 : mt_rand(0, $secqaanum - 10);
$query = $db->query("SELECT question, answer FROM {$tablepre}itempool LIMIT $start_limit, 10");
while($secqaa = $db->fetch_array($query)) {
$secqaa['answer'] = md5($secqaa['answer']);
$data[] = $secqaa;
}
while(($secqaas = count($data)) < 10) {
$data[$secqaas] = $data[array_rand($data)];
}
break;
case 'supe_updateusers':
global $supe;
supe_dbconnect();
if($supe['status'] && $supe['maxupdateusers']) {
$query = $supe['db']->query("SELECT uid, username FROM {$supe[tablepre]}userspaces WHERE islock=0 ORDER BY lastpost DESC LIMIT $supe[maxupdateusers]", 'SILENT');
while($datarow = $supe['db']->fetch_array($query)) {
$data[$datarow['uid']] = $datarow;
}
}
break;
case 'supe_updateitems':
global $supe;
supe_dbconnect();
if($supe['status'] && $supe['items']['status']) {
$limit = $supe['items']['rows'] * $supe['items']['columns'];
switch($supe['items']['orderby']) {
case '1':
$orderby = 'viewnum';
break;
case '2':
$orderby = 'replynum';
break;
case '3':
$orderby = 'dateline';
break;
case '4':
$orderby = 'lastpost';
break;
default:
$orderby = 'itemid';
}
$supe['items']['hours'] = $supe['items']['hours'] > 0 ? $supe['items']['hours'] : 24;
$conditions = !in_array($orderby, array('dateline', 'lastpost')) ? 'WHERE folder=1 AND type<>\'news\' AND dateline >='.($timestamp - $supe['items']['hours'] * 3600) : 'WHERE folder=1 AND type<>\'news\'';
$query = $supe['db']->query("SELECT itemid, uid, username, type, subject FROM {$supe[tablepre]}spaceitems $conditions ORDER BY $orderby DESC LIMIT $limit", 'SILENT');
$itemtable = '';
$items = array();
include language('templates');
while($item = $supe['db']->fetch_array($query)) {
$typename = $language['supe_'.$item['type']];
$items[] = '<em>[<a href="'.$supe['siteurl'].'/?action-'.$item['type'].'" target="_blank">'.$typename.'</a>]</em> <cite><a href="'.$supe['siteurl'].'/?uid-'.$item['uid'].'" target="_blank">'.addcslashes(addslashes($item['username']), '\\\'').'</a></cite>: <a href="'.$supe['siteurl'].'/?action-viewspace-itemid-'.$item['itemid'].'.html" target="_blank">'.addcslashes(addslashes(cutstr($item['subject'], 35)), '\\\'').'</a>';
}
if($items) {
for($i = 0; $i < $limit; $i++) {
$itemtable .= '<li style="width: '.intval(100 / $supe['items']['columns']).'%;">'.(isset($items[$i]) ? $items[$i] : ' ').'</li>';
}
}
$data = $itemtable;
}
break;
case 'supe_updatecircles':
global $supe;
if($supe['status'] && $supe['circlestatus'] && $supe['updatecircles']) {
supe_dbconnect();
$query = $supe['db']->query("SELECT gid, uid, username, groupname, logo, usernum, lastpost FROM {$supe['tablepre']}groups WHERE catid>0 AND flag=1 ORDER BY lastpost DESC LIMIT 8", 'SILENT');
while($datarow = $supe['db']->fetch_array($query)) {
$datarow['groupname'] = cutstr($datarow['groupname'], 30);
$data[] = $datarow;
}
}
break;
case substr($cachename, 0, 5) == 'tags_':
global $tagstatus, $hottags;
$tagnames = array();
if($tagstatus) {
if(substr($cachename, 5) == 'index') {
if($hottags) {
$tagary = array();
while($tagrow = $db->fetch_array($query)) {
$tagary[] = '<a href="tag.php?name='.rawurlencode($tagrow['tagname']).'" target="_blank">'.$tagrow['tagname'].'<em>('.$tagrow['total'].')</em></a>';
}
$data = implode(' ', $tagary);
} else {
$data = '';
}
} else {
$data[0] = $data[1] = array();
while($tagrow = $db->fetch_array($query)) {
$data[0][] = $tagrow['tagname'];
$data[1][] = rawurlencode($tagrow['tagname']);
}
$data[0] = '[\''.implode('\',\'', $data[0]).'\']';
$data[1] = '[\''.implode('\',\'', $data[1]).'\']';
}
}
break;
default:
while($datarow = $db->fetch_array($query)) {
$data[] = $datarow;
}
}
$dbcachename = $cachename;
$cachename = in_array(substr($cachename, 0, 5), array('advs_', 'tags_')) ? substr($cachename, 0, 4) : $cachename;
$curdata = "\$_DCACHE['$cachename'] = ".arrayeval($data).";\n\n";
$db->query("REPLACE INTO {$tablepre}caches (cachename, type, dateline, data) VALUES ('$dbcachename', '1', '$timestamp', '".addslashes($curdata)."')");
return $curdata;
}
function getcachevars($data, $type = 'VAR') {
$evaluate = '';
foreach($data as $key => $val) {
if(!preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", $key)) {
continue;
}
if(is_array($val)) {
$evaluate .= "\$$key = ".arrayeval($val).";\n";
} else {
$val = addcslashes($val, '\'\\');
$evaluate .= $type == 'VAR' ? "\$$key = '$val';\n" : "define('".strtoupper($key)."', '$val');\n";
}
}
return $evaluate;
}
function advertisement($range) {
global $db, $tablepre, $timestamp;
$advs = array();
$query = $db->query("SELECT * FROM {$tablepre}advertisements WHERE available>'0' AND starttime<='$timestamp' ORDER BY displayorder");
if($db->num_rows($query)) {
while($adv = $db->fetch_array($query)) {
if(in_array($adv['type'], array('footerbanner', 'thread'))) {
$parameters = unserialize($adv['parameters']);
$position = isset($parameters['position']) && in_array($parameters['position'], array(2, 3)) ? $parameters['position'] : 1;
$type = $adv['type'].$position;
} else {
$type = $adv['type'];
}
$adv['targets'] = in_array($adv['targets'], array('', 'all')) ? ($type == 'text' ? 'forum' : (substr($type, 0, 6) == 'thread' ? 'forum' : 'all')) : $adv['targets'];
foreach(explode("\t", $adv['targets']) as $target) {
$target = $target == '0' ? 'index' : (in_array($target, array('all', 'index', 'forumdisplay', 'viewthread', 'register', 'redirect', 'archiver')) ? $target : ($target == 'forum' ? 'forum_all' : 'forum_'.$target));
if((($range == 'forumdisplay' && !in_array($adv['type'], array('thread', 'interthread'))) || $range == 'viewthread') && substr($target, 0, 6) == 'forum_') {
if($adv['type'] == 'thread') {
foreach(isset($parameters['displayorder']) ? explode("\t", $parameters['displayorder']) : array('0') as $postcount) {
$advs['type'][$type.'_'.$postcount][$target][] = $adv['advid'];
}
} else {
$advs['type'][$type][$target][] = $adv['advid'];
}
$advs['items'][$adv['advid']] = $adv['code'];
} elseif($range == 'all' && in_array($target, array('all', 'redirect'))) {
$advs[$target]['type'][$type][] = $adv['advid'];
$advs[$target]['items'][$adv['advid']] = $adv['code'];
} elseif($range == 'index' && $type == 'intercat') {
$parameters = unserialize($adv['parameters']);
foreach(is_array($parameters['position']) ? $parameters['position'] : array('0') as $position) {
$advs['type'][$type][$position][] = $adv['advid'];
$advs['items'][$adv['advid']] = $adv['code'];
}
} elseif($target == $range || ($range == 'index' && $target == 'forum_all')) {
$advs['type'][$type][] = $adv['advid'];
$advs['items'][$adv['advid']] = $adv['code'];
}
}
}
}
return $advs;
}
function pluginmodulecmp($a, $b) {
return $a['displayorder'] > $b['displayorder'] ? 1 : -1;
}
function smthumb($size, $smthumb = 50) {
if($size[0] <= $smthumb && $size[1] <= $smthumb) {
return array('w' => $size[0], 'h' => $size[1]);
}
$sm = array();
$x_ratio = $smthumb / $size[0];
$y_ratio = $smthumb / $size[1];
if(($x_ratio * $size[1]) < $smthumb) {
$sm['h'] = ceil($x_ratio * $size[1]);
$sm['w'] = $smthumb;
} else {
$sm['w'] = ceil($y_ratio * $size[0]);
$sm['h'] = $smthumb;
}
return $sm;
}
function arrayeval($array, $level = 0) {
if(!is_array($array)) {
return "'".$array."'";
}
if(is_array($array) && function_exists('var_export')) {
return var_export($array, true);
}
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "\t";
}
$evaluate = "Array\n$space(\n";
$comma = $space;
if(is_array($array)) {
foreach($array as $key => $val) {
$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
$val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
} else {
$evaluate .= "$comma$key => $val";
}
$comma = ",\n$space";
}
}
$evaluate .= "\n$space)";
return $evaluate;
}
?> | zyyhong | trunk/jiaju001/bbs/include/cache.func.php | PHP | asf20 | 65,548 |
<html>
<head>
<title>Service Unavailable</title>
</head>
<body bgcolor="#FFFFFF">
<table cellpadding="0" cellspacing="0" border="0" width="700" align="center" height="85%">
<tr align="center" valign="middle">
<td>
<table cellpadding="10" cellspacing="0" border="0" width="80%" align="center" style="font-family: Verdana, Tahoma; color: #666666; font-size: 11px">
<tr>
<td valign="middle" align="center" bgcolor="#EBEBEB">
<br /><b style="font-size: 16px">Service Unavailable</b>
<br /><br />The server can't process your request due to a high load, please try again later.
<br /><br />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html> | zyyhong | trunk/jiaju001/bbs/include/serverbusy.htm | HTML | asf20 | 728 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic.func.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function checkmagicperm($perms, $id) {
$id = $id ? intval($id) : '';
if(!strexists("\t".trim($perms)."\t", "\t".trim($id)."\t") && $perms) {
showmessage('magics_target_nopermission');
}
}
function getmagic($magicid, $magicnum, $weight, $totalweight, $uid, $maxmagicsweight) {
global $db, $tablepre;
if($weight + $totalweight > $maxmagicsweight) {
showmessage('magics_weight_range_invalid');
} else {
$query = $db->query("SELECT magicid FROM {$tablepre}membermagics WHERE magicid='$magicid' AND uid='$uid'");
if($db->num_rows($query)) {
$db->query("UPDATE {$tablepre}membermagics SET num=num+'$magicnum' WHERE magicid='$magicid' AND uid='$uid'");
} else {
$db->query("INSERT INTO {$tablepre}membermagics (uid, magicid, num) VALUES ('$uid', '$magicid', '$magicnum')");
}
}
}
function getmagicweight($uid, $magicarray) {
global $db, $tablepre;
$totalweight = 0;
$query = $db->query("SELECT magicid, num FROM {$tablepre}membermagics WHERE uid='$uid'");
while($magic = $db->fetch_array($query)) {
$totalweight += $magicarray[$magic['magicid']]['weight'] * $magic['num'];
}
return $totalweight;
}
function getpostinfo($id, $type, $colsarray = '') {
global $db, $tablepre;
$sql = $comma = '';
$type = in_array($type, array('tid', 'pid')) && !empty($type) ? $type : 'tid';
$cols = '*';
if(!empty($colsarray) && is_array($colsarray)) {
$cols = '';
foreach($colsarray as $val) {
$cols .= $comma.$val;
$comma = ', ';
}
}
switch($type) {
case 'tid': $sql = "SELECT $cols FROM {$tablepre}threads WHERE tid='$id' AND digest>='0' AND displayorder>='0'"; break;
case 'pid': $sql = "SELECT $cols FROM {$tablepre}posts p, {$tablepre}threads t WHERE pid='$id' AND invisible='0' AND t.tid=p.tid AND digest>=0"; break;
}
if($sql) {
$query = $db->query($sql);
if(!$post = $db->fetch_array($query)) {
showmessage('magics_target_nonexistence');
} else {
return daddslashes($post, 1);
}
}
}
function getuserinfo($username, $colsarray = '') {
global $db, $tablepre;
$cols = '*';
if(!empty($colsarray) && is_array($colsarray)) {
$cols = '';
foreach($colsarray as $val) {
$cols .= $comma.$val;
$comma = ', ';
}
}
$query = $db->query("SELECT $cols FROM {$tablepre}members WHERE username='$username'");
if(!$member = $db->fetch_array($query)) {
showmessage('magics_target_nonexistence');
} else {
return daddslashes($member, 1);
}
}
function givemagic($username, $magicid, $magicnum, $totalnum, $totalprice) {
global $db, $tablepre, $discuz_uid, $discuz_user, $creditstrans, $magicarray;
$query = $db->query("SELECT m.uid, m.username, u.maxmagicsweight FROM {$tablepre}members m LEFT JOIN {$tablepre}usergroups u ON u.groupid=m.groupid WHERE m.username='$username'");
if(!$member = $db->fetch_array($query)) {
showmessage('magics_target_nonexistence');
} elseif($member['uid'] == $discuz_uid) {
showmessage('magics_give_myself');
}
$totalweight = getmagicweight($member['uid'], $magicarray);
$magicweight = $magicarray[$magicid]['weight'] * $magicnum;
getmagic($magicid, $magicnum, $magicweight, $totalweight, $member['uid'], $member['maxmagicsweight']);
sendpm($member['uid'], 'magics_receive_subject', 'magics_receive_message');
updatemagiclog($magicid, '3', $magicnum, $magicarray[$magicid]['price'], '0', '0', $member['uid']);
if(empty($totalprice)) {
usemagic($magicid, $totalnum, $magicnum);
showmessage('magics_give_succeed', 'magic.php?action=user');
}
}
function magicrand($odds) {
$odds = $odds > 100 ? 100 : intval($odds);
$odds = $odds < 0 ? 0 : intval($odds);
if(rand(1, 100) > 100 - $odds) {
return TRUE;
} else {
return FALSE;
}
}
function marketmagicnum($magicid, $marketnum, $magicnum) {
global $db, $tablepre;
if($magicnum == $marketnum) {
$db->query("DELETE FROM {$tablepre}magicmarket WHERE mid='$magicid'");
} else {
$db->query("UPDATE {$tablepre}magicmarket SET num=num+(-'$magicnum') WHERE mid='$magicid'");
}
}
function magicthreadmod($tid) {
global $db, $tablepre;
$query = $db->query("SELECT * FROM {$tablepre}threadsmod WHERE magicid='0' AND tid='$tid'");
while($threadmod = $db->fetch_array($query)) {
if(!$threadmod['magicid'] && in_array($threadmod['action'], array('CLS', 'ECL', 'STK', 'EST', 'HLT', 'EHL'))) {
showmessage('magics_mod_forbidden');
}
}
}
function magicshowsetting($setname, $varname, $value, $type = 'radio', $width = '20%') {
$check = array();
$comment = $GLOBALS['lang'][$setname.'_comment'];
$aligntop = $type == "textarea" ? "valign=\"top\"" : NULL;
echo "<tr><th>".(isset($GLOBALS['lang'][$setname]) ? $GLOBALS['lang'][$setname] : $setname).''.($comment ? '<br /><span class="smalltxt">'.$comment.'</span>' : NULL).'</th>'.
'<th>';
if($type == 'radio') {
$value ? $check['true'] = 'checked="checked"' : $check['false'] = 'checked="checked"';
echo "<input type=\"radio\" name=\"$varname\" value=\"1\" $check[true] /> {$GLOBALS[lang][yes]} \n".
"<input type=\"radio\" name=\"$varname\" value=\"0\" $check[false] /> {$GLOBALS[lang][no]}\n";
} elseif($type == 'text') {
echo "<input type=\"$type\" size=\"30\" name=\"$varname\" value=\"".dhtmlspecialchars($value)."\" />\n";
} else {
echo $type;
}
echo '</th></tr>';
}
function magicshowtips($tips, $title) {
echo '<div class="mainbox"><h1>'.$title.'</h1>'.
'<table summary="" cellspacing="0" cellpadding="0"><tr><td>'.$tips.'</td></tr></table></div>';
}
function magicshowtype($name, $type = '') {
$name = $GLOBALS['lang'][$name] ? $GLOBALS['lang'][$name] : $name;
if($type != 'bottom') {
if(!$type) {
echo '</table></div><br /><br />';
}
if(!$type || $type == 'top') {
?>
<div class="mainbox">
<h1><?=$name?></h1><table summary="" cellspacing="0" cellpadding="0">
<?
}
} else {
echo '</table></div>';
}
}
function usemagic($magicid, $totalnum, $num = 1) {
global $db, $tablepre, $discuz_uid;
if($totalnum == $num) {
$db->query("DELETE FROM {$tablepre}membermagics WHERE uid='$discuz_uid' AND magicid='$magicid'");
} else {
$db->query("UPDATE {$tablepre}membermagics SET num=num+(-'$num') WHERE magicid='$magicid' AND uid='$discuz_uid'");
}
}
function updatemagicthreadlog($tid, $magicid, $action, $expiration, $extra = 0) {
global $db, $tablepre, $timestamp, $discuz_uid, $discuz_user;
$discuz_user = !$extra ? $discuz_user : '';
$db->query("REPLACE INTO {$tablepre}threadsmod (tid, uid, magicid, username, dateline, expiration, action, status)
VALUES ('$tid', '$discuz_uid', '$magicid', '$discuz_user', '$timestamp', '$expiration', '$action', '1')", 'UNBUFFERED');
}
function updatemagiclog($magicid, $action, $amount, $price, $targettid = 0, $targetpid = 0, $targetuid = 0) {
global $db, $tablepre, $timestamp, $discuz_uid, $discuz_user;
$db->query("INSERT INTO {$tablepre}magiclog (uid, magicid, action, dateline, amount, price, targettid, targetpid, targetuid)
VALUES ('$discuz_uid', '$magicid', '$action', '$timestamp', '$amount', '$price','$targettid', '$targetpid', '$targetuid')", 'UNBUFFERED');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic.func.php | PHP | asf20 | 7,477 |
<?php
/*
[Discuz!] (C)2001-2006 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewpro.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$allowviewpro = $discuz_uid && ($uid == $discuz_uid || $username == $discuz_user) ? 1 : $allowviewpro;
if(!$allowviewpro) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
require_once DISCUZ_ROOT.'./include/discuzcode.func.php';
@include_once DISCUZ_ROOT.'./forumdata/cache/cache_viewpro.php';
@extract($_DCACHE['custominfo']);
$discuz_action = 61;
if($oltimespan) {
$oltimeadd1 = ', o.thismonth AS thismonthol, o.total AS totalol';
$oltimeadd2 = "LEFT JOIN {$tablepre}onlinetime o ON o.uid=m.uid";
} else {
$oltimeadd1 = $oltimeadd2 = '';
}
$query = $db->query("SELECT m.*, mf.*, u.grouptitle, u.type, u.creditshigher, u.creditslower, u.readaccess,
u.color AS groupcolor, u.stars AS groupstars, u.allownickname, u.allowuseblog, r.ranktitle,
r.color AS rankcolor, r.stars AS rankstars $oltimeadd1
FROM {$tablepre}members m
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
LEFT JOIN {$tablepre}usergroups u ON u.groupid=m.groupid
LEFT JOIN {$tablepre}ranks r ON m.posts>=r.postshigher
$oltimeadd2
WHERE ".($uid ? "m.uid='$uid'" : "m.username='$username'")."ORDER BY r.postshigher DESC LIMIT 1");
if(!$member = $db->fetch_array($query)) {
showmessage('member_nonexistence');
}
$uid = $member['uid'];
$member['online'] = $db->result($db->query("SELECT lastactivity FROM {$tablepre}sessions WHERE uid='$uid' AND invisible='0'"), 0);
if($member['groupid'] != ($member['groupidnew'] = getgroupid($member['uid'], $member, $member))) {
$query = $db->query("SELECT groupid, grouptitle, type, creditshigher, creditslower, color AS groupcolor,
stars AS groupstars, allownickname, allowuseblog
FROM {$tablepre}usergroups WHERE groupid='$member[groupidnew]'");
$member = array_merge($member, $db->fetch_array($query));
}
$viewspace = !$inajax && $spacestatus && (!$supe['status'] || !$member['xspacestatus']) && !in_array($member['groupid'], array(4, 5, 6));
if($viewspace) {
include_once DISCUZ_ROOT.'./include/space.func.php';
if(!$spacesettings = getspacesettings($member['uid'])) {
dheader("location: $boardurl");
}
include_once language('spaces');
$modulelist = explode('][', ']'.str_replace("\t", '', $spacesettings['layout']).'[');
foreach($modulelist as $module) {
if(array_key_exists($module, $listmodule)) {
$menulist[$listmodule[$module]] = $module;
}
}
ksort($menulist);
}
$modforums = $comma = '';
if($member['adminid'] > 0) {
$query = $db->query("SELECT m.fid, f.name, f.type FROM {$tablepre}moderators m, {$tablepre}forums f WHERE m.uid='$member[uid]' AND m.inherited='0' AND f.fid=m.fid");
while($forum = $db->fetch_array($query)) {
$modforums .= "$comma<a href=\"".($forum['type'] == 'group' ? "$indexname?gid=" : "forumdisplay.php?fid=")."$forum[fid]\">$forum[name]</a>";
$comma = ', ';
}
}
$member['groupterms'] = $member['groupterms'] ? unserialize($member['groupterms']) : array();
$extgrouplist = array();
if($member['extgroupids']) {
$temp = array_map('intval', explode("\t", $member['extgroupids']));
if($temp = implodeids($temp)) {
$query = $db->query("SELECT groupid, grouptitle FROM {$tablepre}usergroups WHERE groupid IN ($temp)");
while($group = $db->fetch_array($query)) {
$extgrouplist[] = array('title' => $group['grouptitle'], 'expiry' => (isset($member['groupterms']['ext'][$group['groupid']]) ? gmdate($dateformat, $member['groupterms']['ext'][$group['groupid']] + $timeoffset * 3600) : ''));
}
}
}
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}posts");
@$percent = round($member['posts'] * 100 / $db->result($query, 0), 2);
$postperday = $timestamp - $member['regdate'] > 86400 ? round(86400 * $member['posts'] / ($timestamp - $member['regdate']), 2) : $member['posts'];
$member['grouptitle'] = $member['groupcolor'] ? '<font color="'.$member['groupcolor'].'">'.$member['grouptitle'].'</font>' : $member['grouptitle'];
$member['ranktitle'] = $member['rankcolor'] ? '<font color="'.$member['rankcolor'].'">'.$member['ranktitle'].'</font>' : $member['ranktitle'];
if($oltimespan) {
$member['totalol'] = round($member['totalol'] / 60, 2);
$member['thismonthol'] = gmdate('Yn', $member['lastactivity']) == gmdate('Yn', $timestamp) ? round($member['thismonthol'] / 60, 2) : 0;
}
$member['usernameenc'] = rawurlencode($member['username']);
$member['regdate'] = gmdate($dateformat, $member['regdate'] + $timeoffset * 3600);
$member['email'] = emailconv($member['email']);
list($member['bio'], $member['biotrade']) = explode("\t\t\t", $member['bio']);
$member['lastvisit'] = gmdate("$dateformat $timeformat", $member['lastvisit'] + ($timeoffset * 3600));
$member['lastpost'] = $member['lastpost'] ? gmdate("$dateformat $timeformat", $member['lastpost'] + ($timeoffset * 3600)) : 'x';
$member['lastdate'] = gmdate($dateformat, $member['lastactivity'] + ($timeoffset * 3600));
$member['taobaoas'] = addslashes($member['taobao']);
$member['olupgrade'] = $member['totalol'] ? 20 - $member['totalol'] % 20 : 20;
list($year, $month, $day) = explode('-', $member['bday']);
$member['bday'] = intval($year) ? $dateformat : preg_replace("/[^nj]*[Yy][^nj]*/", '', $dateformat);
$member['bday'] = str_replace('n', $month, $member['bday']);
$member['bday'] = str_replace('j', $day, $member['bday']);
$member['bday'] = str_replace('Y', $year, $member['bday']);
$member['bday'] = str_replace('y', substr($year, 2, 4), $member['bday']);
if($member['groupexpiry'] && isset($member['groupterms']['main']['time'])) {
$member['maingroupexpiry'] = gmdate($dateformat, $member['groupterms']['main']['time'] + $timeoffset * 3600);
}
if($allowviewip && !($adminid == 2 && $member['adminid'] == 1) && !($adminid == 3 && ($member['adminid'] == 1 || $member['adminid'] == 2))) {
require_once DISCUZ_ROOT.'./include/misc.func.php';
$member['regiplocation'] = convertip($member['regip']);
$member['lastiplocation'] = convertip($member['lastip']);
} else {
$allowviewip = 0;
}
$_DCACHE['fields_required'] = is_array($_DCACHE['fields_required']) ? $_DCACHE['fields_required'] : array();
$_DCACHE['fields_optional'] = is_array($_DCACHE['fields_optional']) ? $_DCACHE['fields_optional'] : array();
foreach(array_merge($_DCACHE['fields_required'], $_DCACHE['fields_optional']) as $field) {
if(!$field['invisible'] || $adminid == 1 || $member['uid'] == $discuz_uid) {
$_DCACHE['fields'][] = $field;
}
}
unset($_DCACHE['fields_required'], $_DCACHE['fields_optional']);
if($member['medals']) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_medals.php';
foreach($member['medals'] = explode("\t", $member['medals']) as $key => $medalid) {
if(isset($_DCACHE['medals'][$medalid])) {
$member['medals'][$key] = $_DCACHE['medals'][$medalid];
} else {
unset($member['medals'][$key]);
}
}
}
$member['buyerrank'] = 0;
if($member['buyercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($member['buyercredit'] <= $credit) {
$member['buyerrank'] = $level;
break;
}
}
}
$member['sellerrank'] = 0;
if($member['sellercredit']){
foreach($ec_credit['rank'] AS $level => $credit) {
if($member['sellercredit'] <= $credit) {
$member['sellerrank'] = $level;
break;
}
}
}
if($inajax) {
$post = $member;unset($member);
include template('space_viewpro');
} elseif($viewspace) {
include template('space');
} else {
include template('viewpro_classic');
}
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewpro.inc.php | PHP | asf20 | 7,716 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: attachment.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function attachtype($type, $returnval = 'html') {
static $attachicons = array(
1 => 'common.gif',
2 => 'binary.gif',
3 => 'zip.gif',
4 => 'rar.gif',
5 => 'msoffice.gif',
6 => 'text.gif',
7 => 'html.gif',
8 => 'real.gif',
9 => 'av.gif',
10 => 'flash.gif',
11 => 'image.gif',
12 => 'pdf.gif',
13 => 'torrent.gif'
);
if(is_numeric($type)) {
$typeid = $type;
} else {
if(preg_match("/bittorrent|^torrent\t/", $type)) {
$typeid = 13;
} elseif(preg_match("/pdf|^pdf\t/", $type)) {
$typeid = 12;
} elseif(preg_match("/image|^(jpg|gif|png|bmp)\t/", $type)) {
$typeid = 11;
} elseif(preg_match("/flash|^(swf|fla|swi)\t/", $type)) {
$typeid = 10;
} elseif(preg_match("/audio|video|^(wav|mid|mp3|m3u|wma|asf|asx|vqf|mpg|mpeg|avi|wmv)\t/", $type)) {
$typeid = 9;
} elseif(preg_match("/real|^(ra|rm|rv)\t/", $type)) {
$typeid = 8;
} elseif(preg_match("/htm|^(php|js|pl|cgi|asp)\t/", $type)) {
$typeid = 7;
} elseif(preg_match("/text|^(txt|rtf|wri|chm)\t/", $type)) {
$typeid = 6;
} elseif(preg_match("/word|powerpoint|^(doc|ppt)\t/", $type)) {
$typeid = 5;
} elseif(preg_match("/^rar\t/", $type)) {
$typeid = 4;
} elseif(preg_match("/compressed|^(zip|arj|arc|cab|lzh|lha|tar|gz)\t/", $type)) {
$typeid = 3;
} elseif(preg_match("/octet-stream|^(exe|com|bat|dll)\t/", $type)) {
$typeid = 2;
} elseif($type) {
$typeid = 1;
} else {
$typeid = 0;
}
}
if($returnval == 'html') {
return '<img src="images/attachicons/'.$attachicons[$typeid].'" border="0" class="absmiddle" alt="" />';
} elseif($returnval == 'id') {
return $typeid;
}
}
function sizecount($filesize) {
if($filesize >= 1073741824) {
$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
} elseif($filesize >= 1048576) {
$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
} elseif($filesize >= 1024) {
$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
} else {
$filesize = $filesize . ' Bytes';
}
return $filesize;
}
function parseattach($attachpids, $attachtags, &$postlist, $showimages = 1, $skipaids = array()) {
global $db, $tablepre, $discuz_uid, $readaccess, $attachlist, $attachimgpost, $maxchargespan, $timestamp, $forum, $ftp, $attachurl, $dateformat, $timeformat, $timeoffset, $hideattach, $thread, $tradesaids, $trades, $exthtml, $tagstatus;
$query = $db->query("SELECT a.*, ap.aid AS payed FROM {$tablepre}attachments a LEFT JOIN {$tablepre}attachpaymentlog ap ON ap.aid=a.aid AND ap.uid='$discuz_uid' WHERE a.pid IN ($attachpids)");
if($db->num_rows($query)) {
while($attach = $db->fetch_array($query)) {
$exthtml = '';
if($skipaids && in_array($attach['aid'], $skipaids)) {
continue;
}
$attached = 0;
$extension = strtolower(fileext($attach['filename']));
$attach['attachicon'] = attachtype($extension."\t".$attach['filetype']);
$attach['attachsize'] = sizecount($attach['filesize']);
$attach['attachimg'] = $showimages && $attachimgpost && $attach['isimage'] && (!$attach['readperm'] || $readaccess >= $attach['readperm']) ? 1 : 0;
if($attach['price']) {
if($maxchargespan && $timestamp - $attach['dateline'] >= $maxchargespan * 3600) {
$db->query("UPDATE {$tablepre}attachments SET price='0' WHERE aid='$attach[aid]'");
$attach['price'] = 0;
} else {
if(!$discuz_uid || (!$forum['ismoderator'] && $attach['uid'] != $discuz_uid && !$attach['payed'])) {
$attach['unpayed'] = 1;
}
}
}
$attach['payed'] = $attach['payed'] || $forum['ismoderator'] || $attach['uid'] == $discuz_uid ? 1 : 0;
$attach['url'] = $attach['remote'] ? $ftp['attachurl'] : $attachurl;
$attach['dateline'] = gmdate("$dateformat $timeformat", $attach['dateline'] + $timeoffset * 3600);
$postlist[$attach['pid']]['attachments'][$attach['aid']] = $attach;
if(is_array($attachtags[$attach['pid']]) && in_array($attach['aid'], $attachtags[$attach['pid']])) {
$findattach[$attach['pid']][] = "/\[attach\]$attach[aid]\[\/attach\]/i";
$replaceattach[$attach['pid']][] = $hideattach[$attach['pid']] ? '[attach]***[/attach]' : attachtag($attach['pid'], $attach['aid'], $postlist);
$attached = 1;
}
if(!$attached || $attach['unpayed']) {
$postlist[$attach['pid']]['attachlist'] .= attachlist($attach);
}
}
foreach($attachtags as $pid => $aids) {
if($findattach[$pid]) {
$postlist[$pid]['message'] = preg_replace($findattach[$pid], $replaceattach[$pid], $postlist[$pid]['message'], 1);
$postlist[$pid]['message'] = preg_replace($findattach[$pid], '', $postlist[$pid]['message']);
}
}
} else {
$db->query("UPDATE {$tablepre}posts SET attachment='0' WHERE pid IN ($attachpids)", 'UNBUFFERED');
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/attachment.func.php | PHP | asf20 | 5,094 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: newreply.inc.php 10449 2007-08-31 03:05:08Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$discuz_action = 12;
if($special == 5) {
$query = $db->query("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
$debate = array_merge($thread, $db->fetch_array($query));
$standquery = $db->query("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$discuz_uid' AND stand<>'0' ORDER BY dateline LIMIT 1");
$firststand = $db->result($standquery, 0);
if($debate['endtime'] && $debate['endtime'] < $timestamp) {
showmessage('debate_end');
}
}
if($iscircle && ($sgid = $thread['sgid'])) {
supe_dbconnect();
$query = $supe['db']->query("SELECT g.ispublic, g.allowshare, g.password, g.groupname, gf.headerimage, gf.css FROM {$supe[tablepre]}groups g, {$supe[tablepre]}groupfields gf WHERE g.gid='$sgid' AND g.flag=1 AND g.gid=gf.gid", 'SILENT');
$circle = $supe['db']->fetch_array($query);
$incircle = $discuz_uid ? $supe['db']->result($supe['db']->query("SELECT COUNT(*) FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND gid='$sgid' AND flag>0", 'SILENT'), 0) : 0;
if(!$incircle && !($circle['allowshare'] && ($circle['ispublic'] == 1 || ($circle['ispublic'] == 2 && $circle['password'] == $_DCOOKIE['gidpw'.$gid])))) {
showmessage('circle_nopermission');
}
}
if(!$discuz_uid && !((!$forum['replyperm'] && $allowreply) || ($forum['replyperm'] && forumperm($forum['replyperm'])))) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(empty($forum['allowreply'])) {
if(!$forum['replyperm'] && !$allowreply) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['replyperm'] && !forumperm($forum['replyperm'])) {
showmessage('post_forum_newreply_nopermission', NULL, 'HALTED');
}
}
if(empty($thread)) {
showmessage('thread_nonexistence');
} elseif($thread['price'] > 0 && $thread['special'] == 0 && !$discuz_uid) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
checklowerlimit($replycredits);
if(!supe_submitcheck() && !submitcheck('replysubmit', 0, $seccodecheck, $secqaacheck)) {
if($thread['special'] == 2 && ((!isset($addtrade) || $thread['authorid'] != $discuz_uid) && !$tradenum = $db->result($db->query("SELECT count(*) FROM {$tablepre}trades WHERE tid='$tid'"), 0))) {
showmessage('trade_newreply_nopermission', NULL, 'HALTED');
}
include_once language('misc');
if(isset($repquote) && (!$thread['price'] || $thread['special'])) {
$query = $db->query("SELECT tid, fid, author, authorid, message, useip, dateline, anonymous, status FROM {$tablepre}posts WHERE pid='$repquote' AND invisible='0'");
$thaquote = $db->fetch_array($query);
if($thaquote['tid'] != $tid) {
showmessage('undefined_action', NULL, 'HALTED');
}
$quotefid = $thaquote['fid'];
$message = $thaquote['message'];
if($bannedmessages && $thaquote['authorid']) {
$query = $db->query("SELECT groupid FROM {$tablepre}members WHERE uid='$thaquote[authorid]'");
$author = $db->fetch_array($query);
if(!$author['groupid'] || $author['groupid'] == 4 || $author['groupid'] == 5) {
$message = $language['post_banned'];
} elseif($thaquote['status']) {
$message = $language['post_single_banned'];
}
}
$time = gmdate("$dateformat $timeformat", $thaquote['dateline'] + ($timeoffset * 3600));
$bbcodes = 'b|i|u|color|size|font|align|list|indent|url|email|code|free|table|tr|td|img|swf|attach|payto|float'.($_DCACHE['bbcodes_display'] ? '|'.implode('|', array_keys($_DCACHE['bbcodes_display'])) : '');
$message = cutstr(strip_tags(preg_replace(array(
"/\[hide=?\d*\](.+?)\[\/hide\]/is",
"/\[quote](.*)\[\/quote]/siU",
$language['post_edit_regexp'],
"/\[($bbcodes)=?.*\]/iU",
"/\[\/($bbcodes)\]/i",
), array(
"[b]$language[post_hidden][/b]",
'',
'',
'',
''
), $message)), 200);
$thaquote['useip'] = substr($thaquote['useip'], 0, strrpos($thaquote['useip'], '.')).'.x';
if($thaquote['author'] && $thaquote['anonymous']) {
$thaquote['author'] = '[i]Anonymous[/i]';
} elseif(!$thaquote['author']) {
$thaquote['author'] = '[i]Guest[/i] from '.$thaquote['useip'];
} else {
$thaquote['author'] = '[i]'.$thaquote['author'].'[/i]';
}
eval("\$language['post_reply_quote'] = \"$language[post_reply_quote]\";");
$message = "[quote]$language[post_reply_quote] [url={$boardurl}redirect.php?goto=findpost&pid=$repquote&ptid=$tid][img]{$boardurl}images/common/back.gif[/img][/url]\n$message [/quote]\n";
}
if(isset($addtrade) && $thread['special'] == 2 && $allowposttrade && $thread['authorid'] == $discuz_uid) {
$expiration_7days = date('Y-m-d', $timestamp + 86400 * 7);
$expiration_14days = date('Y-m-d', $timestamp + 86400 * 14);
$trade['expiration'] = $expiration_month = date('Y-m-d', mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
$expiration_3months = date('Y-m-d', mktime(0, 0, 0, date('m')+3, date('d'), date('Y')));
$expiration_halfyear = date('Y-m-d', mktime(0, 0, 0, date('m')+6, date('d'), date('Y')));
$expiration_year = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')+1));
}
if($thread['replies'] <= $ppp) {
$postlist = array();
$query = $db->query("SELECT p.* ".($bannedmessages ? ', m.groupid ' : '').
"FROM {$tablepre}posts p ".($bannedmessages ? "LEFT JOIN {$tablepre}members m ON p.authorid=m.uid " : '').
"WHERE p.tid='$tid' AND p.invisible='0' ".($thread['price'] > 0 && $thread['special'] == 0 ? 'AND p.first = 0' : '')." ORDER BY p.dateline DESC");
while($post = $db->fetch_array($query)) {
$post['dateline'] = gmdate("$dateformat $timeformat", $post['dateline'] + $timeoffset * 3600);
if($bannedmessages && ($post['authorid'] && (!$post['groupid'] || $post['groupid'] == 4 || $post['groupid'] == 5))) {
$post['message'] = $language['post_banned'];
} elseif($post['status']) {
$post['message'] = $language['post_single_banned'];
} else {
$post['message'] = preg_replace("/\[hide=?\d*\](.+?)\[\/hide\]/is", "[b]$language[post_hidden][/b]", $post['message']);
$post['message'] = discuzcode($post['message'], $post['smileyoff'], $post['bbcodeoff'], $post['htmlon'] & 1, $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'], $forum['allowhtml'], $forum['jammer']);
}
$postlist[] = $post;
}
}
if($special == 2 && isset($addtrade) && $thread['authorid'] == $discuz_uid) {
$tradetypeselect = '';
$forum['tradetypes'] = $forum['tradetypes'] == '' ? -1 : unserialize($forum['tradetypes']);
if($tradetypes && !empty($forum['tradetypes'])) {
$tradetypeselect = '<select name="tradetypeid" onchange="ajaxget(\'post.php?action=threadtypes&tradetype=yes&typeid=\'+this.options[this.selectedIndex].value+\'&sid='.$sid.'\', \'threadtypes\', \'threadtypeswait\')"><option value="0"> </option>';
foreach($tradetypes as $typeid => $name) {
if($forum['tradetypes'] == -1 || @in_array($typeid, $forum['tradetypes'])) {
$tradetypeselect .= '<option value="'.$typeid.'">'.strip_tags($name).'</option>';
}
}
$tradetypeselect .= '</select><span id="threadtypeswait"></span>';
}
include template('post_newreply_trade');
} else {
include template('post_newreply');
}
} else {
require_once DISCUZ_ROOT.'./include/forum.func.php';
if($subject == '' && $message == '') {
showmessage('post_sm_isnull');
} elseif($thread['closed'] && !$forum['ismoderator']) {
showmessage('post_thread_closed');
} elseif($post_autoclose = checkautoclose()) {
showmessage($post_autoclose);
} elseif($post_invalid = checkpost()) {
showmessage($post_invalid);
} elseif(checkflood()) {
showmessage('post_flood_ctrl');
}
if(!empty($trade) && $thread['special'] == 2 && $allowposttrade) {
$item_price = floatval($item_price);
if(!trim($item_name)) {
showmessage('trade_please_name');
} elseif($maxtradeprice && ($mintradeprice > $item_price || $maxtradeprice < $item_price)) {
showmessage('trade_price_between');
} elseif(!$maxtradeprice && $mintradeprice > $item_price) {
showmessage('trade_price_more_than');
} elseif($item_number < 1) {
showmessage('tread_please_number');
}
threadtype_checkoption(1, 1);
$optiondata = array();
if($tradetypes && $typeoption && $checkoption) {
$optiondata = threadtype_validator($typeoption);
}
if(!empty($_FILES['tradeattach']['tmp_name'][0])) {
$_FILES['attach'] = array_merge_recursive((array)$_FILES['attach'], $_FILES['tradeattach']);
}
}
$attachnum = 0;
if($allowpostattach && !empty($_FILES['attach']) && is_array($_FILES['attach'])) {
foreach($_FILES['attach']['name'] as $attachname) {
if($attachname != '') {
$attachnum ++;
}
}
$attachnum && checklowerlimit($postattachcredits, $attachnum);
} else {
$_FILES = array();
}
$attachments = $attachnum ? attach_upload() : array();
$attachment = empty($attachments) ? 0 : 1;
$subscribed = $thread['subscribed'] && $timestamp - $thread['lastpost'] < 7776000;
$newsubscribed = !empty($emailnotify) && $discuz_uid;
if($subscribed && !$modnewreplies) {
$db->query("UPDATE {$tablepre}subscriptions SET lastpost='$timestamp' WHERE tid='$tid' AND uid<>'$discuz_uid'", 'UNBUFFERED');
}
if($newsubscribed) {
$db->query("REPLACE INTO {$tablepre}subscriptions (uid, tid, lastpost, lastnotify)
VALUES ('$discuz_uid', '$tid', '".($modnewreplies ? $thread['lastpost'] : $timestamp)."', '$timestamp')", 'UNBUFFERED');
}
$bbcodeoff = checkbbcodes($message, !empty($bbcodeoff));
$smileyoff = checksmilies($message, !empty($smileyoff));
$parseurloff = !empty($parseurloff);
$htmlon = $allowhtml && !empty($htmlon) ? 1 : 0;
$usesig = !empty($usesig) ? 1 : 0;
$isanonymous = $allowanonymous && !empty($isanonymous)? 1 : 0;
$author = empty($isanonymous) ? $discuz_user : '';
$pinvisible = $modnewreplies ? -2 : 0;
$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
VALUES ('$fid', '$tid', '0', '$discuz_user', '$discuz_uid', '$subject', '$timestamp', '$message', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '$attachment')");
$pid = $db->insert_id();
$db->query("REPLACE INTO {$tablepre}myposts (uid, tid, pid, position, dateline, special) VALUES ('$discuz_uid', '$tid', '$pid', '".($thread['replies'] + 1)."', '$timestamp', '$special')", 'UNBUFFERED');
if($special == 3 && $thread['authorid'] != $discuz_uid && $thread['price'] > 0) {
$query = $db->query("SELECT * FROM {$tablepre}rewardlog WHERE tid='$tid' AND answererid='$discuz_uid'");
if(!$rewardlog = $db->fetch_array($query)) {
$db->query("INSERT INTO {$tablepre}rewardlog (tid, answererid, dateline) VALUES ('$tid', '$discuz_uid', '$timestamp')");
}
} elseif($special == 5) {
$stand = intval($stand);
if(!$db->num_rows($standquery)) {
if($stand == 1) {
$db->query("UPDATE {$tablepre}debates SET affirmdebaters=affirmdebaters+1 WHERE tid='$tid'");
} elseif($stand == 2) {
$db->query("UPDATE {$tablepre}debates SET negadebaters=negadebaters+1 WHERE tid='$tid'");
}
} else {
$stand = $firststand;
}
if($stand == 1) {
$db->query("UPDATE {$tablepre}debates SET affirmreplies=affirmreplies+1 WHERE tid='$tid'");
} elseif($stand == 2) {
$db->query("UPDATE {$tablepre}debates SET negareplies=negareplies+1 WHERE tid='$tid'");
}
$db->query("INSERT INTO {$tablepre}debateposts (tid, pid, uid, dateline, stand, voters, voterids) VALUES ('$tid', '$pid', '$discuz_uid', '$timestamp', '$stand', '0', '')");
}
$tradeaid = 0;
if($attachment) {
$searcharray = $pregarray = $replacearray = array();
foreach($attachments as $key => $attach) {
$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, price, filename, description, filetype, filesize, attachment, downloads, isimage, uid, thumb, remote)
VALUES ('$tid', '$pid', '$timestamp', '$attach[perm]', '$attach[price]', '$attach[name]', '$attach[description]', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$attach[uid]', '$attach[thumb]', '$attach[remote]')");
$searcharray[] = '[local]'.$localid[$key].'[/local]';
$pregarray[] = '/\[localimg=(\d{1,3}),(\d{1,3})\]'.$localid[$key].'\[\/localimg\]/is';
$insertid = $db->insert_id();
$replacearray[] = '[attach]'.$insertid.'[/attach]';
}
if(!empty($trade) && $thread['special'] == 2 && !empty($_FILES['tradeattach']['tmp_name'][0])) {
$tradeaid = $insertid;
}
$message = str_replace($searcharray, $replacearray, preg_replace($pregarray, $replacearray, $message));
$db->query("UPDATE {$tablepre}posts SET message='$message' WHERE pid='$pid'");
updatecredits($discuz_uid, $postattachcredits, count($attachments));
}
$replymessage = 'post_reply_succeed';
if($special == 2 && $allowposttrade && $thread['authorid'] == $discuz_uid && !empty($trade) && !empty($item_name) && !empty($item_price)) {
if($tradetypes && $optiondata) {
foreach($optiondata as $optionid => $value) {
$db->query("INSERT INTO {$tablepre}tradeoptionvars (typeid, pid, optionid, value)
VALUES ('$tradetypeid', '$pid', '$optionid', '$value')");
}
}
require_once DISCUZ_ROOT.'./api/alipayapi.php';
trade_create(array(
'tid' => $tid,
'pid' => $pid,
'aid' => $tradeaid,
'typeid' => $tradetypeid,
'item_expiration' => $item_expiration,
'thread' => $thread,
'discuz_uid' => $discuz_uid,
'author' => $author,
'seller' => $seller,
'item_name' => $item_name,
'item_price' => $item_price,
'item_number' => $item_number,
'item_quality' => $item_quality,
'item_locus' => $item_locus,
'transport' => $transport,
'postage_mail' => $postage_mail,
'postage_express' => $postage_express,
'postage_ems' => $postage_ems,
'item_type' => $item_type,
'item_costprice' => $item_costprice
));
$replymessage = 'trade_add_succeed';
}
$forum['threadcaches'] && deletethreadcaches($tid);
if($modnewreplies) {
$db->query("UPDATE {$tablepre}forums SET todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
if($newsubscribed) {
$db->query("UPDATE {$tablepre}threads SET subscribed='1' WHERE tid='$tid'", 'UNBUFFERED');
}
if(!$allowuseblog || empty($isblog)) {
showmessage('post_reply_mod_succeed', "forumdisplay.php?fid=$fid");
} else {
showmessage('post_reply_mod_blog_succeed', "blog.php?tid=$tid&starttime=$starttime&endtime=$endtime&page=$page");
}
} else {
$db->query("UPDATE {$tablepre}threads SET lastposter='$author', lastpost='$timestamp', replies=replies+1 ".($attachment ? ', attachment=\'1\'' : '').", subscribed='".($subscribed || $newsubscribed ? 1 : 0)."' WHERE tid='$tid'", 'UNBUFFERED');
updatepostcredits('+', $discuz_uid, $replycredits);
$lastpost = "$thread[tid]\t".addslashes($thread['subject'])."\t$timestamp\t$author";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', posts=posts+1, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
if($forum['type'] == 'sub') {
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
}
if(!$allowuseblog || empty($isblog)) {
showmessage($replymessage, "viewthread.php?tid=$tid&pid=$pid&page=".(@ceil(($thread['special'] ? $thread['replies'] + 1 : $thread['replies'] + 2) / $ppp))."&extra=$extra#pid$pid");
} else {
showmessage('post_reply_blog_succeed', "blog.php?tid=$tid&starttime=$starttime&endtime=$endtime&page=".(@ceil(($thread['replies'] + 1) / $ppp))."#bottom");
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/newreply.inc.php | PHP | asf20 | 16,127 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_special.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$query = $db->query("SELECT count(*) FROM {$tablepre}posts WHERE tid='$tid' AND first=0 AND invisible='0'");
$repostnum = $db->result($query, 0);
$ppp = $forum['threadcaches'] && !$discuz_uid ? $_DCACHE['settings']['postperpage'] : $ppp;
$start_limit = $numpost = ($page - 1) * $ppp;
if($start_limit > $repostnum) {
$start_limit = $numpost = 0;
$page = 1;
}
if($thread['special'] == 3) {
$thread['price'] < 0 && $start_limit++;
$repostnum--;
}
$multipage = multi($repostnum, $ppp, $page, "viewthread.php?tid=$tid&do=$do&extra=$extra".(isset($highlight) ? "&highlight=".rawurlencode($highlight) : ''));
$query = $db->query("SELECT p.*,m.username,m.adminid,m.groupid,m.credits FROM {$tablepre}posts p LEFT JOIN {$tablepre}members m ON m.uid=p.authorid WHERE p.tid='$tid' AND p.invisible='0' AND p.first='0' ORDER BY p.dateline LIMIT $start_limit, $ppp");
while($post = $db->fetch_array($query)) {
$post['first'] = 0;
$post = viewthread_procpost($post, 1);
$postlist[$post['pid']] = $post;
}
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
include template('viewthread_special_post');
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_special.inc.php | PHP | asf20 | 1,489 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$RCSfile: search_qihoo.inc.php,v $
$Revision: 1.8 $
$Date: 2007/08/06 09:54:48 $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(empty($srchtxt) && empty($srchuname)) {
showmessage('search_invalid', 'search.php');
}
$keywordlist = '';
foreach(explode("\n", trim($qihoo_keyword)) as $key => $keyword) {
$keywordlist .= $comma.trim($keyword);
$comma = '|';
if(strlen($keywordlist) >= 100) {
break;
}
}
if($orderby == 'lastpost') {
$orderby = 'rdate';
} elseif($orderby == 'dateline') {
$orderby = 'pdate';
} else {
$orderby = '';
}
$stype = empty($stype) ? '' : ($stype == 2 ? 'author' : 'title');
$url = 'http://search.qihoo.com/usearch.html?site='.rawurlencode(site()).
'&kw='.rawurlencode($srchtxt).
'&ics='.$charset.
'&ocs='.$charset.
($orderby ? '&sort='.$orderby : '').
($srchfid ? '&chanl='.rawurlencode($_DCACHE['forums'][$srchfid]['name']) : '').
'&bbskw='.rawurlencode($keywordlist).
'&summary='.$qihoo['summary'].
'&stype='.$stype.
'&count='.$tpp.
'&fw=dz&SITEREFER='.rawurlencode($boardurl);
dheader("Location: $url");
?> | zyyhong | trunk/jiaju001/bbs/include/search_qihoo.inc.php | PHP | asf20 | 1,227 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: search_trade.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(isset($searchid)) {
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$query = $db->query("SELECT searchstring, keywords, threads, threadtypeid, tids FROM {$tablepre}searchindex WHERE searchid='$searchid' AND threadtypeid='$typeid'");
if(!$index = $db->fetch_array($query)) {
showmessage('search_id_invalid');
}
$threadlist = $typelist = $resultlist = $optionlist = array();
$query = $db->query("SELECT tid, subject, dateline FROM {$tablepre}threads WHERE tid IN ($index[tids]) AND displayorder>=0 ORDER BY dateline LIMIT $start_limit, $tpp");
while($info = $db->fetch_array($query)) {
$threadlist[$info['tid']]['dateline'] = gmdate("$dateformat $timeformat", $info['dateline'] + $timeoffset * 3600);
$threadlist[$info['tid']]['subject'] = $info['subject'];
}
@include_once DISCUZ_ROOT.'./forumdata/cache/threadtype_'.$index['threadtypeid'].'.php';
$query = $db->query("SELECT tid, optionid, value FROM {$tablepre}typeoptionvars WHERE tid IN ($index[tids])");
while($info = $db->fetch_array($query)) {
if($_DTYPE[$info['optionid']]['search']) {
$typelist[$info['tid']][$info['optionid']]['value'] = $info['value'];
$optionlist[] = $_DTYPE[$info['optionid']]['title'];
}
}
$optionlist = $optionlist ? array_unique($optionlist) : '';
$choiceshow = '';
foreach($threadlist as $tid => $thread) {
$resultlist[$tid]['subject'] = $thread['subject'];
$resultlist[$tid]['dateline'] = $thread['dateline'];
foreach($typelist[$tid] as $optionid => $value) {
if(in_array($_DTYPE[$optionid]['type'], array('select', 'radio'))) {
$resultlist[$tid]['option'][] = $_DTYPE[$optionid]['choices'][$value['value']];
} elseif($_DTYPE[$optionid]['type'] == 'checkbox') {
foreach(explode("\t", $value['value']) as $choiceid) {
$choiceshow .= $_DTYPE[$optionid]['choices'][$choiceid].' ';
}
$resultlist[$tid]['option'][] = $choiceshow;
} elseif($_DTYPE[$optionid]['type'] == 'image') {
$maxwidth = $_DTYPE[$optionid]['maxwidth'] ? 'width="'.$_DTYPE[$optionid]['maxwidth'].'"' : '';
$maxheight = $_DTYPE[$optionid]['maxheight'] ? 'height="'.$_DTYPE[$optionid]['maxheight'].'"' : '';
$resultlist[$tid]['option'][] = $optiondata[$optionid] ? "<a href=\"$optiondata[$optionid]\" target=\"_blank\"><img src=\"$value[value]\" $maxwidth $maxheight border=\"0\"></a>" : '';
} elseif($_DTYPE[$optionid]['type'] == 'url') {
$resultlist[$tid]['option'][] = $optiondata[$optionid] ? "<a href=\"$value[value]\" target=\"_blank\">$value[value]</a>" : '';
} else {
$resultlist[$tid]['option'][] = $value['value'];
}
}
}
$colspan = count($optionlist) + 2;
$multipage = multi($index['threads'], $tpp, $page, "search.php?searchid=$searchid&srchtype=threadtype&typeid=$index[threadtypeid]&searchsubmit=yes");
$url_forward = 'search.php?'.$_SERVER['QUERY_STRING'];
include template('search_type');
} else {
checklowerlimit($creditspolicy['search'], -1);
$forumsarray = array();
if(!empty($srchfid)) {
foreach((is_array($srchfid) ? $srchfid : explode('_', $srchfid)) as $forum) {
if($forum = intval(trim($forum))) {
$forumsarray[] = $forum;
}
}
}
$fids = $comma = '';
foreach($_DCACHE['forums'] as $fid => $forum) {
if($forum['type'] != 'group' && (!$forum['viewperm'] && $readaccess) || ($forum['viewperm'] && forumperm($forum['viewperm']))) {
if(!$forumsarray || in_array($fid, $forumsarray)) {
$fids .= "$comma'$fid'";
$comma = ',';
}
}
}
$srchoption = $tab = '';
if($searchoption && is_array($searchoption)) {
foreach($searchoption as $optionid => $option) {
$srchoption .= $tab.$optionid;
$tab = "\t";
}
}
$searchstring = 'type|'.addslashes($srchoption);
$searchindex = array('id' => 0, 'dateline' => '0');
$query = $db->query("SELECT searchid, dateline,
('$searchctrl'<>'0' AND ".(empty($discuz_uid) ? "useip='$onlineip'" : "uid='$discuz_uid'")." AND $timestamp-dateline<$searchctrl) AS flood,
(searchstring='$searchstring' AND expiration>'$timestamp') AS indexvalid
FROM {$tablepre}searchindex
WHERE ('$searchctrl'<>'0' AND ".(empty($discuz_uid) ? "useip='$onlineip'" : "uid='$discuz_uid'")." AND $timestamp-dateline<$searchctrl) OR (searchstring='$searchstring' AND expiration>'$timestamp')
ORDER BY flood");
while($index = $db->fetch_array($query)) {
if($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']) {
$searchindex = array('id' => $index['searchid'], 'dateline' => $index['dateline']);
break;
} elseif($index['flood']) {
showmessage('search_ctrl', "search.php?srchtype=threadtype&typeid=$selecttypeid&srchfid=$fid");
}
}
if($searchindex['id']) {
$searchid = $searchindex['id'];
} else {
if((!$searchoption || !is_array($searchoption)) && !$selecttypeid) {
showmessage('search_threadtype_invalid', "search.php?srchtype=threadtype&typeid=$selecttypeid&srchfid=$fid");
} elseif(isset($srchfid) && $srchfid != 'all' && !(is_array($srchfid) && in_array('all', $srchfid)) && empty($forumsarray)) {
showmessage('search_forum_invalid', "search.php?srchtype=threadtype&typeid=$selecttypeid&srchfid=$fid");
} elseif(!$fids) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if($maxspm) {
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}searchindex WHERE dateline>'$timestamp'-60");
if(($db->result($query, 0)) >= $maxspm) {
showmessage('search_toomany', 'search.php');
}
}
$sqlsrch = $or = '';
if(!empty($searchoption) && is_array($searchoption)) {
foreach($searchoption as $optionid => $option) {
if($option['value']) {
if(in_array($option['type'], array('number', 'radio', 'select'))) {
$option['value'] = intval($option['value']);
$exp = '=';
if($option['condition']) {
$exp = $option['condition'] == 1 ? '>' : '<';
}
$sql = "value$exp'$option[value]'";
} elseif($option['type'] == 'checkbox') {
$sql = "value LIKE '%\t".(implode("\t", $option['value']))."\t%'";
} else {
$sql = "value LIKE '%$option[value]%'";
}
$sqlsrch .= $or."(optionid='$optionid' AND $sql) ";
$or = 'OR ';
}
}
}
$threads = $tids = 0;
$query = $db->query("SELECT tid, typeid FROM {$tablepre}typeoptionvars WHERE (expiration='0' OR expiration>'$timestamp') ".($sqlsrch ? 'AND '.$sqlsrch : '')."");
while($post = $db->fetch_array($query)) {
if($post['typeid'] == $selecttypeid) {
if($thread['closed'] <= 1) {
$tids .= ','.$post['tid'];
}
}
}
$db->free_result($query);
if($fids) {
$query = $db->query("SELECT tid, closed FROM {$tablepre}threads WHERE tid IN ($tids) AND fid IN ($fids) LIMIT $maxsearchresults");
while($post = $db->fetch_array($query)) {
if($thread['closed'] <= 1) {
$tids .= ','.$post['tid'];
$threads++;
}
}
}
$db->query("INSERT INTO {$tablepre}searchindex (keywords, searchstring, useip, uid, dateline, expiration, threads, threadtypeid, tids)
VALUES ('$keywords', '$searchstring', '$onlineip', '$discuz_uid', '$timestamp', '$expiration', '$threads', '$selecttypeid', '$tids')");
$searchid = $db->insert_id();
updatecredits($discuz_uid, $creditspolicy['search'], -1);
}
showmessage('search_redirect', "search.php?searchid=$searchid&srchtype=threadtype&typeid=$selecttypeid&searchsubmit=yes");
}
?> | zyyhong | trunk/jiaju001/bbs/include/search_type.inc.php | PHP | asf20 | 7,776 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: db_mysql_error.inc.php 11168 2007-11-08 05:23:57Z tiger $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$timestamp = time();
$errmsg = '';
$dberror = $this->error();
$dberrno = $this->errno();
if($dberrno == 1114) {
?>
<html>
<head>
<title>Max Onlines Reached</title>
</head>
<body bgcolor="#FFFFFF">
<table cellpadding="0" cellspacing="0" border="0" width="600" align="center" height="85%">
<tr align="center" valign="middle">
<td>
<table cellpadding="10" cellspacing="0" border="0" width="80%" align="center" style="font-family: Verdana, Tahoma; color: #666666; font-size: 9px">
<tr>
<td valign="middle" align="center" bgcolor="#EBEBEB">
<br /><b style="font-size: 10px">Forum onlines reached the upper limit</b>
<br /><br /><br />Sorry, the number of online visitors has reached the upper limit.
<br />Please wait for someone else going offline or visit us in idle hours.
<br /><br />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<?
exit();
} else {
if($message) {
$errmsg = "<b>Discuz! info</b>: $message\n\n";
}
if(isset($GLOBALS['_DSESSION']['discuz_user'])) {
$errmsg .= "<b>User</b>: ".htmlspecialchars($GLOBALS['_DSESSION']['discuz_user'])."\n";
}
$errmsg .= "<b>Time</b>: ".gmdate("Y-n-j g:ia", $timestamp + ($GLOBALS['timeoffset'] * 3600))."\n";
$errmsg .= "<b>Script</b>: ".$GLOBALS['PHP_SELF']."\n\n";
if($sql) {
$errmsg .= "<b>SQL</b>: ".htmlspecialchars($sql)."\n";
}
$errmsg .= "<b>Error</b>: $dberror\n";
$errmsg .= "<b>Errno.</b>: $dberrno";
echo "</table></table></table></table></table>\n";
echo "<p style=\"font-family: Verdana, Tahoma; font-size: 11px; background: #FFFFFF;\">";
echo nl2br(str_replace($GLOBALS['tablepre'], '[Table]', $errmsg));
if($GLOBALS['adminemail']) {
$errlog = array();
if(@$fp = fopen(DISCUZ_ROOT.'./forumdata/dberror.log', 'r')) {
while((!feof($fp)) && count($errlog) < 20) {
$log = explode("\t", fgets($fp, 50));
if($timestamp - $log[0] < 86400) {
$errlog[$log[0]] = $log[1];
}
}
fclose($fp);
}
if(!in_array($dberrno, $errlog)) {
$errlog[$timestamp] = $dberrno;
@$fp = fopen(DISCUZ_ROOT.'./forumdata/dberror.log', 'w');
@flock($fp, 2);
foreach(array_unique($errlog) as $dateline => $errno) {
@fwrite($fp, "$dateline\t$errno");
}
@fclose($fp);
if(function_exists('errorlog')) {
errorlog('MySQL', basename($GLOBALS['_SERVER']['PHP_SELF'])." : $dberror - ".cutstr($sql, 120), 0);
}
if($GLOBALS['dbreport']) {
echo "<br /><br />An error report has been dispatched to our administrator.";
@sendmail($GLOBALS['adminemail'], '[Discuz!] MySQL Error Report',
"There seems to have been a problem with the database of your Discuz! Board\n\n".
strip_tags($errmsg)."\n\n".
"Please check-up your MySQL server and forum scripts, similar errors will not be reported again in recent 24 hours\n".
"If you have troubles in solving this problem, please visit Discuz! Community http://www.Discuz.net.");
}
} else {
echo '<br /><br />Similar error report has beed dispatched to administrator before.';
}
}
echo '</p>';
exit();
}
?> | zyyhong | trunk/jiaju001/bbs/include/db_mysql_error.inc.php | PHP | asf20 | 3,432 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: supe_daily.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($supe['status'] && $supe['maxupdateusers']) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache(array('supe_updateusers', 'supe_updateitems'));
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/supe_daily.inc.php | PHP | asf20 | 415 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: announcements_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$db->query("DELETE FROM {$tablepre}announcements WHERE endtime<'$timestamp' AND endtime<>'0'");
if($db->affected_rows()) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('announcements');
updatecache('announcements_forum');
updatecache('pmlist');
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/announcements_daily.inc.php | PHP | asf20 | 533 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: todayposts_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$query = $db->query("SELECT sum(todayposts) FROM {$tablepre}forums");
$yesterdayposts = intval($db->result($query, 0));
$query = $db->query("SELECT value FROM {$tablepre}settings WHERE variable='historyposts'");
$historypost = $db->result($query, 0);
$hpostarray = explode("\t", $historypost);
$historyposts = $hpostarray[1] < $yesterdayposts ? "$yesterdayposts\t$yesterdayposts" : "$yesterdayposts\t$hpostarray[1]";
$db->query("REPLACE INTO {$tablepre}settings (variable, value) VALUES ('historyposts', '$historyposts')");
$db->query("UPDATE {$tablepre}forums SET todayposts='0'");
require_once DISCUZ_ROOT.'./include/cache.func.php';
$_DCACHE['settings']['historyposts'] = $historyposts;
updatesettings();
?> | zyyhong | trunk/jiaju001/bbs/include/crons/todayposts_daily.inc.php | PHP | asf20 | 977 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cleanup_monthly.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$myrecordtimes = $timestamp - $_DCACHE['settings']['myrecorddays'] * 86400;
$db->query("DELETE FROM {$tablepre}mythreads WHERE dateline<'$myrecordtimes'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}myposts WHERE dateline<'$myrecordtimes'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}invites WHERE dateline<'$timestamp' - 2592000 AND status='4'", 'UNBUFFERED');
$db->query("TRUNCATE {$tablepre}relatedthreads");
?> | zyyhong | trunk/jiaju001/bbs/include/crons/cleanup_monthly.inc.php | PHP | asf20 | 681 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: birthdays_daily.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($maxbdays) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('birthdays');
updatecache('birthdays_index');
}
if($bdaystatus) {
$today = gmdate('m-d', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600);
$query = $db->query("SELECT uid, username, email, bday FROM {$tablepre}members WHERE RIGHT(bday, 5)='$today' ORDER BY bday");
global $member;
while($member = $db->fetch_array($query)) {
sendmail("$member[username] <$member[email]>", 'birthday_subject', 'birthday_message');
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/birthdays_daily.inc.php | PHP | asf20 | 780 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: promotions_hourly.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($creditspolicy['promotion_visit']) {
$uidarray = $userarray = array();
$query = $db->query("SELECT * FROM {$tablepre}promotions");
while($promotion = $db->fetch_array($query)) {
if($promotion['uid']) {
$uidarray[] = $promotion['uid'];
} elseif($promotion['username']) {
$userarray[] = addslashes($promotion['username']);
}
}
if($uidarray || $userarray) {
if($userarray) {
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username IN ('".implode('\',\'', $userarray)."')");
while($member = $db->fetch_array($query)) {
$uidarray[] = $member['uid'];
}
}
$countarray = array();
foreach(array_count_values($uidarray) as $uid => $count) {
$countarray[$count][] = $uid;
}
foreach($countarray as $count => $uids) {
updatecredits(implode('\',\'', $uids), $creditspolicy['promotion_visit'], $count);
}
$db->query("DELETE FROM {$tablepre}promotions");
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/promotions_hourly.inc.php | PHP | asf20 | 1,208 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: onlinetime_monthly.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$db->query("UPDATE {$tablepre}onlinetime SET thismonth='0'");
$db->query("UPDATE {$tablepre}statvars SET value='0' WHERE type='onlines' AND variable='lastupdate'");
?> | zyyhong | trunk/jiaju001/bbs/include/crons/onlinetime_monthly.inc.php | PHP | asf20 | 419 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: notify_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$subscriptions = array();
$query = $db->query("SELECT t.tid, t.subject, t.author, t.lastpost, t.lastposter, t.views, t.replies, m.username, m.email
FROM {$tablepre}subscriptions s, {$tablepre}members m, {$tablepre}threads t
WHERE s.lastpost>s.lastnotify AND m.uid=s.uid AND t.tid=s.tid");
while($sub = $db->fetch_array($query)) {
if(empty($subscriptions[$sub['tid']])) {
$subscriptions[$sub['tid']] = array
(
'thread' => array
(
'tid' => $sub['tid'],
'subject' => $sub['subject'],
'author' => ($sub['author'] ? $sub['author'] : 'Guest'),
'lastpost' => gmdate($_DCACHE['settings']['dateformat'].' '.$_DCACHE['settings']['timeformat'], $sub['lastpost'] + $_DCACHE['settings']['timeoffset'] * 3600),
'lastposter' => ($sub['lastposter'] ? $sub['lastposter'] : 'Guest'),
'views' => $sub['views'],
'replies' => $sub['replies']
),
'emails' => array("$sub[username] <$sub[email]>")
);
} else {
$subscriptions[$sub['tid']]['emails'][] = $sub['email'];
}
}
foreach($subscriptions as $sub) {
$thread = $sub['thread'];
sendmail(implode(',', $sub['emails']), 'email_notify_subject', 'email_notify_message');
}
$db->query("UPDATE {$tablepre}subscriptions SET lastnotify='$timestamp' WHERE lastpost>lastnotify");
?> | zyyhong | trunk/jiaju001/bbs/include/crons/notify_daily.inc.php | PHP | asf20 | 1,542 |
<?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($tagstatus) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache(array('tags_index', 'tags_viewthread'));
$db->query("DELETE FROM {$tablepre}tags WHERE total=0", 'UNBUFFERED');
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/tags_daily.inc.php | PHP | asf20 | 276 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magics_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!empty($magicstatus)) {
$magicarray = array();
$query = $db->query("SELECT magicid, supplytype, supplynum, num FROM {$tablepre}magics WHERE available='1'");
while($magic = $db->fetch_array($query)) {
if($magic['supplytype'] && $magic['supplynum'] && !$magic['num']) {
$magicarray[$magic['magicid']]['supplytype'] = $magic['supplytype'];
$magicarray[$magic['magicid']]['supplynum'] = $magic['supplynum'];
}
}
list($daynow, $weekdaynow) = explode('-', gmdate('d-w', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600));
foreach($magicarray as $id => $magic) {
$autosupply = 0;
if($magic['supplytype'] == 1) {
$autosupply = 1;
} elseif($magic['supplytype'] == 2 && $weekdaynow == 1) {
$autosupply = 1;
} elseif($magic['supplytype'] == 3 && $daynow == 1) {
$autosupply = 1;
}
if(!empty($autosupply)) {
$db->query("UPDATE {$tablepre}magics SET num=num+'$magic[supplynum]' WHERE magicid='$id'");
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/magics_daily.inc.php | PHP | asf20 | 1,222 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cleanup_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$db->query("UPDATE {$tablepre}advertisements SET available='0' WHERE endtime>'0' AND endtime<='$timestamp'", 'UNBUFFERED');
if($db->affected_rows()) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache(array('settings', 'advs_archiver', 'advs_register', 'advs_index', 'advs_forumdisplay', 'advs_viewthread'));
}
$db->query("TRUNCATE {$tablepre}searchindex");
$db->query("DELETE FROM {$tablepre}threadsmod WHERE dateline<'$timestamp'-31536000", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}subscriptions WHERE lastpost<'$timestamp'-7776000", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}forumrecommend WHERE expiration<'$timestamp'", 'UNBUFFERED');
if($qihoo['status'] && $qihoo['relatedthreads']) {
$db->query("DELETE FROM {$tablepre}relatedthreads WHERE expiration<'$timestamp'", 'UNBUFFERED');
}
$db->query("UPDATE {$tablepre}trades SET closed='1' WHERE expiration<>0 AND expiration<'$timestamp'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}tradelog WHERE status=0 AND lastupdate<'".($timestamp - 5 * 86400)."'", 'UNBUFFERED');
if($cachethreadon) {
removedir($cachethreaddir, TRUE);
}
if($regstatus > 1) {
$db->query("UPDATE {$tablepre}invites SET status='4' WHERE expiration<'$timestamp' AND status IN ('1', '3')");
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/cleanup_daily.inc.php | PHP | asf20 | 1,530 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: secqaa_daily.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($secqaa['status'] > 0) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('secqaa');
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/secqaa_daily.inc.php | PHP | asf20 | 358 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: threadexpiries_hourly.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$actionarray = array();
$query = $db->query("SELECT * FROM {$tablepre}threadsmod WHERE expiration>'0' AND expiration<'$timestamp' AND status='1'");
while($expiry = $db->fetch_array($query)) {
$threads[] = $expiry;
switch($expiry['action']) {
case 'EST': $actionarray['UES'][] = $expiry['tid']; break;
case 'EHL': $actionarray['UEH'][] = $expiry['tid']; break;
case 'ECL': $actionarray['UEC'][] = $expiry['tid']; break;
case 'EOP': $actionarray['UEO'][] = $expiry['tid']; break;
case 'EDI': $actionarray['UED'][] = $expiry['tid']; break;
case 'TOK': $actionarray['UES'][] = $expiry['tid']; break;
case 'CCK': $actionarray['UEH'][] = $expiry['tid']; break;
case 'CLK': $actionarray['UEC'][] = $expiry['tid']; break;
}
}
if($actionarray) {
foreach($actionarray as $action => $tids) {
$tids = implode(',', $tids);
switch($action) {
case 'UES':
$db->query("UPDATE {$tablepre}threads SET displayorder='0' WHERE tid IN ($tids)", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($tids) AND action IN ('EST', 'TOK')", 'UNBUFFERED');
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
break;
case 'UEH':
$db->query("UPDATE {$tablepre}threads SET highlight='0' WHERE tid IN ($tids)", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($tids) AND action IN ('EHL', 'CCK')", 'UNBUFFERED');
break;
case 'UEC':
case 'UEO':
$closed = $action == 'UEO' ? 1 : 0;
$db->query("UPDATE {$tablepre}threads SET closed='$closed' WHERE tid IN ($tids)", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($tids) AND action IN ('EOP', 'ECL', 'CLK')", 'UNBUFFERED');
break;
case 'UED':
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($tids) AND action='EDI'", 'UNBUFFERED');
$digestarray = $authoridarry = array();
$query = $db->query("SELECT authorid, digest FROM {$tablepre}threads WHERE tid IN ($tids)");
while($digest = $db->fetch_array($query)) {
$authoridarry[] = $digest['authorid'];
$digestarray[$digest['digest']][] = $digest['authorid'];
}
$db->query("UPDATE {$tablepre}members SET digestposts=digestposts-1 WHERE uid IN (".implode(',', $authoridarry).")", 'UNBUFFERED');
foreach($digestarray as $digest => $authorids) {
updatecredits(implode('\',\'', $authorids), $creditspolicy['digest'], 0 - $digest);
}
$db->query("UPDATE {$tablepre}threads SET digest='0' WHERE tid IN ($tids)", 'UNBUFFERED');
break;
}
}
require_once DISCUZ_ROOT.'./include/post.func.php';
foreach($actionarray as $action => $tids) {
updatemodlog(implode(',', $tids), $action, 0, 1);
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/crons/threadexpiries_hourly.inc.php | PHP | asf20 | 3,084 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: sendmail.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$mail = unserialize($mail);
$errorlog = $action != 'mailcheck' ? 'errorlog' : 'checkmailerror';
@include language('emails');
if($mail['sendmail_silent']) {
error_reporting(0);
}
if(isset($language[$email_subject])) {
eval("\$email_subject = \"".$language[$email_subject]."\";");
}
if(isset($language[$email_message])) {
eval("\$email_message = \"".$language[$email_message]."\";");
}
$maildelimiter = $mail['maildelimiter'] == 1 ? "\r\n" : ($mail['maildelimiter'] == 2 ? "\r" : "\n");
$mailusername = isset($mail['mailusername']) ? $mail['mailusername'] : 1;
$email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', '['.$bbname.'] '.$email_subject))).'?=';
$email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))))));
$email_from = $email_from == '' ? '=?'.$charset.'?B?'.base64_encode($bbname)."?= <$adminemail>" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$charset.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);
foreach(explode(',', $email_to) as $touser) {
$tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$charset.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
}
$email_to = implode(',', $tousers);
$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Discuz! $version{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/plain; charset=$charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";
$mail['port'] = $mail['port'] ? $mail['port'] : 25;
if($mail['mailsend'] == 1 && function_exists('mail')) {
@mail($email_to, $email_subject, $email_message, $headers);
} elseif($mail['mailsend'] == 2) {
if(!$fp = fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
$errorlog('SMTP', "($mail[server]:$mail[port]) CONNECT - Unable to connect to the SMTP server", 0);
}
stream_set_blocking($fp, true);
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != '220') {
$errorlog('SMTP', "$mail[server]:$mail[port] CONNECT - $lastmessage", 0);
}
fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." discuz\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
$errorlog('SMTP', "($mail[server]:$mail[port]) HELO/EHLO - $lastmessage", 0);
}
while(1) {
if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
break;
}
$lastmessage = fgets($fp, 512);
}
if($mail['auth']) {
fputs($fp, "AUTH LOGIN\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
$errorlog('SMTP', "($mail[server]:$mail[port]) AUTH LOGIN - $lastmessage", 0);
}
fputs($fp, base64_encode($mail['auth_username'])."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
$errorlog('SMTP', "($mail[server]:$mail[port]) USERNAME - $lastmessage", 0);
}
fputs($fp, base64_encode($mail['auth_password'])."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 235) {
$errorlog('SMTP', "($mail[server]:$mail[port]) PASSWORD - $lastmessage", 0);
}
$email_from = $mail['from'];
}
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
$errorlog('SMTP', "($mail[server]:$mail[port]) MAIL FROM - $lastmessage", 0);
}
}
$email_tos = array();
foreach(explode(',', $email_to) as $touser) {
$touser = trim($touser);
if($touser) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
$errorlog('SMTP', "($mail[server]:$mail[port]) RCPT TO - $lastmessage", 0);
}
}
}
fputs($fp, "DATA\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 354) {
$errorlog('SMTP', "($mail[server]:$mail[port]) DATA - $lastmessage", 0);
}
$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";
fputs($fp, "Date: ".gmdate('r')."\r\n");
fputs($fp, "To: ".$email_to."\r\n");
fputs($fp, "Subject: ".$email_subject."\r\n");
fputs($fp, $headers."\r\n");
fputs($fp, "\r\n\r\n");
fputs($fp, "$email_message\r\n.\r\n");
fputs($fp, "QUIT\r\n");
} elseif($mail['mailsend'] == 3) {
ini_set('SMTP', $mail['server']);
ini_set('smtp_port', $mail['port']);
ini_set('sendmail_from', $email_from);
@mail($email_to, $email_subject, $email_message, $headers);
}
?> | zyyhong | trunk/jiaju001/bbs/include/sendmail.inc.php | PHP | asf20 | 5,391 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: security.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($attackevasive & 1 || $attackevasive & 4) {
$_DCOOKIE['lastrequest'] = authcode($_DCOOKIE['lastrequest'], 'DECODE');
dsetcookie('lastrequest', authcode($timestamp, 'ENCODE'), $timestamp + 816400);
}
if($attackevasive & 1) {
if($timestamp - $_DCOOKIE['lastrequest'] < 1) {
securitymessage('attachsave_1_subject', 'attachsave_1_message');
}
}
if(($attackevasive & 2) && ($_SERVER['HTTP_X_FORWARDED_FOR'] ||
$_SERVER['HTTP_VIA'] || $_SERVER['HTTP_PROXY_CONNECTION'] ||
$_SERVER['HTTP_USER_AGENT_VIA'] || $_SERVER['HTTP_CACHE_INFO'] ||
$_SERVER['HTTP_PROXY_CONNECTION'])) {
securitymessage('attachsave_2_subject', 'attachsave_2_message', FALSE);
}
if($attackevasive & 4) {
if(empty($_DCOOKIE['lastrequest']) || $timestamp - $_DCOOKIE['lastrequest'] > 60) {
securitymessage('attachsave_4_subject', 'attachsave_4_message');
}
}
if($attackevasive & 8) {
list($questionkey, $questionanswer, $questiontime) = explode('|', authcode($_DCOOKIE['secqcode'], 'DECODE'));
include_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
if(!$questionanswer || !$questiontime || $_DCACHE['secqaa'][$questionkey]['answer'] != $questionanswer) {
if(empty($_POST['secqsubmit']) || (!empty($_POST['secqsubmit']) && $_DCACHE['secqaa'][$questionkey]['answer'] != md5($_POST['answer']))) {
$questionkey = array_rand($_DCACHE['secqaa']);
dsetcookie('secqcode', authcode($questionkey.'||'.$timestamp, 'ENCODE'), $timestamp + 816400);
securitymessage($_DCACHE['secqaa'][$questionkey]['question'], '<input type="text" name="answer" size="8" maxlength="150" /><input class="button" type="submit" name="secqsubmit" value=" Submit " />', FALSE, TRUE);
} else {
dsetcookie('secqcode', authcode($questionkey.'|'.$_DCACHE['secqaa'][$questionkey]['answer'].'|'.$timestamp, 'ENCODE'), $timestamp + 816400);
}
}
}
function securitymessage($subject, $message, $reload = TRUE, $form = FALSE) {
$scuritylang = array(
'attachsave_1_subject' => '频繁刷新限制',
'attachsave_1_message' => '您访问本站速度过快或者刷新间隔时间小于两秒!请等待页面自动跳转 ...',
'attachsave_2_subject' => '代理服务器访问限制',
'attachsave_2_message' => '本站现在限制使用代理服务器访问,请去除您的代理设置,直接访问本站。',
'attachsave_4_subject' => '页面重载开启',
'attachsave_4_message' => '欢迎光临本站,页面正在重新载入,请稍候 ...'
);
$subject = $scuritylang[$subject] ? $scuritylang[$subject] : $subject;
$message = $scuritylang[$message] ? $scuritylang[$message] : $message;
if($_GET['inajax']) {
ajaxshowheader();
echo '<div id="attackevasive_1" class="popupmenu_option"><b style="font-size: 16px">'.$subject.'</b><br /><br />'.$message.'</div>';
ajaxshowfooter();
} else {
echo '<html>';
echo '<head>';
echo '<title>'.$subject.'</title>';
echo '</head>';
echo '<body bgcolor="#FFFFFF">';
if($reload) {
echo '<script language="JavaScript">';
echo 'function reload() {';
echo ' document.location.reload();';
echo '}';
echo 'setTimeout("reload()", 1001);';
echo '</script>';
}
if($form) {
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
}
echo '<table cellpadding="0" cellspacing="0" border="0" width="700" align="center" height="85%">';
echo ' <tr align="center" valign="middle">';
echo ' <td>';
echo ' <table cellpadding="10" cellspacing="0" border="0" width="80%" align="center" style="font-family: Verdana, Tahoma; color: #666666; font-size: 11px">';
echo ' <tr>';
echo ' <td valign="middle" align="center" bgcolor="#EBEBEB">';
echo ' <br /><br /> <b style="font-size: 16px">'.$subject.'</b> <br /><br />';
echo $message;
echo ' <br /><br />';
echo ' </td>';
echo ' </tr>';
echo ' </table>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
if($form) {
echo '</form>';
}
echo '</body>';
echo '</html>';
}
exit();
}
function ajaxshowheader() {
global $charset, $inajax;
ob_end_clean();
@header("Expires: -1");
@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
@header("Pragma: no-cache");
header("Content-type: application/xml");
echo "<?xml version=\"1.0\" encoding=\"$charset\"?>\n<root><![CDATA[";
}
function ajaxshowfooter() {
echo ']]></root>';
}
?> | zyyhong | trunk/jiaju001/bbs/include/security.inc.php | PHP | asf20 | 5,275 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: promotion.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!empty($fromuid)) {
$fromuid = intval($fromuid);
$fromuser = '';
}
if(!$discuz_uid || !($fromuid == $discuz_uid || $fromuser == $discuz_user)) {
if($creditspolicy['promotion_visit']) {
$db->query("REPLACE INTO {$tablepre}promotions (ip, uid, username)
VALUES ('$onlineip', '$fromuid', '$fromuser')");
}
if($creditspolicy['promotion_register']) {
if(!empty($fromuser) && empty($fromuid)) {
if(empty($_DCOOKIE['promotion'])) {
$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username='$fromuser'");
$fromuid = $db->result($query, 0);
} else {
$fromuid = intval($_DCOOKIE['promotion']);
}
}
if($fromuid) {
dsetcookie('promotion', ($_DCOOKIE['promotion'] = $fromuid), 1800);
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/promotion.inc.php | PHP | asf20 | 1,011 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: newtrade.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$discuz_action = 11;
if(empty($forum['fid']) || $forum['type'] == 'group') {
showmessage('forum_nonexistence');
}
if($special != 2 || !submitcheck('topicsubmit', 0, $seccodecheck, $secqaacheck)) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(!$allowposttrade) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
$sgid = intval($sgid);
if($iscircle) {
$mycircles = array();
if($discuz_uid) {
supe_dbconnect();
$query = $supe['db']->query("SELECT gid, groupname FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND flag>0", 'SILENT');
while($mycircle = $supe['db']->fetch_array($query)) {
$mycircles[$mycircle['gid']] = cutstr($mycircle['groupname'], 30);
}
}
if($sgid) {
supe_dbconnect();
$query = $supe['db']->query("SELECT g.groupname, gf.headerimage, gf.css FROM {$supe[tablepre]}groups g, {$supe[tablepre]}groupfields gf WHERE g.gid='$sgid' AND g.flag=1 AND g.gid=gf.gid", 'SILENT');
$circle = $supe['db']->fetch_array($query);
if(!$discuz_uid || !$supe['db']->result($supe['db']->query("SELECT COUNT(*) FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND gid='$sgid' AND flag>0", 'SILENT'), 0)) {
showmessage('circle_nopermission');
}
}
}
if(!$discuz_uid && !((!$forum['postperm'] && $allowpost) || ($forum['postperm'] && forumperm($forum['postperm'])))) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(empty($forum['allowpost'])) {
if(!$forum['postperm'] && !$allowpost) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['postperm'] && !forumperm($forum['postperm'])) {
showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
}
}
$isblog = empty($isblog) ? '' : 'yes';
if($isblog && (!$allowuseblog || !$forum['allowshare'])) {
showmessage('post_newthread_blog_invalid', NULL, 'HALT');
}
checklowerlimit($postcredits);
if($subject == '' || $message == '') {
showmessage('post_sm_isnull');
}
if($post_invalid = checkpost()) {
showmessage($post_invalid);
}
if(checkflood()) {
showmessage('post_flood_ctrl');
}
$item_price = floatval($item_price);
if(!trim($item_name)) {
showmessage('trade_please_name');
} elseif($maxtradeprice && ($mintradeprice > $item_price || $maxtradeprice < $item_price)) {
showmessage('trade_price_between');
} elseif(!$maxtradeprice && $mintradeprice > $item_price) {
showmessage('trade_price_more_than');
} elseif($item_number < 1) {
showmessage('tread_please_number');
}
if(!empty($_FILES['tradeattach']['tmp_name'][0])) {
$_FILES['attach'] = array_merge_recursive((array)$_FILES['attach'], $_FILES['tradeattach']);
}
if($allowpostattach && is_array($_FILES['attach'])) {
foreach($_FILES['attach']['name'] as $attachname) {
if($attachname != '') {
checklowerlimit($postattachcredits);
break;
}
}
}
$typeid = isset($typeid) ? $typeid : 0;
$tradetypeid = isset($tradetypeid) ? $tradetypeid : 0;
$iconid = !empty($iconid) && isset($_DCACHE['icons'][$iconid]) ? $iconid : 0;
$displayorder = $modnewthreads ? -2 : (($forum['ismoderator'] && !empty($sticktopic)) ? 1 : 0);
$digest = ($forum['ismoderator'] && !empty($addtodigest)) ? 1 : 0;
$blog = $allowuseblog && $forum['allowshare'] && !empty($addtoblog) ? 1 : 0;
$readperm = $allowsetreadperm ? $readperm : 0;
$isanonymous = $isanonymous && $allowanonymous ? 1 : 0;
$threadmessage = $counterdesc."\t\t\t".$aboutcounter;
$author = !$isanonymous ? $discuz_user : '';
$moderated = $digest || $displayorder > 0 ? 1 : 0;
$attachment = ($allowpostattach && $attachments = attach_upload()) ? 1 : 0;
$subscribed = !empty($emailnotify) && $discuz_uid ? 1 : 0;
$supe_pushstatus = $supe['status'] && $forum['supe_pushsetting']['status'] == 1 && !$modnewthreads ? '1' : '0';
$sgidadd1 = $sgidadd2 = '';
if($iscircle) {
$sgidadd1 = ', sgid';
$sgidadd2 = ", '$sgid'";
}
$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, blog, special, attachment, subscribed, moderated, supe_pushstatus, replies $sgidadd1)
VALUES ('$fid', '$readperm', '$price', '$iconid', '$typeid', '$author', '$discuz_uid', '$subject', '$timestamp', '$timestamp', '$author', '$displayorder', '$digest', '$blog', '$special', '$attachment', '$subscribed', '$moderated', '$supe_pushstatus', '1' $sgidadd2)");
$tid = $db->insert_id();
if($subscribed) {
$db->query("REPLACE INTO {$tablepre}subscriptions (uid, tid, lastpost, lastnotify)
VALUES ('$discuz_uid', '$tid', '$timestamp', '$timestamp')", 'UNBUFFERED');
}
$db->query("REPLACE INTO {$tablepre}mythreads (uid, tid, dateline, special) VALUES ('$discuz_uid', '$tid', '$timestamp', '$special')", 'UNBUFFERED');
if($moderated) {
updatemodlog($tid, ($displayorder > 0 ? 'STK' : 'DIG'));
updatemodworks(($displayorder > 0 ? 'STK' : 'DIG'), 1);
}
$bbcodeoff = checkbbcodes($message, !empty($bbcodeoff));
$smileyoff = checksmilies($message, !empty($smileyoff));
$parseurloff = !empty($parseurloff);
$htmlon = bindec(($tagstatus && !empty($tagoff) ? 1 : 0).($allowhtml && !empty($htmlon) ? 1 : 0));
$pinvisible = $modnewthreads ? -2 : 0;
$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
VALUES ('$fid', '$tid', '1', '$discuz_user', '$discuz_uid', '$subject', '$timestamp', '$threadmessage', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '0')");
if($tagstatus && $tags != '') {
$tagarray = array_unique(explode(' ', censor($tags)));
$tagcount = 0;
foreach($tagarray as $tagname) {
$tagname = trim($tagname);
if(preg_match('/^([\x7f-\xff_-]|\w){3,20}$/', $tagname)) {
$query = $db->query("SELECT closed FROM {$tablepre}tags WHERE tagname='$tagname'");
if($db->num_rows($query)) {
if(!$tagstatus = $db->result($query, 0)) {
$db->query("UPDATE {$tablepre}tags SET total=total+1 WHERE tagname='$tagname'", 'UNBUFFERED');
}
} else {
$db->query("INSERT INTO {$tablepre}tags (tagname, closed, total)
VALUES ('$tagname', 0, 1)", 'UNBUFFERED');
$tagstatus = 0;
}
if(!$tagstatus) {
$db->query("INSERT {$tablepre}threadtags (tagname, tid) VALUES ('$tagname', $tid)", 'UNBUFFERED');
}
$tagcount++;
if($tagcount > 4) {
unset($tagarray);
break;
}
}
}
}
$pinvisible = $modnewreplies ? -2 : 0;
$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
VALUES ('$fid', '$tid', '0', '$discuz_user', '$discuz_uid', '$subject', '$timestamp', '$message', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '$attachment')");
$pid = $db->insert_id();
threadtype_checkoption(1, 1);
$optiondata = array();
if($tradetypes && $typeoption && $checkoption) {
$optiondata = threadtype_validator($typeoption);
}
if($tradetypes && $optiondata) {
foreach($optiondata as $optionid => $value) {
$db->query("INSERT INTO {$tablepre}tradeoptionvars (typeid, pid, optionid, value)
VALUES ('$tradetypeid', '$pid', '$optionid', '$value')");
}
}
$tradeaid = 0;
if($attachment) {
$searcharray = $pregarray = $replacearray = array();
foreach($attachments as $key => $attach) {
$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, price, filename, description, filetype, filesize, attachment, downloads, isimage, uid, thumb, remote)
VALUES ('$tid', '$pid', '$timestamp', '$attach[perm]', '$attach[price]', '$attach[name]', '$attach[description]', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$attach[uid]', '$attach[thumb]', '$attach[remote]')");
$searcharray[] = '[local]'.$localid[$key].'[/local]';
$pregarray[] = '/\[localimg=(\d{1,3}),(\d{1,3})\]'.$localid[$key].'\[\/localimg\]/is';
$insertid = $db->insert_id();
$replacearray[] = '[attach]'.$db->insert_id().'[/attach]';
}
if(!empty($_FILES['tradeattach']['tmp_name'][0])) {
$tradeaid = $insertid;
}
$message = str_replace($searcharray, $replacearray, preg_replace($pregarray, $replacearray, $message));
$db->query("UPDATE {$tablepre}posts SET message='$message' WHERE pid='$pid'");
updatecredits($discuz_uid, $postattachcredits, count($attachments));
}
require_once DISCUZ_ROOT.'./api/alipayapi.php';
trade_create(array(
'tid' => $tid,
'pid' => $pid,
'aid' => $tradeaid,
'typeid' => $tradetypeid,
'item_expiration' => $item_expiration,
'thread' => $thread,
'discuz_uid' => $discuz_uid,
'author' => $author,
'seller' => $seller,
'item_name' => $item_name,
'item_price' => $item_price,
'item_number' => $item_number,
'item_quality' => $item_quality,
'item_locus' => $item_locus,
'transport' => $transport,
'postage_mail' => $postage_mail,
'postage_express' => $postage_express,
'postage_ems' => $postage_ems,
'item_type' => $item_type,
'item_costprice' => $item_costprice
));
if($iscircle && $sgid) {
supe_dbconnect();
$query = $supe['db']->query("UPDATE {$supe[tablepre]}groups SET lastpost='$timestamp' WHERE gid='$sgid'", 'SILENT');
}
if($modnewthreads) {
$db->query("UPDATE {$tablepre}forums SET todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
$allowuseblog && $isblog && $blog ? showmessage('post_newthread_mod_blog_succeed', "blog.php?uid=$discuz_uid") :
showmessage('post_newthread_mod_succeed', "forumdisplay.php?fid=$fid");
} else {
if($digest) {
foreach($digestcredits as $id => $addcredits) {
$postcredits[$id] = (isset($postcredits[$id]) ? $postcredits[$id] : 0) + $addcredits;
}
}
updatepostcredits('+', $discuz_uid, $postcredits);
$lastpost = "$tid\t$subject\t$timestamp\t$author";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+2, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
if($forum['type'] == 'sub') {
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
}
if($allowuseblog && $isblog && $blog) {
showmessage('post_newthread_blog_succeed', "blog.php?tid=$tid");
} else {
showmessage('post_newthread_succeed', "viewthread.php?tid=$tid&extra=$extra".(!empty($frombbs) ? "&frombbs=$frombbs" : ''));
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/newtrade.inc.php | PHP | asf20 | 10,993 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: misc.func.php 10443 2007-08-30 10:14:18Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function convertip($ip) {
$return = '';
if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
$iparray = explode('.', $ip);
if($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) {
$return = '- LAN';
} elseif($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) {
$return = '- Invalid IP Address';
} else {
$tinyipfile = DISCUZ_ROOT.'./ipdata/tinyipdata.dat';
$fullipfile = DISCUZ_ROOT.'./ipdata/wry.dat';
if(@file_exists($tinyipfile)) {
$return = convertip_tiny($ip, $tinyipfile);
} elseif(@file_exists($fullipfile)) {
$return = convertip_full($ip, $fullipfile);
}
}
}
return $return;
}
function convertip_tiny($ip, $ipdatafile) {
static $fp = NULL, $offset = array(), $index = NULL;
$ipdot = explode('.', $ip);
$ip = pack('N', ip2long($ip));
$ipdot[0] = (int)$ipdot[0];
$ipdot[1] = (int)$ipdot[1];
if($fp === NULL && $fp = @fopen($ipdatafile, 'rb')) {
$offset = unpack('Nlen', fread($fp, 4));
$index = fread($fp, $offset['len'] - 4);
} elseif($fp == FALSE) {
return '- Invalid IP data file';
}
$length = $offset['len'] - 1028;
$start = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {
if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) {
$index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
$index_length = unpack('Clen', $index{$start + 7});
break;
}
}
fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
if($index_length['len']) {
return '- '.fread($fp, $index_length['len']);
} else {
return '- Unknown';
}
}
function convertip_full($ip, $ipdatafile) {
if(!$fd = @fopen($ipdatafile)) {
return '- Invalid IP data file';
}
$ip = explode('.', $ip);
$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
if(!($DataBegin = fread($fd, 4)) || !($DataEnd = fread($fd, 4)) ) return;
@$ipbegin = implode('', unpack('L', $DataBegin));
if($ipbegin < 0) $ipbegin += pow(2, 32);
@$ipend = implode('', unpack('L', $DataEnd));
if($ipend < 0) $ipend += pow(2, 32);
$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
$BeginNum = $ip2num = $ip1num = 0;
$ipAddr1 = $ipAddr2 = '';
$EndNum = $ipAllNum;
while($ip1num > $ipNum || $ip2num < $ipNum) {
$Middle= intval(($EndNum + $BeginNum) / 2);
fseek($fd, $ipbegin + 7 * $Middle);
$ipData1 = fread($fd, 4);
if(strlen($ipData1) < 4) {
fclose($fd);
return '- System Error';
}
$ip1num = implode('', unpack('L', $ipData1));
if($ip1num < 0) $ip1num += pow(2, 32);
if($ip1num > $ipNum) {
$EndNum = $Middle;
continue;
}
$DataSeek = fread($fd, 3);
if(strlen($DataSeek) < 3) {
fclose($fd);
return '- System Error';
}
$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
fseek($fd, $DataSeek);
$ipData2 = fread($fd, 4);
if(strlen($ipData2) < 4) {
fclose($fd);
return '- System Error';
}
$ip2num = implode('', unpack('L', $ipData2));
if($ip2num < 0) $ip2num += pow(2, 32);
if($ip2num < $ipNum) {
if($Middle == $BeginNum) {
fclose($fd);
return '- Unknown';
}
$BeginNum = $Middle;
}
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(1)) {
$ipSeek = fread($fd, 3);
if(strlen($ipSeek) < 3) {
fclose($fd);
return '- System Error';
}
$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
fseek($fd, $ipSeek);
$ipFlag = fread($fd, 1);
}
if($ipFlag == chr(2)) {
$AddrSeek = fread($fd, 3);
if(strlen($AddrSeek) < 3) {
fclose($fd);
return '- System Error';
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return '- System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
fseek($fd, $AddrSeek);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
} else {
fseek($fd, -1, SEEK_CUR);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return '- System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
}
fclose($fd);
if(preg_match('/http/i', $ipAddr2)) {
$ipAddr2 = '';
}
$ipaddr = "$ipAddr1 $ipAddr2";
$ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
$ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
$ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
$ipaddr = '- Unknown';
}
return '- '.$ipaddr;
}
function procthread($thread) {
global $dateformat, $timeformat, $timeoffset, $ppp, $colorarray;
if(empty($colorarray)) {
$colorarray = array('', 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'gray');
}
$thread['icon'] = isset($GLOBALS['_DCACHE']['icons'][$thread['iconid']]) ? '<img src="images/icons/'.$GLOBALS['_DCACHE']['icons'][$thread['iconid']].'" alt="Icon'.$thread['iconid'].'" class="icon" />' : ' ';
$thread['forumname'] = $GLOBALS['_DCACHE']['forums'][$thread['fid']]['name'];
$thread['dateline'] = gmdate($dateformat, $thread['dateline'] + $timeoffset * 3600);
$thread['lastpost'] = gmdate("$dateformat $timeformat", $thread['lastpost'] + $timeoffset * 3600);
$thread['lastposterenc'] = rawurlencode($thread['lastposter']);
if($thread['replies'] > $thread['views']) {
$thread['views'] = $thread['replies'];
}
$postsnum = $thread['special'] ? $thread['replies'] : $thread['replies'] + 1;
$thread['special'] == 3 && $thread['price'] < 0 && $thread['replies']--;
$pagelinks = '';
if($postsnum > $ppp) {
$posts = $postsnum;
$topicpages = ceil($posts / $ppp);
for($i = 1; $i <= $topicpages; $i++) {
$pagelinks .= '<a href="viewthread.php?tid='.$thread['tid'].'&page='.$i.'" target="_blank">'.$i.'</a> ';
if($i == 6) {
$i = $topicpages + 1;
}
}
if($topicpages > 6) {
$pagelinks .= ' .. <a href="viewthread.php?tid='.$thread['tid'].'&page='.$topicpages.'" target="_blank">'.$topicpages.'</a> ';
}
$thread['multipage'] = ' '.$pagelinks;
} else {
$thread['multipage'] = '';
}
if($thread['highlight']) {
$string = sprintf('%02d', $thread['highlight']);
$stylestr = sprintf('%03b', $string[0]);
$thread['highlight'] = 'style="';
$thread['highlight'] .= $stylestr[0] ? 'font-weight: bold;' : '';
$thread['highlight'] .= $stylestr[1] ? 'font-style: italic;' : '';
$thread['highlight'] .= $stylestr[2] ? 'text-decoration: underline;' : '';
$thread['highlight'] .= $string[1] ? 'color: '.$colorarray[$string[1]] : '';
$thread['highlight'] .= '"';
} else {
$thread['highlight'] = '';
}
if($thread['attachment']) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
$thread['attachment'] = attachtype($thread['attachment']).' ';
} else {
$thread['attachment'] = '';
}
return $thread;
}
function updateviews($table, $idcol, $viewscol, $logfile) {
global $db, $tablepre;
$viewlog = $viewarray = array();
if(@$viewlog = file($logfile = DISCUZ_ROOT.$logfile)) {
@unlink($logfile);
$viewlog = array_count_values($viewlog);
foreach($viewlog as $id => $views) {
$viewarray[$views] .= ($id > 0) ? ','.intval($id) : '';
}
foreach($viewarray as $views => $ids) {
$db->query("UPDATE LOW_PRIORITY $tablepre$table SET $viewscol=$viewscol+'$views' WHERE $idcol IN (0$ids)", 'UNBUFFERED');
}
}
}
function modlog($thread, $action) {
global $discuz_user, $adminid, $onlineip, $timestamp, $forum, $reason;
writelog('modslog', dhtmlspecialchars("$timestamp\t$discuz_user\t$adminid\t$onlineip\t$forum[fid]\t$forum[name]\t$thread[tid]\t$thread[subject]\t$action\t$reason"));
}
function checkreasonpm() {
global $reason;
$reason = trim(strip_tags($reason));
if(($GLOBALS['reasonpm'] == 1 || $GLOBALS['reasonpm'] == 3) && !$reason) {
showmessage('admin_reason_invalid');
}
}
function sendreasonpm($var, $item) {
global $$var;
${$var}['subject'] = strtr(${$var}['subject'], array_flip(get_html_translation_table(HTML_ENTITIES)));
${$var}['dateline'] = gmdate($GLOBALS['_DCACHE']['settings']['dateformat'].' '.$GLOBALS['_DCACHE']['settings']['timeformat'], ${$var}['dateline'] + ($GLOBALS['timeoffset'] * 3600));
sendpm(${$var}['authorid'], $item.'_subject', $item.'_message');
}
function modreasonselect() {
global $_DCACHE;
if(!isset($_DCACHE['modreasons']) || !is_array($_DCACHE['modreasons'])) {
@include DISCUZ_ROOT.'./forumdata/cache/cache_topicadmin.php';
}
$select = '';
foreach($_DCACHE['modreasons'] as $reason) {
$select .= $reason ? '<option value="'.dhtmlspecialchars($reason).'">'.$reason.'</option>' : '<option value="">--------</option>';
}
return $select;
}
function logincheck() {
global $db, $tablepre, $onlineip, $timestamp;
$query = $db->query("SELECT count, lastupdate FROM {$tablepre}failedlogins WHERE ip='$onlineip'");
if($login = $db->fetch_array($query)) {
if($timestamp - $login['lastupdate'] > 900) {
return 3;
} elseif($login['count'] < 5) {
return 2;
} else {
return 0;
}
} else {
return 1;
}
}
function loginfailed($permission) {
global $db, $tablepre, $onlineip, $timestamp;
switch($permission) {
case 1:
$db->query("REPLACE INTO {$tablepre}failedlogins (ip, count, lastupdate) VALUES ('$onlineip', '1', '$timestamp')");
break;
case 2:
$db->query("UPDATE {$tablepre}failedlogins SET count=count+1, lastupdate='$timestamp' WHERE ip='$onlineip'");
break;
case 3:
$db->query("UPDATE {$tablepre}failedlogins SET count='1', lastupdate='$timestamp' WHERE ip='$onlineip'");
$db->query("DELETE FROM {$tablepre}failedlogins WHERE lastupdate<$timestamp-901", 'UNBUFFERED');
break;
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/misc.func.php | PHP | asf20 | 10,847 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: pmprompt.inc.php 10530 2007-09-04 02:01:18Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($maxpmnum == 0) {
$query = $db->query("DELETE FROM {$tablepre}pms WHERE msgtoid='$discuz_uid' AND folder='inbox' AND delstatus='1'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}pms SET delstatus='2' WHERE msgtoid='$discuz_uid' AND folder='inbox'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}members SET newpm='0' WHERE uid='$discuz_uid'");
if($supe['status'] && $xspacestatus) {
supe_dbconnect();
$supe['db']->query("UPDATE {$supe[tablepre]}members SET newpm='0' WHERE uid='$discuz_uid'", 'SILENT');
}
} else {
$newpmexists = 0;
$pmlist = $pmlist ? $pmlist : array();
$query = $db->query("SELECT pmid, msgfrom, msgfromid, subject, message FROM {$tablepre}pms WHERE msgtoid='$discuz_uid' AND folder='inbox' AND delstatus!='2' AND new='1'");
if($newpmnum = $db->num_rows($query)) {
$newpmexists = 1;
if($newpmnum <= 10) {
$pmdetail = '';
while($pm = $db->fetch_array($query)) {
$pm['subject'] = cutstr($pm['subject'], 60);
$pmlist[] = $pm;
}
}
} else {
$db->query("UPDATE {$tablepre}members SET newpm='0' WHERE uid='$discuz_uid'");
if($supe['status'] && $xspacestatus) {
supe_dbconnect();
$supe['db']->query("UPDATE {$supe[tablepre]}members SET newpm='0' WHERE uid='$discuz_uid'", 'SILENT');
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/pmprompt.inc.php | PHP | asf20 | 1,545 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editpost.inc.php 10329 2007-08-27 00:58:57Z heyond $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$discuz_action = 13;
$query = $db->query("SELECT m.adminid, p.first, p.authorid, p.author, p.dateline, u.allowhtml, p.anonymous, p.invisible FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}usergroups u USING(groupid)
WHERE pid='$pid' AND tid='$tid' AND fid='$fid'");
$orig = $db->fetch_array($query);
if($magicstatus) {
$query = $db->query("SELECT magicid FROM {$tablepre}threadsmod WHERE tid='$tid' AND magicid='10'");
$magicid = $db->result($query, 0);
$allowanonymous = $allowanonymous || $magicid ? 1 : $allowanonymous;
}
$isfirstpost = $orig['first'] ? 1 : 0;
$isorigauthor = $discuz_uid && $discuz_uid == $orig['authorid'];
$isanonymous = $isanonymous && $allowanonymous ? 1 : 0;
$audit = $orig['invisible'] == -2 || $thread['displayorder'] == -2 ? $audit : 0;
if(empty($orig)) {
showmessage('undefined_action');
} elseif((!$forum['ismoderator'] || !$alloweditpost || (in_array($orig['adminid'], array(1, 2, 3)) && $adminid > $orig['adminid'])) && !($forum['alloweditpost'] && $isorigauthor)) {
showmessage('post_edit_nopermission', NULL, 'HALTED');
} elseif($thread['digest'] == '-1' && $isfirstpost) {
showmessage('special_noaction');
} elseif($isorigauthor && !$forum['ismoderator']) {
if($edittimelimit && $timestamp - $orig['dateline'] > $edittimelimit * 60) {
showmessage('post_edit_timelimit', NULL, 'HALTED');
} elseif(($isfirstpost && $modnewthreads) || (!$isfirstpost && $modnewreplies)) {
showmessage('post_edit_moderate');
}
}
$thread['pricedisplay'] = $thread['price'] == -1 ? 0 : $thread['price'];
if($tagstatus) {
$query = $db->query("SELECT tagname FROM {$tablepre}threadtags WHERE tid='$tid'");
$threadtagary = array();
while($tagname = $db->fetch_array($query)) {
$threadtagary[] = $tagname['tagname'];
}
$threadtags = dhtmlspecialchars(implode(' ',$threadtagary));
}
if($special == 5) {
$query = $db->query("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
$debate = array_merge($thread, daddslashes((array)$db->fetch_array($query), 1));
$standquery = $db->query("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$discuz_uid' AND stand<>'0' ORDER BY dateline LIMIT 1");
$firststand = $db->result($standquery, 0);
if(!$isfirstpost && $debate['endtime'] && $debate['endtime'] < $timestamp && !$forum['ismoderator']) {
showmessage('debate_end');
}
if($isfirstpost && $debate['umpirepoint'] && !$forum['ismoderator']) {
showmessage('debate_umpire_comment_invalid');
}
}
if(!submitcheck('editsubmit')) {
include_once language('misc');
$typespecial = $forum['threadtypes']['special'][$thread['typeid']] ? 'disabled' : 1;
$typeselect = typeselect($thread['typeid'], $typespecial);
if($iscircle) {
$mycircles = array();
if($discuz_uid) {
supe_dbconnect();
$query = $supe['db']->query("SELECT gid, groupname FROM {$supe[tablepre]}groupuid WHERE uid='$discuz_uid' AND flag>0", 'SILENT');
while($mycircle = $supe['db']->fetch_array($query)) {
$mycircles[$mycircle['gid']] = $mycircle['groupname'];
}
}
if($sgid = $thread['sgid']) {
supe_dbconnect();
$query = $supe['db']->query("SELECT g.groupname, gf.headerimage, gf.css FROM {$supe[tablepre]}groups g, {$supe[tablepre]}groupfields gf WHERE g.gid='$sgid' AND g.flag=1 AND g.gid=gf.gid", 'SILENT');
$circle = $supe['db']->fetch_array($query);
}
}
$icons = '';
if(!$special && is_array($_DCACHE['icons']) && $isfirstpost) {
$key = 1;
foreach($_DCACHE['icons'] as $id => $icon) {
$icons .= ' <input class="radio" type="radio" name="iconid" value="'.$id.'" '.($thread['iconid'] == $id ? 'checked="checked"' : '').' /><img src="images/icons/'.$icon.'" alt="" />';
$icons .= !(++$key % 10) ? '<br />' : '';
}
}
$query = $db->query("SELECT * FROM {$tablepre}posts WHERE pid='$pid' AND tid='$tid' AND fid='$fid'");
$postinfo = $db->fetch_array($query);
$usesigcheck = $postinfo['usesig'] ? 'checked="checked"' : '';
$urloffcheck = $postinfo['parseurloff'] ? 'checked="checked"' : '';
$smileyoffcheck = $postinfo['smileyoff'] == 1 ? 'checked="checked"' : '';
$codeoffcheck = $postinfo['bbcodeoff'] == 1 ? 'checked="checked"' : '';
$tagoffcheck = $postinfo['htmlon'] & 2 ? 'checked="checked"' : '';
$htmloncheck = $postinfo['htmlon'] & 1 ? 'checked="checked"' : '';
$poll = $temppoll = '';
if($isfirstpost) {
$thread['freecharge'] = $maxchargespan && $timestamp - $thread['dateline'] >= $maxchargespan * 3600 ? 1 : 0;
if($thread['special'] == 1 && ($alloweditpoll || $thread['authorid'] == $discuz_uid)) {
$query = $db->query("SELECT polloptionid, displayorder, polloption, multiple, visible, maxchoices, expiration FROM {$tablepre}polloptions AS polloptions LEFT JOIN {$tablepre}polls AS polls ON polloptions.tid=polls.tid WHERE polls.tid ='$tid' ORDER BY displayorder");
while($temppoll = $db->fetch_array($query)) {
$poll['multiple'] = $temppoll['multiple'];
$poll['visible'] = $temppoll['visible'];
$poll['maxchoices'] = $temppoll['maxchoices'];
$poll['expiration'] = $temppoll['expiration'];
$poll['polloptionid'][] = $temppoll['polloptionid'];
$poll['displayorder'][] = $temppoll['displayorder'];
$poll['polloption'][] = stripslashes($temppoll['polloption']);
}
} elseif($thread['special'] == 3) {
$rewardprice = abs($thread['price']);
} elseif($thread['special'] == 4) {
$activitytypelist = $activitytype ? explode("\n", trim($activitytype)) : '';
$query = $db->query("SELECT * FROM {$tablepre}activities WHERE tid='$tid'");
$activity = $db->fetch_array($query);
$activity['starttimefrom'] = gmdate("Y-m-d H:i", $activity['starttimefrom'] + $timeoffset * 3600);
$activity['starttimeto'] = $activity['starttimeto'] ? gmdate("Y-m-d H:i", $activity['starttimeto'] + $timeoffset * 3600) : '';
$activity['expiration'] = $activity['expiration'] ? gmdate("Y-m-d H:i", $activity['expiration'] + $timeoffset * 3600) : '';
} elseif($thread['special'] == 5 ) {
$debate['endtime'] = $debate['endtime'] ? gmdate("Y-m-d H:i", $debate['endtime'] + $timeoffset * 3600) : '';
}
}
if($thread['special'] == 2 && $allowposttrade) {
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE pid='$pid'");
$tradetypeselect = '';
if($db->num_rows($query)) {
$trade = $db->fetch_array($query);
$trade['expiration'] = $trade['expiration'] ? date('Y-m-d', $trade['expiration']) : '';
$trade['message'] = dhtmlspecialchars($trade['message']);
$tradetypeid = $trade['typeid'];
$forum['tradetypes'] = $forum['tradetypes'] == '' ? -1 : unserialize($forum['tradetypes']);
if((!$tradetypeid || !isset($tradetypes[$tradetypeid]) && !empty($forum['tradetypes']))) {
$tradetypeselect = '<select name="tradetypeid" onchange="ajaxget(\'post.php?action=threadtypes&tradetype=yes&typeid=\'+this.options[this.selectedIndex].value+\'&sid='.$sid.'\', \'threadtypes\', \'threadtypeswait\')"><option value="0"> </option>';
foreach($tradetypes as $typeid => $name) {
if($forum['tradetypes'] == -1 || @in_array($typeid, $forum['tradetypes'])) {
$tradetypeselect .= '<option value="'.$typeid.'">'.strip_tags($name).'</option>';
}
}
$tradetypeselect .= '</select><span id="threadtypeswait"></span>';
} else {
$tradetypeselect = '<select disabled><option>'.$tradetypes[$trade['typeid']].'</option></select>';
}
$expiration_7days = date('Y-m-d', $timestamp + 86400 * 7);
$expiration_14days = date('Y-m-d', $timestamp + 86400 * 14);
$expiration_month = date('Y-m-d', mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
$expiration_3months = date('Y-m-d', mktime(0, 0, 0, date('m')+3, date('d'), date('Y')));
$expiration_halfyear = date('Y-m-d', mktime(0, 0, 0, date('m')+6, date('d'), date('Y')));
$expiration_year = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')+1));
} else {
$tradetypeid = $special = 0;
$trade = array();
}
if($postinfo['first']) {
$tmp = explode("\t\t\t", $postinfo['message']);
$postinfo['message'] = $tmp[0];
$postinfo['aboutcounter'] = dhtmlspecialchars($tmp[1]);
}
}
if($postinfo['attachment']) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
$attachfind = $attachreplace = $attachments = array();
$query = $db->query("SELECT * FROM {$tablepre}attachments WHERE pid='$postinfo[pid]'");
while($attach = $db->fetch_array($query)) {
$attach['dateline'] = gmdate("$dateformat $timeformat", $attach['dateline'] + $timeoffset * 3600);
$attach['filesize'] = sizecount($attach[filesize]);
$attach['filetype'] = attachtype(fileext($attach['attachment'])."\t".$attach['filetype']);
if($attach['isimage']) {
$attach['url'] = $attach['remote'] ? $ftp['attachurl'] : $attachurl;
$attachfind[] = "/\[attach\]$attach[aid]\[\/attach\]/i";
$attachreplace[] = '[attachimg]'.$attach['aid'].'[/attachimg]';
}
if($special == 2 && $trade['aid'] == $attach['aid']) {
$tradeattach = $attach;
continue;
}
$attachments[] = $attach;
}
}
$postinfo['subject'] = str_replace('"', '"', $postinfo['subject']);
$postinfo['message'] = dhtmlspecialchars($postinfo['message']);
$postinfo['message'] = preg_replace($language['post_edit_regexp'], '', $postinfo['message']);
if($postinfo['attachment'] && $attachfind) {
$postinfo['message'] = preg_replace($attachfind, $attachreplace, $postinfo['message']);
}
if($special == 5) {
$standselected = array($firststand => 'selected="selected"');
}
if($thread['special'] == 2) {
include template('post_editpost_trade');
} elseif($special == 4 && $isfirstpost) {
include template('post_editpost_activity');
} else {
include template('post_editpost');
}
} else {
$redirecturl = "viewthread.php?tid=$tid&page=$page&extra=$extra#pid$pid";
if(empty($delete)) {
if($post_invalid = checkpost()) {
showmessage($post_invalid);
}
if($allowpostattach && is_array($_FILES['attach'])) {
foreach($_FILES['attach']['name'] as $attachname) {
if($attachname != '') {
checklowerlimit($creditspolicy['postattach']);
break;
}
}
}
if(!$isorigauthor && !$allowanonymous) {
if($orig['anonymous'] && !$isanonymous) {
$isanonymous = 0;
$authoradd = ', author=\''.addslashes($orig['author']).'\'';
$anonymousadd = ', anonymous=\'0\'';
} else {
$isanonymous = $orig['anonymous'];
$authoradd = $anonymousadd = '';
}
} else {
$authoradd = ', author=\''.($isanonymous ? '' : addslashes($orig['author'])).'\'';
$anonymousadd = ", anonymous='$isanonymous'";
}
if($isfirstpost) {
if($subject == '' || $message == '') {
showmessage('post_sm_isnull');
}
$typeid = isset($forum['threadtypes']['types'][$typeid]) ? $typeid : 0;
$iconid = isset($_DCACHE['icons'][$iconid]) ? $iconid : 0;
if(!$typeid && $forum['threadtypes']['required'] && !$thread['special']) {
showmessage('post_type_isnull');
}
$readperm = $allowsetreadperm ? intval($readperm) : ($isorigauthor ? 0 : 'readperm');
$price = intval($price);
$price = $thread['price'] < 0 && !$thread['special']
?($isorigauthor || !$price ? -1 : $price)
:($maxprice ? ($price <= $maxprice ? ($price > 0 ? $price : 0) : $maxprice) : ($isorigauthor ? 0 : $thread['price']));
if($price > 0 && floor($price * (1 - $creditstax)) == 0) {
showmessage('post_net_price_iszero');
}
$polladd = '';
if($thread['special'] == 1 && ($alloweditpoll || $isorigauthor) && !empty($polls)) {
$pollarray = '';
$pollarray['options'] = $polloption;
if($pollarray['options']) {
if(count($pollarray['options']) > $maxpolloptions) {
showmessage('post_poll_option_toomany');
}
foreach($pollarray['options'] as $key => $value) {
if(!trim($value)) {
$db->query("DELETE FROM {$tablepre}polloptions WHERE polloptionid='$key' AND tid='$tid'");
unset($pollarray['options'][$key]);
}
}
$polladd = ', special=\'1\'';
foreach($displayorder as $key => $value) {
if(preg_match("/^-?\d*$/", $value)) {
$pollarray['displayorder'][$key] = $value;
}
}
$pollarray['multiple'] = !empty($multiplepoll);
$pollarray['visible'] = empty($visibilitypoll);
$pollarray['expiration'] = $expiration;
foreach($polloptionid as $key => $value) {
if(!preg_match("/^\d*$/", $value)) {
showmessage('submit_invalid');
}
}
$maxchoices = $maxchoices >= count($pollarray['options']) ? count($pollarray['options']) : $maxchoices;
if(preg_match("/^\d*$/", $maxchoices)) {
if(!$pollarray['multiple']) {
$pollarray['maxchoices'] = 1;
} elseif(empty($maxchoices)) {
$pollarray['maxchoices'] = 0;
} else {
$pollarray['maxchoices'] = $maxchoices;
}
}
$expiration = intval($expiration);
if($close) {
$pollarray['expiration'] = $timestamp;
} elseif($expiration) {
if(empty($pollarray['expiration'])) {
$pollarray['expiration'] = 0;
} else {
$pollarray['expiration'] = $timestamp + 86400 * $expiration;
}
}
$optid = '';
$query = $db->query("SELECT polloptionid FROM {$tablepre}polloptions WHERE tid='$tid'");
while($tempoptid = $db->fetch_array($query)) {
$optid[] = $tempoptid['polloptionid'];
}
foreach($pollarray['options'] as $key => $value) {
$value = dhtmlspecialchars(trim($value));
if(in_array($polloptionid[$key], $optid)) {
if($alloweditpoll) {
$db->query("UPDATE {$tablepre}polloptions SET displayorder='".$pollarray['displayorder'][$key]."', polloption='$value' WHERE polloptionid='$polloptionid[$key]' AND tid='$tid'");
} else {
$db->query("UPDATE {$tablepre}polloptions SET displayorder='".$pollarray['displayorder'][$key]."' WHERE polloptionid='$polloptionid[$key]' AND tid='$tid'");
}
} else {
$db->query("INSERT INTO {$tablepre}polloptions (tid, displayorder, polloption) VALUES ('$tid', '".$pollarray['displayorder'][$key]."', '$value')");
}
}
$db->query("UPDATE {$tablepre}polls SET multiple='$pollarray[multiple]', visible='$pollarray[visible]', maxchoices='$pollarray[maxchoices]', expiration='$pollarray[expiration]' WHERE tid='$tid'", 'UNBUFFERED');
} else {
$polladd = ', special=\'0\'';
$db->query("DELETE FROM {$tablepre}polls WHERE tid='$tid'");
$db->query("DELETE FROM {$tablepre}polloptions WHERE tid='$tid'");
}
} elseif($thread['special'] == 2 && $allowposttrade) {
$message = $message."\t\t\t".$aboutcounter;
} elseif($thread['special'] == 3 && $allowpostreward) {
if($thread['price'] > 0 && $thread['price'] != $rewardprice) {
$rewardprice = intval($rewardprice);
if($rewardprice <= 0){
showmessage("reward_credits_invalid");
}
$addprice = ceil(($rewardprice - $thread['price']) + ($rewardprice - $thread['price']) * $creditstax);
if(!$forum['ismoderator']) {
if($rewardprice < $thread['price']) {
showmessage("reward_credits_fall");
} elseif($rewardprice < $minrewardprice || ($maxrewardprice > 0 && $rewardprice > $maxrewardprice)) {
showmessage("reward_credits_between");
} elseif($addprice > $_DSESSION["extcredits$creditstrans"]) {
showmessage('reward_credits_shortage');
}
}
$realprice = ceil($thread['price'] + $thread['price'] * $creditstax) + $addprice;
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans-$addprice WHERE uid='$thread[authorid]'");
$db->query("UPDATE {$tablepre}rewardlog SET netamount='$realprice' WHERE tid='$tid' AND authorid='$thread[authorid]'");
}
if(!$forum['ismoderator']) {
if($thread['replies'] > 1) {
$subject = addslashes($thread['subject']);
}
if($thread['price'] < 0) {
$rewardprice = abs($thread['price']);
}
}
$price = $thread['price'] > 0 ? $rewardprice : -$rewardprice;
} elseif($thread['special'] == 4 && $allowpostactivity) {
if(empty($starttimefrom[$activitytime])) {
showmessage('activity_fromtime_please');
} elseif(strtotime($starttimefrom[$activitytime]) === -1 || @strtotime($starttimefrom[$activitytime]) === FALSE) {
showmessage('activity_fromtime_error');
} elseif(@strtotime($starttimefrom[$activitytime]) < $timestamp) {
showmessage('activity_smaller_current');
} elseif($activitytime && ((@strtotime($starttimefrom) > @strtotime($starttimeto) || !$starttimeto))) {
showmessage('activity_fromtime_error');
} elseif(!trim($activityclass)) {
showmessage('activity_sort_please');
} elseif(!trim($activityplace)) {
showmessage('activity_address_please');
} elseif(trim($activityexpiration) && (@strtotime($activityexpiration) === -1 || @strtotime($activityexpiration) === FALSE)) {
showmessage('activity_totime_error');
}
$activity = array();
$activity['class'] = dhtmlspecialchars(trim($activityclass));
$activity['starttimefrom'] = @strtotime($starttimefrom[$activitytime]);
$activity['starttimeto'] = $activitytime ? @strtotime($starttimeto) : 0;
$activity['place'] = dhtmlspecialchars(trim($activityplace));
$activity['cost'] = intval($cost);
$activity['gender'] = intval($gender);
$activity['number'] = intval($activitynumber);
if($activityexpiration) {
$activity['expiration'] = @strtotime($activityexpiration);
} else {
$activity['expiration'] = 0;
}
$db->query("UPDATE {$tablepre}activities SET cost='$activity[cost]', starttimefrom='$activity[starttimefrom]', starttimeto='$activity[starttimeto]', place='$activity[place]', class='$activity[class]', gender='$activity[gender]', number='$activity[number]', expiration='$activity[expiration]' WHERE tid='$tid'", 'UNBUFFERED');
} elseif($thread['special'] == 5 && $allowpostdebate) {
if(empty($affirmpoint) || empty($negapoint)) {
showmessage('debate_position_nofound');
} elseif(!empty($endtime) && (!($endtime = @strtotime($endtime)) || $endtime < $timestamp)) {
showmessage('debate_endtime_invalid');
} elseif(!empty($umpire)) {
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}members WHERE username='$umpire'");
if(!$db->result($query, 0)) {
$umpire = dhtmlspecialchars($umpire);
showmessage('debate_umpire_invalid');
}
}
$affirmpoint = dhtmlspecialchars($affirmpoint);
$negapoint = dhtmlspecialchars($negapoint);
$db->query("UPDATE {$tablepre}debates SET affirmpoint='$affirmpoint', negapoint='$negapoint', endtime='$endtime', umpire='$umpire' WHERE tid='$tid' AND uid='$discuz_uid'");
}
$optiondata = array();
if($forum['threadtypes']['special'][$typeid] && $typeoption && is_array($typeoption) && $checkoption) {
$optiondata = threadtype_validator($typeoption);
}
if($forum['threadtypes']['special'][$typeid] && $optiondata && is_array($optiondata)) {
foreach($optiondata as $optionid => $value) {
$db->query("UPDATE {$tablepre}typeoptionvars SET value='$value' WHERE tid='$tid' AND optionid='$optionid'");
}
}
$sgidadd = '';
if($iscircle && $sgid) {
$sgidadd = ', sgid=0';
require_once DISCUZ_ROOT.'./include/supesite.func.php';
if(supe_circlepermission($sgid)) {
$sgidadd = ", sgid='$sgid'";
}
}
$db->query("UPDATE {$tablepre}threads SET iconid='$iconid', typeid='$typeid', subject='$subject', readperm='$readperm', price='$price' $authoradd $polladd $sgidadd ".($auditstatuson && $audit == 1 ? ",displayorder='0', moderated='1'" : '')." WHERE tid='$tid'", 'UNBUFFERED');
if($tagstatus) {
$tags = str_replace(array(chr(0xa1).chr(0xa1), chr(0xa1).chr(0x40), chr(0xe3).chr(0x80).chr(0x80)), ' ', $tags);
$tagarray = array_unique(explode(' ', censor($tags)));
$threadtagsnew = array();
$tagcount = 0;
foreach($tagarray as $tagname) {
$tagname = trim($tagname);
if(preg_match('/^([\x7f-\xff_-]|\w){3,20}$/', $tagname)) {
$threadtagsnew[] = $tagname;
if(!in_array($tagname, $threadtagary)) {
$query = $db->query("SELECT closed FROM {$tablepre}tags WHERE tagname='$tagname'");
if($db->num_rows($query)) {
if(!$tagstatus = $db->result($query, 0)) {
$db->query("UPDATE {$tablepre}tags SET total=total+1 WHERE tagname='$tagname'", 'UNBUFFERED');
}
} else {
$db->query("INSERT INTO {$tablepre}tags (tagname, closed, total)
VALUES ('$tagname', 0, 1)", 'UNBUFFERED');
$tagstatus = 0;
}
if(!$tagstatus) {
$db->query("INSERT {$tablepre}threadtags (tagname, tid) VALUES ('$tagname', '$tid')", 'UNBUFFERED');
}
}
}
$tagcount++;
if($tagcount > 4) {
unset($tagarray);
break;
}
}
foreach($threadtagary as $tagname) {
if(!in_array($tagname, $threadtagsnew)) {
if($db->result($db->query("SELECT count(*) FROM {$tablepre}threadtags WHERE tagname='$tagname' AND tid!='$tid'"), 0)) {
$db->query("UPDATE {$tablepre}tags SET total=total-1 WHERE tagname='$tagname'", 'UNBUFFERED');
} else {
$db->query("DELETE FROM {$tablepre}tags WHERE tagname='$tagname'", 'UNBUFFERED');
}
$db->query("DELETE FROM {$tablepre}threadtags WHERE tagname='$tagname' AND tid='$tid'", 'UNBUFFERED');
}
}
}
} else {
if($subject == '' && $message == '') {
showmessage('post_sm_isnull');
}
}
if($editedby && ($timestamp - $orig['dateline']) > 60 && $adminid != 1) {
include_once language('misc');
$editor = $isanonymous && $isorigauthor ? $language['anonymous'] : $discuz_user;
$edittime = gmdate($_DCACHE['settings']['dateformat'].' '.$_DCACHE['settings']['timeformat'], $timestamp + $timeoffset * 3600);
eval("\$message .= \"$language[post_edit]\";");
}
$bbcodeoff = checkbbcodes($message, !empty($bbcodeoff));
$smileyoff = checksmilies($message, !empty($smileyoff));
$tagoff = $isfirstpost ? !empty($tagoff) : 0;
$htmlon = bindec(($tagstatus && $tagoff ? 1 : 0).($allowhtml && !empty($htmlon) ? 1 : 0));
$tattachment = 0;
if($special == 2 && !empty($_FILES['tradeattach']['tmp_name'][0])) {
$_FILES['attach'] = array_merge_recursive($_FILES['attach'], $_FILES['tradeattach']);
$deleteaid[] = $tradeaid;
}
$pattachment = ($allowpostattach && $attachments = attach_upload()) ? 1 : 0;
$uattachment = ($allowpostattach && $uattachments = attach_upload('attachupdate')) ? 1 : 0;
$query = $db->query("SELECT aid, readperm, price, attachment, description, thumb, remote FROM {$tablepre}attachments WHERE pid='$pid'");
$attachdescnew = is_array($attachdescnew) ? $attachdescnew : array();
$attachpermnew = is_array($attachpermnew) ? $attachpermnew : array();
$attachpricenew = is_array($attachpricenew) ? $attachpricenew : array();
while($attach = $db->fetch_array($query)) {
$attachpermnew[$attach['aid']] = intval($attachpermnew[$attach['aid']]);
$attachpermadd = $allowsetattachperm && $attach['readperm'] != $attachpermnew[$attach['aid']] ? ", readperm='{$attachpermnew[$attach['aid']]}'" : '' ;
$attachpricenew[$attach['aid']] = intval($attachpricenew[$attach['aid']]);
$attachpriceadd = $maxprice && $attach['price'] != $attachpricenew[$attach['aid']] && $attachpricenew[$attach['aid']] <= $maxprice ? ", price='{$attachpricenew[$attach['aid']]}'" : '' ;
$attachdescnew[$attach['aid']] = cutstr(dhtmlspecialchars($attachdescnew[$attach['aid']]), 100);
$attachdescadd = $attach['description'] != $attachdescnew[$attach['aid']] ? 1 : 0;
if($uattachment || $attachpermadd || $attachdescadd || $attachpriceadd) {
$paid = 'paid'.$attach['aid'];
$attachfileadd = '';
if($uattachment && isset($uattachments[$paid])) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
$attachfileadd = ', dateline=\''.$timestamp.'\',
filename=\''.$uattachments[$paid]['name'].'\',
filetype=\''.$uattachments[$paid]['type'].'\',
filesize=\''.$uattachments[$paid]['size'].'\',
attachment=\''.$uattachments[$paid]['attachment'].'\',
thumb=\''.$uattachments[$paid]['thumb'].'\',
isimage=\''.$uattachments[$paid]['isimage'].'\',
remote=\''.$uattachments[$paid]['remote'].'\'';
unset($uattachments[$paid]);
}
$db->query("UPDATE {$tablepre}attachments SET description='{$attachdescnew[$attach['aid']]}' $attachpermadd $attachpriceadd $attachfileadd WHERE aid='$attach[aid]'");
}
}
if($uattachment && !empty($uattachments)) {
foreach($uattachments as $attach) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
}
}
if(!empty($deleteaid) || $pattachment) {
if(!empty($deleteaid) && is_array($deleteaid)) {
$deleteaids = '\''.implode("','", $deleteaid).'\'';
$query = $db->query("SELECT aid, attachment, thumb, remote FROM {$tablepre}attachments WHERE aid IN ($deleteaids) AND pid='$pid'");
while($attach = $db->fetch_array($query)) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
}
$db->query("DELETE FROM {$tablepre}attachments WHERE aid IN ($deleteaids) AND pid='$pid'");
updatecredits($orig['authorid'], $postattachcredits, -($db->affected_rows()));
}
if($pattachment) {
$searcharray = $pregarray = $replacearray = array();
foreach($attachments as $key => $attach) {
$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, price, filename, description, filetype, filesize, attachment, downloads, isimage, uid, thumb, remote)
VALUES ('$tid', '$pid', '$timestamp', '$attach[perm]', '$attach[price]', '$attach[name]', '$attach[description]', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$attach[uid]', '$attach[thumb]', '$attach[remote]')");
$searcharray[] = '[local]'.$localid[$key].'[/local]';
$pregarray[] = '/\[localimg=(\d{1,3}),(\d{1,3})\]'.$localid[$key].'\[\/localimg\]/is';
$insertid = $db->insert_id();
$replacearray[] = '[attach]'.$insertid.'[/attach]';
}
if($special == 2 && !empty($_FILES['tradeattach']['tmp_name'][0])) {
$tradeaid = $insertid;
}
$message = str_replace($searcharray, $replacearray, preg_replace($pregarray, $replacearray, $message));
updatecredits($orig['authorid'], $postattachcredits, count($attachments));
} else {
$query = $db->query("SELECT aid FROM {$tablepre}attachments WHERE pid='$pid' LIMIT 1");
$pattachment = $db->result($query, 0) ? 1 : 0;
}
if($pattachment) {
$tattachment = 1;
} else {
$query = $db->query("SELECT a.aid FROM {$tablepre}posts p, {$tablepre}attachments a WHERE a.tid='$tid' AND a.pid=p.pid AND p.invisible='0' LIMIT 1");
$tattachment = $db->result($query, 0) ? 1 : 0;
}
$db->query("UPDATE {$tablepre}threads SET attachment='$tattachment' WHERE tid='$tid'");
}
if($special == 2 && $allowposttrade) {
$oldtypeid = $db->result($db->query("SELECT typeid FROM {$tablepre}trades WHERE pid='$pid'"), 0);
$oldtypeid = isset($tradetypes[$oldtypeid]) ? $oldtypeid : 0;
$tradetypeid = !$tradetypeid ? $oldtypeid : $tradetypeid;
$optiondata = array();
threadtype_checkoption($oldtypeid, 1);
$optiondata = array();
if($tradetypes && $typeoption && is_array($typeoption) && $checkoption) {
$optiondata = threadtype_validator($typeoption);
}
if($tradetypes && $optiondata && is_array($optiondata)) {
foreach($optiondata as $optionid => $value) {
if($oldtypeid) {
$db->query("UPDATE {$tablepre}tradeoptionvars SET value='$value' WHERE pid='$pid' AND optionid='$optionid'");
} else {
$db->query("INSERT INTO {$tablepre}tradeoptionvars (typeid, pid, optionid, value)
VALUES ('$tradetypeid', '$pid', '$optionid', '$value')");
}
}
}
if(!$oldtypeid) {
$db->query("UPDATE {$tablepre}trades SET typeid='$tradetypeid' WHERE pid='$pid'");
}
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE tid='$tid' AND pid='$pid'");
if($db->num_rows($query)) {
$seller = dhtmlspecialchars(trim($seller));
$item_name = dhtmlspecialchars(trim($item_name));
$item_price = floatval($item_price);
$item_locus = dhtmlspecialchars(trim($item_locus));
$item_number = intval($item_number);
$item_quality = intval($item_quality);
$item_transport = intval($item_transport);
$postage_mail = intval($postage_mail);
$postage_express = intval(trim($postage_express));
$postage_ems = intval($postage_ems);
$item_type = intval($item_type);
$item_costprice = floatval($item_costprice);
if(!$item_name) {
showmessage('trade_please_name');
} elseif($maxtradeprice && ($mintradeprice > $item_price || $maxtradeprice < $item_price)) {
showmessage('trade_price_between');
} elseif(!$maxtradeprice && $mintradeprice > $item_price) {
showmessage('trade_price_more_than');
} elseif($item_number < 0) {
showmessage('tread_please_number');
}
$expiration = $item_expiration ? @strtotime($item_expiration) : 0;
$closed = $expiration > 0 && @strtotime($item_expiration) < $timestamp ? 1 : $closed;
switch($transport) {
case 'seller':$item_transport = 1;break;
case 'buyer':$item_transport = 2;break;
case 'virtual':$item_transport = 3;break;
case 'logistics':$item_transport = 4;break;
}
$tradeaidadd = $special == 2 && !empty($_FILES['tradeattach']['tmp_name'][0]) ? "aid='$tradeaid'," : '';
$db->query("UPDATE {$tablepre}trades SET $tradeaidadd account='$seller', subject='$item_name', price='$item_price', amount='$item_number', quality='$item_quality', locus='$item_locus',
transport='$item_transport', ordinaryfee='$postage_mail', expressfee='$postage_express', emsfee='$postage_ems', itemtype='$item_type', expiration='$expiration', closed='$closed',
costprice='$item_costprice' WHERE tid='$tid' AND pid='$pid'", 'UNBUFFERED');
$redirecturl = "viewthread.php?do=tradeinfo&tid=$tid&pid=$pid";
}
}
if($auditstatuson && $audit == 1) {
updatepostcredits('+', $orig['authorid'], ($isfirstpost ? $postcredits : $replycredits));
updatemodworks('MOD', 1);
updatemodlog($tid, 'MOD');
}
$message = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $message);
$db->query("UPDATE {$tablepre}posts SET message='$message', usesig='$usesig', htmlon='$htmlon', bbcodeoff='$bbcodeoff', parseurloff='$parseurloff',
smileyoff='$smileyoff', subject='$subject' ".($pattachment ? ", attachment='1'" : '')." $anonymousadd ".($auditstatuson && $audit == 1 ? ",invisible='0'" : '')." WHERE pid='$pid'");
$forum['lastpost'] = explode("\t", $forum['lastpost']);
if($orig['dateline'] == $forum['lastpost'][2] && ($orig['author'] == $forum['lastpost'][3] || ($forum['lastpost'][3] == '' && $orig['anonymous']))) {
$lastpost = "$tid\t".($isfirstpost ? $subject : addslashes($thread['subject']))."\t$orig[dateline]\t".($isanonymous ? '' : addslashes($orig['author']));
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$fid'", 'UNBUFFERED');
}
if($thread['lastpost'] == $orig['dateline'] && ((!$orig['anonymous'] && $thread['lastposter'] == $orig['author']) || ($orig['anonymous'] && $thread['lastposter'] == '')) && $orig['anonymous'] != $isanonymous) {
$db->query("UPDATE {$tablepre}threads SET lastposter='".($isanonymous ? '' : addslashes($orig['author']))."' WHERE tid='$tid'", 'UNBUFFERED');
}
if(!$isorigauthor) {
updatemodworks('EDT', 1);
require_once DISCUZ_ROOT.'./include/misc.func.php';
modlog($thread, 'EDT');
}
} else {
if(($isfirstpost && $thread['replies'] > 0) || !$isorigauthor) {
showmessage(($thread['special'] == 3 ? 'post_edit_reward_already_reply' : 'post_edit_nopermission'), NULL, 'HALTED');
}
if($thread['special'] == 3) {
if($thread['price'] < 0 && ($thread['dateline'] + 1 == $orig['dateline'])) {
showmessage('post_edit_reward_nopermission', NULL, 'HALTED');
}
} elseif($thread['special'] == 6 && $isfirstpost && $videoopen) {
videodelete($tid);
}
updatepostcredits('-', $orig['authorid'], ($isfirstpost ? $postcredits : $replycredits));
if($thread['special'] == 3 && $isfirstpost) {
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans+$thread[price] WHERE uid='$orig[authorid]'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}rewardlog WHERE tid='$tid'", 'UNBUFFERED');
}
$thread_attachment = $post_attachment = 0;
$query = $db->query("SELECT pid, attachment, thumb, remote FROM {$tablepre}attachments WHERE tid='$tid'");
while($attach = $db->fetch_array($query)) {
if($attach['pid'] == $pid) {
$post_attachment ++;
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
} else {
$thread_attachment = 1;
}
}
if($post_attachment) {
$db->query("DELETE FROM {$tablepre}attachments WHERE pid='$pid'", 'UNBUFFEREED');
updatecredits($orig['authorid'], $postattachcredits, -($post_attachment));
}
$db->query("DELETE FROM {$tablepre}posts WHERE pid='$pid'");
if($thread['special'] == 2) {
$db->query("DELETE FROM {$tablepre}trades WHERE pid='$pid'");
}
if($isfirstpost) {
$forumadd = 'threads=threads-\'1\', posts=posts-\'1\'';
$tablearray = array('threadsmod','relatedthreads','threads','debates','debateposts','polloptions','polls','mythreads','typeoptionvars');
foreach ($tablearray as $table) {
$db->query("DELETE FROM {$tablepre}$table WHERE tid='$tid'", 'UNBUFFERED');
}
if($globalstick && in_array($thread['displayorder'], array(2, 3))) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
} else {
$forumadd = 'posts=posts-\'1\'';
$query = $db->query("SELECT author, dateline, anonymous FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0' ORDER BY dateline DESC LIMIT 1");
$lastpost = $db->fetch_array($query);
$lastpost['author'] = !$lastpost['anonymous'] ? addslashes($lastpost['author']) : '';
$db->query("UPDATE {$tablepre}threads SET replies=replies-'1', attachment='$thread_attachment', lastposter='$lastpost[author]', lastpost='$lastpost[dateline]' WHERE tid='$tid'", 'UNBUFFERED');
}
$forum['lastpost'] = explode("\t", $forum['lastpost']);
if($orig['dateline'] == $forum['lastpost'][2] && ($orig['author'] == $forum['lastpost'][3] || ($forum['lastpost'][3] == '' && $orig['anonymous']))) {
$query = $db->query("SELECT tid, subject, lastpost, lastposter FROM {$tablepre}threads
WHERE fid='$fid' AND displayorder>='0' ORDER BY lastpost DESC LIMIT 1");
$lastthread = daddslashes($db->fetch_array($query), 1);
$forumadd .= ", lastpost='$lastthread[tid]\t$lastthread[subject]\t$lastthread[lastpost]\t$lastthread[lastposter]'";
}
$db->query("UPDATE {$tablepre}forums SET $forumadd WHERE fid='$fid'", 'UNBUFFERED');
}
// debug: update thread caches ?
if($forum['threadcaches']) {
if($isfirstpost || $page == 1 || $thread['replies'] < $_DCACHE['pospperpage'] || !empty($delete)) {
$forum['threadcaches'] && deletethreadcaches($tid);
} else {
$query = $db->query("SELECT COUNT(*) FROM {$tablepre}posts WHERE tid='$tid' AND pid<'$pid'");
if($db->result($query, 0) < $_DCACHE['settings']['postperpage']) {
$forum['threadcaches'] && deletethreadcaches($tid);
}
}
}
if($auditstatuson) {
if($audit == 1) {
showmessage('auditstatuson_succeed', $redirecturl);
} else {
showmessage('audit_edit_succeed');
}
} else {
if(!empty($delete) && $isfirstpost) {
showmessage('post_edit_delete_succeed', "forumdisplay.php?fid=$fid");
} else {
showmessage('post_edit_succeed', $redirecturl);
}
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/editpost.inc.php | PHP | asf20 | 36,925 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: insenz.func.php 10100 2007-08-23 09:37:14Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
define('INSENZ_VERSION', '1.1');
function insenz_authcode($string, $operation, $key = '') {
$key = md5($key);
$key_length = strlen($key);
$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
$string_length = strlen($string);
$rndkey = $box = array();
$result = '';
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($key[$i % $key_length]);
$box[$i] = $i;
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
return substr($result, 8);
} else {
return '';
}
} else {
return str_replace('=', '', base64_encode($result));
}
}
function insenz_convert($str, $type = 1) {
global $charset, $discuz_chs, $insenz_chs;
if($charset != 'utf-8') {
require_once DISCUZ_ROOT.'./include/chinese.class.php';
if($type) {
if(!$insenz_chs) {
$insenz_chs = new Chinese($charset, 'utf-8', TRUE);
}
$str = $insenz_chs->convert($str);
} else {
if(!$discuz_chs) {
$discuz_chs = new Chinese('utf-8', $charset, TRUE);
}
$str = $discuz_chs->convert($str);
}
}
return $type ? htmlspecialchars($str) : addslashes($str);
}
function insenz_respond($data, $status = 1, $force = 0) {
global $insenz, $timestamp;
@include_once DISCUZ_ROOT.'./discuz_version.php';
$authkey = !empty($insenz['authkey']) && !$force ? $insenz['authkey'] : 'Discuz!INSENZ';
$t_hex = sprintf("%08x", $timestamp);
$postdata = '<?xml version="1.0" encoding="UTF'.'-8"?>'.
'<response insenz_version="'.INSENZ_VERSION.'" discuz_version="'.DISCUZ_VERSION.' - '.DISCUZ_RELEASE.'">'.
($status ? "<status>1</status><reason>$data</reason>" : $data).
'</response>';
echo insenz_authcode($t_hex.md5($authkey.$postdata.$t_hex).$postdata, 'ENCODE', $authkey);
exit;
}
function insenz_cronnextrun($cronnextrun) {
global $_DCACHE;
if(empty($_DCACHE['settings']['insenz']['cronnextrun']) || $cronnextrun < $_DCACHE['settings']['insenz']['cronnextrun']) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
$_DCACHE['settings']['insenz']['cronnextrun'] = $cronnextrun;
updatesettings();
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/insenz.func.php | PHP | asf20 | 2,846 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: supesite_import.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!$supe['status']) {
showmessage('supe_resource_imported_forbid');
}
supe_dbconnect();
$discuz_action = 15;
$navtitle = '';
if(!$discuz_uid && !((!$forum['postperm'] && $allowpost) || ($forum['postperm'] && forumperm($forum['postperm'])))) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(empty($forum['allowpost'])) {
if(!$forum['postperm'] && !$allowpost) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif($forum['postperm'] && !forumperm($forum['postperm'])) {
showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
}
}
checklowerlimit($postcredits);
$itemid = intval($itemid);
if(!submitcheck('importsubmit', 0, $seccodecheck, $secqaacheck)) {
include_once DISCUZ_ROOT.'./include/forum.func.php';
$forumselect = forumselect();
$query = $db->query("SELECT f.fid,ff.threadtypes
FROM {$tablepre}forumfields ff
LEFT JOIN {$tablepre}forums f ON f.fid=ff.fid
ORDER BY f.type, f.displayorder");
$data = $threadtypes = array();
$js_threadtypes = '';
$js_threadtypesrequired = '';
while($data = $db->fetch_array($query)) {
$data['threadtypes'] = unserialize($data['threadtypes']);
$threadtypes[$data['fid']] = $data['threadtypes']['types'];
$js_threadtypes .= "threadtypes[{$data[fid]}] = new Array();\r\n";
if(is_array($data['threadtypes']['types']) && $data['threadtypes']['types']) {
foreach($data['threadtypes']['types'] as $k=>$v) {
$js_threadtypes .= "threadtypes[{$data[fid]}][$k] = '$v';\r\n";
}
}
$js_threadtypesrequired .= "threadtypesrequired[{$data[fid]}] = '{$data[threadtypes][required]}';\r\n";
}
include template('supesite_import');
} else {
if(!$fid = intval($fid)) {
showmessage('supe_pls_select_forum');
}
if(checkflood()) {
showmessage('post_flood_ctrl');
}
$typeid = intval($_POST['typeid']);
@list($defaulttypeid) = array_slice($forum['threadtypes']['types'], 0, 1);
$typeid = isset($forum['threadtypes']['types'][$typeid]) ? $typeid : ($forum['threadtypes']['required'] ? $defaulttypeid : 0);
include_once DISCUZ_ROOT.'./include/supesite.func.php';
$trade = array();
$special = 0;
$subject = $message = '';
$item = supe_xspace2forum($itemid, $subject, $message, $special, $iconid, $trade);
$iconid = intval($iconid);
$item = daddslashes($item, 1);
$subject = addslashes($subject);
$message = addslashes($message);
if(!$item) {
showmessage('supe_resource_not_exist');
}
if($item['uid'] != $discuz_uid) {
showmessage('supe_resource_is_not_of_you');
}
if($item['tid']) {
showmessage('supe_resource_have_imported_into_forum');
}
if($item['replynum'] && ($modnewthreads || $modnewreplies)) {
showmessage('supe_imported_newthread_have_replies');
}
if($special == 2) {
$allowposttrade = substr(sprintf('%04b', $forum['allowpostspecial']), -2, 1) && $allowposttrade;
if(!$ec_account) {
showmessage('supe_imported_trade_notallowed');
} elseif(!$allowposttrade) {
showmessage('supe_imported_trade_forum_notallowed');
}
}
$displayorder = $modnewthreads ? '-2' : '0';
$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, blog, special, attachment, moderated, itemid)
VALUES ('$fid', '0', '0', '$iconid', '$typeid', '$item[username]', '$item[uid]', '$subject', '$item[dateline]', '$timestamp', '$item[username]', '$displayorder', '0', '0', '$special', '0', '0', '$itemid')");
$tid = $db->insert_id();
if($special == 2) {
require_once DISCUZ_ROOT.'./api/alipayapi.php';
$trade['tid'] = $tid;
$trade['thread'] = $thread;
$trade['discuz_uid'] = $discuz_uid;
$trade['author'] = $discuz_user;
trade_create($trade);
}
unset($displayorder, $trade);
$pinvisible = $modnewthreads ? -2 : 0;
$htmlon = $forum['allowhtml'] || $allowhtml ? 1 : 0;
$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
VALUES ('$fid', '$tid', '1', '$item[username]', '$item[uid]', '$subject', '$item[dateline]', '$message', '$onlineip', '$pinvisible', '1', '$htmlon', '0', '1', '0', '0')");
$pid = $db->insert_id();
$postuids = $lastreply = $reply = array();
$replypost = 0;
if($item['replynum'] == 0) {
if(!$modnewthreads) {
updatepostcredits('+', $discuz_uid, $postcredits);
$lastpost = "$tid\t$subject\t$timestamp\t$item[username]";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+1, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
if($forum['type'] == 'sub') {
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
}
unset($lastpost);
$supe['db']->query("UPDATE {$supe[tablepre]}spaceitems SET tid='$tid' WHERE itemid='$itemid'", 'UNBUFFERED');
showmessage('supe_imported_succeed', "viewthread.php?tid=$tid");
} else {
$supe['db']->query("UPDATE {$supe[tablepre]}spaceitems SET tid='$tid' WHERE itemid='$itemid'", 'UNBUFFERED');
showmessage('supe_newthread_import_mod_succeed', "forumdisplay.php?fid=$fid");
}
} else {
$query = $supe['db']->query("SELECT cid, itemid, type, uid, authorid, author, ip, dateline, rates, message FROM {$supe[tablepre]}spacecomments WHERE itemid='$itemid' ORDER BY dateline ASC");
while($reply = $db->fetch_array($query)) {
$reply = daddslashes($reply, 1);
$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
VALUES ('$fid', '$tid', '0', '$reply[author]', '$reply[authorid]', '', '$reply[dateline]', '$reply[message]', '$reply[ip]', '0', '', '0', '0', '0', '1', '0')");
$postuids[] = $reply['uid'];
$lastreply = $reply;
$replypost++;
}
$db->query("UPDATE {$tablepre}threads SET lastpost='$timestamp', replies=replies+$replypost WHERE fid='$fid' AND tid='$tid'", 'UNBUFFERED');
$replycredits = $forum['replycredits'] ? $forum['replycredits'] : $_DCACHE['settings']['creditspolicy']['reply'];
updatepostcredits('+', $postuids, $replycredits);
unset($postuids, $reply);
$lastpost = "$tid\t$subject\t$timestamp\t$lastreply[author]";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+$replypost, todayposts=todayposts+$replypost WHERE fid='$fid'", 'UNBUFFERED');
unset($lastreply, $replypost);
if($forum['type'] == 'sub') {
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
}
$supe['db']->query("DELETE FROM {$supe[tablepre]}spacecomments WHERE itemid='$itemid'", 'UNBUFFERED');
$supe['db']->query("UPDATE {$supe[tablepre]}spaceitems SET tid='$tid' WHERE itemid='$itemid'", 'UNBUFFERED');
showmessage('supe_imported_succeed', "viewthread.php?tid=$tid");
}
}
?> | zyyhong | trunk/jiaju001/bbs/include/supesite_import.inc.php | PHP | asf20 | 7,368 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: gifmerge.class.php 9837 2007-08-16 08:23:44Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class GifMerge {
var $ver = '1.1';
var $dly = 50;
var $mod = 'C_FILE';
var $first = true;
var $use_loop = false;
var $transparent = false;
var $use_global_in = false;
var $x = 0;
var $y = 0;
var $ch = 0;
var $fin = 0;
var $fout = '';
var $loop = 0;
var $delay = 0;
var $width = 0;
var $height = 0;
var $trans1 = 255;
var $trans2 = 255;
var $trans3 = 255;
var $disposal = 2;
var $out_color_table_size = 0;
var $local_color_table_flag = 0;
var $global_color_table_size = 0;
var $out_color_table_sizecode = 0;
var $global_color_table_sizecode= 0;
var $gif = array(0x47, 0x49, 0x46);
var $buffer = array();
var $local_in = array();
var $global_in = array();
var $global_out = array();
var $logical_screen_descriptor = array();
function GifMerge($images, $t1, $t2, $t3, $loop, $dl, $xpos, $ypos, $model) {
if($model) {
$this->mod = $model;
}
if($loop > -1) {
$this->loop = floor($loop - 1);
$this->use_loop = true;
}
if($t1 > -1 && $t2 > -1 && $t3 > -1) {
$this->trans1 = $t1;
$this->trans2 = $t2;
$this->trans3 = $t3;
$this->transparent = true;
}
for($i = 0; $i < count($images); $i++) {
$dl[$i] ? $this->delay = $dl[$i] : $this->delay = $this->dly;
$xpos[$i] ? $this->x = $xpos[$i] : $this->x = 0;
$ypos[$i] ? $this->y = $ypos[$i] : $this->y = 0;
$this->start_gifmerge_process($images[$i]);
}
$this->fout .= "\x3b";
}
function start_gifmerge_process($fp) {
if($this->mod == 'C_FILE') {
if(!$this->fin = fopen($fp, 'rb')) {
return;
}
} elseif($this->mod == 'C_MEMORY') {
$this->ch = 0;
$this->fin = $fp;
}
$this->getbytes(6);
if(!$this->arrcmp($this->buffer, $this->gif, 3)) {
return;
}
$this->getbytes(7);
if($this->first) $this->logical_screen_descriptor = $this->buffer;
$this->global_color_table_sizecode = $this->buffer[4] & 0x07;
$this->global_color_table_size = 2 << $this->global_color_table_sizecode;
if($this->buffer[4] & 0x80) {
$this->getbytes((3 * $this->global_color_table_size));
for($i = 0; $i < ((3 * $this->global_color_table_size)); $i++) {
$this->global_in[$i] = $this->buffer[$i];
}
if($this->out_color_table_size == 0) {
$this->out_color_table_size = $this->global_color_table_size;
$out_color_table_sizecode = $this->global_color_table_sizecode;
$this->global_out = $this->global_in;
}
if($this->global_color_table_size != $this->out_color_table_size || $this->arrcmp($this->global_out, $this->global_in, (3 * $this->global_color_table_size))) {
$this->use_global_in = true;
}
}
for($loop = true; $loop;) {
$this->getbytes(1);
switch($this->buffer[0]) {
case 0x21:
$this->read_extension();
break;
case 0x2c:
$this->read_image_descriptor();
break;
case 0x3b:
$loop = false;
break;
default:
$loop = false;
}
}
if($this->mod == 'C_FILE') {
fclose($this->fin);
}
}
function read_image_descriptor() {
$this->getbytes(9);
$head = $this->buffer;
$this->local_color_table_flag = ($this->buffer[8] & 0x80) ? true : false;
if($this->local_color_table_flag) {
$sizecode = $this->buffer[8] & 0x07;
$size = 2 << $sizecode;
$this->getbytes(3 * $size);
for($i = 0; $i < (3 * $size); $i++) {
$this->local_in[$i] = $this->buffer[$i];
}
if($this->out_color_table_size == 0) {
$this->out_color_table_size = $size;
$out_color_table_sizecode = $sizecode;
for($i = 0; $i < (3 * $size); $i++)
{
$this->global_out[$i] = $this->local_in[$i];
}
}
}
if($this->first) {
$this->first = false;
$this->fout .= "\x47\x49\x46\x38\x39\x61";
if($this->width && $this->height) {
$this->logical_screen_descriptor[0] = $this->width & 0xFF;
$this->logical_screen_descriptor[1] = ($this->width & 0xFF00) >> 8;
$this->logical_screen_descriptor[2] = $this->height & 0xFF;
$this->logical_screen_descriptor[3] = ($this->height & 0xFF00) >> 8;
}
$this->logical_screen_descriptor[4] |= 0x80;
$this->logical_screen_descriptor[5] &= 0xF0;
$this->logical_screen_descriptor[6] |= $this->out_color_table_sizecode;
$this->putbytes($this->logical_screen_descriptor, 7);
$this->putbytes($this->global_out, ($this->out_color_table_size * 3));
if($this->use_loop) {
$ns[0] = 0x21;
$ns[1] = 0xFF;
$ns[2] = 0x0B;
$ns[3] = 0x4e;
$ns[4] = 0x45;
$ns[5] = 0x54;
$ns[6] = 0x53;
$ns[7] = 0x43;
$ns[8] = 0x41;
$ns[9] = 0x50;
$ns[10] = 0x45;
$ns[11] = 0x32;
$ns[12] = 0x2e;
$ns[13] = 0x30;
$ns[14] = 0x03;
$ns[15] = 0x01;
$ns[16] = $this->loop & 255;
$ns[17] = $this->loop >> 8;
$ns[18] = 0x00;
$this->putbytes($ns, 19);
}
}
if($this->use_global_in) {
$outtable = $this->global_in;
$outsize = $this->global_color_table_size;
$outsizecode = $this->global_color_table_sizecode;
} else {
$outtable = $this->global_out;
$outsize = $this->out_color_table_size;
}
if($this->local_color_table_flag) {
if($size == $this->out_color_table_size && !$this->arrcmp($this->local_in, $this->global_out, $size)) {
$outtable = $global_out;
$outsize = $this->out_color_table_size;
} else {
$outtable = $this->local_in;
$outsize = $size;
$outsizecode = $sizecode;
}
}
$use_trans = false;
if($this->transparent) {
for($i = 0; $i < $outsize; $i++) {
if($outtable[3 * $i] == $this->trans1 && $outtable [3 * $i + 1] == $this->trans2 && $outtable [3 * $i + 2] == $this->trans3) {
break;
}
}
if($i < $outsize) {
$transindex = $i;
$use_trans = true;
}
}
if($this->delay || $use_trans) {
$this->buffer[0] = 0x21;
$this->buffer[1] = 0xf9;
$this->buffer[2] = 0x04;
$this->buffer[3] = ($this->disposal << 2) + ($use_trans ? 1 : 0);
$this->buffer[4] = $this->delay & 0xff;
$this->buffer[5] = ($this->delay & 0xff00) >> 8;
$this->buffer[6] = $use_trans ? $transindex : 0;
$this->buffer[7] = 0x00;
$this->putbytes($this->buffer,8);
}
$this->buffer[0] = 0x2c;
$this->putbytes($this->buffer,1);
$head[0] = $this->x & 0xff;
$head[1] = ($this->x & 0xff00) >> 8;
$head[2] = $this->y & 0xff;
$head[3] = ($this->y & 0xff00) >> 8;
$head[8] &= 0x40;
if($outtable != $this->global_out) {
$head[8] |= 0x80;
$head[8] |= $outsizecode;
}
$this->putbytes($head,9);
if($outtable != $this->global_out) {
$this->putbytes($outtable, (3 * $outsize));
}
$this->getbytes(1);
$this->putbytes($this->buffer,1);
for(;;) {
$this->getbytes(1);
$this->putbytes($this->buffer,1);
if(($u = $this->buffer[0]) == 0) {
break;
}
$this->getbytes($u);
$this->putbytes($this->buffer, $u);
}
}
function read_extension() {
$this->getbytes(1);
switch($this->buffer[0]) {
case 0xf9:
$this->getbytes(6);
break;
case 0xfe:
for(;;) {
$this->getbytes(1);
if(($u = $this->buffer[0]) == 0) {
break;
}
$this->getbytes($u);
}
break;
case 0x01:
$this->getbytes(13);
for(;;) {
$this->getbytes(0);
if(($u = $this->buffer[0]) == 0) {
break;
}
$this->getbytes($u);
}
break;
case 0xff:
$this->getbytes(9);
$this->getbytes(3);
for(;;) {
$this->getbytes(1);
if(!$this->buffer[0]) {
break;
}
$this->getbytes($this->buffer[0]);
}
break;
default:
for(;;) {
$this->getbytes(1);
if(!$this->buffer[0]) {
break;
}
$this->getbytes($this->buffer[0]);
}
}
}
function arrcmp($b, $s, $l) {
for($i = 0; $i < $l; $i++) {
if($s{$i} != $b{$i}) {
return false;
}
}
return true;
}
function getbytes($l) {
for($i = 0; $i < $l; $i++) {
if($this->mod == 'C_FILE') {
$bin = unpack('C*', fread($this->fin, 1));
$this->buffer[$i] = $bin[1];
} elseif($this->mod == 'C_MEMORY') {
$bin = unpack('C*', substr($this->fin, $this->ch, 1));
$this->buffer[$i] = $bin[1];
$this->ch++;
}
}
return $this->buffer;
}
function putbytes($s, $l) {
for($i = 0; $i < $l; $i++) {
$this->fout .= pack('C*', $s[$i]);
}
}
function getAnimation() {
return $this->fout;
}
}
?>
| zyyhong | trunk/jiaju001/bbs/include/gifmerge.class.php | PHP | asf20 | 9,141 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: db_mysql.class.php 11168 2007-11-08 05:23:57Z tiger $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class dbstuff {
var $version = '';
var $querynum = 0;
var $link;
function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {
$func = empty($pconnect) ? 'mysql_connect' : 'mysql_pconnect';
if(!$this->link = @$func($dbhost, $dbuser, $dbpw)) {
$halt && $this->halt('Can not connect to MySQL server');
} else {
if($this->version() > '4.1') {
global $charset, $dbcharset;
$dbcharset = !$dbcharset && in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : $dbcharset;
$serverset = $dbcharset ? 'character_set_connection='.$dbcharset.', character_set_results='.$dbcharset.', character_set_client=binary' : '';
$serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',').'sql_mode=\'\'') : '';
$serverset && mysql_query("SET $serverset", $this->link);
}
$dbname && @mysql_select_db($dbname, $this->link);
}
}
function select_db($dbname) {
return mysql_select_db($dbname, $this->link);
}
function fetch_array($query, $result_type = MYSQL_ASSOC) {
return mysql_fetch_array($query, $result_type);
}
function fetch_first($sql) {
return $this->fetch_array($this->query($sql));
}
function result_first($sql) {
return $this->result($this->query($sql), 0);
}
function query($sql, $type = '') {
global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;
if($_GET['debug'] == '1')
{
echo $sql.'<hr>';
}
$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql, $this->link))) {
if(in_array($this->errno(), array(2006, 2013)) && substr($type, 0, 5) != 'RETRY') {
$this->close();
require DISCUZ_ROOT.'./config.inc.php';
$this->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$this->query($sql, 'RETRY'.$type);
} elseif($type != 'SILENT' && substr($type, 5) != 'SILENT') {
$this->halt('MySQL Query Error', $sql);
}
}
$this->querynum++;
return $query;
}
function affected_rows() {
return mysql_affected_rows($this->link);
}
function error() {
return (($this->link) ? mysql_error($this->link) : mysql_error());
}
function errno() {
return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
}
function result($query, $row) {
$query = @mysql_result($query, $row);
return $query;
}
function num_rows($query) {
$query = mysql_num_rows($query);
return $query;
}
function num_fields($query) {
return mysql_num_fields($query);
}
function free_result($query) {
return mysql_free_result($query);
}
function insert_id() {
return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
}
function fetch_row($query) {
$query = mysql_fetch_row($query);
return $query;
}
function fetch_fields($query) {
return mysql_fetch_field($query);
}
function version() {
if(empty($this->version)) {
$this->version = mysql_get_server_info($this->link);
}
return $this->version;
}
function close() {
return mysql_close($this->link);
}
function halt($message = '', $sql = '') {
define('CACHE_FORBIDDEN', TRUE);
require_once DISCUZ_ROOT.'./include/db_mysql_error.inc.php';
}
}
?>
| zyyhong | trunk/jiaju001/bbs/include/db_mysql.class.php | PHP | asf20 | 3,699 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: printable.inc.php 10115 2007-08-24 00:58:08Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$thisbg = '#FFFFFF';
$query = $db->query("SELECT p.*, m.username, m.groupid FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
WHERE p.tid='$tid' AND p.invisible='0' ORDER BY p.dateline LIMIT 100");
while($post = $db->fetch_array($query)) {
$post['dateline'] = gmdate("$dateformat $timeformat", $post['dateline'] + ($timeoffset * 3600));
$post['message'] = discuzcode($post['message'], $post['smileyoff'], $post['bbcodeoff'], sprintf('%00b', $post['htmlon']), $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'], $forum['allowhtml'], ($forum['jammer'] && $post['authorid'] != $discuz_uid ? 1 : 0));
if($post['attachment']) {
$attachment = 1;
}
$post['attachments'] = array();
if($post['attachment'] && $allowgetattach) {
$attachpids .= ",$post[pid]";
$post['attachment'] = 0;
if(preg_match_all("/\[attach\](\d+)\[\/attach\]/i", $post['message'], $matchaids)) {
$attachtags[$post['pid']] = $matchaids[1];
}
}
$postlist[$post['pid']] = $post;
}
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist);
}
include template('viewthread_printable');
?> | zyyhong | trunk/jiaju001/bbs/include/printable.inc.php | PHP | asf20 | 1,465 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_poll.inc.php 10458 2007-08-31 07:10:55Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($iscircle) {
$allowvote = ($circle['allowshare'] && ($circle['ispublic'] == 1 || ($circle['ispublic'] == 2 && $circle['password'] == $_DCOOKIE['gidpw'.$gid]))) || $incircle;
}
$polloptions = array();
$votersuid = '';
$query = $db->query("SELECT MAX(votes) AS max, SUM(votes) AS total FROM {$tablepre}polloptions WHERE tid = '$tid'");
if($count = $db->fetch_array($query)) {
// $query = $db->query("SELECT MAX(votes) AS max, SUM(votes) AS total FROM {$tablepre}polloptions WHERE tid = '$tid' GROUP BY tid");
$query = $db->query("SELECT multiple, visible, maxchoices, expiration FROM {$tablepre}polls WHERE tid='$tid'");
$options = $db->fetch_array($query);
$multiple = $options['multiple'];
$visible = $options['visible'];
$maxchoices = $options['maxchoices'];
$expiration = $options['expiration'];
$query = $db->query("SELECT polloptionid, votes, polloption, voterids FROM {$tablepre}polloptions WHERE tid='$tid' ORDER BY displayorder");
$voterids = '';
while($options = $db->fetch_array($query)) {
$viewvoteruid[] = $options['voterids'];
$voterids .= "\t".$options['voterids'];
$polloptions[] = array
(
'polloptionid' => $options['polloptionid'],
'polloption' => preg_replace("/\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/([^\[\"']+?)\](.+?)\[\/url\]/i",
"<a href=\"\\1://\\2\" target=\"_blank\">\\3</a>", $options['polloption']),
'votes' => $options['votes'],
'width' => @round($options['votes'] * 300 / $count['max']) + 2,
'percent' => @sprintf("%01.2f", $options['votes'] * 100 / $count['total'])
);
}
$voterids = explode("\t", $voterids);
$voters = array_unique($voterids);
$voterscount = count($voters) - 1;
array_shift($voters);
if(!$expiration) {
$expirations = $timestamp + 86400;
} else {
$expirations = $expiration;
if($expirations > $timestamp) {
$thread['remaintime'] = remaintime($expirations - $timestamp);
}
}
$allowvote = $allowvote && (empty($thread['closed']) || $alloweditpoll) && !in_array(($discuz_uid ? $discuz_uid : $onlineip), $voters) && $timestamp < $expirations && $expirations > 0;
$optiontype = $multiple ? 'checkbox' : 'radio';
$visiblepoll = $visible || $forum['ismoderator'] || ($discuz_uid && $discuz_uid == $thread['authorid']) || ($expirations >= $timestamp && in_array(($discuz_uid ? $discuz_uid : $onlineip), $voters)) ? 0 : 1;
} else {
$db->query("UPDATE {$tablepre}threads SET special='0' WHERE tid='$tid'", 'UNBUFFERED');
}
$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts, m.digestposts, m.oltime,
m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
m.extcredits7, m.extcredits8, m.email, m.gender, m.showemail, m.invisible, m.xspacestatus, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals, mf.avatar, mf.avatarwidth,
mf.avatarheight, mf.customstatus, mf.spacename $fieldsadd
FROM {$tablepre}posts p
LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
LEFT JOIN {$tablepre}memberfields mf ON mf.uid=m.uid
WHERE p.tid='$tid' AND first=1 LIMIT 1");
$post = $db->fetch_array($query);
$pid = $post['pid'];
$postlist[$post['pid']] = viewthread_procpost($post);
if($attachpids) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($attachpids, $attachtags, $postlist, $showimages);
}
viewthread_parsetags();
$post = $postlist[$post['pid']];
include template('viewthread_poll');
exit;
?> | zyyhong | trunk/jiaju001/bbs/include/viewthread_poll.inc.php | PHP | asf20 | 3,876 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common.inc.php 10344 2007-08-27 02:36:30Z monkey $
*/
error_reporting(0);
set_magic_quotes_runtime(0);
$mtime = explode(' ', microtime());
$discuz_starttime = $mtime[1] + $mtime[0];
define('SYS_DEBUG', FALSE);
define('IN_DISCUZ', TRUE);
define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -7));
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
!defined('CURSCRIPT') && define('CURSCRIPT', '');
if(PHP_VERSION < '4.1.0') {
$_GET = &$HTTP_GET_VARS;
$_POST = &$HTTP_POST_VARS;
$_COOKIE = &$HTTP_COOKIE_VARS;
$_SERVER = &$HTTP_SERVER_VARS;
$_ENV = &$HTTP_ENV_VARS;
$_FILES = &$HTTP_POST_FILES;
}
if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) {
exit('Request tainting attempted.');
}
require_once DISCUZ_ROOT.'./include/global.func.php';
define('ISROBOT', getrobot());
if(defined('NOROBOT') && ISROBOT) {
exit(header("HTTP/1.1 403 Forbidden"));
}
if(trim($_SERVER['SERVER_NAME']) == 'bbs.homebjjj.com')
{
@header('location: http://' . str_replace('.homebjjj.', '.jiaju001.', $_SERVER['SERVER_NAME']) . $_SERVER['REQUEST_URI']);
}
foreach(array('_COOKIE', '_POST', '_GET') as $_request) {
foreach($$_request as $_key => $_value) {
$_key{0} != '_' && $$_key = daddslashes($_value);
}
}
if (!MAGIC_QUOTES_GPC && $_FILES) {
$_FILES = daddslashes($_FILES);
}
$charset = $dbcharset = $forumfounders = $metakeywords = $extrahead = $seodescription = '';
$plugins = $hooks = $admincp = $jsmenu = $forum = $thread = $language = $actioncode = $modactioncode = $lang = array();
require_once DISCUZ_ROOT.'./config.inc.php';
$_DCOOKIE = $_DSESSION = $_DCACHE = $_DPLUGIN = $advlist = array();
$prelength = strlen($cookiepre);
foreach($_COOKIE as $key => $val) {
if(substr($key, 0, $prelength) == $cookiepre) {
$_DCOOKIE[(substr($key, $prelength))] = MAGIC_QUOTES_GPC ? $val : daddslashes($val);
}
}
unset($prelength, $_request, $_key, $_value);
$inajax = !empty($inajax);
$timestamp = time();
if($attackevasive) {
require_once DISCUZ_ROOT.'./include/security.inc.php';
}
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';
$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$BASESCRIPT = basename($PHP_SELF);
$boardurl = htmlspecialchars('http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api|archiver|wap)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/');
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
unset($onlineipmatches);
$cachelost = (@include DISCUZ_ROOT.'./forumdata/cache/cache_settings.php') ? '' : 'settings';
@extract($_DCACHE['settings']);
if($gzipcompress && function_exists('ob_gzhandler') && CURSCRIPT != 'wap' && !$inajax) {
ob_start('ob_gzhandler');
} else {
$gzipcompress = 0;
ob_start();
}
if(!empty($loadctrl) && substr(PHP_OS, 0, 3) != 'WIN') {
if($fp = @fopen('/proc/loadavg', 'r')) {
list($loadaverage) = explode(' ', fread($fp, 6));
fclose($fp);
if($loadaverage > $loadctrl) {
header("HTTP/1.0 503 Service Unavailable");
include DISCUZ_ROOT.'./include/serverbusy.htm';
exit();
}
}
}
if(in_array(CURSCRIPT, array('index', 'forumdisplay', 'viewthread', 'post', 'blog', 'topicadmin', 'register', 'archiver'))) {
$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/cache_'.CURSCRIPT.'.php') ? '' : ' '.CURSCRIPT;
}
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$dbuser = $dbpw = $dbname = $pconnect = NULL;
$sid = daddslashes(($transsidstatus || CURSCRIPT == 'wap') && (isset($_GET['sid']) || isset($_POST['sid'])) ?
(isset($_GET['sid']) ? $_GET['sid'] : $_POST['sid']) :
(isset($_DCOOKIE['sid']) ? $_DCOOKIE['sid'] : ''));
$discuz_auth_key = md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']);
list($discuz_pw, $discuz_secques, $discuz_uid) = empty($_DCOOKIE['auth']) ? array('', '', 0) : daddslashes(explode("\t", authcode($_DCOOKIE['auth'], 'DECODE')), 1);
$newpm = $newpmexists = $sessionexists = $seccode = $bloguid = 0;
$membertablefields = 'm.uid AS discuz_uid, m.username AS discuz_user, m.password AS discuz_pw, m.secques AS discuz_secques,
m.adminid, m.groupid, m.groupexpiry, m.extgroupids, m.email, m.timeoffset, m.tpp, m.ppp, m.posts, m.digestposts,
m.oltime, m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5,
m.extcredits6, m.extcredits7, m.extcredits8, m.timeformat, m.dateformat, m.pmsound, m.sigstatus, m.invisible,
m.lastvisit, m.lastactivity, m.lastpost, m.newpm, m.accessmasks, m.xspacestatus, m.editormode, m.customshow';
if($sid) {
if($discuz_uid) {
$query = $db->query("SELECT s.sid, s.styleid, s.groupid='6' AS ipbanned, s.pageviews AS spageviews, s.lastolupdate, s.seccode, $membertablefields
FROM {$tablepre}sessions s, {$tablepre}members m
WHERE m.uid=s.uid AND s.sid='$sid' AND CONCAT_WS('.',s.ip1,s.ip2,s.ip3,s.ip4)='$onlineip' AND m.uid='$discuz_uid'
AND m.password='$discuz_pw' AND m.secques='$discuz_secques'");
} else {
$query = $db->query("SELECT sid, uid AS sessionuid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'");
}
if($_DSESSION = $db->fetch_array($query)) {
$sessionexists = 1;
if(!empty($_DSESSION['sessionuid'])) {
$query = $db->query("SELECT $membertablefields
FROM {$tablepre}members m WHERE uid='$_DSESSION[sessionuid]'");
$_DSESSION = array_merge($_DSESSION, $db->fetch_array($query));
}
} else {
$query = $db->query("SELECT sid, groupid, groupid='6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
FROM {$tablepre}sessions WHERE sid='$sid' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'");
if($_DSESSION = $db->fetch_array($query)) {
clearcookies();
$sessionexists = 1;
}
}
}
if(!$sessionexists) {
if($discuz_uid) {
$query = $db->query("SELECT $membertablefields, m.styleid
FROM {$tablepre}members m WHERE m.uid='$discuz_uid' AND m.password='$discuz_pw' AND m.secques='$discuz_secques'");
if(!($_DSESSION = $db->fetch_array($query))) {
clearcookies();
}
}
if(ipbanned($onlineip)) $_DSESSION['ipbanned'] = 1;
$_DSESSION['sid'] = random(6);
$_DSESSION['seccode'] = random(6, 1);
}
$_DSESSION['dateformat'] = empty($_DSESSION['dateformat']) || empty($_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1])? $_DCACHE['settings']['dateformat'] : $_DCACHE['settings']['userdateformat'][$_DSESSION['dateformat'] -1];
$_DSESSION['timeformat'] = empty($_DSESSION['timeformat']) ? $_DCACHE['settings']['timeformat'] : ($_DSESSION['timeformat'] == 1 ? 'h:i A' : 'H:i');
$_DSESSION['timeoffset'] = isset($_DSESSION['timeoffset']) && $_DSESSION['timeoffset'] != 9999 ? $_DSESSION['timeoffset'] : $_DCACHE['settings']['timeoffset'];
$membertablefields = '';
@extract($_DSESSION);
$lastvisit = empty($lastvisit) ? $timestamp - 86400 : $lastvisit;
$timenow = array('time' => gmdate("$dateformat $timeformat", $timestamp + 3600 * $timeoffset),
'offset' => ($timeoffset >= 0 ? ($timeoffset == 0 ? '' : '+'.$timeoffset) : $timeoffset));
if(PHP_VERSION > '5.1') {
@date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
}
$accessadd1 = $accessadd2 = $modadd1 = $modadd2 = $metadescription = '';
if(empty($discuz_uid) || empty($discuz_user)) {
$discuz_user = $extgroupids = '';
$discuz_uid = $adminid = $posts = $digestposts = $pageviews = $oltime = $invisible
= $credits = $extcredits1 = $extcredits2 = $extcredits3 = $extcredits4
= $extcredits5 = $extcredits6 = $extcredits7 = $extcredits8 = 0;
$groupid = empty($groupid) || $groupid != 6 ? 7 : 6;
} else {
$discuz_userss = $discuz_user;
$discuz_user = addslashes($discuz_user);
if($accessmasks) {
$accessadd1 = ', a.allowview, a.allowpost, a.allowreply, a.allowgetattach, a.allowpostattach';
$accessadd2 = "LEFT JOIN {$tablepre}access a ON a.uid='$discuz_uid' AND a.fid=f.fid";
}
if($adminid == 3) {
$modadd1 = ', m.uid AS ismoderator';
$modadd2 = "LEFT JOIN {$tablepre}moderators m ON m.uid='$discuz_uid' AND m.fid=f.fid";
}
}
if($errorreport == 2 || ($errorreport == 1 && $adminid > 0)) {
error_reporting(E_ERROR | E_WARNING | E_PARSE);
}
define('FORMHASH', formhash());
$statstatus && !$inajax && require_once DISCUZ_ROOT.'./include/counter.inc.php';
$extra = isset($extra) && @preg_match("/^[&=;a-z0-9]+$/i", $extra) ? $extra : '';
$rsshead = $navtitle = $navigation = '';
$_DSESSION['groupid'] = $groupid = empty($ipbanned) ? (empty($groupid) ? 7 : intval($groupid)) : 6;
if(!@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.$groupid.'.php') {
$query = $db->query("SELECT type FROM {$tablepre}usergroups WHERE groupid='$groupid'");
$grouptype = $db->result($query, 0);
if(!empty($grouptype)) {
$cachelost .= ' usergroup_'.$groupid;
} else {
$grouptype = 'member';
}
}
if($passport_status && ($passport_status != 'shopex' || !$passport_shopex)) {
$passport_forward = rawurlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$link_login = $passport_url.$passport_login_url.(strpos($passport_login_url, '?') === FALSE ? '?' : '&').'forward='.$passport_forward;
$link_logout = $passport_url.$passport_logout_url.(strpos($passport_logout_url, '?') === FALSE ? '?' : '&').'forward='.$passport_forward;
$link_register = $passport_url.$passport_register_url.(strpos($passport_register_url, '?') === FALSE ? '?' : '&').'forward='.$passport_forward;
} else {
$link_login = 'logging.php?action=login';
$link_logout = 'logging.php?action=logout&formhash='.FORMHASH;
$link_register = $regname;
}
if($discuz_uid && $_DSESSION) {
if(!empty($groupexpiry) && $groupexpiry < $timestamp && !in_array(CURSCRIPT, array('wap', 'member'))) {
dheader("Location: {$boardurl}member.php?action=groupexpiry");
} elseif($grouptype && $groupid != getgroupid($discuz_uid, array
(
'type' => $grouptype,
'creditshigher' => $groupcreditshigher,
'creditslower' => $groupcreditslower
), $_DSESSION)) {
@extract($_DSESSION);
$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/usergroup_'.intval($groupid).'.php') ? '' : ' usergroup_'.$groupid;
}
}
$tpp = intval(empty($_DSESSION['tpp']) ? $topicperpage : $_DSESSION['tpp']);
$ppp = intval(empty($_DSESSION['ppp']) ? $postperpage : $_DSESSION['ppp']);
if(!in_array($adminid, array(1, 2, 3))) {
$alloweditpost = $alloweditpoll = $allowstickthread = $allowmodpost = $allowdelpost = $allowmassprune
= $allowrefund = $allowcensorword = $allowviewip = $allowbanip = $allowedituser = $allowmoduser
= $allowbanuser = $allowpostannounce = $allowviewlog = $disablepostctrl = $supe_allowpushthread = 0;
} elseif(isset($radminid) && $adminid != $radminid && $adminid != $groupid) {
$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/admingroup_'.intval($adminid).'.php') ? '' : ' admingroup_'.$groupid;
}
$auditstatuson = !empty($mod) && $mod == 'edit' && in_array($adminid, array(1, 2, 3)) && $allowmodpost ? true : false;
$page = isset($page) ? max(1, intval($page)) : 1;
$tid = isset($tid) && is_numeric($tid) ? $tid : 0;
$fid = isset($fid) && is_numeric($fid) ? $fid : 0;
$typeid = isset($typeid) ? intval($typeid) : 0;
if(!empty($tid) || !empty($fid)) {
if(empty($tid)) {
$query = $db->query("SELECT f.fid, f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
FROM {$tablepre}forums f
LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
WHERE f.fid='$fid'");
$forum = $db->fetch_array($query);
} else {
$query = $db->query("SELECT t.tid, t.closed,".(defined('SQL_ADD_THREAD') ? SQL_ADD_THREAD : '')." f.*, ff.* $accessadd1 $modadd1, f.fid AS fid
FROM {$tablepre}threads t
INNER JOIN {$tablepre}forums f ON f.fid=t.fid
LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid $accessadd2 $modadd2
WHERE t.tid='$tid'".($auditstatuson ? '' : " AND t.displayorder>='0'")." LIMIT 1");
$forum = $db->fetch_array($query);
$tid = $forum['tid'];
}
if($forum) {
$fid = $forum['fid'];
$forum['ismoderator'] = !empty($forum['ismoderator']) || $adminid == 1 || $adminid == 2 ? 1 : 0;
foreach(array('postcredits', 'replycredits', 'threadtypes', 'digestcredits', 'postattachcredits', 'getattachcredits', 'supe_pushsetting') as $key) {
$forum[$key] = !empty($forum[$key]) ? unserialize($forum[$key]) : array();
}
} else {
$fid = 0;
}
}
$styleid = intval(!empty($_GET['styleid']) ? $_GET['styleid'] :
(!empty($_POST['styleid']) ? $_POST['styleid'] :
(!empty($_DSESSION['styleid']) ? $_DSESSION['styleid'] :
$_DCACHE['settings']['styleid'])));
$styleid = intval(isset($stylejump[$styleid]) ? $styleid : $_DCACHE['settings']['styleid']);
if(@!include DISCUZ_ROOT.'./forumdata/cache/style_'.intval(!empty($forum['styleid']) ? $forum['styleid'] : $styleid).'.php') {
$cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/style_'.($styleid = $_DCACHE['settings']['styleid']).'.php') ? '' : ' style_'.$styleid;
}
if($cachelost) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache();
exit('Cache List: '.$cachelost.'<br />Caches successfully created, please refresh.');
}
if(CURSCRIPT != 'wap') {
if($nocacheheaders) {
@dheader("Expires: 0");
@dheader("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE);
@dheader("Pragma: no-cache");
}
if($headercharset) {
@dheader('Content-Type: text/html; charset='.$charset);
}
if(empty($_DCOOKIE['sid']) || $sid != $_DCOOKIE['sid']) {
dsetcookie('sid', $sid, 604800);
}
}
if(!empty($insenz['cronnextrun']) && $insenz['cronnextrun'] <= $timestamp) {
require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
insenz_runcron();
} elseif($cronnextrun && $cronnextrun <= $timestamp) {
require_once DISCUZ_ROOT.'./include/cron.func.php';
runcron();
} elseif(isset($insenz['statsnextrun']) && $insenz['statsnextrun'] <= $timestamp) {
require_once DISCUZ_ROOT.'./include/insenz_cron.func.php';
insenz_onlinestats();
}
if(isset($plugins['include']) && is_array($plugins['include'])) {
foreach($plugins['include'] as $include) {
if(!$include['adminid'] || ($include['adminid'] && $include['adminid'] >= $adminid)) {
@include_once DISCUZ_ROOT.'./plugins/'.$include['script'].'.inc.php';
}
}
}
if((!empty($_DCACHE['advs']) || $globaladvs) && !defined('IN_ADMINCP')) {
require_once DISCUZ_ROOT.'./include/advertisements.inc.php';
}
if(isset($allowvisit) && $allowvisit == 0 && !(CURSCRIPT == 'member' && ($action == 'groupexpiry' || $action == 'activate'))) {
showmessage('user_banned', NULL, 'HALTED');
} elseif(!(in_array(CURSCRIPT, array('logging', 'wap', 'seccode')) || $adminid == 1)) {
if($bbclosed) {
clearcookies();
$closedreason = $db->result($db->query("SELECT value FROM {$tablepre}settings WHERE variable='closedreason'"), 0);
showmessage($closedreason ? $closedreason : 'board_closed', NULL, 'NOPERM');
}
periodscheck('visitbanperiods');
}
if((!empty($fromuid) || !empty($fromuser)) && ($creditspolicy['promotion_visit'] || $creditspolicy['promotion_register'])) {
require_once DISCUZ_ROOT.'/include/promotion.inc.php';
}
$rssauth = $rssstatus && $discuz_uid ? rawurlencode(authcode("$discuz_uid\t".($fid ? $fid : '')."\t".substr(md5($discuz_pw.$discuz_secques), 0, 8), 'ENCODE', md5($_DCACHE['settings']['authkey']))) : '0';
$transferstatus = $transferstatus && $allowtransfer;
?>
| zyyhong | trunk/jiaju001/bbs/include/common.inc.php | PHP | asf20 | 16,422 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_close.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($tid)) {
showmessage('magics_info_nonexistence');
}
$thread = getpostinfo($tid, 'tid', array('fid'));
checkmagicperm($magicperm['forum'], $thread['fid']);
$db->query("UPDATE {$tablepre}threads SET closed='1', moderated='1' WHERE tid='$tid'");
$expiration = $timestamp + 86400;
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', $tid);
updatemagicthreadlog($tid, $magicid, $magic['identifier'], $expiration);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $tid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_tid'], 'tid', $tid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_close.inc.php | PHP | asf20 | 1,005 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_hidden.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($pid)) {
showmessage('magics_info_nonexistence');
}
$post = getpostinfo($pid, 'pid', array('p.tid', 'p.fid', 'p.author', 'p.authorid', 'first', 'p.dateline', 'anonymous'));
checkmagicperm($magicperm['forum'], $post['fid']);
if($post['authorid'] != $discuz_uid) {
showmessage('magics_operation_nopermission');
}
$thread = getpostinfo($post['tid'], 'tid', array('tid', 'subject', 'author', 'replies', 'lastposter'));
if($post['first']) {
$author = '';
$lastposter = $thread['replies'] > 0 ? $thread['lastposter'] : '';
$db->query("UPDATE {$tablepre}posts SET anonymous='1' WHERE tid='$post[tid]' AND first='1'");
updatemagicthreadlog($post['tid'], $magicid, $magic['identifier'], '0', '1');
} else {
$author = $thread['author'];
$lastposter = '';
$db->query("UPDATE {$tablepre}posts SET anonymous='1' WHERE pid='$pid'");
}
$query = $db->query("SELECT lastpost FROM {$tablepre}forums WHERE fid='$post[fid]'");
$forum['lastpost'] = explode("\t", $db->result($query, 0));
if($post['dateline'] == $forum['lastpost'][2] && ($post['author'] == $forum['lastpost'][3] || ($forum['lastpost'][3] == '' && $post['anonymous']))) {
$lastpost = "$thread[tid]\t$thread[subject]\t$timestamp\t$lastposter";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$post[fid]'", 'UNBUFFERED');
}
$db->query("UPDATE {$tablepre}threads SET author='$author', lastposter='$lastposter', moderated='1' WHERE tid='$post[tid]'");
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '0', $pid);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $pid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_pid'], 'pid', $pid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_hidden.inc.php | PHP | asf20 | 2,135 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_del.inc.php 10463 2007-09-03 01:23:37Z tiger $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($pid)) {
showmessage('magics_info_nonexistence');
}
$post = getpostinfo($pid, 'pid', array('t.tid', 't.fid', 't.authorid', 'first'));
checkmagicperm($magicperm['forum'], $post['fid']);
if($post['authorid'] != $discuz_uid) {
showmessage('magics_operation_nopermission');
}
require_once DISCUZ_ROOT.'./include/post.func.php';
if($post['first']) {
foreach(array('threads', 'threadsmod', 'relatedthreads', 'posts', 'polls', 'polloptions', 'trades', 'activities', 'activityapplies', 'attachments', 'favorites', 'mythreads', 'myposts', 'subscriptions', 'debates', 'debateposts', 'typeoptionvars', 'forumrecommend') as $value) {
$db->query("DELETE FROM {$tablepre}$value WHERE tid='$post[tid]'", 'UNBUFFERED');
}
$query = $db->query("SELECT uid, attachment, dateline, thumb, remote FROM {$tablepre}attachments WHERE tid='$post[tid]'");
while($attach = $db->fetch_array($query)) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
}
updateforumcount($post['fid']);
} else {
$db->query("DELETE FROM {$tablepre}posts WHERE pid='$pid'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}myposts WHERE pid='$pid'", 'UNBUFFERED');
$db->query("DELETE FROM {$tablepre}attachments WHERE pid='$pid'", 'UNBUFFERED');
$query = $db->query("SELECT uid, attachment, dateline, thumb, remote FROM {$tablepre}attachments WHERE pid='$pid'");
while($attach = $db->fetch_array($query)) {
dunlink($attach['attachment'], $attach['thumb'], $attach['remote']);
}
updatethreadcount($post['tid']);
}
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '0', $pid);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $pid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_pid'], 'pid', $pid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_del.inc.php | PHP | asf20 | 2,206 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_renew.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($pid)) {
showmessage('magics_info_nonexistence');
}
$post = getpostinfo($pid, 'pid', array('p.tid', 'p.fid', 'p.authorid', 'first', 'anonymous'));
checkmagicperm($magicperm['forum'], $post['fid']);
$query = $db->query("SELECT username FROM {$tablepre}members WHERE uid='$post[authorid]'");
$author = daddslashes($db->result($query, 0), 1);
$thread = getpostinfo($post['tid'], 'tid', array('tid', 'subject', 'author', 'replies', 'lastposter'));
if($post['first']) {
$lastposter = $thread['replies'] > 0 ? $thread['lastposter'] : $author;
$db->query("UPDATE {$tablepre}posts SET anonymous='0' WHERE tid='$post[tid]' AND first='1'");
updatemagicthreadlog($post['tid'], $magicid, $magic['identifier'], '0', '1');
} else {
$lastposter = $author;
$author = $thread['author'];
$db->query("UPDATE {$tablepre}posts SET anonymous='0' WHERE pid='$pid'");
}
$query = $db->query("SELECT lastpost FROM {$tablepre}forums WHERE fid='$post[fid]'");
$forum['lastpost'] = explode("\t", $db->result($query, 0));
if($thread['subject'] == $forum['lastpost'][1] && ($forum['lastpost'][3] == '' && $post['anonymous'])) {
$lastpost = "$thread[tid]\t$thread[subject]\t$timestamp\t$lastposter";
$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$post[fid]'", 'UNBUFFERED');
}
$db->query("UPDATE {$tablepre}threads SET author='$author', lastposter='$lastposter', moderated='1' WHERE tid='$post[tid]'");
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '0', $pid);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $pid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_pid'], 'pid', $pid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_renew.inc.php | PHP | asf20 | 2,106 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_open.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($tid)) {
showmessage('magics_info_nonexistence');
}
$thread = getpostinfo($tid, 'tid', array('fid'));
checkmagicperm($magicperm['forum'], $thread['fid']);
magicthreadmod($tid);
$db->query("UPDATE {$tablepre}threads SET closed='0', moderated='1' WHERE tid='$tid'");
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', $tid);
updatemagicthreadlog($tid, $magicid, $magic['identifier']);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $tid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_tid'], 'tid', $tid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_open.inc.php | PHP | asf20 | 979 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_up.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($tid)) {
showmessage('magics_info_nonexistence');
}
$thread = getpostinfo($tid, 'tid', array('fid'));
checkmagicperm($magicperm['forum'], $thread['fid']);
$db->query("UPDATE {$tablepre}threads SET lastpost='$timestamp', moderated='1' WHERE tid='$tid'");
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', $tid);
updatemagicthreadlog($tid, $magicid, $magic['identifier']);
showmessage('magics_operation_succeed', 'magic.php?action=user');
}
function showmagic() {
global $tid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_tid'], 'tid', $tid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_up.inc.php | PHP | asf20 | 964 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_reporter.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($username)) {
showmessage('magics_info_nonexistence');
}
$member = getuserinfo($username, array('uid', 'groupid'));
checkmagicperm($magicperm['targetgroups'], $member['groupid']);
$query = $db->query("SELECT action FROM {$tablepre}sessions WHERE uid='$member[uid]'");
if(!$msession = $db->fetch_array($query)) {
$magicmessage = 'magics_RTK_on_message';
} else {
include language('actions');
$magicmessage = 'magics_RTK_off_message';
}
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '', '', $member['uid']);
showmessage($magicmessage);
}
function showmagic() {
global $username, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_username'], 'username', $username, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_reporter.inc.php | PHP | asf20 | 1,104 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_see.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
if(empty($pid)) {
showmessage('magics_info_nonexistence');
}
$post = getpostinfo($pid, 'pid', array('p.fid', 'useip'));
checkmagicperm($magicperm['forum'], $post['fid']);
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '0', $pid);
showmessage('magics_SEK_message');
}
function showmagic() {
global $pid, $lang;
magicshowtype($lang['option'], 'top');
magicshowsetting($lang['target_pid'], 'pid', $pid, 'text');
magicshowtype('', 'bottom');
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_see.inc.php | PHP | asf20 | 781 |
<?php
/*
[Discuz!] (C)2001-2007 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic_money.inc.php 9806 2007-08-15 06:04:37Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(submitcheck('usesubmit')) {
$getmoney = rand(1, intval($magic['price'] * 1.5));
$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans+'$getmoney' WHERE uid='$discuz_uid'");
usemagic($magicid, $magic['num']);
updatemagiclog($magicid, '2', '1', '0', '', '', $discuz_uid);
showmessage('magics_MOK_message');
}
function showmagic() {
global $lang;
magicshowtips($lang['MOK_info'], $lang['option']);
}
?> | zyyhong | trunk/jiaju001/bbs/include/magic/magic_money.inc.php | PHP | asf20 | 707 |