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
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: mail.php 847 2008-12-08 05:43:24Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
define('UC_MAIL_REPEAT', 5);
class mailmodel {
var $db;
var $base;
var $apps;
function __construct(&$base) {
$this->mailmodel($base);
}
function mailmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
$this->apps = &$this->base->cache['apps'];
}
function get_total_num() {
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."mailqueue");
return $data;
}
function get_list($page, $ppp, $totalnum) {
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$data = $this->db->fetch_all("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid ORDER BY dateline DESC LIMIT $start, $ppp");
foreach((array)$data as $k => $v) {
$data[$k]['subject'] = htmlspecialchars($v['subject']);
$data[$k]['tomail'] = empty($v['tomail']) ? $v['email'] : $v['tomail'];
$data[$k]['dateline'] = $v['dateline'] ? $this->base->date($data[$k]['dateline']) : '';
$data[$k]['appname'] = $this->base->cache['apps'][$v['appid']]['name'];
}
return $data;
}
function delete_mail($ids) {
$ids = $this->base->implode($ids);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."mailqueue WHERE mailid IN ($ids)");
return $this->db->affected_rows();
}
function add($mail) {
if($mail['level']) {
$sql = "INSERT INTO ".UC_DBTABLEPRE."mailqueue (touid, tomail, subject, message, frommail, charset, htmlon, level, dateline, failures, appid) VALUES ";
$values_arr = array();
foreach($mail['uids'] as $uid) {
if(empty($uid)) continue;
$values_arr[] = "('$uid', '', '$mail[subject]', '$mail[message]', '$mail[frommail]', '$mail[charset]', '$mail[htmlon]', '$mail[level]', '$mail[dateline]', '0', '$mail[appid]')";
}
foreach($mail['emails'] as $email) {
if(empty($email)) continue;
$values_arr[] = "('', '$email', '$mail[subject]', '$mail[message]', '$mail[frommail]', '$mail[charset]', '$mail[htmlon]', '$mail[level]', '$mail[dateline]', '0', '$mail[appid]')";
}
$sql .= implode(',', $values_arr);
$this->db->query($sql);
$insert_id = $this->db->insert_id();
$insert_id && $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='mailexists', value='1'");
return $insert_id;
} else {
$mail['email_to'] = array();
$uids = 0;
foreach($mail['uids'] as $uid) {
if(empty($uid)) continue;
$uids .= ','.$uid;
}
$users = $this->db->fetch_all("SELECT uid, username, email FROM ".UC_DBTABLEPRE."members WHERE uid IN ($uids)");
foreach($users as $v) {
$mail['email_to'][] = $v['username'].'<'.$v['email'].'>';
}
foreach($mail['emails'] as $email) {
if(empty($email)) continue;
$mail['email_to'][] = $email;
}
$mail['message'] = str_replace('\"', '"', $mail['message']);
$mail['email_to'] = implode(',', $mail['email_to']);
return $this->send_one_mail($mail);
}
}
function send() {
register_shutdown_function(array($this, '_send'));
}
function _send() {
$mail = $this->_get_mail();
if(empty($mail)) {
$this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='mailexists', value='0'");
return NULL;
} else {
$mail['email_to'] = $mail['tomail'] ? $mail['tomail'] : $mail['username'].'<'.$mail['email'].'>';
if($this->send_one_mail($mail)) {
$this->_delete_one_mail($mail['mailid']);
return true;
} else {
$this->_update_failures($mail['mailid']);
return false;
}
}
}
function send_by_id($mailid) {
if ($this->send_one_mail($this->_get_mail_by_id($mailid))) {
$this->_delete_one_mail($mailid);
return true;
}
}
function send_one_mail($mail) {
if(empty($mail)) return;
$mail['email_to'] = $mail['email_to'] ? $mail['email_to'] : $mail['username'].'<'.$mail['email'].'>';
$mail_setting = $this->base->settings;
return include UC_ROOT.'lib/sendmail.inc.php';
}
function _get_mail() {
$data = $this->db->fetch_first("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid WHERE failures<'".UC_MAIL_REPEAT."' ORDER BY level DESC, mailid ASC LIMIT 1");
return $data;
}
function _get_mail_by_id($mailid) {
$data = $this->db->fetch_first("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid WHERE mailid='$mailid'");
return $data;
}
function _delete_one_mail($mailid) {
$mailid = intval($mailid);
return $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mailqueue WHERE mailid='$mailid'");
}
function _update_failures($mailid) {
$mailid = intval($mailid);
return $this->db->query("UPDATE ".UC_DBTABLEPRE."mailqueue SET failures=failures+1 WHERE mailid='$mailid'");
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/mail.php
|
PHP
|
asf20
| 5,074
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: setting.php 845 2008-12-08 05:36:51Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class settingmodel {
var $db;
var $base;
function __construct(&$base) {
$this->settingmodel($base);
}
function settingmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_settings($keys = '') {
if($keys) {
$keys = $this->base->implode($keys);
$sqladd = "k IN ($keys)";
} else {
$sqladd = '1';
}
$arr = array();
$arr = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."settings WHERE $sqladd");
if($arr) {
foreach($arr as $k => $v) {
$arr[$v['k']] = $v['v'];
unset($arr[$k]);
}
}
return $arr;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/setting.php
|
PHP
|
asf20
| 839
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: pm.php 907 2008-12-26 07:27:40Z monkey $
*/
!defined('IN_UC') && exit('Access Denied');
class pmmodel {
var $db;
var $base;
var $lang;
function __construct(&$base) {
$this->pmmodel($base);
}
function pmmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function pmintval($pmid) {
return @is_numeric($pmid) ? $pmid : 0;
}
function get_pm_by_pmid($uid, $pmid) {
$arr = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE pmid='$pmid' AND (msgtoid IN ('$uid','0') OR msgfromid='$uid')");
return $arr;
}
function get_pm_by_touid($uid, $touid, $starttime, $endtime) {
$arr1 = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' AND msgtoid='$touid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,2) ORDER BY dateline");
$arr2 = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$touid' AND msgtoid='$uid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,1) ORDER BY dateline");
$arr = array_merge($arr1, $arr2);
uasort($arr, 'pm_datelinesort');
return $arr;
}
function get_pmnode_by_pmid($uid, $pmid, $type = 0) {
$arr = array();
if($type == 1) {
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1");
} elseif($type == 2) {
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1");
} else {
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE pmid='$pmid'");
}
return $arr;
}
function set_pm_status($uid, $touid, $pmid = 0, $status = 0) {
if(!$status) {
$oldstatus = 1;
$newstatus = 0;
} else {
$oldstatus = 0;
$newstatus = 1;
}
if($touid) {
$ids = is_array($touid) ? $this->base->implode($touid) : $touid;
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET new='$newstatus' WHERE msgfromid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED');
}
if($pmid) {
$ids = is_array($pmid) ? $this->base->implode($pmid) : $pmid;
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET new='$newstatus' WHERE pmid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED');
}
}
function get_pm_num($uid, $folder, $filter, $a) {
$folder = $folder;
$get_pm_num = 0;
$pm_num = isset($_COOKIE['uc_pmnum']) && ($pm_num = explode('|', $_COOKIE['uc_pmnum'])) && $pm_num[0] == $uid ? $pm_num : array(0,0,0,0);
switch($folder) {
case 'newbox':
$get_pm_num = $this->get_num($uid, 'newbox');
break;
case 'inbox':
if(!$filter && $a != 'view') {
$get_pm_num = $this->get_num($uid, 'inbox');
} else {
$get_pm_num = $pm_num[1];
}
break;
}
if($a == 'ls') {
$get_announcepm_num = $this->get_num($uid, 'inbox', 'announcepm');
$get_systempm_num = $this->get_num($uid, 'inbox', 'systempm');
$get_newinbox_num = $this->get_num($uid, 'inbox', 'newpm');
} else {
list(, $get_newinbox_num, $get_systempm_num, $get_announcepm_num) = $pm_num;
}
if($pm_num[2] != $get_newinbox_num || $pm_num[3] != $get_systempm_num || $pm_num[4] != $get_announcepm_num) {
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
$this->base->setcookie('uc_pmnum', $uid.'|'.$get_pm_num.'|'.$get_systempm_num.'|'.$get_announcepm_num, 3600);
}
return array($get_pm_num, $get_newinbox_num, 0, $get_systempm_num, $get_announcepm_num);
}
function get_num($uid, $folder, $filter = '') {
switch($folder) {
case 'newbox':
$sql = "SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND folder='inbox' AND new='1'";
$num = $this->db->result_first($sql);
return $num;
case 'inbox':
if($filter == 'newpm') {
$filteradd = "msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND folder='inbox' AND new='1'";
} elseif($filter == 'systempm') {
$filteradd = "msgtoid='$uid' AND msgfromid='0' AND folder='inbox'";
} elseif($filter == 'privatepm') {
$filteradd = "msgtoid='$uid' AND related='0' AND msgfromid>'0' AND folder='inbox'";
} elseif($filter == 'announcepm') {
$filteradd = "msgtoid='0' AND folder='inbox'";
} else {
$filteradd = "msgtoid='$uid' AND related='0' AND folder='inbox'";
}
$sql = "SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE $filteradd";
break;
case 'savebox':
$sql = "SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgfromid='$uid' AND folder='outbox'";
break;
}
$num = $this->db->result_first($sql);
return $num;
}
function get_pm_list($uid, $pmnum, $folder, $filter, $page, $ppp = 10, $new = 0) {
$ppp = $ppp ? $ppp : 10;
if($folder != 'searchbox') {
$start_limit = $this->base->page_get_start($page, $ppp, $pmnum);
} else {
$start_limit = ($page - 1) * $ppp;
}
switch($folder) {
case 'newbox':
$folder = 'inbox';
$filter = 'newpm';
case 'inbox':
if($filter == 'newpm') {
$filteradd = "pm.msgtoid='$uid' AND (pm.related='0' AND pm.msgfromid>'0' OR pm.msgfromid='0') AND pm.folder='inbox' AND pm.new='1'";
} elseif($filter == 'systempm') {
$filteradd = "pm.msgtoid='$uid' AND pm.msgfromid='0' AND pm.folder='inbox'";
} elseif($filter == 'privatepm') {
$filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.msgfromid>'0' AND pm.folder='inbox'";
} elseif($filter == 'announcepm') {
$filteradd = "pm.msgtoid='0' AND pm.folder='inbox'";
} else {
$filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.folder='inbox'";
}
$sql = "SELECT pm.*,m.username as msgfrom FROM ".UC_DBTABLEPRE."pms pm
LEFT JOIN ".UC_DBTABLEPRE."members m ON pm.msgfromid = m.uid
WHERE $filteradd ORDER BY pm.dateline DESC LIMIT $start_limit, $ppp";
break;
case 'searchbox':
$filteradd = "msgtoid='$uid' AND folder='inbox' AND message LIKE '%".(str_replace('_', '\_', addcslashes($filter, '%_')))."%'";
$sql = "SELECT * FROM ".UC_DBTABLEPRE."pms
WHERE $filteradd ORDER BY dateline DESC LIMIT $start_limit, $ppp";
break;
case 'savebox':
$sql = "SELECT p.*, m.username AS msgto FROM ".UC_DBTABLEPRE."pms p
LEFT JOIN ".UC_DBTABLEPRE."members m ON m.uid=p.msgtoid
WHERE p.related='0' AND p.msgfromid='$uid' AND p.folder='outbox'
ORDER BY p.dateline DESC LIMIT $start_limit, $ppp";
break;
}
$query = $this->db->query($sql);
$array = array();
$today = $this->base->time - ($this->base->time + $this->base->settings['timeoffset']) % 86400;
while($data = $this->db->fetch_array($query)) {
$daterange = 5;
if($data['dateline'] >= $today) {
$daterange = 1;
} elseif($data['dateline'] >= $today - 86400) {
$daterange = 2;
} elseif($data['dateline'] >= $today - 172800) {
$daterange = 3;
} elseif($data['dateline'] >= $today - 604800) {
$daterange = 4;
}
$data['daterange'] = $daterange;
$data['daterangetext'] = !empty($this->lang['pm_daterange_'.$daterange]) ? $this->lang['pm_daterange_'.$daterange] : $daterange;
$data['dbdateline'] = $data['dateline'];
$data['datelinetime'] = $this->base->date($data['dateline'], 1);
$data['dateline'] = $this->base->date($data['dateline']);
$data['subject'] = $data['subject'] != '' ? htmlspecialchars($data['subject']) : $this->lang['pm_notitle'];
$data['newstatus'] = $data['new'];
$data['touid'] = $data['avataruid'] = $uid == $data['msgfromid'] ? $data['msgtoid'] : $data['msgfromid'];
$data['message'] = $this->removecode($data['message'], 80);
$array[] = $data;
}
if(in_array($folder, array('inbox', 'outbox'))) {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'", 'UNBUFFERED');
}
return $array;
}
function sendpm($subject, $message, $msgfrom, $msgto, $pmid = 0, $savebox = 0, $related = 0) {
$_CACHE['badwords'] = $this->base->cache('badwords');
if($_CACHE['badwords']['findpattern']) {
$subject = @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $subject);
$message = @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $message);
}
if($savebox && $pmid) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET msgtoid= '$msgto', subject='$subject', dateline='".$this->base->time."', related='$related', message='$message'
WHERE pmid='$pmid' AND folder='outbox' AND msgfromid='".$msgfrom['uid']."'");
} else {
if($msgfrom['uid'] && $msgfrom['uid'] == $msgto) {
return 0;
}
$box = $savebox ? 'outbox' : 'inbox';
$subject = trim($subject);
if($subject == '' && !$related) {
$subject = $this->removecode(trim($message), 75);
} else {
$subject = $this->base->cutstr(trim($subject), 75, ' ');
}
if($msgfrom['uid']) {
if($msgto) {
$sessionexist = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'");
} else {
$sessionexist = 0;
}
if(!$sessionexist || $sessionexist > 1) {
if($sessionexist > 1) {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'");
}
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES
('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','0','$message','".$this->base->app['appid']."')");
$lastpmid = $this->db->insert_id();
} else {
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET subject='$subject', message='$message', dateline='".$this->base->time."', new='1', fromappid='".$this->base->app['appid']."'
WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'");
}
if($msgto && !$savebox) {
$sessionexist = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgto' AND msgtoid='$msgfrom[uid]' AND folder='inbox' AND related='0'");
if($msgfrom['uid'] && !$sessionexist) {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES
('".$msgfrom['username']."','$msgto','".$msgfrom['uid']."','$box','0','$subject','".$this->base->time."','0','$message','0')");
}
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES
('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','".($msgfrom['uid'] ? 1 : 0)."','$message','".$this->base->app['appid']."')");
$lastpmid = $this->db->insert_id();
}
if($msgto) {
$this->db->query("REPLACE INTO ".UC_DBTABLEPRE."newpm (uid) VALUES ('$msgto')");
}
} else {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES
('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','0','$message','".$this->base->app['appid']."')");
$lastpmid = $this->db->insert_id();
}
}
return $lastpmid;
}
function set_ignore($uid) {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'");
}
function check_newpm($uid, $more) {
if($more < 2) {
$newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'");
if($newpm) {
$newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND folder='inbox' AND new='1'");
if($more) {
$newprvpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND folder='inbox' AND new='1'");
return array('newpm' => $newpm, 'newprivatepm' => $newprvpm);
} else {
return $newpm;
}
}
} else {
$newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND folder='inbox' AND new='1'");
$newprvpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND folder='inbox' AND new='1'");
if($more == 2 || $more == 3) {
$annpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgtoid='0' AND folder='inbox'");
$syspm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgtoid='$uid' AND folder='inbox' AND msgfromid='0'");
}
if($more == 2) {
return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm);
} if($more == 4) {
return array('newpm' => $newpm, 'newprivatepm' => $newprvpm);
} else {
$pm = $this->db->fetch_first("SELECT pm.dateline,pm.msgfromid,m.username as msgfrom,pm.message FROM ".UC_DBTABLEPRE."pms pm LEFT JOIN ".UC_DBTABLEPRE."members m ON pm.msgfromid = m.uid WHERE (pm.related='0' OR pm.msgfromid='0') AND pm.msgtoid='$uid' AND pm.folder='inbox' ORDER BY pm.dateline DESC LIMIT 1");
return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm, 'lastdate' => $pm['dateline'], 'lastmsgfromid' => $pm['msgfromid'], 'lastmsgfrom' => $pm['msgfrom'], 'lastmsg' => $pm['message']);
}
}
}
function deletepm($uid, $pmids) {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' AND pmid IN (".$this->base->implode($pmids).")");
$delnum = $this->db->affected_rows();
return $delnum;
}
function deleteuidpm($uid, $ids, $folder = 'inbox', $filter = '') {
$delnum = 0;
if($folder == 'inbox' || $folder == 'newbox') {
if($filter == 'announcepm' && $this->base->user['admin']) {
$pmsadd = "pmid IN (".$this->base->implode($ids).")";
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE folder='inbox' AND msgtoid='0' AND $pmsadd", 'UNBUFFERED');
} elseif($ids) {
$delnum = 1;
$deluids = $this->base->implode($ids);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms
WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND related='0'", 'UNBUFFERED');
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET delstatus=2
WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED');
$this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET delstatus=1
WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED');
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms
WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND delstatus=1 AND folder='inbox'", 'UNBUFFERED');
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms
WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND delstatus=2 AND folder='inbox'", 'UNBUFFERED');
}
} elseif($folder == 'savebox') {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms
WHERE pmid IN (".$this->base->implode($ids).") AND folder='outbox' AND msgfromid='$uid'", 'UNBUFFERED');
$delnum = 1;
}
return $delnum;
}
function get_blackls($uid, $uids = array()) {
if(!$uids) {
$blackls = $this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'");
} else {
$uids = $this->base->implode($uids);
$blackls = array();
$query = $this->db->query("SELECT uid, blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid IN ($uids)");
while($data = $this->db->fetch_array($query)) {
$blackls[$data['uid']] = explode(',', $data['blacklist']);
}
}
return $blackls;
}
function set_blackls($uid, $blackls) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."memberfields SET blacklist='$blackls' WHERE uid='$uid'");
return $this->db->affected_rows();
}
function update_blackls($uid, $username, $action = 1) {
$username = !is_array($username) ? array($username) : $username;
if($action == 1) {
if(!in_array('{ALL}', $username)) {
$usernames = $this->base->implode($username);
$query = $this->db->query("SELECT username FROM ".UC_DBTABLEPRE."members WHERE username IN ($usernames)");
$usernames = array();
while($data = $this->db->fetch_array($query)) {
$usernames[addslashes($data['username'])] = addslashes($data['username']);
}
if(!$usernames) {
return 0;
}
$blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'"));
if($blackls) {
$list = explode(',', $blackls);
foreach($list as $k => $v) {
if(in_array($v, $usernames)) {
unset($usernames[$v]);
}
}
}
if(!$usernames) {
return 1;
}
$listnew = implode(',', $usernames);
$blackls .= $blackls !== '' ? ','.$listnew : $listnew;
} else {
$blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'"));
$blackls .= ',{ALL}';
}
} else {
$blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'"));
$list = $blackls = explode(',', $blackls);
foreach($list as $k => $v) {
if(in_array($v, $username)) {
unset($blackls[$k]);
}
}
$blackls = implode(',', $blackls);
}
$this->db->query("UPDATE ".UC_DBTABLEPRE."memberfields SET blacklist='$blackls' WHERE uid='$uid'");
return 1;
}
function removecode($str, $length) {
return trim($this->base->cutstr(preg_replace(array(
"/\[(email|code|quote|img)=?.*\].*?\[\/(email|code|quote|img)\]/siU",
"/\[\/?(b|i|url|u|color|size|font|align|list|indent|float)=?.*\]/siU",
"/\r\n/",
), '', $str), $length));
}
function count_pm_by_fromuid($uid, $timeoffset = 86400) {
$dateline = $this->base->time - intval($timeoffset);
return $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' AND dateline>'$dateline'");
}
function is_reply_pm($uid, $touids) {
$touid_str = implode("', '", $touids);
$pm_reply = $this->db->fetch_all("SELECT msgfromid, msgtoid FROM ".UC_DBTABLEPRE."pms WHERE msgfromid IN ('$touid_str') AND msgtoid='$uid' AND related=1", 'msgfromid');
foreach($touids as $val) {
if(!isset($pm_reply[$val])) {
return false;
}
}
return true;
}
}
function pm_datelinesort($a, $b) {
if ($a['dateline'] == $b['dateline']) {
return 0;
}
return ($a['dateline'] < $b['dateline']) ? -1 : 1;
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/pm.php
|
PHP
|
asf20
| 19,367
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: domain.php 847 2008-12-08 05:43:24Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class domainmodel {
var $db;
var $base;
function __construct(&$base) {
$this->domainmodel($base);
}
function domainmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function add_domain($domain, $ip) {
if($domain) {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."domains SET domain='$domain', ip='$ip'");
}
return $this->db->insert_id();
}
function get_total_num() {
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."domains");
return $data;
}
function get_list($page, $ppp, $totalnum) {
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."domains LIMIT $start, $ppp");
return $data;
}
function delete_domain($arr) {
$domainids = $this->base->implode($arr);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."domains WHERE id IN ($domainids)");
return $this->db->affected_rows();
}
function update_domain($domain, $ip, $id) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."domains SET domain='$domain', ip='$ip' WHERE id='$id'");
return $this->db->affected_rows();
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/domain.php
|
PHP
|
asf20
| 1,389
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: note.php 915 2009-01-19 05:55:43Z monkey $
*/
!defined('IN_UC') && exit('Access Denied');
define('UC_NOTE_REPEAT', 5);
define('UC_NOTE_TIMEOUT', 15);
define('UC_NOTE_GC', 10000);
define('API_RETURN_FAILED', '-1');
class notemodel {
var $db;
var $base;
var $apps;
var $operations = array();
var $notetype = 'HTTP';
function __construct(&$base) {
$this->notemodel($base);
}
function notemodel(&$base) {
$this->base = $base;
$this->db = $base->db;
$this->apps = $this->base->cache('apps');
$this->operations = array(
'test'=>array('', 'action=test'),
'deleteuser'=>array('', 'action=deleteuser'),
'renameuser'=>array('', 'action=renameuser'),
'deletefriend'=>array('', 'action=deletefriend'),
'gettag'=>array('', 'action=gettag', 'tag', 'updatedata'),
'getcreditsettings'=>array('', 'action=getcreditsettings'),
'getcredit'=>array('', 'action=getcredit'),
'updatecreditsettings'=>array('', 'action=updatecreditsettings'),
'updateclient'=>array('', 'action=updateclient'),
'updatepw'=>array('', 'action=updatepw'),
'updatebadwords'=>array('', 'action=updatebadwords'),
'updatehosts'=>array('', 'action=updatehosts'),
'updateapps'=>array('', 'action=updateapps'),
'updatecredit'=>array('', 'action=updatecredit'),
);
}
function get_total_num($all = TRUE) {
$closedadd = $all ? '' : ' WHERE closed=\'0\'';
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."notelist $closedadd");
return $data;
}
function get_list($page, $ppp, $totalnum, $all = TRUE) {
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$closedadd = $all ? '' : ' WHERE closed=\'0\'';
$data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."notelist $closedadd ORDER BY dateline DESC LIMIT $start, $ppp");
foreach((array)$data as $k => $v) {
$data[$k]['postdata2'] = addslashes(str_replace('"', '', $data[$k]['postdata']));
$data[$k]['getdata2'] = addslashes(str_replace('"', '', $v['getdata']));
$data[$k]['dateline'] = $v['dateline'] ? $this->base->date($data[$k]['dateline']) : '';
}
return $data;
}
function delete_note($ids) {
$ids = $this->base->implode($ids);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."notelist WHERE noteid IN ($ids)");
return $this->db->affected_rows();
}
function add($operation, $getdata='', $postdata='', $appids=array(), $pri = 0) {
$extra = $varextra = '';
foreach((array)$this->apps as $appid => $app) {
$appid = $app['appid'];
if($appid == intval($appid)) {
if($appids && !in_array($appid, $appids)) {
$appadd[] = 'app'.$appid."='1'";
} else {
$varadd[] = "('noteexists{$appid}', '1')";
}
}
}
if($appadd) {
$extra = implode(',', $appadd);
$extra = $extra ? ', '.$extra : '';
}
if($varadd) {
$varextra = implode(', ', $varadd);
$varextra = $varextra ? ', '.$varextra : '';
}
$getdata = addslashes($getdata);
$postdata = addslashes($postdata);
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."notelist SET getdata='$getdata', operation='$operation', pri='$pri', postdata='$postdata'$extra");
$insert_id = $this->db->insert_id();
$insert_id && $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars (name, value) VALUES ('noteexists', '1')$varextra");
return $insert_id;
}
function send() {
register_shutdown_function(array($this, '_send'));
}
function _send() {
$note = $this->_get_note();
if(empty($note)) {
$this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='noteexists', value='0'");
return NULL;
}
$closenote = TRUE;
foreach((array)$this->apps as $appid => $app) {
$appnotes = $note['app'.$appid];
if($app['recvnote'] && $appnotes != 1 && $appnotes > -UC_NOTE_REPEAT) {
$this->sendone($appid, 0, $note);
$closenote = FALSE;
break;
}
}
if($closenote) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."notelist SET closed='1' WHERE noteid='$note[noteid]'");
}
$this->_gc();
}
function sendone($appid, $noteid = 0, $note = '') {
require_once UC_ROOT.'./lib/xml.class.php';
$return = FALSE;
$app = $this->apps[$appid];
if($noteid) {
$note = $this->_get_note_by_id($noteid);
}
$this->base->load('misc');
$apifilename = isset($app['apifilename']) && $app['apifilename'] ? $app['apifilename'] : 'uc.php';
if($app['extra']['apppath'] && @include $app['extra']['apppath'].'./api/'.$apifilename) {
$uc_note = new uc_note();
$method = $note['operation'];
if(is_string($method) && !empty($method)) {
parse_str($note['getdata'], $note['getdata']);
if(get_magic_quotes_gpc()) {
$note['getdata'] = $this->base->dstripslashes($note['getdata']);
}
$note['postdata'] = xml_unserialize($note['postdata']);
$response = $uc_note->$method($note['getdata'], $note['postdata']);
}
unset($uc_note);
} else {
$url = $this->get_url_code($note['operation'], $note['getdata'], $appid);
$note['postdata'] = str_replace(array("\n", "\r"), '', $note['postdata']);
$response = trim($_ENV['misc']->dfopen2($url, 0, $note['postdata'], '', 1, $app['ip'], UC_NOTE_TIMEOUT, TRUE));
}
$returnsucceed = $response != '' && ($response == 1 || is_array(xml_unserialize($response)));
$closedsqladd = $this->_close_note($note, $this->apps, $returnsucceed, $appid) ? ",closed='1'" : '';//
if($returnsucceed) {
if($this->operations[$note['operation']][2]) {
$this->base->load($this->operations[$note['operation']][2]);
$func = $this->operations[$note['operation']][3];
$_ENV[$this->operations[$note['operation']][2]]->$func($appid, $response);
}
$this->db->query("UPDATE ".UC_DBTABLEPRE."notelist SET app$appid='1', totalnum=totalnum+1, succeednum=succeednum+1, dateline='{$this->base->time}' $closedsqladd WHERE noteid='$note[noteid]'", 'SILENT');
$return = TRUE;
} else {
$this->db->query("UPDATE ".UC_DBTABLEPRE."notelist SET app$appid = app$appid-'1', totalnum=totalnum+1, dateline='{$this->base->time}' $closedsqladd WHERE noteid='$note[noteid]'", 'SILENT');
$return = FALSE;
}
return $return;
}
function _get_note() {
$data = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."notelist WHERE closed='0' ORDER BY pri DESC, noteid ASC LIMIT 1");
return $data;
}
function _gc() {
rand(0, UC_NOTE_GC) == 0 && $this->db->query("DELETE FROM ".UC_DBTABLEPRE."notelist WHERE closed='1'");
}
function _close_note($note, $apps, $returnsucceed, $appid) {
$note['app'.$appid] = $returnsucceed ? 1 : $note['app'.$appid] - 1;
$appcount = count($apps);
foreach($apps as $key => $app) {
$appstatus = $note['app'.$app['appid']];
if(!$app['recvnote'] || $appstatus == 1 || $appstatus <= -UC_NOTE_REPEAT) {
$appcount--;
}
}
if($appcount < 1) {
return TRUE;
//$closedsqladd = ",closed='1'";
}
}
function _get_note_by_id($noteid) {
$data = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."notelist WHERE noteid='$noteid'");
return $data;
}
function get_url_code($operation, $getdata, $appid) {
$app = $this->apps[$appid];
$authkey = $app['authkey'];
$url = $app['url'];
$apifilename = isset($app['apifilename']) && $app['apifilename'] ? $app['apifilename'] : 'uc.php';
$action = $this->operations[$operation][1];
$code = urlencode($this->base->authcode("$action&".($getdata ? "$getdata&" : '')."time=".$this->base->time, 'ENCODE', $authkey));
return $url."/api/$apifilename?code=$code";
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/note.php
|
PHP
|
asf20
| 7,748
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: user.php 879 2008-12-15 03:28:36Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class usermodel {
var $db;
var $base;
function __construct(&$base) {
$this->usermodel($base);
}
function usermodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_user_by_uid($uid) {
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."members WHERE uid='$uid'");
return $arr;
}
function get_user_by_username($username) {
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."members WHERE username='$username'");
return $arr;
}
function check_username($username) {
$guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
$len = strlen($username);
if($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
return FALSE;
} else {
return TRUE;
}
}
function check_mergeuser($username) {
$data = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->base->app['appid']."' AND username='$username'");
return $data;
}
function check_usernamecensor($username) {
$_CACHE['badwords'] = $this->base->cache('badwords');
$censorusername = $this->base->get_setting('censorusername');
$censorusername = $censorusername['censorusername'];
$censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censorusername = trim($censorusername)), '/')).')$/i';
$usernamereplaced = isset($_CACHE['badwords']['findpattern']) && !empty($_CACHE['badwords']['findpattern']) ? @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $username) : $username;
if(($usernamereplaced != $username) || ($censorusername && preg_match($censorexp, $username))) {
return FALSE;
} else {
return TRUE;
}
}
function check_usernameexists($username) {
$data = $this->db->result_first("SELECT username FROM ".UC_DBTABLEPRE."members WHERE username='$username'");
return $data;
}
function check_emailformat($email) {
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
function check_emailaccess($email) {
$setting = $this->base->get_setting(array('accessemail', 'censoremail'));
$accessemail = $setting['accessemail'];
$censoremail = $setting['censoremail'];
$accessexp = '/('.str_replace("\r\n", '|', preg_quote(trim($accessemail), '/')).')$/i';
$censorexp = '/('.str_replace("\r\n", '|', preg_quote(trim($censoremail), '/')).')$/i';
if($accessemail || $censoremail) {
if(($accessemail && !preg_match($accessexp, $email)) || ($censoremail && preg_match($censorexp, $email))) {
return FALSE;
} else {
return TRUE;
}
} else {
return TRUE;
}
}
function check_emailexists($email, $username = '') {
$sqladd = $username !== '' ? "AND username<>'$username'" : '';
$email = $this->db->result_first("SELECT email FROM ".UC_DBTABLEPRE."members WHERE email='$email' $sqladd");
return $email;
}
function check_login($username, $password, &$user) {
$user = $this->get_user_by_username($username);
if(empty($user['username'])) {
return -1;
} elseif($user['password'] != md5(md5($password).$user['salt'])) {
return -2;
}
return $user['uid'];
}
function add_user($username, $password, $email, $uid = 0, $questionid = '', $answer = '') {
$salt = substr(uniqid(rand()), -6);
$password = md5(md5($password).$salt);
$sqladd = $uid ? "uid='".intval($uid)."'," : '';
$sqladd .= $questionid > 0 ? " secques='".$this->quescrypt($questionid, $answer)."'," : " secques='',";
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."members SET $sqladd username='$username', password='$password', email='$email', regip='".$this->base->onlineip."', regdate='".$this->base->time."', salt='$salt'");
$uid = $this->db->insert_id();
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."memberfields SET uid='$uid'");
return $uid;
}
function edit_user($username, $oldpw, $newpw, $email, $ignoreoldpw = 0, $questionid = '', $answer = '') {
$data = $this->db->fetch_first("SELECT username, uid, password, salt FROM ".UC_DBTABLEPRE."members WHERE username='$username'");
if($ignoreoldpw) {
$isprotected = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."protectedmembers WHERE uid = '$data[uid]'");
if($isprotected) {
return -8;
}
}
if(!$ignoreoldpw && $data['password'] != md5(md5($oldpw).$data['salt'])) {
return -1;
}
$sqladd = $newpw ? "password='".md5(md5($newpw).$data['salt'])."'" : '';
$sqladd .= $email ? ($sqladd ? ',' : '')." email='$email'" : '';
if($questionid !== '') {
if($questionid > 0) {
$sqladd .= ($sqladd ? ',' : '')." secques='".$this->quescrypt($questionid, $answer)."'";
} else {
$sqladd .= ($sqladd ? ',' : '')." secques=''";
}
}
if($sqladd || $emailadd) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."members SET $sqladd WHERE username='$username'");
return $this->db->affected_rows();
} else {
return -7;
}
}
function delete_user($uidsarr) {
$uidsarr = (array)$uidsarr;
$uids = $this->base->implode($uidsarr);
$arr = $this->db->fetch_all("SELECT uid FROM ".UC_DBTABLEPRE."protectedmembers WHERE uid IN ($uids)");
$puids = array();
foreach((array)$arr as $member) {
$puids[] = $member['uid'];
}
$uids = $this->base->implode(array_diff($uidsarr, $puids));
if($uids) {
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."members WHERE uid IN($uids)");
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."memberfields WHERE uid IN($uids)");
$this->delete_useravatar($uidsarr);
$this->base->load('note');
$_ENV['note']->add('deleteuser', "ids=$uids");
return $this->db->affected_rows();
} else {
return 0;
}
}
function delete_useravatar($uidsarr) {
$uidsarr = (array)$uidsarr;
foreach((array)$uidsarr as $uid) {
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'big', 'real')) && unlink($avatar_file);
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'middle', 'real')) && unlink($avatar_file);
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'small', 'real')) && unlink($avatar_file);
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'big')) && unlink($avatar_file);
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'middle')) && unlink($avatar_file);
file_exists($avatar_file = UC_DATADIR.'./avatar/'.$this->base->get_avatar($uid, 'small')) && unlink($avatar_file);
}
}
function get_total_num($sqladd = '') {
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."members $sqladd");
return $data;
}
function get_list($page, $ppp, $totalnum, $sqladd) {
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."members $sqladd LIMIT $start, $ppp");
return $data;
}
function name2id($usernamesarr) {
$usernamesarr = daddslashes($usernamesarr, 1, TRUE);
$usernames = $this->base->implode($usernamesarr);
$query = $this->db->query("SELECT uid FROM ".UC_DBTABLEPRE."members WHERE username IN($usernames)");
$arr = array();
while($user = $this->db->fetch_array($query)) {
$arr[] = $user['uid'];
}
return $arr;
}
function quescrypt($questionid, $answer) {
return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : '';
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/user.php
|
PHP
|
asf20
| 7,843
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: friend.php 772 2008-11-26 08:44:48Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class friendmodel {
var $db;
var $base;
function __construct(&$base) {
$this->friendmodel($base);
}
function friendmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function add($uid, $friendid, $comment='') {
$direction = $this->db->result_first("SELECT direction FROM ".UC_DBTABLEPRE."friends WHERE uid='$friendid' AND friendid='$uid' LIMIT 1");
if($direction == 1) {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."friends SET uid='$uid', friendid='$friendid', comment='$comment', direction='3'", 'SILENT');
$this->db->query("UPDATE ".UC_DBTABLEPRE."friends SET direction='3' WHERE uid='$friendid' AND friendid='$uid'");
return 1;
} elseif($direction == 2) {
return 1;
} elseif($direction == 3) {
return -1;
} else {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."friends SET uid='$uid', friendid='$friendid', comment='$comment', direction='1'", 'SILENT');
return $this->db->insert_id();
}
}
function delete($uid, $friendids) {
$friendids = $this->base->implode($friendids);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."friends WHERE uid='$uid' AND friendid IN ($friendids)");
$affectedrows = $this->db->affected_rows();
if($affectedrows > 0) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."friends SET direction=1 WHERE uid IN ($friendids) AND friendid='$uid' AND direction='3'");
}
return $affectedrows;
}
function get_totalnum_by_uid($uid, $direction = 0) {
$sqladd = '';
if($direction == 0) {
$sqladd = "uid='$uid'";
} elseif($direction == 1) {
$sqladd = "uid='$uid' AND direction='1'";
} elseif($direction == 2) {
$sqladd = "friendid='$uid' AND direction='1'";
} elseif($direction == 3) {
$sqladd = "uid='$uid' AND direction='3'";
}
$totalnum = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."friends WHERE $sqladd");
return $totalnum;
}
function get_list($uid, $page, $pagesize, $totalnum, $direction = 0) {
$start = $this->base->page_get_start($page, $pagesize, $totalnum);
$sqladd = '';
if($direction == 0) {
$sqladd = "f.uid='$uid'";
} elseif($direction == 1) {
$sqladd = "f.uid='$uid' AND f.direction='1'";
} elseif($direction == 2) {
$sqladd = "f.friendid='$uid' AND f.direction='1'";
} elseif($direction == 3) {
$sqladd = "f.uid='$uid' AND f.direction='3'";
}
if($sqladd) {
$data = $this->db->fetch_all("SELECT f.*, m.username FROM ".UC_DBTABLEPRE."friends f LEFT JOIN ".UC_DBTABLEPRE."members m ON f.friendid=m.uid WHERE $sqladd LIMIT $start, $pagesize");
return $data;
} else {
return array();
}
}
function is_friend($uid, $friendids, $direction = 0) {
$friendid_str = implode("', '", $friendids);
$sqladd = '';
if($direction == 0) {
$sqladd = "uid='$uid'";
} elseif($direction == 1) {
$sqladd = "uid='$uid' AND friendid IN ('$friendid_str') AND direction='1'";
} elseif($direction == 2) {
$sqladd = "friendid='$uid' AND uid IN ('$friendid_str') AND direction='1'";
} elseif($direction == 3) {
$sqladd = "uid='$uid' AND friendid IN ('$friendid_str') AND direction='3'";
}
if($this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."friends WHERE $sqladd") == count($friendids)) {
return true;
} else {
return false;
}
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/friend.php
|
PHP
|
asf20
| 3,574
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: admin.php 753 2008-11-14 06:48:25Z cnteacher $
*/
!defined('IN_UC') && exit('Access Denied');
class adminbase extends base {
var $cookie_status = 1;
function __construct() {
$this->adminbase();
}
function adminbase() {
parent::__construct();
$this->cookie_status = isset($_COOKIE['sid']) ? 1 : 0;
$sid = $this->cookie_status ? getgpc('sid', 'C') : rawurlencode(getgpc('sid', 'R'));
$this->view->sid = $sid;
$this->view->assign('sid', $this->view->sid);
$this->view->assign('iframe', getgpc('iframe'));
$a = getgpc('a');
if(getgpc('m') !='user' && $a != 'login' && $a != 'logout') {
$this->check_priv();
}
}
function check_priv() {
$username = $this->sid_decode($this->view->sid);
if(empty($username)) {
header('Location: '.UC_API.'/admin.php?m=user&a=login&iframe='.getgpc('iframe', 'G').($this->cookie_status ? '' : '&sid='.$this->view->sid));
exit;
} else {
$this->user['isfounder'] = $username == 'UCenterAdministrator' ? 1 : 0;
if(!$this->user['isfounder']) {
$admin = $this->db->fetch_first("SELECT a.*, m.* FROM ".UC_DBTABLEPRE."admins a LEFT JOIN ".UC_DBTABLEPRE."members m USING(uid) WHERE a.username='$username'");
if(empty($admin)) {
header('Location: '.UC_API.'/admin.php?m=user&a=login&iframe='.getgpc('iframe', 'G').($this->cookie_status ? '' : '&sid='.$this->view->sid));
exit;
} else {
$this->user = $admin;
$this->user['username'] = $username;
$this->user['admin'] = 1;
$this->view->sid = $this->sid_encode($username);
$this->setcookie('sid', $this->view->sid, 86400);
}
} else {
$this->user['username'] = 'UCenterAdministrator';
$this->user['admin'] = 1;
}
$this->view->assign('user', $this->user);
}
}
function is_founder($username) {
return $this->user['isfounder'];
}
function writelog($action, $extra = '') {
$log = htmlspecialchars($this->user['username']."\t".$this->onlineip."\t".$this->time."\t$action\t$extra");
$logfile = UC_ROOT.'./data/logs/'.gmdate('Ym', $this->time).'.php';
if(@filesize($logfile) > 2048000) {
PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
$hash = '';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
for($i = 0; $i < 4; $i++) {
$hash .= $chars[mt_rand(0, 61)];
}
@rename($logfile, UC_ROOT.'./data/logs/'.gmdate('Ym', $this->time).'_'.$hash.'.php');
}
if($fp = @fopen($logfile, 'a')) {
@flock($fp, 2);
@fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $log)."\n");
@fclose($fp);
}
}
function fetch_plugins() {
$plugindir = UC_ROOT.'./plugin';
$d = opendir($plugindir);
while($f = readdir($d)) {
if($f != '.' && $f != '..' && is_dir($plugindir.'/'.$f)) {
$pluginxml = $plugindir.$f.'/plugin.xml';
$plugins[] = xml_unserialize($pluginxml);
}
}
}
function _call($a, $arg) {
if(method_exists($this, $a) && $a{0} != '_') {
$this->$a();
} else {
exit('Method does not exists');
}
}
function sid_encode($username) {
$ip = $this->onlineip;
$agent = $_SERVER['HTTP_USER_AGENT'];
$authkey = md5($ip.$agent.UC_KEY);
$check = substr(md5($ip.$agent), 0, 8);
return rawurlencode($this->authcode("$username\t$check", 'ENCODE', $authkey, 1800));
}
function sid_decode($sid) {
$ip = $this->onlineip;
$agent = $_SERVER['HTTP_USER_AGENT'];
$authkey = md5($ip.$agent.UC_KEY);
$s = $this->authcode(rawurldecode($sid), 'DECODE', $authkey, 1800);
if(empty($s)) {
return FALSE;
}
@list($username, $check) = explode("\t", $s);
if($check == substr(md5($ip.$agent), 0, 8)) {
return $username;
} else {
return FALSE;
}
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/admin.php
|
PHP
|
asf20
| 3,911
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: user.php 753 2008-11-14 06:48:25Z cnteacher $
*/
!defined('IN_UC') && exit('Access Denied');
class versionmodel {
var $db;
var $base;
function __construct(&$base) {
$this->versionmodel($base);
}
function versionmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function check() {
$data = $this->db->result_first("SELECT v FROM ".UC_DBTABLEPRE."settings WHERE k='version'");
return $data;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/version.php
|
PHP
|
asf20
| 575
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: app.php 844 2008-12-08 02:06:04Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class appmodel {
var $db;
var $base;
function __construct(&$base) {
$this->appmodel($base);
}
function appmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_apps($col = '*', $where = '') {
$arr = $this->db->fetch_all("SELECT $col FROM ".UC_DBTABLEPRE."applications".($where ? ' WHERE '.$where : ''), 'appid');
foreach($arr as $k => $v) {
isset($v['extra']) && !empty($v['extra']) && $v['extra'] = unserialize($v['extra']);
if($tmp = $this->base->authcode($v['authkey'], 'DECODE', UC_MYKEY)) {
$v['authkey'] = $tmp;
}
$arr[$k] = $v;
}
return $arr;
}
function get_app_by_appid($appid, $includecert = FALSE) {
$appid = intval($appid);
$arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."applications WHERE appid='$appid'");
$arr['extra'] = unserialize($arr['extra']);
if($tmp = $this->base->authcode($arr['authkey'], 'DECODE', UC_MYKEY)) {
$arr['authkey'] = $tmp;
}
if($includecert) {
$this->load('plugin');
$certfile = $_ENV['plugin']->cert_get_file();
$appdata = $_ENV['plugin']->cert_dump_decode($certfile);
if(is_array($appdata[$appid])) {
$arr += $appdata[$appid];
}
}
return $arr;
}
function delete_apps($appids) {
$appids = $this->base->implode($appids);
$this->db->query("DELETE FROM ".UC_DBTABLEPRE."applications WHERE appid IN ($appids)");
return $this->db->affected_rows();
}
/* function update_app($appid, $name, $url, $authkey, $charset, $dbcharset) {
if($name && $appid) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."applications SET name='$name', url='$url', authkey='$authkey', ip='$ip', synlogin='$synlogin', charset='$charset', dbcharset='$dbcharset' WHERE appid='$appid'");
return $this->db->affected_rows();
}
return 0;
}*/
//private
function alter_app_table($appid, $operation = 'ADD') {
if($operation == 'ADD') {
$this->db->query("ALTER TABLE ".UC_DBTABLEPRE."notelist ADD COLUMN app$appid tinyint NOT NULL", 'SILENT');
} else {
$this->db->query("ALTER TABLE ".UC_DBTABLEPRE."notelist DROP COLUMN app$appid", 'SILENT');
}
}
function test_api($url, $ip = '') {
$this->base->load('misc');
if(!$ip) {
$ip = $_ENV['misc']->get_host_by_url($url);
}
if($ip < 0) {
return FALSE;
}
return $_ENV['misc']->dfopen($url, 0, '', '', 1, $ip);
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/app.php
|
PHP
|
asf20
| 2,628
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: feed.php 845 2008-12-08 05:36:51Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class feedmodel {
var $db;
var $base;
var $apps;
var $operations = array();
function __construct(&$base) {
$this->feedmodel($base);
}
function feedmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_total_num() {
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."feeds");
return $data;
}
function get_list($page, $ppp, $totalnum) {
$start = $this->base->page_get_start($page, $ppp, $totalnum);
$data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."feeds LIMIT $start, $ppp");
foreach((array)$data as $k=> $v) {
$searchs = $replaces = array();
$title_data = $_ENV['misc']->string2array($v['title_data']);
foreach(array_keys($title_data) as $key) {
$searchs[] = '{'.$key.'}';
$replaces[] = $title_data[$key];
}
$searchs[] = '{actor}';
$replaces[] = $v['username'];
$searchs[] = '{app}';
$replaces[] = $this->base->apps[$v['appid']]['name'];
$data[$k]['title_template'] = str_replace($searchs, $replaces, $data[$k]['title_template']);
$data[$k]['dateline'] = $v['dateline'] ? $this->base->date($data[$k]['dateline']) : '';
}
return $data;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/feed.php
|
PHP
|
asf20
| 1,433
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: misc.php 845 2008-12-08 05:36:51Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
define('UC_ARRAY_SEP_1', 'UC_ARRAY_SEP_1');
define('UC_ARRAY_SEP_2', 'UC_ARRAY_SEP_2');
class miscmodel {
var $db;
var $base;
function __construct(&$base) {
$this->miscmodel($base);
}
function miscmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_host_by_url($url) {
$m = parse_url($url);
if(!$m['host']) {
return -1;
}
if(!preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $m['host'])) {
$ip = @gethostbyname($m['host']);
if(!$ip || $ip == $m['host']) {
return -2;
}
return $ip;
} else {
return $m['host'];
}
}
function check_url($url) {
return preg_match("/(https?){1}:\/\/|www\.([^\[\"']+?)?/i", $url);
}
function check_ip($url) {
return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $url);
}
function dfopen2($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') {
$__times__ = isset($_GET['__times__']) ? intval($_GET['__times__']) + 1 : 1;
if($__times__ > 2) {
return '';
}
$url .= (strpos($url, '?') === FALSE ? '?' : '&')."__times__=$__times__";
return $this->dfopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $encodetype);
}
function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE , $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') {
//error_log("[uc_server]\r\nurl: $url\r\npost: $post\r\n\r\n", 3, 'c:/log/php_fopen.txt');
$return = '';
$matches = parse_url($url);
$host = $matches['host'];
$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
$port = !empty($matches['port']) ? $matches['port'] : 80;
if($post) {
$out = "POST $path HTTP/1.0\r\n";
$out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "\n")));
$out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\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 $path HTTP/1.0\r\n";
$out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
}
$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
if(!$fp) {
return '';
} else {
stream_set_blocking($fp, $block);
stream_set_timeout($fp, $timeout);
@fwrite($fp, $out);
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
$return .= $data;
if($limit) {
$limit -= strlen($data);
$stop = $limit <= 0;
}
}
}
@fclose($fp);
return $return;
}
}
function array2string($arr) {
$s = $sep = '';
if($arr && is_array($arr)) {
foreach($arr as $k => $v) {
$s .= $sep.$k.UC_ARRAY_SEP_1.$v;
$sep = UC_ARRAY_SEP_2;
}
}
return $s;
}
function string2array($s) {
$arr = explode(UC_ARRAY_SEP_2, $s);
$arr2 = array();
foreach($arr as $k => $v) {
list($key, $val) = explode(UC_ARRAY_SEP_1, $v);
$arr2[$key] = $val;
}
return $arr2;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/misc.php
|
PHP
|
asf20
| 4,198
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tag.php 753 2008-11-14 06:48:25Z cnteacher $
*/
!defined('IN_UC') && exit('Access Denied');
class tagmodel {
var $db;
var $base;
function __construct(&$base) {
$this->tagmodel($base);
}
function tagmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_tag_by_name($tagname) {
$arr = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."tags WHERE tagname='$tagname'");
return $arr;
}
function get_template($appid) {
$result = $this->db->result_first("SELECT tagtemplates FROM ".UC_DBTABLEPRE."applications WHERE appid='$appid'");
return $result;
}
function updatedata($appid, $data) {
$appid = intval($appid);
include_once UC_ROOT.'lib/xml.class.php';
$data = xml_unserialize($data);
$this->base->load('app');
$data[0] = addslashes($data[0]);
$datanew = array();
if(is_array($data[1])) {
foreach($data[1] as $r) {
$datanew[] = $_ENV['misc']->array2string($r);
}
}
$tmp = $_ENV['app']->get_apps('type', "appid='$appid'");
$datanew = addslashes($tmp[0]['type']."\t".implode("\t", $datanew));
if(!empty($data[0])) {
$return = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."tags WHERE tagname='$data[0]' AND appid='$appid'");
if($return) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."tags SET data='$datanew', expiration='".$this->base->time."' WHERE tagname='$data[0]' AND appid='$appid'");
} else {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."tags (tagname, appid, data, expiration) VALUES ('$data[0]', '$appid', '$datanew', '".$this->base->time."')");
}
}
}
function formatcache($appid, $tagname) {
$return = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."tags WHERE tagname='$tagname' AND appid='$appid'");
if($return) {
$this->db->query("UPDATE ".UC_DBTABLEPRE."tags SET expiration='0' WHERE tagname='$tagname' AND appid='$appid'");
} else {
$this->db->query("INSERT INTO ".UC_DBTABLEPRE."tags (tagname, appid, expiration) VALUES ('$tagname', '$appid', '0')");
}
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/tag.php
|
PHP
|
asf20
| 2,212
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cron.php 847 2008-12-08 05:43:24Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class cronmodel {
var $db;
var $base;
function __construct(&$base) {
$this->cronmodel($base);
}
function cronmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function note_delete_user() {
//
}
function note_delete_pm() {
//
$data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."badwords");
return $data;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/cron.php
|
PHP
|
asf20
| 617
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cache.php 845 2008-12-08 05:36:51Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
if(!function_exists('file_put_contents')) {
function file_put_contents($filename, $s) {
$fp = @fopen($filename, 'w');
@fwrite($fp, $s);
@fclose($fp);
}
}
class cachemodel {
var $db;
var $base;
var $map;
function __construct(&$base) {
$this->cachemodel($base);
}
function cachemodel(&$base) {
$this->base = $base;
$this->db = $base->db;
$this->map = array(
'settings' => array('settings'),
'badwords' => array('badwords'),
'plugins' => array('plugins'),
'apps' => array('apps'),
);
}
//public
function updatedata($cachefile = '') {
if($cachefile) {
foreach((array)$this->map[$cachefile] as $modules) {
$s = "<?php\r\n";
foreach((array)$modules as $m) {
$method = "_get_$m";
$s .= '$_CACHE[\''.$m.'\'] = '.var_export($this->$method(), TRUE).";\r\n";
}
$s .= "\r\n?>";
@file_put_contents(UC_DATADIR."./cache/$cachefile.php", $s);
}
} else {
foreach((array)$this->map as $file => $modules) {
$s = "<?php\r\n";
foreach($modules as $m) {
$method = "_get_$m";
$s .= '$_CACHE[\''.$m.'\'] = '.var_export($this->$method(), TRUE).";\r\n";
}
$s .= "\r\n?>";
@file_put_contents(UC_DATADIR."./cache/$file.php", $s);
}
}
}
function updatetpl() {
$tpl = dir(UC_DATADIR.'view');
while($entry = $tpl->read()) {
if(preg_match("/\.php$/", $entry)) {
@unlink(UC_DATADIR.'view/'.$entry);
}
}
$tpl->close();
}
//private
function _get_badwords() {
$data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."badwords");
$return = array();
if(is_array($data)) {
foreach($data as $k => $v) {
$return['findpattern'][$k] = $v['findpattern'];
$return['replace'][$k] = $v['replacement'];
}
}
return $return;
}
//private
function _get_apps() {
$this->base->load('app');
$apps = $_ENV['app']->get_apps();
$apps2 = array();
if(is_array($apps)) {
foreach($apps as $v) {
$apps2[$v['appid']] = $v;
}
}
return $apps2;
}
//private
function _get_settings() {
return $this->base->get_setting();
}
//private
function _get_plugins() {
$this->base->load('plugin');
return $_ENV['plugin']->get_plugins();
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/cache.php
|
PHP
|
asf20
| 2,504
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: plugin.php 845 2008-12-08 05:36:51Z zhaoxiongfei $
*/
!defined('IN_UC') && exit('Access Denied');
class pluginmodel {
var $db;
var $base;
function __construct(&$base) {
$this->pluginmodel($base);
}
function pluginmodel(&$base) {
$this->base = $base;
$this->db = $base->db;
}
function get_plugins() {
include_once UC_ROOT.'./lib/xml.class.php';
$arr = array();
$dir = UC_ROOT.'./plugin';
$d = opendir($dir);
while($f = readdir($d)) {
if($f != '.' && $f != '..' && $f != '.svn' && is_dir($dir.'/'.$f)) {
$s = file_get_contents($dir.'/'.$f.'/plugin.xml');
$arr1 = xml_unserialize($s);
$arr1['dir'] = $f;
unset($arr1['lang']);
$arr[] = $arr1;
}
}
$arr = $this->orderby_tabindex($arr);
return $arr;
}
function get_plugin($pluginname) {
$f = file_get_contents(UC_ROOT."./plugin/$pluginname/plugin.xml");
include_once UC_ROOT.'./lib/xml.class.php';
return xml_unserialize($f);
}
function get_plugin_by_name($pluginname) {
$dir = UC_ROOT.'./plugin';
$s = file_get_contents($dir.'/'.$pluginname.'/plugin.xml');
return xml_unserialize($s, TRUE);
}
function orderby_tabindex($arr1) {
$arr2 = array();
$t = array();
foreach($arr1 as $k => $v) {
$t[$k] = $v['tabindex'];
}
asort($t);
$arr3 = array();
foreach($t as $k => $v) {
$arr3[$k] = $arr1[$k];
}
return $arr3;
}
function cert_get_file() {
return UC_ROOT.'./data/tmp/ucenter_'.substr(md5(UC_KEY), 0, 16).'.cert';
}
function cert_dump_encode($arr, $life = 0) {
$s = "# UCenter Applications Setting Dump\n".
"# Version: UCenter ".UC_SERVER_VERSION."\n".
"# Time: ".$this->time."\n".
"# Expires: ".($this->time + $life)."\n".
"# From: ".UC_API."\n".
"#\n".
"# This file was BASE64 encoded\n".
"#\n".
"# UCenter Community: http://www.discuz.net\n".
"# Please visit our website for latest news about UCenter\n".
"# --------------------------------------------------------\n\n\n".
wordwrap(base64_encode(serialize($arr)), 50, "\n", 1);
return $s;
}
function cert_dump_decode($certfile) {
$s = @file_get_contents($certfile);
if(empty($s)) {
return array();
}
preg_match("/# Expires: (.*?)\n/", $s, $m);
if(empty($m[1]) || $m[1] < $this->time) {
unlink($certfile);
return array();
}
$s = preg_replace("/(#.*\s+)*/", '', $s);
$arr = daddslashes(unserialize(base64_decode($s)), 1);
return $arr;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/model/plugin.php
|
PHP
|
asf20
| 2,621
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: avatar.php 910 2008-12-30 03:51:44Z monkey $
*/
error_reporting(0);
define('UC_API', strtolower(($_SERVER['HTTPS'] == 'on' ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'))));
$uid = isset($_GET['uid']) ? $_GET['uid'] : 0;
$size = isset($_GET['size']) ? $_GET['size'] : '';
$random = isset($_GET['random']) ? $_GET['random'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';
$check = isset($_GET['check_file_exists']) ? $_GET['check_file_exists'] : '';
$avatar = './data/avatar/'.get_avatar($uid, $size, $type);
if(file_exists(dirname(__FILE__).'/'.$avatar)) {
if($check) {
echo 1;
exit;
}
$random = !empty($random) ? rand(1000, 9999) : '';
$avatar_url = empty($random) ? $avatar : $avatar.'?random='.$random;
} else {
if($check) {
echo 0;
exit;
}
$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
$avatar_url = 'images/noavatar_'.$size.'.gif';
}
if(empty($random)) {
header("HTTP/1.1 301 Moved Permanently");
header("Last-Modified:".date('r'));
header("Expires: ".date('r', time() + 86400));
}
header('Location: '.UC_API.'/'.$avatar_url);
exit;
function get_avatar($uid, $size = 'middle', $type = '') {
$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
$uid = abs(intval($uid));
$uid = sprintf("%09d", $uid);
$dir1 = substr($uid, 0, 3);
$dir2 = substr($uid, 3, 2);
$dir3 = substr($uid, 5, 2);
$typeadd = $type == 'real' ? '_real' : '';
return $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).$typeadd."_avatar_$size.jpg";
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/uc_server/avatar.php
|
PHP
|
asf20
| 1,756
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: ajax.php 17239 2008-12-11 05:12:34Z liuqiang $
*/
define('CURSCRIPT', 'ajax');
define('NOROBOT', TRUE);
require_once './include/common.inc.php';
if($action == 'updatesecqaa') {
$message = '';
if($secqaa) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
$secqaa = max(1, random(1, 1));
$message = $_DCACHE['secqaa'][$secqaa]['question'];
if($seclevel) {
$seccode = $secqaa * 1000000 + substr($seccode, -6);
updatesession();
} else {
dsetcookie('secq', authcode($secqaa."\t".$timestamp."\t".$discuz_uid, 'ENCODE'), 3600);
}
}
showmessage($message);
} elseif($action == 'updateseccode') {
$message = '';
if($seccodestatus) {
$secqaa = substr($seccode, 0, 1);
$seccode = random(6, 1);
$rand = random(5, 1);
if($seclevel) {
$seccode += $secqaa * 1000000;
updatesession();
} else {
$key = $seccodedata['type'] != 3 ? '' : $_DCACHE['settings']['authkey'].date('Ymd');
dsetcookie('secc', authcode($seccode."\t".$timestamp."\t".$discuz_uid, 'ENCODE', $key), 3600);
}
if($seccodedata['type'] == 2) {
$message = '<span id="seccodeswf_'.$secchecktype.'"></span>'.(extension_loaded('ming') ? "<script type=\"text/javascript\" reload=\"1\">\n$('seccodeswf_$secchecktype').innerHTML=AC_FL_RunContent(
'width', '$seccodedata[width]', 'height', '$seccodedata[height]', 'src', 'seccode.php?update=$rand',
'quality', 'high', 'wmode', 'transparent', 'bgcolor', '#ffffff',
'align', 'middle', 'menu', 'false', 'allowScriptAccess', 'sameDomain');\n</script>" :
"<script type=\"text/javascript\" reload=\"1\">\n$('seccodeswf_$secchecktype').innerHTML=AC_FL_RunContent(
'width', '$seccodedata[width]', 'height', '$seccodedata[height]', 'src', '{$boardurl}images/seccode/flash/flash2.swf',
'FlashVars', 'sFile={$boardurl}seccode.php?update=$rand', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true');\n</script>");
} elseif($seccodedata['type'] == 3) {
$flashcode = "<span id=\"seccodeswf_$secchecktype\"></span><script type=\"text/javascript\" reload=\"1\">\n$('seccodeswf_$secchecktype').innerHTML=AC_FL_RunContent(
'id', 'seccodeplayer', 'name', 'seccodeplayer', 'width', '0', 'height', '0', 'src', '{$boardurl}images/seccode/flash/flash1.swf',
'FlashVars', 'sFile={$boardurl}seccode.php?update=$rand', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true');\n</script>";
$message = 'seccode_player';
} else {
$message = '<img onclick="updateseccode'.$secchecktype.'()" width="'.$seccodedata['width'].'" height="'.$seccodedata['height'].'" src="seccode.php?update='.$rand.'" class="absmiddle" alt="" />';
}
}
showmessage($message);
} elseif($action == 'checkseccode') {
if($seclevel) {
$tmp = $seccode;
} else {
$key = $seccodedata['type'] != 3 ? '' : $_DCACHE['settings']['authkey'].date('Ymd');
list($tmp, $expiration, $seccodeuid) = explode("\t", authcode($_DCOOKIE['secc'], 'DECODE', $key));
if($seccodeuid != $discuz_uid || $timestamp - $expiration > 600) {
showmessage('submit_seccode_invalid');
}
}
seccodeconvert($tmp);
strtoupper($seccodeverify) != $tmp && showmessage('submit_seccode_invalid');
showmessage('succeed');
} elseif($action == 'checksecanswer') {
if($seclevel) {
$tmp = $seccode;
} else {
list($tmp, $expiration, $seccodeuid) = explode("\t", authcode($_DCOOKIE['secq'], 'DECODE'));
if($seccodeuid != $discuz_uid || $timestamp - $expiration > 600) {
showmessage('submit_secqaa_invalid');
}
}
require_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
!$headercharset && @dheader('Content-Type: text/html; charset='.$charset);
if(md5($secanswer) != $_DCACHE['secqaa'][substr($tmp, 0, 1)]['answer']) {
showmessage('submit_secqaa_invalid');
}
showmessage('succeed');
} elseif($action == 'checkusername') {
$username = trim($username);
require_once DISCUZ_ROOT.'./uc_client/client.php';
$ucresult = uc_user_checkname($username);
if($ucresult == -1) {
showmessage('profile_username_illegal', '', 1);
} elseif($ucresult == -2) {
showmessage('profile_username_protect', '', 1);
} elseif($ucresult == -3) {
if($db->result_first("SELECT uid FROM {$tablepre}members WHERE username='$username'")) {
showmessage('register_check_found', '', 1);
} else {
showmessage('register_activation', '', 1);
}
}
} elseif($action == 'checkemail') {
$email = trim($email);
require_once DISCUZ_ROOT.'./uc_client/client.php';
$ucresult = uc_user_checkemail($email);
if($ucresult == -4) {
showmessage('profile_email_illegal', '', 1);
} elseif($ucresult == -5) {
showmessage('profile_email_domain_illegal', '', 1);
} elseif($ucresult == -6) {
showmessage('profile_email_duplicate', '', 1);
}
} elseif($action == 'checkuserexists') {
$check = $db->result_first("SELECT uid FROM {$tablepre}members WHERE username='".trim($username)."'");
$check ? showmessage('<img src="'.IMGDIR.'/check_right.gif" width="13" height="13">')
: showmessage('username_nonexistence');
} elseif($action == 'checkinvitecode') {
$invitecode = trim($invitecode);
$check = $db->result_first("SELECT invitecode FROM {$tablepre}invites WHERE invitecode='".trim($invitecode)."' AND status IN ('1', '3')");
if(!$check) {
showmessage('invite_invalid', '', 1);
} else {
$query = $db->query("SELECT m.username FROM {$tablepre}invites i, {$tablepre}members m WHERE invitecode='".trim($invitecode)."' AND i.uid=m.uid");
$inviteuser = $db->fetch_array($query);
$inviteuser = $inviteuser['username'];
showmessage('invite_send', '', 1);
}
} elseif($action == 'swfattachlist') {
if($swfupload) {
require_once DISCUZ_ROOT.'./include/swfupload.func.php';
$swfattachs = getswfattach(0);
}
include template('header_ajax');
include template('post_swfattachlist');
include template('footer_ajax');
}
showmessage($reglinkname, '', 2);
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/ajax.php
|
PHP
|
asf20
| 6,139
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: space.php 17199 2008-12-09 14:29:41Z liuqiang $
*/
if(!defined('CURSCRIPT')) {
define('CURSCRIPT', 'profile');
}
require_once './include/common.inc.php';
$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';
require_once DISCUZ_ROOT.'./include/forum.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 = '';
}
$member = $db->fetch_first("SELECT m.*, mf.*, u.grouptitle, u.type, u.creditshigher, u.creditslower, u.readaccess,
u.color AS groupcolor, u.stars AS groupstars, u.allownickname, 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) {
showmessage('member_nonexistence');
}
$profileuid = $member['uid'];
$member['online'] = $db->result_first("SELECT lastactivity FROM {$tablepre}sessions WHERE uid='$uid' AND invisible='0'");
if($member['groupid'] != ($member['groupidnew'] = getgroupid($member['uid'], $member, $member))) {
$member = array_merge($member, $db->fetch_first("SELECT groupid, grouptitle, type, creditshigher, creditslower, color AS groupcolor,
stars AS groupstars, allownickname
FROM {$tablepre}usergroups WHERE groupid='$member[groupidnew]'"));
}
$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) : ''));
}
}
}
@$percent = round($member['posts'] * 100 / $db->result_first("SELECT COUNT(*) FROM {$tablepre}posts"), 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($inajax) {
$member['userstatusby'] = $member['stars'] = '';
if($userstatusby == 1) {
$member['userstatusby'] = $member['grouptitle'];
$member['stars'] = $member['groupstars'];
} elseif($userstatusby == 2) {
if($member['type'] != 'member') {
$member['userstatusby'] = $member['grouptitle'];
$member['stars'] = $member['groupstars'];
} else {
$member['userstatusby'] = $member['ranktitle'];
$member['stars'] = $member['rankstars'];
}
}
}
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']);
$member['msn']= explode("\t", $member['msn']);
$member['lastvisit'] = dgmdate("$dateformat $timeformat", $member['lastvisit'] + ($timeoffset * 3600));
$member['lastpost'] = $member['lastpost'] ? dgmdate("$dateformat $timeformat", $member['lastpost'] + ($timeoffset * 3600)) : 'x';
$member['lastdate'] = gmdate($dateformat, $member['lastactivity'] + ($timeoffset * 3600));
$member['taobaoas'] = str_replace("'", '', 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;
include template('viewpro_inajax');
} else {
include template('viewpro_classic');
}
function emailconv($email, $tolink = 1) {
$email = str_replace(array('@', '.'), array('@', '.'), $email);
return $tolink ? '<a href="mailto:'.$email.'">'.$email.'</a>': $email;
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/space.php
|
PHP
|
asf20
| 7,690
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: modcp.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
define('NOROBOT', TRUE);
define('IN_MODCP', true);
define('CURSCRIPT', 'modcp');
$action = !empty($_REQUEST['action']) ? $_GET['action'] : (!empty($_POST['action']) ? $_POST['action'] : '');
require_once './include/common.inc.php';
require_once './admin/cpanel.share.php';
$action = empty($action) && $fid ? 'threads' : $action;
$cpscript = basename($PHP_SELF);
$modsession = new AdminSession($discuz_uid, $groupid, $adminid, $onlineip);
if($modsession->cpaccess == 1) {
if($action == 'login' && $cppwd && submitcheck('submit')) {
require_once DISCUZ_ROOT.'./uc_client/client.php';
$ucresult = uc_user_login($discuz_uid, $cppwd, 1);
if($ucresult[0] > 0) {
$modsession->errorcount = '-1';
$url_forward = $modsession->get('url_forward');
$modsession->clear(true);
$url_forward && dheader("Location: $cpscript?$url_forward");
$action = 'home';
} else{
$modsession->errorcount ++;
$modsession->update();
}
} else {
$action = 'login';
}
}
if($action == 'logout') {
$modsession->destroy();
showmessage('modcp_logout_succeed', $indexname);
}
$modforums = $modsession->get('modforums');
if($modforums === null) {
$modforums = array('fids' => '', 'list' => array(), 'recyclebins' => array());
$comma = '';
if($adminid == 3) {
$query = $db->query("SELECT m.fid, f.name, f.recyclebin
FROM {$tablepre}moderators m
LEFT JOIN {$tablepre}forums f ON f.fid=m.fid
WHERE m.uid='$discuz_uid' AND f.status>0 AND f.type<>'group'");
while($tforum = $db->fetch_array($query)) {
$modforums['fids'] .= $comma.$tforum['fid']; $comma = ',';
$modforums['recyclebins'][$tforum['fid']] = $tforum['recyclebin'];
$modforums['list'][$tforum['fid']] = strip_tags($tforum['name']);
}
} else {
$sql = !empty($accessmasks) ?
"SELECT f.fid, f.name, f.threads, f.recyclebin, 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 ff.redirect=''"
: "SELECT f.fid, f.name, f.threads, f.recyclebin, ff.viewperm, ff.redirect FROM {$tablepre}forums f
LEFT JOIN {$tablepre}forumfields ff USING(fid)
WHERE f.status>0 AND f.type<>'group' AND ff.redirect=''";
$query = $db->query($sql);
while ($tforum = $db->fetch_array($query)) {
if($tforum['allowview'] == 1 || ($tforum['allowview'] == 0 && ((!$tforum['viewperm'] && $readaccess) || ($tforum['viewperm'] && forumperm($tforum['viewperm']))))) {
$modforums['fids'] .= $comma.$tforum['fid']; $comma = ',';
$modforums['recyclebins'][$tforum['fid']] = $tforum['recyclebin'];
$modforums['list'][$tforum['fid']] = strip_tags($tforum['name']);
}
}
}
$modsession->set('modforums', $modforums, true);
}
if($fid && $forum['ismoderator']) {
dsetcookie('modcpfid', $fid);
$forcefid = "&fid=$fid";
} elseif(!empty($modforums) && count($modforums['list']) == 1) {
$forcefid = "&fid=$modforums[fids]";
} else {
$forcefid = '';
}
$script = $modtpl = '';
switch ($action) {
case 'announcements':
$allowpostannounce && $script = 'announcements';
break;
case 'members':
$op == 'edit' && $allowedituser && $script = 'members';
$op == 'ban' && $allowbanuser && $script = 'members';
$op == 'ipban' && $allowbanip && $script = 'members';
break;
case 'report':
$script = 'report';
break;
case 'moderate':
$allowmodpost && $script = 'moderate';
break;
case 'forums':
$script = 'forums';
break;
case 'forumaccess':
$script = 'forumaccess';
break;
case 'logs':
$script = 'logs';
break;
case 'login':
$script = $modsession->cpaccess == 1 ? 'login' : 'home';
break;
case 'threads':
$script = 'threads';
break;
case 'recyclebins':
$script = 'recyclebins';
break;
default:
$action = $script = 'home';
$modtpl = 'modcp_home';
}
$script = empty($script) ? 'noperm' : $script;
$modtpl = empty($modtpl) ? (!empty($script) ? 'modcp_'.$script : '') : $modtpl;
$op = isset($op) ? trim($op) : '';
if($script != 'logs') {
$extra = implodearray(array('GET' => $_GET, 'POST' => $_POST), array('cppwd', 'formhash', 'submit', 'addsubmit'));
$modcplog = array($timestamp, $discuz_user, $adminid, $onlineip, $action, $op, $fid, $extra);
writelog('modcp', implode("\t", clearlogstring($modcplog)));
}
require DISCUZ_ROOT.'./modcp/'.$script.'.inc.php';
$reportnum = $modpostnum = $modthreadnum = $modforumnum = 0;
$modforumnum = count($modforums['list']);
if($modforumnum) {
$reportnum = $db->result_first("SELECT COUNT(*) FROM {$tablepre}reportlog WHERE fid IN($modforums[fids]) AND status='1'");
$modnum = $db->result_first("SELECT COUNT(*) FROM {$tablepre}posts WHERE invisible='-2' AND first='0' and fid IN($modforums[fids])") +
$db->result_first("SELECT COUNT(*) FROM {$tablepre}threads WHERE fid IN($modforums[fids]) AND displayorder='-2'");
}
switch($adminid) {
case 1: $access = '1,2,3,4,5,6,7'; break;
case 2: $access = '2,3,6,7'; break;
default: $access = '1,3,5,7'; break;
}
$notenum = $db->result_first("SELECT COUNT(*) FROM {$tablepre}adminnotes WHERE access IN ($access)");
include template('modcp');
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/modcp.php
|
PHP
|
asf20
| 5,478
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: video.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
error_reporting(0);
define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -3));
require_once DISCUZ_ROOT.'./forumdata/cache/cache_settings.php';
$appid = 'c4ca4238a0b923820dcc509a6f75849b';
$siteid = $_DCACHE['settings']['vsiteid'];
$sitekey = $_DCACHE['settings']['vkey'];
define('VIDEO_DEBUG', 0);
define('SERVER_HOST', 'api.v.insenz.com');
define('SERVER_URL', 'http://' . SERVER_HOST . '/video_api.php');
define('PIC_SERVER_HOST', 'p.v.insenz.com');
if($_GET['action'] == 'createcode') {
echo VideoClient_Util::createCode();
}
class VideoClient_Result {
var $status;
var $errMessage;
var $errCode;
var $_result;
function VideoClient_Result($result) {
$this->status = $result['status'];
$this->errMessage = $result['errMessage'];
$this->errCode = $result['errCode'];
$this->_result = $result;
if($result['resultData']) {
foreach($result['resultData'] as $value) {
$this->_result['results'][] = new VideoClient_Result($value);
}
}
}
function isError() {
return VideoClient::isError($this->_result);
}
function getCode() {
return VideoClient::getCode($this->_result);
}
function getMessage() {
return VideoClient::getMessage($this->_result);
}
function get($field = false) {
return $field ? $this->_result[$field] : $this->_result;
}
}
class VideoClient {
var $appId;
var $version = '0.1';
var $key = 'ComsenzVideoService';
var $apiServerUrl = SERVER_URL;
function VideoClient($appId) {
$this->appId = $appId;
}
function getUrl() {
return $this->apiServerUrl;
}
function setUrl($url) {
$this->url = $url;
}
function _sign($args) {
return md5($args);
}
function _encrypt($str) {
return $this->authcode($str, $this->key);
}
function _decrypt($str) {
return $this->authcode($str, $this->key, 'DECODE');
}
function authcode($string, $key, $operation = 'ENCODE') {
$key_length = strlen($key);
if($key_length == 0) {
return false;
}
$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 _postCurl($url, $post_data) {
$cookie = '';
if($_COOKIE['insenz_session_id']) {
$cookies .= (session_name()) . "=" . urlencode($_COOKIE['insenz_session_id']) . ";";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
$result = curl_exec($ch);
$errorMsg = curl_error($ch);
if(!empty($errorMsg)) {
return new VideoClient_Result(array('status' => -1 , 'errMessage' => $errorMsg ));
}
if(is_resource($ch)) {
curl_close($ch);
}
return $result;
}
function _postSock($url, $post_data) {
if(!function_exists('fsockopen')) {
return new VideoClient_Result(array('status' => -1));
}
$urlInfo = array();
$urlInfo = parse_url($url);
$port = (0 == strcasecmp($urlInfo['scheme'], 'https')) ? 443 : 80;
$httpHeader = "POST " . $urlInfo['path'] . '?' . $urlInfo['query'] . ' ' . strtoupper($urlInfo['scheme']) . "/1.0\r\n";
$httpHeader .= "Host: " . $urlInfo['host'] . " \r\n";
$httpHeader .= "Connection: Close\r\n";
$httpHeader .= "Content-type: application/x-www-form-urlencoded\r\n";
$httpHeader .= "Content-length: " . strlen($post_data) . "\r\n";
$httpHeader .= "Referer: " . $_SERVER['HTTP_HOST'] . $_SERVER["SCRIPT_NAME"] . "\r\n";
$cookie = '';
if($_COOKIE['insenz_session_id']) {
$cookies .= (session_name()) . "=" . urlencode($_COOKIE['insenz_session_id']) . ";";
}
$httpHeader .= "Cookie: " . $cookies . "\r\n";
$httpHeader .= "\r\n";
$httpHeader .= $post_data;
$httpHeader .= "\r\n\r\n";
$fp = @fsockopen($urlInfo['host'], $port);
if($fp) {
if(fwrite($fp, $httpHeader)) {
$resData = '';
while(!feof($fp)) {
$resData .= fread($fp, 8192);
}
fclose($fp);
$resContent = substr(strstr($resData, "\r\n\r\n"), 4);
return $resContent;
} else {
return new VideoClient_Result(array('status' => -1));
}
} else {
return new VideoClient_Result(array('status' => -1));
}
}
function _doCall($mod, $params) {
$tmpArgs = array();
$url = '';
if($this->appId) {
$params['appId'] = $this->appId;
}
$params['method'] = $mod;
$params['version'] = $this->version;
foreach($params as $paramName => $paramValue) {
$tmpArgs[] = urlencode($paramName) . '=' . urlencode($paramValue);
}
$args = join('&', $tmpArgs);
$args .= '&sign=' . $this->_sign($args);
$tmpArgs = $args;
$url = $this->apiServerUrl . '?siteId=' . (($params['siteId']) ? $params['siteId'] : '0');
$resultString = '';
$result = array();
$args = urlencode($this->_encrypt(urlencode($args), $this->key));
if(function_exists('curl_init')) {
$resultString = $this->_postCurl($url, $args);
} else {
$resultString = $this->_postSock($url, $args);
}
if(is_object($resultString)) {
return $resultString;
}
if(empty($resultString)) {
return new VideoClient_Result(array('status' => -1));
}
$tmp = $resultString;
$decodeString = $this->_decrypt($resultString, $this->key);
if($decodeString) {
$resultString = $decodeString;
}
$resultString = urldecode($resultString);
parse_str($resultString, $result);
if(!is_array($result)) {
return new VideoClient_Result(array('status' => -1));
}
return new VideoClient_Result($result);
}
function isError($result) {
return $result['status'] != 0 || $result['status'] === NULL;
}
function getCode($result) {
return $result['errCode'];
}
function getMessage($result) {
return $result['errMessage'];
}
}
class VideoClient_AccountService extends VideoClient {
var $handle;
var $passwd;
function VideoClient_AccountService($appId, $handle = false, $passwd = false) {
parent::VideoClient($appId);
$this->handle = $handle;
$this->passwd = $passwd;
}
function handleIsExists($handle) {
if(!$handle) {
$handle = $this->handle;
}
return $this->_doCall('account_check', array('handle' => $handle));
}
function register($handle, $passwd, $code, $email = '', $name = '', $qq = '', $msn = '', $tel= '', $mobile = '', $addr = '' , $postcode = '') {
$result = $this->_doCall('account_register', array('handle' => $handle, 'passwd' => $passwd, 'code' => $code, 'email' => $email, 'name' => $name, 'qq' => $qq, 'msn' => $msn, 'tel' => $tel, 'mobile' => $mobile, 'addr' => $addr, 'postcode' => $postcode));
if(!$result->isError()) {
$this->handle = $handle;
$this->passwd = $passwd;
}
return $result;
}
function bind($uniqKey, $siteName, $siteUrl, $logoUrl, $cateId) {
return $this->_doCall('account_bind', array('handle' => $this->handle, 'passwd' => $this->passwd, 'uniqKey' => $uniqKey, 'siteName' => $siteName, 'siteUrl' => $siteUrl, 'logoUrl' => $logoUrl, 'cateId' => $cateId));
}
function getPmNum(){
$secuKey = '1oidjoqfuikj3487vl8k3lsfdo399ckl4kvzp';
$sk = md5($secuKey.$this->handle);
return $this->_doCall('pm_number', array('handle' => $this->handle, 'sk' => $sk, 'appid' => $this->appId));
}
}
class VideoClient_SiteService extends VideoClient {
var $siteId = '';
var $siteKey = '';
function VideoClient_SiteService($appId, $siteId, $siteKey) {
parent::VideoClient($appId);
$this->siteId = $siteId;
$this->siteKey = $siteKey;
$this->key = $siteKey;
}
function edit($siteName, $siteUrl, $logoUrl, $cateId) {
return $this->_doCall('site_edit', array('siteId' => $this->siteId, 'siteKey' => $this->siteKey, 'siteName' => $siteName, 'siteUrl' => $siteUrl, 'logoUrl' => $logoUrl, 'cateId' => $cateId));
}
function getInfo($uniqKey) {
return $this->_doCall('site_info', array('siteId' => $this->siteId, 'siteKey' => $this->siteKey, 'uniqKey' => $uniqKey));
}
}
class VideoClient_VideoService extends VideoClient {
var $siteId = '';
var $siteKey = '';
function VideoClient_VideoService($appId, $siteId, $siteKey) {
parent::VideoClient($appId);
$this->siteId = $siteId;
$this->siteKey = $siteKey;
$this->key = $siteKey;
}
function upload($videoId, $tid, $isup = VIDEO_ISUP_UPLOAD, $subject, $tags, $description, $cateId, $autoplay = VIDEO_AUOT_PLAY_TRUE, $share = VIDEO_SHARE_FALSE) {
$videoData[] = array( 'videoId' => $videoId, 'tid' => $tid,'isup' => $isup, 'subject' => $subject, 'tags' => $tags, 'description' => $description,
'category' => $cateId, 'autoplay' => $autoplay, 'share' => $share);
$results = $this->uploadMulti($videoData);
return ($result = $results->get('results')) ? $result[0] : $results;
}
function getInfo($videoId) {
return $this->_doCall('video_info', array('siteId' => $this->siteId, 'siteKey' => $this->siteKey, 'videoId' => $videoId));
}
function uploadMulti($videoArr = array()) {
$data = array('siteId' => $this->siteId, 'siteKey' => $this->siteKey);
foreach($videoArr as $index => $video) {
foreach($video as $key => $item) {
$data["videoData[$index][$key]"] = $item;
}
}
return $this->_doCall('video_uploads', $data);
}
function edit($videoId, $tid, $subject, $tags, $description, $cateId, $autoplay = VIDEO_AUOT_PLAY_TRUE, $share = VIDEO_SHARE_FALSE) {
$videoData[] = array( 'videoId' => $videoId, 'tid' => $tid, 'subject' => $subject, 'tags' => $tags, 'description' => $description,
'category' => $cateId, 'autoplay' => $autoplay, 'share' => $share);
$results = $this->editMulti($videoData);
return ($result = $results->get('results')) ? $result[0] : $results;
}
function editMulti($videoArr) {
$data = array('siteId' => $this->siteId, 'siteKey' => $this->siteKey);
foreach($videoArr as $index => $video) {
foreach($video as $key => $item) {
$data["videoData[$index][$key]"] = $item;
}
}
return $this->_doCall('video_edit', $data);
}
function remove($videoId) {
$videoData[] = array( 'videoId' => $videoId);
$results = $this->removeMulti($videoData);
return ($result = $results->get('results')) ? $result[0] : $results;
}
function removeMulti($videoArr) {
$data = array('siteId' => $this->siteId, 'siteKey' => $this->siteKey);
foreach($videoArr as $index => $video) {
foreach($video as $key => $item) {
$data["videoData[$index][$key]"] = $item;
}
}
return $this->_doCall('video_remove', $data);
}
}
class VideoClient_Util extends VideoClient {
var $siteId = '';
var $siteKey = '';
var $flashKey ='87ed8f664329817c99bb02e08db9eeb9ade7981d44f2b50a5ac6461dfde3d95d';
function VideoClient_Util($appId, $siteId = '', $siteKey = '') {
parent::VideoClient($appId);
$this->siteId = $siteId;
$this->siteKey = $siteKey;
}
function createUploadFrom($options, $flashVars) {
if(!$this->siteId || !$this->siteKey) {
return FALSE;
}
$time = time();
$flashVars['sid'] = $this->siteId;
$flashVars['ts'] = $time;
$flashVars['sk'] = md5($this->siteId . $this->siteKey . $this->flashKey . $time);
$js = '';
foreach($flashVars as $key => $value) {
$js .= "\t\tso.addVariable('" . $key . "', '" . $value . "');\n";
$varArr[] = $key . '=' . $value;
}
$flashVarStr = join('&', $varArr);
(!$options['width']) && $options['width'] = 480;
(!$options['height']) && $options['height'] = 60;
(!$options['id']) && $options['id'] = 'flashUpload';
$SERVER_HOST = SERVER_HOST;
$PIC_SERVER_HOST = PIC_SERVER_HOST;
$html = <<<EOF
<div id="video_uploader_wrap">
<div id="video_uploader_div"></div>
<script type="text/javascript" reload="1">
function video_uploader_show() {
var so = new SWFObject('http://$SERVER_HOST/flash/video_uploader.swf','video_uploader','$options[width]','$options[height]','9.0.0', '#ffffff', 'high', 'http://www.macromedia.com/go/getflashplayer', 'http://www.macromedia.com/go/getflashplayer');
so.addParam('allowfullscreen','true');
so.addParam('allowscriptaccess','always');
so.addParam('wmode','transparent');
so.addParam('scale', 'noScale');
$js
if(!so.write('video_uploader_div'))document.getElementById("video_uploader_div").innerHTML='<span align="center" valign="middle"><a href="http://www.macromedia.com/go/getflashplayer" target=_blank><img src="http://$PIC_SERVER_HOST/flashdownload.jpg" width="468" height="370" border="0" /></a></span>';
window.focus();
if(document.getElementById('video_uploader')) {window.video_uploader = document.getElementById('video_uploader');}
}
</script>
</div>
EOF;
return $html;
}
function createPlayer($options, $flashVars) {
if(!$this->siteId || !$this->siteKey || !$this->appId || !$flashVars['site']) {
return FALSE;
}
$time = time();
$flashVars['m'] = 'play';
$flashVars['istyle'] = 'shallow_blue';
$flashVars['sid'] = $this->siteId;
$flashVars['ts'] = $time;
$flashVars['sk'] = md5($this->siteId . $this->siteKey . $this->flashKey . $time);
$flashVars['site'] = trim($flashVars['site'], '/') . '/';
$js = '';
foreach($flashVars as $key => $value) {
$js .= "\t\tso.addVariable('" . $key . "', '" . $value . "');\n";
$varArr[] = $key . '=' .$value;
}
$flashVarStr = join('&', $varArr);
(!$options['width']) && $options['width'] = 480;
(!$options['height']) && $options['height'] = 410;
(!$options['id']) && $options['id'] = 'flashPlayer';
$SERVER_HOST = SERVER_HOST;
$PIC_SERVER_HOST = PIC_SERVER_HOST;
$html = <<<EOF
<div id="video_Player_wrap">
<div id='video_player_div'></div>
<script type="text/javascript" reload="1">
var so = new SWFObject('http://$SERVER_HOST/flash/FLVPlayer2.swf','video_player','$options[width]','$options[height]','8.0.0', '#ffffff', 'high', 'http://www.macromedia.com/go/getflashplayer', 'http://www.macromedia.com/go/getflashplayer');
so.addParam('allowfullscreen','true');
so.addParam('allowscriptaccess','always');
so.addParam('scale', 'noScale');
$js
if(!so.write('video_player_div'))document.getElementById("video_player_div").innerHTML='<span align="center" valign="middle"><a href="http://www.macromedia.com/go/getflashplayer" target=_blank><img src="http://$PIC_SERVER_HOST/flashdownload.jpg" width="468" height="370" border="0" /></a></span>';
window.focus();
if(document.getElementById('video_player')) {window.video_uploader = document.getElementById('video_player');}
</script>
</div>
EOF;
return $html;
}
function createReferPlayer($params = array()) {
unset($params['ts']);
unset($params['ks']);
unset($params['sid']);
$params['refer'] = 1;
foreach($params as $key => $value) {
$query[] = urlencode($key).'='.urlencode($value);
}
$time = time();
$sk = md5($this->siteId . $this->siteKey . $this->flashKey . $time);
return 'http://'.SERVER_HOST.'/flash/FLVPlayer2.swf?'.join('&', $query).'&ts='.$time.'&sid='.$this->siteId.'&sk='.$sk;
}
function createCode() {
$httpHeader = "GET /video_api.php?m=seccode HTTP/1.0\r\n";
$httpHeader .= "Host: " . SERVER_HOST . " \r\n";
$httpHeader .= "Connection: Close\r\n\r\n";
$fp = fsockopen(SERVER_HOST, 80);
if($fp) {
if(fwrite($fp, $httpHeader)) {
$resData = '';
while(!feof($fp)) {
$resData .= fread($fp, 8192);
}
fclose($fp);
$sessionstr = strstr($resData, "insenz_session_id=");
$sessionid = substr($sessionstr, 18, 32);
setCookie('insenz_session_id', $sessionid, (time() + 600), '/');
$resContent = substr(strstr($resData, "\r\n\r\n"), 4);
return $resContent;
}
}
}
function getThumbUrl($vid, $type = '') {
$queryStr = 'id=' . $vid;
if($type == 'small') {
$queryStr .= '&type=small';
}
$url = 'http://' . PIC_SERVER_HOST . '/thumb?%s';
return sprintf($url, $queryStr);
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/video.php
|
PHP
|
asf20
| 17,006
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: javascript.php 16688 2008-11-14 06:41:07Z 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_request.php';
if($_DCACHE['settings']['gzipcompress']) {
ob_start('ob_gzhandler');
}
$jsstatus = isset($_DCACHE['settings']['jsstatus']) ? $_DCACHE['settings']['jsstatus'] : 1;
if(!$jsstatus && !empty($_GET['key'])) {
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['request'][$_GET['key']]['url'])) {
$cachefile = DISCUZ_ROOT.'./forumdata/cache/javascript_'.$_GET['key'].'.php';
parse_str($_DCACHE['request'][$_GET['key']]['url'], $requestdata);
} else {
exit;
}
$expiration = 0;
$timestamp = time();
$rewritestatus = $_DCACHE['settings']['rewritestatus'];
$uc = $_DCACHE['settings']['uc'];
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';
require_once DISCUZ_ROOT.'./include/request.func.php';
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$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)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/';
$datalist = parse_request($requestdata, $cachefile, 1);
}
echo $datalist;
function jsprocdata($data, $requestcharset) {
global $boardurl, $_DCACHE, $charset;
if($requestcharset) {
include DISCUZ_ROOT.'include/chinese.class.php';
if(strtoupper($charset) != 'UTF-8') {
$c = new Chinese($charset, 'utf8');
} else {
$c = new Chinese('utf8', $requestcharset == 1 ? 'gbk' : 'big5');
}
$data = $c->Convert($data);
}
return 'document.write(\''.preg_replace("/\r\n|\n|\r/", '\n', addcslashes($data, "'\\")).'\');';
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/javascript.php
|
PHP
|
asf20
| 3,228
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: advcache.php 16698 2008-11-14 07:58:56Z cnteacher $
*/
error_reporting(0);
define('IN_DISCUZ', TRUE);
define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -3));
$timestamp = time();
@set_time_limit(1000);
@ignore_user_abort(TRUE);
require_once DISCUZ_ROOT.'./config.inc.php';
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';
require_once DISCUZ_ROOT.'./include/insenz.func.php';
$db = new dbstuff;
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$query = $db->query("SELECT value FROM {$tablepre}settings WHERE variable='insenz'");
$insenz = ($insenz = $db->result($query, 0)) ? unserialize($insenz) : array();
$insenz['host'] = empty($insenz['host']) ? 'api.insenz.com' : $insenz['host'];
$insenz['url'] = empty($insenz['url']) ? 'api.insenz.com' : $insenz['url'];
$insenz['siteid'] = intval($insenz['siteid']);
if(empty($insenz['authkey'])) {
exit;
}
$type = intval($_GET['type']);
$cid = intval($_GET['cid']);
if(empty($type)) {
if(empty($insenz['hardadstatus']) || (!empty($insenz['lastupdated']) && ($timestamp - $insenz['lastupdated'] < 600))) {
exit;
}
$response = insenz_request('adv.php', '<cmd id="getSiteAdJs"><site_id>'.$insenz['siteid'].'</site_id></cmd>');
$hash = $response[0]['hash'][0]['VALUE'];
$updateadvcache = FALSE;
if($insenz['hash'] != $hash) {
$updateadvcache = TRUE;
$db->query("TRUNCATE TABLE {$tablepre}advcaches");
if(is_array($response[0]['ads'][0]['ad'])) {
$discuz_chs = '';
$typearray = array(0 => 'insenz', 1 => 'headerbanner', 2 => 'thread3_1', 3 => 'thread2_1', 4 => 'thread1_1', 5 => 'interthread', 6 => 'footerbanner1', 7 => 'footerbanner2', 8 => 'footerbanner3');
foreach($response[0]['ads'][0]['ad'] AS $k => $v) {
$type = intval($v['typeid'][0]['VALUE']);
$target = intval($v['target'][0]['VALUE']);
$code = insenz_convert($v['code'][0]['VALUE'], 0);
$db->query("INSERT INTO {$tablepre}advcaches (type, target, code) VALUES ('".$typearray[$type]."', '$target', '$code')");
}
}
}
$insenz['lastupdated'] = $timestamp;
$insenz['hash'] = $hash;
$db->query("REPLACE INTO {$tablepre}settings (variable, value) VALUES ('insenz', '".addslashes(serialize($insenz))."')");
require_once DISCUZ_ROOT.'./include/global.func.php';
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache($updateadvcache ? array('settings', 'advs_forumdisplay', 'advs_viewthread') : 'settings');
} elseif($type == 4 && $cid) {
$campaign = $db->fetch_first("SELECT autoupdate, lastupdated FROM {$tablepre}campaigns WHERE id='$cid' AND type=4");
if(!$campaign || !$campaign['autoupdate'] || ($timestamp - $campaign['lastupdated'] < 600)) {
exit;
}
$response = insenz_request('forum.php', '<cmd id="getForumDetails"><c_id>'.$cid.'</c_id></cmd>');
$threads = intval($response[0]['threads'][0]['VALUE']);
$posts = intval($response[0]['posts'][0]['VALUE']);
$lastpost = insenz_convert($response[0]['lastpost'][0]['VALUE'], 0);
$db->query("UPDATE {$tablepre}virtualforums SET threads='$threads', posts='$posts', lastpost='$lastpost' WHERE cid='$cid'");
$db->query("UPDATE {$tablepre}campaigns SET lastupdated='$timestamp' WHERE id='$cid'");
} elseif(in_array($type, array(1, 2, 3)) && $cid) {
$campaign = $db->fetch_first("SELECT tid, autoupdate, lastupdated FROM {$tablepre}campaigns WHERE id='$cid' AND type='$type'");
if(!$campaign || !$campaign['autoupdate'] || ($timestamp - $campaign['lastupdated'] < 600)) {
exit;
}
$response = insenz_request('campaign.php', '<cmd id="getTopicDetails"><c_id>'.$cid.'</c_id></cmd>');
$replies = intval($response[0]['replies'][0]['VALUE']);
$views = intval($response[0]['views'][0]['VALUE']);
$lastpost = intval($response[0]['lastpost'][0]['VALUE']);
$lastposter = insenz_convert($response[0]['lastposter'][0]['VALUE'], 0);
$db->query("UPDATE {$tablepre}threads SET replies='$replies', views='$views', lastpost='$lastpost', lastposter='$lastposter' WHERE tid='$campaign[tid]'");
$db->query("UPDATE {$tablepre}campaigns SET lastupdated='$timestamp' WHERE id='$cid'");
}
function insenz_request($script, $data) {
global $timestamp, $insenz;
@include_once DISCUZ_ROOT.'./discuz_version.php';
$authkey = $insenz['authkey'];
$t_hex = sprintf("%08x", $timestamp);
$postdata = '<?xml version="1.0" encoding="UTF'.'-8"?><request insenz_version="'.INSENZ_VERSION.'" discuz_version="'.DISCUZ_VERSION.' - '.DISCUZ_RELEASE.'">'.$data.'</request>';
$postdata = insenz_authcode($t_hex.md5($authkey.$postdata.$t_hex).$postdata, 'ENCODE', $authkey);
if(!$fp = @fsockopen($insenz['host'], 80)) {
exit;
}
@fwrite($fp, "POST http://$insenz[url]/$script?s_id=$insenz[siteid] HTTP/1.0\r\n");
@fwrite($fp, "Host: $insenz[host]\r\n");
@fwrite($fp, "Content-Type: file\r\n");
@fwrite($fp, "Content-Length: " . strlen($postdata) ."\r\n\r\n");
@fwrite($fp, $postdata);
$res = '';
$isheader = 1;
while(!feof($fp)) {
$buffer = @fgets($fp, 1024);
if(!$isheader) {
$res .= $buffer;
} elseif(trim($buffer) == '') {
$isheader = 0;
}
}
@fclose($fp);
if(empty($res)) {
exit;
}
if(!$response = insenz_authcode($res, 'DECODE', $authkey)) {
exit;
}
$checkKey = substr($response, 0, 40);
$response = substr($response, 40);
$t_hex = substr($checkKey, 0, 8);
$t = base_convert($t_hex, 16, 10);
if(abs($timestamp - $t) > 1200) {
exit;
} elseif($checkKey != $t_hex.md5($authkey.$response.$t_hex)) {
exit;
}
require_once DISCUZ_ROOT.'./include/xmlparser.class.php';
$xmlparse = new XMLParser;
$xmlparseddata = $xmlparse->getXMLTree($response);
unset($response);
if(!is_array($xmlparseddata) || !is_array($xmlparseddata['response'])) {
exit;
}
return $xmlparseddata['response'];
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/advcache.php
|
PHP
|
asf20
| 6,047
|
<?php
define('IN_DISCUZ', TRUE);
define('UC_CLIENT_VERSION', '1.5.0');
define('UC_CLIENT_RELEASE', '20090121');
define('API_DELETEUSER', 1);
define('API_RENAMEUSER', 1);
define('API_GETTAG', 1);
define('API_SYNLOGIN', 1);
define('API_SYNLOGOUT', 1);
define('API_UPDATEPW', 1);
define('API_UPDATEBADWORDS', 1);
define('API_UPDATEHOSTS', 1);
define('API_UPDATEAPPS', 1);
define('API_UPDATECLIENT', 1);
define('API_UPDATECREDIT', 1);
define('API_GETCREDITSETTINGS', 1);
define('API_GETCREDIT', 1);
define('API_UPDATECREDITSETTINGS', 1);
define('API_RETURN_SUCCEED', '1');
define('API_RETURN_FAILED', '-1');
define('API_RETURN_FORBIDDEN', '-2');
define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -3));
if(!defined('IN_UC')) {
error_reporting(0);
set_magic_quotes_runtime(0);
defined('MAGIC_QUOTES_GPC') || define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
include_once DISCUZ_ROOT.'./config.inc.php';
$_DCACHE = $get = $post = array();
$code = @$_GET['code'];
parse_str(_authcode($code, 'DECODE', UC_KEY), $get);
if(MAGIC_QUOTES_GPC) {
$get = _stripslashes($get);
}
$timestamp = time();
if(empty($get)) {
exit('Invalid Request');
} elseif($timestamp - $get['time'] > 3600) {
exit('Authracation has expiried');
}
$action = $get['action'];
require_once DISCUZ_ROOT.'./uc_client/lib/xml.class.php';
$post = xml_unserialize(file_get_contents('php://input'));
if(in_array($get['action'], array('test', 'deleteuser', 'renameuser', 'gettag', 'synlogin', 'synlogout', 'updatepw', 'updatebadwords', 'updatehosts', 'updateapps', 'updateclient', 'updatecredit', 'getcredit', 'getcreditsettings', 'updatecreditsettings'))) {
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';
$GLOBALS['db'] = new dbstuff;
$GLOBALS['db']->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
$GLOBALS['tablepre'] = $tablepre;
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
$uc_note = new uc_note();
exit($uc_note->$get['action']($get, $post));
} else {
exit(API_RETURN_FAILED);
}
} else {
/*$uc_note = new uc_note('../', '../config.inc.php');
$uc_note->deleteuser('3');*/
define('DISCUZ_ROOT', $app['extra']['apppath']);
include DISCUZ_ROOT.'./config.inc.php';
require_once DISCUZ_ROOT.'./include/db_'.$database.'.class.php';
$GLOBALS['db'] = new dbstuff;
$GLOBALS['db']->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
$GLOBALS['tablepre'] = $tablepre;
unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
}
class uc_note {
var $db = '';
var $tablepre = '';
var $appdir = '';
function _serialize($arr, $htmlon = 0) {
if(!function_exists('xml_serialize')) {
include_once DISCUZ_ROOT.'./uc_client/lib/xml.class.php';
}
return xml_serialize($arr, $htmlon);
}
function uc_note() {
$this->appdir = DISCUZ_ROOT;
$this->db = $GLOBALS['db'];
$this->tablepre = $GLOBALS['tablepre'];
}
function test($get, $post) {
return API_RETURN_SUCCEED;
}
function deleteuser($get, $post) {
$uids = $get['ids'];
!API_DELETEUSER && exit(API_RETURN_FORBIDDEN);
$threads = array();
$query = $this->db->query("SELECT f.fid, t.tid FROM ".$this->tablepre."threads t LEFT JOIN ".$this->tablepre."forums f ON t.fid=f.fid WHERE t.authorid IN ($uids) ORDER BY f.fid");
while($thread = $this->db->fetch_array($query)) {
$threads[$thread['fid']] .= ($threads[$thread['fid']] ? ',' : '').$thread['tid'];
}
if($threads) {
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
foreach($threads as $fid => $tids) {
$query = $this->db->query("SELECT attachment, thumb, remote FROM ".$this->tablepre."attachments WHERE tid IN ($tids)");
while($attach = $this->db->fetch_array($query)) {
@unlink($_DCACHE['settings']['attachdir'].'/'.$attach['attachment']);
$attach['thumb'] && @unlink($_DCACHE['settings']['attachdir'].'/'.$attach['attachment'].'.thumb.jpg');
}
foreach(array('threads', 'threadsmod', 'relatedthreads', 'posts', 'polls', 'polloptions', 'trades', 'activities', 'activityapplies', 'debates', 'debateposts', 'attachments', 'favorites', 'mythreads', 'myposts', 'subscriptions', 'typeoptionvars', 'forumrecommend') as $value) {
$this->db->query("DELETE FROM ".$this->tablepre."$value WHERE tid IN ($tids)", 'UNBUFFERED');
}
require_once $this->appdir.'./include/post.func.php';
updateforumcount($fid);
}
if($globalstick && $stickmodify) {
require_once $this->appdir.'./include/cache.func.php';
updatecache('globalstick');
}
}
$query = $this->db->query("DELETE FROM ".$this->tablepre."members WHERE uid IN ($uids)");
$this->db->query("DELETE FROM ".$this->tablepre."access WHERE uid IN ($uids)", 'UNBUFFERED');
$this->db->query("DELETE FROM ".$this->tablepre."memberfields WHERE uid IN ($uids)", 'UNBUFFERED');
$this->db->query("DELETE FROM ".$this->tablepre."favorites WHERE uid IN ($uids)", 'UNBUFFERED');
$this->db->query("DELETE FROM ".$this->tablepre."moderators WHERE uid IN ($uids)", 'UNBUFFERED');
$this->db->query("DELETE FROM ".$this->tablepre."subscriptions WHERE uid IN ($uids)", 'UNBUFFERED');
$this->db->query("DELETE FROM ".$this->tablepre."validating WHERE uid IN ($uids)", 'UNBUFFERED');
$query = $this->db->query("SELECT uid, attachment, thumb, remote FROM ".$this->tablepre."attachments WHERE uid IN ($uids)");
while($attach = $this->db->fetch_array($query)) {
@unlink($_DCACHE['settings']['attachdir'].'/'.$attach['attachment']);
$attach['thumb'] && @unlink($_DCACHE['settings']['attachdir'].'/'.$attach['attachment'].'.thumb.jpg');
}
$this->db->query("DELETE FROM ".$this->tablepre."attachments WHERE uid IN ($uids)");
$this->db->query("DELETE FROM ".$this->tablepre."posts WHERE authorid IN ($uids)");
$this->db->query("DELETE FROM ".$this->tablepre."trades WHERE sellerid IN ($uids)");
return API_RETURN_SUCCEED;
}
function renameuser($get, $post) {
$uid = $get['uid'];
$usernameold = $get['oldusername'];
$usernamenew = $get['newusername'];
if(!API_RENAMEUSER) {
return API_RETURN_FORBIDDEN;
}
$this->db->query("UPDATE ".$this->tablepre."announcements SET author='$usernamenew' WHERE author='$usernameold'");
$this->db->query("UPDATE ".$this->tablepre."banned SET admin='$usernamenew' WHERE admin='$usernameold'");
$this->db->query("UPDATE ".$this->tablepre."forums SET lastpost=REPLACE(lastpost, '\t$usernameold', '\t$usernamenew')");
$this->db->query("UPDATE ".$this->tablepre."members SET username='$usernamenew' WHERE uid='$uid'");
$this->db->query("UPDATE ".$this->tablepre."posts SET author='$usernamenew' WHERE authorid='$uid'");
$this->db->query("UPDATE ".$this->tablepre."threads SET author='$usernamenew' WHERE authorid='$uid'");
$this->db->query("UPDATE ".$this->tablepre."threads SET lastposter='$usernamenew' WHERE lastposter='$usernameold'");
$this->db->query("UPDATE ".$this->tablepre."threadsmod SET username='$usernamenew' WHERE uid='$uid'");
return API_RETURN_SUCCEED;
}
function gettag($get, $post) {
$name = $get['id'];
if(!API_GETTAG) {
return API_RETURN_FORBIDDEN;
}
$name = trim($name);
if(empty($name) || !preg_match('/^([\x7f-\xff_-]|\w|\s)+$/', $name) || strlen($name) > 20) {
return API_RETURN_FAILED;
}
require_once $this->appdir.'./include/misc.func.php';
$tag = $this->db->fetch_first("SELECT * FROM ".$this->tablepre."tags WHERE tagname='$name'");
if($tag['closed']) {
return API_RETURN_FAILED;
}
$tpp = 10;
$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$boardurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/';
$query = $this->db->query("SELECT t.* FROM ".$this->tablepre."threadtags tt LEFT JOIN ".$this->tablepre."threads t ON t.tid=tt.tid AND t.displayorder>='0' WHERE tt.tagname='$name' ORDER BY tt.tid DESC LIMIT $tpp");
$threadlist = array();
while($tagthread = $this->db->fetch_array($query)) {
if($tagthread['tid']) {
$threadlist[] = array(
'subject' => $tagthread['subject'],
'uid' => $tagthread['authorid'],
'username' => $tagthread['author'],
'dateline' => $tagthread['dateline'],
'url' => $boardurl.'viewthread.php?tid='.$tagthread['tid'],
);
}
}
$return = array($name, $threadlist);
return $this->_serialize($return, 1);
}
function synlogin($get, $post) {
$uid = $get['uid'];
$username = $get['username'];
if(!API_SYNLOGIN) {
return API_RETURN_FORBIDDEN;
}
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
$cookietime = 2592000;
$discuz_auth_key = md5($_DCACHE['settings']['authkey'].$_SERVER['HTTP_USER_AGENT']);
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
$uid = intval($uid);
$query = $this->db->query("SELECT username, uid, password, secques FROM ".$this->tablepre."members WHERE uid='$uid'");
if($member = $this->db->fetch_array($query)) {
_setcookie('sid', '', -86400 * 365);
_setcookie('cookietime', $cookietime, 31536000);
_setcookie('auth', _authcode("$member[password]\t$member[secques]\t$member[uid]", 'ENCODE', $discuz_auth_key), $cookietime);
} else {
_setcookie('cookietime', $cookietime, 31536000);
_setcookie('loginuser', $username, $cookietime);
_setcookie('activationauth', _authcode($username, 'ENCODE', $discuz_auth_key), $cookietime);
}
}
function synlogout($get, $post) {
if(!API_SYNLOGOUT) {
return API_RETURN_FORBIDDEN;
}
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
_setcookie('auth', '', -86400 * 365);
_setcookie('sid', '', -86400 * 365);
_setcookie('loginuser', '', -86400 * 365);
_setcookie('activationauth', '', -86400 * 365);
}
function updatepw($get, $post) {
if(!API_UPDATEPW) {
return API_RETURN_FORBIDDEN;
}
$username = $get['username'];
$password = $get['password'];
$newpw = md5(time().rand(100000, 999999));
$this->db->query("UPDATE ".$this->tablepre."members SET password='$newpw' WHERE username='$username'");
return API_RETURN_SUCCEED;
}
function updatebadwords($get, $post) {
if(!API_UPDATEBADWORDS) {
return API_RETURN_FORBIDDEN;
}
$cachefile = $this->appdir.'./uc_client/data/cache/badwords.php';
$fp = fopen($cachefile, 'w');
$data = array();
if(is_array($post)) {
foreach($post as $k => $v) {
$data['findpattern'][$k] = $v['findpattern'];
$data['replace'][$k] = $v['replacement'];
}
}
$s = "<?php\r\n";
$s .= '$_CACHE[\'badwords\'] = '.var_export($data, TRUE).";\r\n";
fwrite($fp, $s);
fclose($fp);
return API_RETURN_SUCCEED;
}
function updatehosts($get, $post) {
if(!API_UPDATEHOSTS) {
return API_RETURN_FORBIDDEN;
}
$cachefile = $this->appdir.'./uc_client/data/cache/hosts.php';
$fp = fopen($cachefile, 'w');
$s = "<?php\r\n";
$s .= '$_CACHE[\'hosts\'] = '.var_export($post, TRUE).";\r\n";
fwrite($fp, $s);
fclose($fp);
return API_RETURN_SUCCEED;
}
function updateapps($get, $post) {
global $_DCACHE;
if(!API_UPDATEAPPS) {
return API_RETURN_FORBIDDEN;
}
$UC_API = $post['UC_API'];
if(empty($post) || empty($UC_API)) {
return API_RETURN_SUCCEED;
}
$cachefile = $this->appdir.'./uc_client/data/cache/apps.php';
$fp = fopen($cachefile, 'w');
$s = "<?php\r\n";
$s .= '$_CACHE[\'apps\'] = '.var_export($post, TRUE).";\r\n";
fwrite($fp, $s);
fclose($fp);
if(is_writeable($this->appdir.'./config.inc.php')) {
$configfile = trim(file_get_contents($this->appdir.'./config.inc.php'));
$configfile = substr($configfile, -2) == '?>' ? substr($configfile, 0, -2) : $configfile;
$configfile = preg_replace("/define\('UC_API',\s*'.*?'\);/i", "define('UC_API', '$UC_API');", $configfile);
if($fp = @fopen($this->appdir.'./config.inc.php', 'w')) {
@fwrite($fp, trim($configfile));
@fclose($fp);
}
}
global $_DCACHE;
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
require_once $this->appdir.'./include/cache.func.php';
foreach($post as $appid => $app) {
$_DCACHE['settings']['ucapp'][$appid]['viewprourl'] = $app['url'].$app['viewprourl'];
}
updatesettings();
return API_RETURN_SUCCEED;
}
function updateclient($get, $post) {
if(!API_UPDATECLIENT) {
return API_RETURN_FORBIDDEN;
}
$cachefile = $this->appdir.'./uc_client/data/cache/settings.php';
$fp = fopen($cachefile, 'w');
$s = "<?php\r\n";
$s .= '$_CACHE[\'settings\'] = '.var_export($post, TRUE).";\r\n";
fwrite($fp, $s);
fclose($fp);
return API_RETURN_SUCCEED;
}
function updatecredit($get, $post) {
if(!API_UPDATECREDIT) {
return API_RETURN_FORBIDDEN;
}
$credit = $get['credit'];
$amount = $get['amount'];
$uid = $get['uid'];
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
$this->db->query("UPDATE ".$this->tablepre."members SET extcredits$credit=extcredits$credit+'$amount' WHERE uid='$uid'");
$discuz_user = $this->db->result_first("SELECT username FROM ".$this->tablepre."members WHERE uid='$uid'");
$this->db->query("INSERT INTO ".$this->tablepre."creditslog (uid, fromto, sendcredits, receivecredits, send, receive, dateline, operation)
VALUES ('$uid', '$discuz_user', '0', '$credit', '0', '$amount', '$timestamp', 'EXC')");
return API_RETURN_SUCCEED;
}
function getcredit($get, $post) {
if(!API_GETCREDIT) {
return API_RETURN_FORBIDDEN;
}
$uid = intval($get['uid']);
$credit = intval($get['credit']);
return $credit >= 1 && $credit <= 8 ? $this->db->result_first("SELECT extcredits$credit FROM ".$this->tablepre."members WHERE uid='$uid'") : 0;
}
function getcreditsettings($get, $post) {
if(!API_GETCREDITSETTINGS) {
return API_RETURN_FORBIDDEN;
}
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
$credits = array();
foreach($_DCACHE['settings']['extcredits'] as $id => $extcredits) {
$credits[$id] = array(strip_tags($extcredits['title']), $extcredits['unit']);
}
return $this->_serialize($credits);
}
function updatecreditsettings($get, $post) {
global $_DCACHE;
if(!API_UPDATECREDITSETTINGS) {
return API_RETURN_FORBIDDEN;
}
$credit = $get['credit'];
$outextcredits = array();
if($credit) {
foreach($credit as $appid => $credititems) {
if($appid == UC_APPID) {
foreach($credititems as $value) {
$outextcredits[] = array(
'appiddesc' => $value['appiddesc'],
'creditdesc' => $value['creditdesc'],
'creditsrc' => $value['creditsrc'],
'title' => $value['title'],
'unit' => $value['unit'],
'ratiosrc' => $value['ratiosrc'],
'ratiodesc' => $value['ratiodesc'],
'ratio' => $value['ratio']
);
}
}
}
}
require_once $this->appdir.'./forumdata/cache/cache_settings.php';
require_once $this->appdir.'./include/cache.func.php';
$this->db->query("REPLACE INTO ".$this->tablepre."settings (variable, value) VALUES ('outextcredits', '".addslashes(serialize($outextcredits))."');", 'UNBUFFERED');
$tmp = array();
foreach($outextcredits as $value) {
$key = $value['appiddesc'].'|'.$value['creditdesc'];
if(!isset($tmp[$key])) {
$tmp[$key] = array('title' => $value['title'], 'unit' => $value['unit']);
}
$tmp[$key]['ratiosrc'][$value['creditsrc']] = $value['ratiosrc'];
$tmp[$key]['ratiodesc'][$value['creditsrc']] = $value['ratiodesc'];
$tmp[$key]['creditsrc'][$value['creditsrc']] = $value['ratio'];
}
$_DCACHE['settings']['outextcredits'] = $tmp;
updatesettings();
return API_RETURN_SUCCEED;
}
}
function _setcookie($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 _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : UC_KEY);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
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, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
function _stripslashes($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = _stripslashes($val);
}
} else {
$string = stripslashes($string);
}
return $string;
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/uc.php
|
PHP
|
asf20
| 18,099
|
<?php
/*
[UCenter] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: dbbak.php 17414 2008-12-19 02:55:20Z zhaoxiongfei $
*/
error_reporting(0);
define('IN_COMSENZ', TRUE);
define('ROOT_PATH', dirname(__FILE__).'/../');
define('EXPLOR_SUCCESS', 0);
define('IMPORT_SUCCESS', 0);
define('DELETE_SQLPATH_SUCCESS', 4);
define('MKDIR_ERROR', 1);
define('DATABASE_EXPORT_FILE_INVALID', 2);
define('RUN_SQL_ERROR', 3);
define('SQLPATH_NULL_NOEXISTS', 4);
define('SQLPATH_NOMATCH_BAKFILE', 5);
define('BAK_FILE_LOSE', 6);
define('DIR_NO_EXISTS', 7);
define('DELETE_DUMPFILE_ERROR', 8);
define('DB_API_NO_MATCH', 9);
$sizelimit = 2000;
$usehex = true;
$code = @$_GET['code'];
$apptype = @$_GET['apptype'];
$apptype = strtolower($apptype);
if($apptype == 'discuz') {
require ROOT_PATH.'./config.inc.php';
} elseif($apptype == 'uchome' || $apptype == 'supesite' || $apptype == 'supev') {
require ROOT_PATH.'./config.php';
} elseif($apptype == 'ucenter') {
require ROOT_PATH.'./data/config.inc.php';
} elseif($apptype == 'ecmall') {
require ROOT_PATH.'./data/inc.config.php';
} elseif($apptype == 'ecshop') {
require ROOT_PATH.'./data/config.php';
} else {
api_msg('db_api_no_match', $apptype);
}
parse_str(_authcode($code, 'DECODE', UC_KEY), $get);
if(get_magic_quotes_gpc()) {
$get = _stripslashes($get);
}
if(empty($get)) {
exit('Invalid Request');
}
$timestamp = time();
if($timestamp - $get['time'] > 3600) {
exit('Authracation has expiried');
}
$get['time'] = $timestamp;
class dbstuff {
var $querynum = 0;
var $link;
var $histories;
var $time;
var $tablepre;
function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset, $pconnect = 0, $tablepre='', $time = 0) {
$this->time = $time;
$this->tablepre = $tablepre;
if($pconnect) {
if(!$this->link = mysql_pconnect($dbhost, $dbuser, $dbpw)) {
$this->halt('Can not connect to MySQL server');
}
} else {
if(!$this->link = mysql_connect($dbhost, $dbuser, $dbpw, 1)) {
$this->halt('Can not connect to MySQL server');
}
}
if($this->version() > '4.1') {
if($dbcharset) {
mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->link);
}
if($this->version() > '5.0.1') {
mysql_query("SET sql_mode=''", $this->link);
}
}
if($dbname) {
mysql_select_db($dbname, $this->link);
}
}
function fetch_array($query, $result_type = MYSQL_ASSOC) {
return mysql_fetch_array($query, $result_type);
}
function result_first($sql) {
$query = $this->query($sql);
return $this->result($query, 0);
}
function fetch_first($sql) {
$query = $this->query($sql);
return $this->fetch_array($query);
}
function fetch_all($sql) {
$arr = array();
$query = $this->query($sql);
while($data = $this->fetch_array($query)) {
$arr[] = $data;
}
return $arr;
}
function cache_gc() {
$this->query("DELETE FROM {$this->tablepre}sqlcaches WHERE expiry<$this->time");
}
function query($sql, $type = '', $cachetime = FALSE) {
$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
$this->halt('MySQL Query Error', $sql);
}
$this->querynum++;
$this->histories[] = $sql;
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() {
return mysql_get_server_info($this->link);
}
function close() {
return mysql_close($this->link);
}
function halt($message = '', $sql = '') {
api_msg('run_sql_error', $message.'<br /><br />'.$sql.'<br /> '.mysql_error());
}
}
$db = new dbstuff();
$version = '';
if($apptype == 'discuz') {
define('BACKUP_DIR', ROOT_PATH.'forumdata/');
$tablepre = $tablepre;
if(empty($dbcharset)) {
$dbcharset = in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : '';
}
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $pconnect, $tablepre);
define('IN_DISCUZ', true);
include ROOT_PATH.'discuz_version.php';
$version = DISCUZ_VERSION;
} elseif($apptype == 'uchome' || $apptype == 'supesite') {
define('BACKUP_DIR', ROOT_PATH.'./data/');
$tablepre = $_SC['tablepre'];
$dbcharset = $_SC['dbcharset'];
$db->connect($_SC['dbhost'], $_SC['dbuser'], $_SC['dbpw'], $_SC['dbname'], $dbcharset, $_SC['pconnect'], $tablepre);
} elseif($apptype == 'ucenter') {
define('BACKUP_DIR', ROOT_PATH.'./data/backup/');
$tablepre = UC_DBTABLEPRE;
$dbcharset = UC_DBCHARSET;
$db->connect(UC_DBHOST, UC_DBUSER, UC_DBPW, UC_DBNAME, $dbcharset, UC_DBCONNECT, $tablepre);
} elseif($apptype == 'ecmall') {
define('BACKUP_DIR', ROOT_PATH.'./data/backup/');
$tablepre = DB_PREFIX;
$dbcharset = strtolower(str_replace('-', '', strstr(LANG, '-')));
$cfg = parse_url(DB_CONFIG);
if(empty($cfg['pass'])) {
$cfg['pass'] = '';
} else {
$cfg['pass'] = urldecode($cfg['pass']);
}
$cfg['user'] = urldecode($cfg['user']);
$cfg['path'] = str_replace('/', '', $cfg['path']);
$db->connect($cfg['host'].':'.$cfg['port'], $cfg['user'], $cfg['pass'], $cfg['path'], $dbcharset, 0, $tablepre);
} elseif($apptype == 'supev') {
define('BACKUP_DIR', ROOT_PATH.'data/backup/');
$tablepre = $tablepre;
if(empty($dbcharset)) {
$dbcharset = in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : '';
}
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $pconnect, $tablepre);
} elseif($apptype == 'ecshop') {
define('BACKUP_DIR', ROOT_PATH.'data/backup/');
$tablepre = $prefix;
$dbcharset = 'utf8';
$db->connect($db_host, $db_user, $db_pass, $db_name, $dbcharset, 0, $tablepre);
}
if($get['method'] == 'export') {
$db->query('SET SQL_QUOTE_SHOW_CREATE=0', 'SILENT');
$time = date("Y-m-d H:i:s", $timestamp);
$tables = array();
$tables = arraykeys2(fetchtablelist($tablepre), 'Name');
if($apptype == 'discuz') {
$query = $db->query("SELECT datatables FROM {$tablepre}plugins WHERE datatables<>''");
while($plugin = $db->fetch_array($query)) {
foreach(explode(',', $plugin['datatables']) as $table) {
if($table = trim($table)) {
$tables[] = $table;
}
}
}
}
$get['volume'] = isset($get['volume']) ? intval($get['volume']) : 0;
$get['volume'] = $get['volume'] + 1;
$version = $version ? $version : $apptype;
$idstring = '# Identify: '.base64_encode("$timestamp,$version,$apptype,multivol,$get[volume]")."\n";
if(!isset($get['sqlpath']) || empty($get['sqlpath'])) {
$get['sqlpath'] = 'backup_'.date('ymd', $timestamp).'_'.random(6);
if(!mkdir(BACKUP_DIR.'./'.$get['sqlpath'], 0777)) {
api_msg('mkdir_error', 'make dir error:'.BACKUP_DIR.'./'.$get['sqlpath']);
}
} elseif(!is_dir(BACKUP_DIR.'./'.$get['sqlpath'])) {
if(!mkdir(BACKUP_DIR.'./'.$get['sqlpath'], 0777)) {
api_msg('mkdir_error', 'make dir error:'.BACKUP_DIR.'./'.$get['sqlpath']);
}
}
if(!isset($get['backupfilename']) || empty($get['backupfilename'])) {
$get['backupfilename'] = date('ymd', $timestamp).'_'.random(6);
}
$sqldump = '';
$get['tableid'] = isset($get['tableid']) ? intval($get['tableid']) : 0;
$get['startfrom'] = isset($get['startfrom']) ? intval($get['startfrom']) : 0;
$complete = TRUE;
for(; $complete && $get['tableid'] < count($tables) && strlen($sqldump) + 500 < $sizelimit * 1000; $get['tableid']++) {
$sqldump .= sqldumptable($tables[$get['tableid']], strlen($sqldump));
if($complete) {
$get['startfrom'] = 0;
}
}
!$complete && $get['tableid']--;
$dumpfile = BACKUP_DIR.$get['sqlpath'].'/'.$get['backupfilename'].'-'.$get['volume'].'.sql';
if(trim($sqldump)) {
$sqldump = "$idstring".
"# <?exit();?>\n".
"# $apptype Multi-Volume Data Dump Vol.$get[volume]\n".
"# Time: $time\n".
"# Type: $apptype\n".
"# Table Prefix: $tablepre\n".
"# $dbcharset\n".
"# $apptype Home: http://www.comsenz.com\n".
"# Please visit our website for newest infomation about $apptype\n".
"# --------------------------------------------------------\n\n\n".
$sqldump;
@$fp = fopen($dumpfile, 'wb');
@flock($fp, 2);
if(@!fwrite($fp, $sqldump)) {
@fclose($fp);
api_msg('database_export_file_invalid', $dumpfile);
} else {
fclose($fp);
auto_next($get, $dumpfile);
}
} else {
@touch(ROOT_PATH.$get['sqlpath'].'/index.htm');
api_msg('explor_success', 'explor_success');
}
} elseif($get['method'] == 'import') {
if(!isset($get['dumpfile']) || empty($get['dumpfile'])) {
$get['dumpfile'] = get_dumpfile_by_path($get['sqlpath']);
$get['volume'] = 0;
}
$get['volume']++;
$next_dumpfile = preg_replace('/^(\d+)\_(\w+)\-(\d+)\.sql$/', '\\1_\\2-'.$get['volume'].'.sql', $get['dumpfile']);
if(!is_file(BACKUP_DIR.$get['sqlpath'].'/'.$get['dumpfile'])) {
if(is_file(BACKUP_DIR.$get['sqlpath'].'/'.$next_dumpfile)) {
api_msg('bak_file_lose', $get['dumpfile']);
} else {
api_msg('import_success', 'import_success');
}
}
$sqldump = file_get_contents(BACKUP_DIR.$get['sqlpath'].'/'.$get['dumpfile']);
$sqlquery = splitsql($sqldump);
unset($sqldump);
foreach($sqlquery as $sql) {
$sql = syntablestruct(trim($sql), $db->version() > '4.1', $dbcharset);
if($sql != '') {
$db->query($sql, 'SILENT');
if(($sqlerror = $db->error()) && $db->errno() != 1062) {
$db->halt('MySQL Query Error', $sql);
}
}
}
$cur_file = $get['dumpfile'];
$get['dumpfile'] = $next_dumpfile;
auto_next($get, BACKUP_DIR.$get['sqlpath'].'/'.$cur_file);
} elseif($get['method'] == 'ping') {
if($get['dir'] && is_dir(BACKUP_DIR.$get['dir'])) {
echo "1";exit;
} else {
echo "-1";exit;
}
} elseif($get['method'] == 'list') {
$str = "<root>\n";
$directory = dir(BACKUP_DIR);
while($entry = $directory->read()) {
$filename = BACKUP_DIR.$entry;
if(is_dir($filename) && preg_match('/backup_(\d+)_\w+$/', $filename, $match)) {
$str .= "\t<dir>\n";
$str .= "\t\t<dirname>$filename</dirname>\n";
$str .= "\t\t<dirdate>$match[1]</dirdate>\n";
$str .= "\t</dir>\n";
}
}
$directory->close();
$str .= "</root>";
echo $str;
exit;
} elseif($get['method'] == 'view') {
$sqlpath = trim($get['sqlpath']);
if(empty($sqlpath) || !is_dir(BACKUP_DIR.$sqlpath)) {
api_msg('dir_no_exists', $sqlpath);
}
$str = "<root>\n";
$directory = dir(BACKUP_DIR.$sqlpath);
while($entry = $directory->read()) {
$filename = BACKUP_DIR.$sqlpath.'/'.$entry;
if(is_file($filename) && preg_match('/\d+_\w+\-(\d+).sql$/', $filename, $match)) {
$str .= "\t<file>\n";
$str .= "\t\t<file_name>$match[0]</file_name>\n";
$str .= "\t\t<file_size>".filesize($filename)."</file_size>\n";
$str .= "\t\t<file_num>$match[1]</file_num>\n";
$str .= "\t\t<file_url>".str_replace(ROOT_PATH, 'http://'.$_SERVER['HTTP_HOST'].'/', $filename)."</file_url>\n";
$str .= "\t\t<last_modify>".filemtime($filename)."</last_modify>\n";
$str .= "\t</file>\n";
}
}
$directory->close();
$str .= "</root>";
echo $str;
exit;
} elseif($get['method'] == 'delete') {
$sqlpath = trim($get['sqlpath']);
if(empty($sqlpath) || !is_dir(BACKUP_DIR.$sqlpath)) {
api_msg('dir_no_exists', $sqlpath);
}
$directory = dir(BACKUP_DIR.$sqlpath);
while($entry = $directory->read()) {
$filename = BACKUP_DIR.$sqlpath.'/'.$entry;
if(is_file($filename) && preg_match('/\d+_\w+\-(\d+).sql$/', $filename) && !@unlink($filename)) {
api_msg('delete_dumpfile_error', $filename);
}
}
$directory->close();
@rmdir(BACKUP_DIR.$sqlpath);
api_msg('delete_sqlpath_success', 'delete_sqlpath_success');
}
function syntablestruct($sql, $version, $dbcharset) {
if(strpos(trim(substr($sql, 0, 18)), 'CREATE TABLE') === FALSE) {
return $sql;
}
$sqlversion = strpos($sql, 'ENGINE=') === FALSE ? FALSE : TRUE;
if($sqlversion === $version) {
return $sqlversion && $dbcharset ? preg_replace(array('/ character set \w+/i', '/ collate \w+/i', "/DEFAULT CHARSET=\w+/is"), array('', '', "DEFAULT CHARSET=$dbcharset"), $sql) : $sql;
}
if($version) {
return preg_replace(array('/TYPE=HEAP/i', '/TYPE=(\w+)/is'), array("ENGINE=MEMORY DEFAULT CHARSET=$dbcharset", "ENGINE=\\1 DEFAULT CHARSET=$dbcharset"), $sql);
} else {
return preg_replace(array('/character set \w+/i', '/collate \w+/i', '/ENGINE=MEMORY/i', '/\s*DEFAULT CHARSET=\w+/is', '/\s*COLLATE=\w+/is', '/ENGINE=(\w+)(.*)/is'), array('', '', 'ENGINE=HEAP', '', '', 'TYPE=\\1\\2'), $sql);
}
}
function splitsql($sql) {
$sql = str_replace("\r", "\n", $sql);
$ret = array();
$num = 0;
$queriesarray = explode(";\n", trim($sql));
unset($sql);
foreach($queriesarray as $query) {
$ret[$num] = isset($ret[$num]) ? $ret[$num] : '';
$queries = explode("\n", trim($query));
foreach($queries as $query) {
$ret[$num] .= isset($query[0]) && $query[0] == "#" ? NULL : $query;
}
$num++;
}
return($ret);
}
function get_dumpfile_by_path($path) {
if(empty($path) || !is_dir(BACKUP_DIR.$path)) {
api_msg('sqlpath_null_noexists', $path);
}
$directory = dir(BACKUP_DIR.$path);
while($entry = $directory->read()) {
$filename = BACKUP_DIR.$path.'/'.$entry;
if(is_file($filename)) {
if(preg_match('/^\d+\_\w+\-\d+\.sql$/', $entry)) {
$file_bakfile = preg_replace('/^(\d+)\_(\w+)\-(\d+)\.sql$/', '\\1_\\2-1.sql', $entry);
if(is_file(BACKUP_DIR.$path.'/'.$file_bakfile)) {
return $file_bakfile;
} else {
api_msg('sqlpath_nomatch_bakfile', $path);
}
}
}
}
$directory->close();
api_msg('sqlpath_nomatch_bakfile', $path);
}
function api_msg($code, $msg) {
$out = "<root>\n";
$out .= "\t<error errorCode=\"".constant(strtoupper($code))."\" errorMessage=\"$msg\" />\n";
$out .= "\t<fileinfo>\n";
$out .= "\t\t<file_num></file_num>\n";
$out .= "\t\t<file_size></file_size>\n";
$out .= "\t\t<file_name></file_name>\n";
$out .= "\t\t<file_url></file_url>\n";
$out .= "\t\t<last_modify></last_modify>\n";
$out .= "\t</fileinfo>\n";
$out .= "\t<nexturl></nexturl>\n";
$out .= "</root>";
echo $out;
exit;
}
function arraykeys2($array, $key2) {
$return = array();
foreach($array as $val) {
$return[] = $val[$key2];
}
return $return;
}
function auto_next($get, $sqlfile) {
$next_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?apptype='.$GLOBALS['apptype'].'&code='.urlencode(encode_arr($get));
$out = "<root>\n";
$out .= "\t<error errorCode=\"0\" errorMessage=\"ok\" />\n";
$out .= "\t<fileinfo>\n";
$out .= "\t\t<file_num>$get[volume]</file_num>\n";
$out .= "\t\t<file_size>".filesize($sqlfile)."</file_size>\n";
$out .= "\t\t<file_name>".basename($sqlfile)."</file_name>\n";
$out .= "\t\t<file_url>".str_replace(ROOT_PATH, 'http://'.$_SERVER['HTTP_HOST'].'/', $sqlfile)."</file_url>\n";
$out .= "\t\t<last_modify>".filemtime($sqlfile)."</last_modify>\n";
$out .= "\t</fileinfo>\n";
$out .= "\t<nexturl><![CDATA[$next_url]]></nexturl>\n";
$out .= "</root>";
echo $out;
exit;
}
function encode_arr($get) {
$tmp = '';
foreach($get as $key => $val) {
$tmp .= '&'.$key.'='.$val;
}
return _authcode($tmp, 'ENCODE', UC_KEY);
}
function sqldumptable($table, $currsize = 0) {
global $get, $db, $sizelimit, $startrow, $extendins, $sqlcompat, $sqlcharset, $dumpcharset, $usehex, $complete, $excepttables;
$offset = 300;
$tabledump = '';
$tablefields = array();
$query = $db->query("SHOW FULL COLUMNS FROM $table", 'SILENT');
if(strexists($table, 'adminsessions')) {
return ;
} elseif(!$query && $db->errno() == 1146) {
return;
} elseif(!$query) {
$usehex = FALSE;
} else {
while($fieldrow = $db->fetch_array($query)) {
$tablefields[] = $fieldrow;
}
}
if(!$get['startfrom']) {
$createtable = $db->query("SHOW CREATE TABLE $table", 'SILENT');
if(!$db->error()) {
$tabledump = "DROP TABLE IF EXISTS $table;\n";
} else {
return '';
}
$create = $db->fetch_row($createtable);
if(strpos($table, '.') !== FALSE) {
$tablename = substr($table, strpos($table, '.') + 1);
$create[1] = str_replace("CREATE TABLE $tablename", 'CREATE TABLE '.$table, $create[1]);
}
$tabledump .= $create[1];
$tablestatus = $db->fetch_first("SHOW TABLE STATUS LIKE '$table'");
$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
}
$tabledumped = 0;
$numrows = $offset;
$firstfield = $tablefields[0];
while($currsize + strlen($tabledump) + 500 < $sizelimit * 1000 && $numrows == $offset) {
if($firstfield['Extra'] == 'auto_increment') {
$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $get[startfrom] LIMIT $offset";
} else {
$selectsql = "SELECT * FROM $table LIMIT $get[startfrom], $offset";
}
$tabledumped = 1;
$rows = $db->query($selectsql);
$numfields = $db->num_fields($rows);
$numrows = $db->num_rows($rows);
while($row = $db->fetch_row($rows)) {
$comma = $t = '';
for($i = 0; $i < $numfields; $i++) {
$t .= $comma.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
$comma = ',';
}
if(strlen($t) + $currsize + strlen($tabledump) + 500 < $sizelimit * 1000) {
if($firstfield['Extra'] == 'auto_increment') {
$get['startfrom'] = $row[0];
} else {
$get['startfrom']++;
}
$tabledump .= "INSERT INTO $table VALUES ($t);\n";
} else {
$complete = FALSE;
break 2;
}
}
}
$tabledump .= "\n";
return $tabledump;
}
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 fetchtablelist($tablepre = '') {
global $db;
$arr = explode('.', $tablepre);
$dbname = isset($arr[1]) && $arr[1] ? $arr[0] : '';
$sqladd = $dbname ? " FROM $dbname LIKE '$arr[1]%'" : "LIKE '$tablepre%'";
!$tablepre && $tablepre = '*';
$tables = $table = array();
$query = $db->query("SHOW TABLE STATUS $sqladd");
while($table = $db->fetch_array($query)) {
$table['Name'] = ($dbname ? "$dbname." : '').$table['Name'];
$tables[] = $table;
}
return $tables;
}
function _stripslashes($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = _stripslashes($val);
}
} else {
$string = stripslashes($string);
}
return $string;
}
function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : UC_KEY);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
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, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
function strexists($haystack, $needle) {
return !(strpos($haystack, $needle) === FALSE);
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/dbbak.php
|
PHP
|
asf20
| 21,712
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: uchome.php 17407 2008-12-18 03:25:16Z liuqiang $
*/
@chdir('../');
require './include/common.inc.php';
if(!$ucappopen['UCHOME']) {
showmessage('uchome_not_installed');
}
if($action == 'getalbums' && $discuz_uid) {
$albums = @unserialize(dfopen("$uchomeurl/api/discuz.php?ac=album&uid=$discuz_uid"));
if($albums && is_array($albums)) {
$str = '<ul>';
foreach($albums as $album) {
$str .= "<li><a href=\"javascript:;\" id=\"uch_album_$album[albumid]\" onclick=\"$('insertimage_www_div').style.display='none';$('insertimage_album_div').style.display='';ajaxget('api/uchome.php?action=getphotoes&inajax=1&aid=$album[albumid]&photonum=$album[picnum]', 'uch_photoes', 'uch_photoes');this.style.fontWeight='bold';if(prealbum){prealbum.style.fontWeight='normal'};prealbum=this;$('uch_createalbum').style.display='';hideMenu(1);\">$album[albumname]</a></li>";
}
$str .= '</ul>';
showmessage($str);
} else {
showmessage('NOALBUM');
}
} elseif($action == 'getphotoes' && $discuz_uid && $aid) {
$page = max(1, intval($page));
$perpage = 8;
$start = ($page - 1) * $perpage;
$aid = intval($aid);
$photonum = intval($photonum);
$photoes = @unserialize(dfopen("$uchomeurl/api/discuz.php?ac=album&uid=$discuz_uid&start=$start&count=$photonum&perpage=$perpage&aid=$aid"));
if($photoes && is_array($photoes)) {
$i = 0;
$str = '<table cellspacing="2" cellpadding="2"><tr>';
foreach($photoes as $photo) {
if($i++ == $perpage) {
break;
}
$picurl = substr(strtolower($photo['bigpic']), 0, 7) == 'http://' ? '' : $uchomeurl.'/';
$str .= '<td><img src="'.$picurl.$photo['pic'].'" title="'.$photo['filename'].'" onclick="wysiwyg ? insertText(\'<img src='.$picurl.$photo[bigpic].' border=0 /> \', false) : insertText(\'[img]'.$picurl.$photo[bigpic].'[/img]\');hideMenu();" onload="thumbImg(this, 1)" _width="80" _height="80" style="cursor: pointer;"></td>'.
($i % 4 == 0 && isset($photoes[$i]) ? '</tr><tr>' : '');
}
$str .= '</tr></table>'.multi($photonum, $perpage, $start / $perpage + 1, "api/uchome.php?action=getphotoes&aid=$aid&photonum=$photonum");
showmessage($str);
} else {
showmessage('NOPHOTO');
}
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/api/uchome.php
|
PHP
|
asf20
| 2,268
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: misc.php 17437 2008-12-22 04:10:42Z monkey $
*/
define('NOROBOT', TRUE);
define('CURSCRIPT', 'misc');
require_once './include/common.inc.php';
require_once './include/post.func.php';
$feed = array();
if($action == 'maxpages') {
$pages = intval($pages);
if(empty($pages)) {
showmessage('undefined_action', NULL, 'HALTED');
} else {
showmessage('max_pages');
}
} elseif($action == 'nav') {
require_once DISCUZ_ROOT.'./include/forumselect.inc.php';
exit;
} 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);
showmessage('customtopics_updated', $indexname);
}
} elseif($action == 'attachcredit') {
if($formhash != FORMHASH) {
showmessage('undefined_action', NULL, 'HALTED');
}
$aid = intval($aid);
$attach = $db->fetch_first("SELECT tid, filename FROM {$tablepre}attachments WHERE aid='$aid'");
$thread = $db->fetch_first("SELECT fid FROM {$tablepre}threads WHERE tid='$attach[tid]' AND displayorder>='0'");
$forum = $db->fetch_first("SELECT getattachcredits FROM {$tablepre}forumfields WHERE fid='$thread[fid]'");
$getattachcredits = $forum['getattachcredits'] ? unserialize($forum['getattachcredits']) : $creditspolicy['getattach'];
checklowerlimit($getattachcredits, -1);
updatecredits($discuz_uid, $getattachcredits, -1);
$ck = substr(md5($aid.$timestamp.md5($authkey)), 0, 8);
$key = md5($aid.md5($authkey).$timestamp);
$policymsgs = $p = '';
foreach($getattachcredits as $id => $policy) {
$policymsg .= $p.($extcredits[$id]['img'] ? $extcredits[$id]['img'].' ' : '').$extcredits[$id]['title'].' '.$policy.' '.$extcredits[$id]['unit'];
$p = ', ';
}
$sidauth = rawurlencode(authcode($sid, 'ENCODE', $authkey));
showmessage('attachment_credit', "attachment.php?aid=$aid&k=$key&t=$timestamp&ck=$ck&sid=$sidauth", '', 1);
} elseif($action == 'attachpay') {
$aid = intval($aid);
if(!$aid) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif(!isset($extcredits[$creditstransextra[1]])) {
showmessage('credits_transaction_disabled');
} elseif(!$discuz_uid) {
showmessage('group_nopermission', NULL, 'NOPERM');
} else {
$attach = $db->fetch_first("SELECT a.tid, a.pid, a.uid, a.price, a.filename, a.description, a.readperm, m.username AS author FROM {$tablepre}attachments a LEFT JOIN {$tablepre}members m ON a.uid=m.uid WHERE a.aid='$aid'");
if($attach['price'] <= 0) {
showmessage('undefined_action', NULL, 'HALTED');
}
}
if($attach['readperm'] && $attach['readperm'] > $readaccess) {
showmessage('attachment_forum_nopermission', NULL, 'NOPERM');
}
if(($balance = ${'extcredits'.$creditstransextra[1]} - $attach['price']) < ($minbalance = 0)) {
showmessage('credits_balance_insufficient');
}
$sidauth = rawurlencode(authcode($sid, 'ENCODE', $authkey));
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}attachpaymentlog WHERE aid='$aid' AND uid='$discuz_uid'")) {
showmessage('attachment_yetpay', "attachment.php?aid=$aid&k=".md5($aid.md5($authkey).$timestamp)."&t=$timestamp&sid=$sidauth", '', 1);
}
$discuz_action = 81;
$attach['netprice'] = round($attach['price'] * (1 - $creditstax));
if(!submitcheck('paysubmit')) {
include template('attachpay');
} else {
$updateauthor = 1;
if($maxincperthread > 0) {
if(($db->result_first("SELECT SUM(netamount) FROM {$tablepre}attachpaymentlog WHERE aid='$aid'")) > $maxincperthread) {
$updateauthor = 0;
}
}
if($updateauthor) {
$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[1]=extcredits$creditstransextra[1]+$attach[netprice] WHERE uid='$attach[uid]'");
}
$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[1]=extcredits$creditstransextra[1]-$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&k=".md5($aid.md5($authkey).$timestamp)."&t=$timestamp&sid=$sidauth", '', 1);
}
} 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'] = dgmdate("$dateformat $timeformat", $log['dateline'] + $timeoffset * 3600);
$loglist[] = $log;
}
include template('attachpay_view');
} elseif($action == 'getonlines') {
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}sessions", 0);
showmessage($num);
} elseif($action == 'swfupload') {
if($operation == 'config' && $discuz_uid) {
$swfhash = md5(substr(md5($_DCACHE['settings']['authkey']), 8).$discuz_uid);
include_once language('swfupload');
if($attachextensions !== '') {
$exts = explode(',', $attachextensions);
$attachextensions = str_replace(' ', '', '*.'.implode(',*.', $exts));
} else {
$attachextensions = '*.*';
}
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><parameter><allowsExtend><extend depict=\"All Support Formats \">$attachextensions</extend></allowsExtend><language>$xmllang</language><config><userid>$discuz_uid</userid><hash>$swfhash</hash><maxupload>$maxattachsize</maxupload></config></parameter>";
} elseif($operation == 'upload') {
$uid = $_POST['uid'];
$swfhash = md5(substr(md5($_DCACHE['settings']['authkey']), 8).$uid);
if(!$_FILES['Filedata']['error'] && $_POST['hash'] == $swfhash) {
require_once './include/post.func.php';
$attachments = attach_upload('Filedata', 1);
if($attachments) {
require_once DISCUZ_ROOT.'include/chinese.class.php';
$c = new Chinese('utf8', $charset);
$attach = $attachments[0];
$attach['name'] = htmlspecialchars(addslashes($c->Convert(urldecode($attach['name']))), ENT_QUOTES);
$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, price, filename, description, filetype, filesize, attachment, downloads, isimage, uid, thumb, remote, width)
VALUES ('0', '0', '$timestamp', '0', '0', '$attach[name]', '', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$uid', '$attach[thumb]', '$attach[remote]', '$attach[width]')");
}
}
}
exit;
} elseif($action == 'imme_binding' && $discuz_uid) {
if(isemail($id)) {
$msn = $db->result_first("SELECT msn FROM {$tablepre}memberfields WHERE uid='$discuz_uid'");
$msn = explode("\t", $msn);
$id = dhtmlspecialchars(substr($id, 0, strpos($id, '@')));
$msn = "$msn[0]\t$id";
$db->query("UPDATE {$tablepre}memberfields SET msn='$msn' WHERE uid='$discuz_uid'");
showmessage('msn_binding_succeed', 'memcp.php');
} else {
if($result == 'Declined') {
dheader("Location: memcp.php");
} else {
showmessage($response['result']);
}
}
} elseif($action == 'imme_cancelbinding' && $discuz_uid) {
$msn = $db->result_first("SELECT msn FROM {$tablepre}memberfields WHERE uid='$discuz_uid'");
$msn = explode("\t", $msn);
$db->query("UPDATE {$tablepre}memberfields SET msn='$msn[0]' WHERE uid='$discuz_uid'");
dheader("Location: http://settings.messenger.live.com/applications/websettings.aspx");
} 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');
}
}
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]) {
showmessage('forum_passwd', "forumdisplay.php?fid=$fid");
}
$thread = $db->fetch_first("SELECT * FROM {$tablepre}threads WHERE tid='$tid' AND displayorder>='0'");
if(!$thread) {
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') {
$fup = $db->fetch_first("SELECT name, fid FROM {$tablepre}forums WHERE fid='$forum[fup]'");
$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', 1)) {
if(!$allowvote) {
showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(!empty($thread['closed'])) {
showmessage('thread_poll_closed');
} elseif(empty($pollanswers)) {
showmessage('thread_poll_invalid');
}
$pollarray = $db->fetch_first("SELECT maxchoices, expiration FROM {$tablepre}polls WHERE tid='$tid'");
if(!$pollarray) {
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']);
if($customaddfeed & 4) {
$feed['icon'] = 'poll';
$feed['title_template'] = 'feed_thread_votepoll_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>",
'author' => "<a href=\"space.php?uid=$thread[authorid]\">$thread[author]</a>"
);
postfeed($feed);
}
$pid = $db->result_first("SELECT pid FROM {$tablepre}posts WHERE tid='$tid' AND first='1'");
if(!empty($inajax)) {
showmessage('thread_poll_succeed', "viewthread.php?tid=$tid&viewpid=$pid&inajax=1");
} else {
showmessage('thread_poll_succeed', "viewthread.php?tid=$tid");
}
} elseif($action == 'viewvote') {
require_once DISCUZ_ROOT.'./include/post.func.php';
$polloptionid = is_numeric($polloptionid) ? $polloptionid : '';
$overt = $db->result_first("SELECT overt FROM {$tablepre}polls WHERE tid='$tid'");
$polloptions = array();
$query = $db->query("SELECT polloptionid, polloption FROM {$tablepre}polloptions WHERE tid='$tid'");
while($options = $db->fetch_array($query)) {
if(empty($polloptionid)) {
$polloptionid = $options['polloptionid'];
}
$options['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']);
$polloptions[] = $options;
}
$arrvoterids = array();
if($overt || $adminid == 1) {
$voterids = '';
$voterids = $db->result_first("SELECT voterids FROM {$tablepre}polloptions WHERE polloptionid='$polloptionid'");
$arrvoterids = explode("\t", trim($voterids));
}
if(!empty($arrvoterids)) {
$arrvoterids = array_slice($arrvoterids, -100);
}
$voterlist = $voter = array();
if($voterids = implodeids($arrvoterids)) {
$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') {
$discuz_action = 122;
if(!submitcheck('sendsubmit')) {
$fromuid = $creditspolicy['promotion_visit'] && $discuz_uid ? '&fromuid='.$discuz_uid : '';
$threadurl = "{$boardurl}viewthread.php?tid=$tid$fromuid";
$subject = $db->result_first("SELECT subject FROM {$tablepre}threads WHERE tid='$tid'");
if($discuz_uid) {
$email = $db->result_first("SELECT email FROM {$tablepre}members WHERE uid='$discuz_uid'");
}
include template('emailfriend');
} else {
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'NOPERM');
}
if(empty($sendtoemail)) {
showmessage('email_friend_invalid', NULL, 'HALTED');
}
sendmail("$sendtoemail", 'email_to_friend_subject', 'email_to_friend_message');
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'];
}
$post = $db->fetch_first("SELECT * FROM {$tablepre}posts WHERE pid='$pid' AND invisible='0' AND authorid<>'0'");
if(!$post || $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'] & 1) {
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] = '';
$rating['max'] = $rating['max'] < $maxratetoday[$id] ? $rating['max'] : $maxratetoday[$id];
$rating['min'] = -$rating['min'] < $maxratetoday[$id] ? $rating['min'] : -$maxratetoday[$id];
$offset = abs(ceil(($rating['max'] - $rating['min']) / 10));
if($rating['max'] > $rating['min']) {
for($vote = $rating['max']; $vote >= $rating['min']; $vote -= $offset) {
$ratelist[$id] .= $vote ? '<li>'.($vote > 0 ? '+'.$vote : $vote).'</li>' : '';
}
}
}
}
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'];
}
$post = $db->fetch_first("SELECT * FROM {$tablepre}posts WHERE pid='$pid' AND invisible='0' AND authorid<>'0'");
if(!$post || $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'] = dgmdate("$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$ratelog[username]\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 DESC");
$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');
}
$loglist = $logcount = array();
while($log = $db->fetch_array($queryr)) {
$logcount[$log['extcredits']] += $log['score'];
$log['dateline'] = dgmdate("$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 == 'viewwarning' && $uid) {
if(!($warnuser = $db->result_first("SELECT username FROM {$tablepre}members WHERE uid='$uid'"))) {
showmessage('undefined_action', NULL, 'HALTED');
}
$query = $db->query("SELECT * FROM {$tablepre}warnings WHERE authorid='$uid'");
if(!($warnnum = $db->num_rows($query))) {
showmessage('thread_warning_nonexistence');
}
$warning = array();
while($warning = $db->fetch_array($query)) {
$warning['dateline'] = dgmdate("$dateformat $timeformat", $warning['dateline'] + $timeoffset * 3600);
$warning['reason'] = dhtmlspecialchars($warning['reason']);
$warnings[] = $warning;
}
$discuz_action = 73;
include template('warn_view');
} elseif($action == 'pay') {
if(!isset($extcredits[$creditstransextra[1]])) {
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'.$creditstransextra[1]} - $thread['price']) < ($minbalance = 0)) {
showmessage('credits_balance_insufficient');
}
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}paymentlog WHERE tid='$tid' AND uid='$discuz_uid'")) {
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) {
if(($db->result_first("SELECT SUM(netamount) FROM {$tablepre}paymentlog WHERE tid='$tid'")) > $maxincperthread) {
$updateauthor = false;
}
}
if($updateauthor) {
$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[1]=extcredits$creditstransextra[1]+$thread[netprice] WHERE uid='$thread[authorid]'");
}
$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[1]=extcredits$creditstransextra[1]-$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'] = dgmdate("$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($db->result_first("SELECT id FROM {$tablepre}reportlog WHERE pid='$pid' AND uid='$discuz_uid'")) {
showmessage('thread_report_existence');
}
if(!submitcheck('reportsubmit')) {
include template('reportpost');
exit;
} else {
$type = intval($type) ? 1 : 0;
$reason = cutstr(dhtmlspecialchars($reason), 40);
$db->query("INSERT INTO {$tablepre}reportlog (fid, pid, uid, username, type, reason, dateline)
VALUES ('$fid', '$pid', '$discuz_uid', '$discuz_user', '$type', '$reason', '$timestamp')");
$db->query("UPDATE {$tablepre}forums SET modworks='1' WHERE fid='$fid'");
$db->query("UPDATE {$tablepre}members SET lastpost='$timestamp' WHERE uid='$discuz_uid'");
showmessage('thread_report_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'] = dgmdate("$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;
$post = $db->fetch_first("SELECT authorid, first FROM {$tablepre}posts WHERE pid='$pid' and tid='$tid'");
if(!($thread['special'] == 3 && $post && ($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$creditstransextra[2]=extcredits$creditstransextra[2]+$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', 0);
}
sendpm($post['authorid'], 'reward_bestanswer_subject', 'reward_bestanswer_message', 0);
showmessage('reward_completion', $forward);
} elseif($action == 'activityapplies') {
if(!$discuz_uid) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(submitcheck('activitysubmit')) {
$expiration = $db->result_first("SELECT expiration FROM {$tablepre}activities WHERE tid='$tid'");
if($expiration && $expiration < $timestamp) {
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')");
if($customaddfeed & 4) {
$feed['icon'] = 'activity';
$feed['title_template'] = 'feed_reply_activity_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>"
);
postfeed($feed);
}
showmessage('activity_completion', "viewthread.php?tid=$tid&viewpid=$pid");
}
} elseif($action == 'activityapplylist') {
$activity = $db->fetch_first("SELECT * FROM {$tablepre}activities WHERE tid='$tid'");
if(!$activity || $thread['special'] != 4 || $thread['authorid'] != $discuz_uid) {
showmessage('undefined_action');
}
if(!submitcheck('applylistsubmit')) {
$sqlverified = $thread['authorid'] == $discuz_uid ? '' : 'AND verified=1';
if(!empty($uid) && $thread['authorid'] == $discuz_uid) {
$sqlverified .= " AND uid='$uid'";
}
$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'] = dgmdate("$dateformat $timeformat", $activityapplies['dateline'] + $timeoffset * 3600);
$applylist[] = $activityapplies;
}
$activity['starttimefrom'] = dgmdate("$dateformat $timeformat", $activity['starttimefrom'] + $timeoffset * 3600);
$activity['starttimeto'] = $activity['starttimeto'] ? dgmdate("$dateformat $timeformat", $activity['starttimeto'] + $timeoffset * 3600) : 0;
$activity['expiration'] = $activity['expiration'] ? dgmdate("$dateformat $timeformat", $activity['expiration'] + $timeoffset * 3600) : 0;
$applynumbers = $db->result_first("SELECT COUNT(*) FROM {$tablepre}activityapplies WHERE tid='$tid' AND verified=1");
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', 0);
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', 0);
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;
$debate = $db->fetch_first("SELECT uid, endtime, affirmvoterids, negavoterids FROM {$tablepre}debates WHERE tid='$tid'");
if(empty($debate)) {
showmessage('debate_nofound');
}
$feed = array();
if($customaddfeed & 4) {
$feed['icon'] = 'debate';
$feed['title_template'] = 'feed_thread_debatevote_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>",
'author' => "<a href=\"space.php?uid=$thread[authorid]\">$thread[author]</a>"
);
}
if($isfirst) {
$stand = intval($stand);
if($stand == 1 || $stand == 2) {
if(strpos("\t".$debate['affirmvoterids'], "\t$discuz_uid\t") !== FALSE || strpos("\t".$debate['negavoterids'], "\t$discuz_uid\t") !== FALSE) {
showmessage('debate_poll_voted');
} elseif($debate['uid'] == $discuz_uid) {
showmessage('debate_poll_myself');
} elseif($debate['endtime'] && $debate['endtime'] < $timestamp) {
showmessage('debate_poll_end');
}
}
if($stand == 1) {
$db->query("UPDATE {$tablepre}debates SET affirmvotes=affirmvotes+1 WHERE tid='$tid'");
$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 WHERE tid='$tid'");
$db->query("UPDATE {$tablepre}debates SET negavoterids=CONCAT(negavoterids, '$discuz_uid\t') WHERE tid='$tid'");
}
if($feed) {
postfeed($feed);
}
showmessage('debate_poll_succeed');
}
$debatepost = $db->fetch_first("SELECT stand, voterids, uid FROM {$tablepre}debateposts WHERE pid='$pid' AND tid='$tid'");
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");
} elseif(strpos("\t".$debate['voterids'], "\t$discuz_uid\t") !== FALSE) {
showmessage('debate_poll_voted', "viewthread.php?tid=$tid");
} elseif($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'");
if($feed) {
postfeed($feed);
}
showmessage('debate_poll_succeed', "viewthread.php?tid=$tid");
} elseif($action == 'debateumpire') {
$debate = $db->fetch_first("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
if(empty($debate)) {
showmessage('debate_nofound');
}elseif(!empty($thread['closed']) && $timestamp - $debate['endtime'] > 3600) {
showmessage('debate_umpire_edit_invalid');
} elseif($discuz_userss != $debate['umpire']) {
showmessage('debate_umpire_nopermission');
}
$debate = array_merge($debate, $thread);
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');
}
$bestdebateruid = $db->result_first("SELECT uid FROM {$tablepre}members WHERE username='$bestdebater' LIMIT 1");
if(!$bestdebateruid) {
showmessage('debate_umpire_bestdebater_invalid');
}
if(!$bestdebaterstand = $db->result_first("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$bestdebateruid' AND stand>'0' AND uid<>'$debate[uid]' AND uid<>'$discuz_uid' LIMIT 1")) {
showmessage('debate_umpire_bestdebater_invalid');
}
$arr = $db->fetch_first("SELECT SUM(voters) as voters, COUNT(*) as replies FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$bestdebateruid'");
$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/51shangcheng.cn/htdocs/misc.php
|
PHP
|
asf20
| 42,588
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: medal.php 17501 2009-01-05 01:19:36Z tiger $
*/
define('CURSCRIPT', 'medal');
require_once './include/common.inc.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_medals.php';
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'HALTED');
}
$medallist = $medallogs = array();
$tpp = 10;
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
if(empty($action)) {
$query = $db->query("SELECT * FROM {$tablepre}medals WHERE available='1' ORDER BY displayorder LIMIT 0,100");
while($medal = $db->fetch_array($query)) {
$medal['permission'] = formulaperm($medal['permission'], 2);
$medallist[$medal['medalid']] = $medal;
}
$medaldata = $db->result_first("SELECT medals FROM {$tablepre}memberfields WHERE uid='$discuz_uid'");
$membermedal = $medaldata ? explode("\t", $medaldata) : array();
$medalcount = count($membermedal);
if(!empty($membermedal)) {
$medallog = array();
foreach($membermedal as $medalid) {
if($medalpos = strpos($medalid, '|')) {
$medalid = substr($medalid, 0, $medalpos);
}
$medallog['name'] = $_DCACHE['medals'][$medalid]['name'];
$medallog['image'] = $medallist[$medalid]['image'];
$medallogs[] = $medallog;
}
}
} elseif($action == 'apply') {
$medalid = intval($medalid);
$formulamessage = '';
$medal = $db->fetch_first("SELECT * FROM {$tablepre}medals WHERE medalid='$medalid'");
if(!$medal['type']) {
showmessage('medal_required_invalid');
}
formulaperm($medal['permission'], 1) && $medal['permission'] = formulaperm($medal['permission'], 2);
if(submitcheck('medalsubmit')) {
$medaldetail = $db->fetch_first("SELECT medalid FROM {$tablepre}medallog WHERE uid='$discuz_uid' AND medalid='$medalid' AND type NOT IN('3', '4')");
if($medaldetail['medalid']) {
showmessage('medal_apply_existence', 'medal.php');
} else {
$expiration = empty($medal['expiration'])? 0 : $timestamp + $medal['expiration'] * 86400;
$db->query("INSERT INTO {$tablepre}medallog (uid, medalid, type, dateline, expiration, status) VALUES ('$discuz_uid', '$medalid', '2', '$timestamp', '$expiration', '0')");
}
showmessage('medal_apply_succeed', 'medal.php');
}
} elseif($action == 'log') {
$medallognum = $db->result_first("SELECT COUNT(*) FROM {$tablepre}medallog WHERE uid='$discuz_uid' AND type IN ('0', '1')");
$multipage = multi($medallognum, $tpp, $page, "medal.php?action=log");
$query = $db->query("SELECT me.*, m.image FROM {$tablepre}medallog me
LEFT JOIN {$tablepre}medals m USING (medalid)
WHERE me.uid='$discuz_uid' AND me.type IN ('0', '1') ORDER BY me.dateline DESC LIMIT $start_limit,$tpp");
while($medallog = $db->fetch_array($query)) {
$medallog['name'] = $_DCACHE['medals'][$medallog['medalid']]['name'];
$medallog['dateline'] = gmdate("$dateformat $timeformat", $medallog['dateline'] + $timeoffset * 3600);
$medallog['expiration'] = !empty($medallog['expiration']) ? gmdate("$dateformat $timeformat", $medallog['expiration'] + $timeoffset * 3600) : '';
$medallogs[] = $medallog;
}
} else {
showmessage('undefined_action', NULL, 'HALTED');
}
include template('medal');
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/medal.php
|
PHP
|
asf20
| 3,301
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tag.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
define('CURSCRIPT', 'tag');
require_once './include/common.inc.php';
if(isset($action) && $action == 'relatetag') {
dheader('Expires: '.gmdate('D, d M Y H:i:s', $timestamp + 3600).' GMT');
!($rtid = intval($rtid)) && exit;
$extscript = '';
$threadtag = array();
$query = $db->query("SELECT tagname FROM {$tablepre}threadtags WHERE tid='$rtid'");
while($tags = $db->fetch_array($query)) {
$threadtag[] = $tags['tagname'];
}
if($threadtag) {
$requesttag = $threadtag[array_rand($threadtag)];
} else {
@include_once DISCUZ_ROOT.'./forumdata/cache/cache_viewthread.php';
$requesttag = $db->result_first("SELECT tagname FROM {$tablepre}tags LIMIT ".rand(0, $_DCACHE['tags'][2] - 1).", 1", 0);
}
if(empty($requesttag)) {
exit;
}
include_once DISCUZ_ROOT.'./uc_client/client.php';
include_once template('relatetag');
$datalist = uc_tag_get($requesttag, $relatedtag['limit']);
$write = '';
if(is_array($datalist)) {
if(empty($datalist)) {
@include_once DISCUZ_ROOT.'./uc_client/data/cache/apps.php';
if(is_array($_CACHE['apps'])) {
foreach($_CACHE['apps'] as $app) {
if(array_key_exists($app['appid'], $relatedtag['limit'])) {
$datalist[$app['appid']] = array('data' => array(), 'type' => $app['type']);
}
}
}
}
$count = 0;
foreach($datalist as $appid => $data) {
$tagdata = '';
$template = $relatedtag['template'][$appid];
$datakey = $ext = array();
$type = $data['type'];
$data = $data['data'];
$i = 0;
foreach($data as $key => $value) {
if($appid == UC_APPID && $value['url'] == $boardurl.'viewthread.php?tid='.$rtid) {
continue;
}
if($type == 'SUPEV') {
$extmsg = '<img src="'.$value['thumb'].'" />';
} elseif(substr($type, 0, 6) == 'ECSHOP') {
$extmsg = '<img src="'.$value['image'].'" />';
} else {
$extmsg = '';
}
if(!$datakey) {
$tmp = array_keys($value);
foreach($tmp as $k => $v) {
$datakey[$k] = '{'.$v.'}';
}
}
if($extmsg) {
$ext[] = '<span id="app_'.$appid.'_'.$i.'"'.($i ? ' style="display: none"' : '').'>'.$extmsg.'</span>';
$tmp = '<li onmouseover="$(\'app_'.$appid.'_\' + last_app_'.$appid.').style.display = \'none\';last_app_'.$appid.' = \''.$i.'\';$(\'app_'.$appid.'_'.$i.'\').style.display = \'\'">'.$template['template'].'</li>';
} else {
$tmp = '<li>'.$template['template'].'</li>';
}
$tmp = str_replace($datakey, $value, $tmp);
$tagdata .= $tmp;
$i++;
}
$ext = implode('', $ext);
$tagdata = str_replace(array('\"', '\\\''), array('"', '\''), $tagdata);
if($data['type'] == 'SUPEV') {
$imgfield = 'thumb';
} elseif(substr($data['type'], 0, 6) == 'ECSHOP') {
$imgfield = 'image';
} else {
$imgfield = '';
}
$write .= tpl_relatetag($tagdata, $relatedtag['name'][$appid], $ext, $count);
if($ext) {
$extscript .= 'var last_app_'.$appid.' = \'0\';';
}
$count++;
if($count == 3) {
break;
}
}
}
$write = preg_replace("/\r\n|\n|\r/", '\n', tpl_relatetagwrap($write));
echo '$(\'relatedtags\').innerHTML = "'.addcslashes($write, '"').'";'.$extscript;
exit;
}
if(!$tagstatus) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(!empty($name)) {
if(!preg_match('/^([\x7f-\xff_-]|\w|\s)+$/', $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_first("SELECT * FROM {$tablepre}tags WHERE tagname='$name'");
if($tag['closed']) {
showmessage('tag_closed');
}
$count = $db->result_first("SELECT count(*) FROM {$tablepre}threadtags WHERE tagname='$name'");
$query = $db->query("SELECT t.*,tt.tid as tagtid FROM {$tablepre}threadtags tt LEFT JOIN {$tablepre}threads t ON t.tid=tt.tid AND t.displayorder>='0' 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 {
$max = $db->result_first("SELECT total FROM {$tablepre}tags WHERE closed=0 ORDER BY total DESC LIMIT 1");
$viewthreadtags = intval($viewthreadtags);
$count = $db->result_first("SELECT count(*) FROM {$tablepre}tags WHERE closed=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['level'] = ceil($tagrow['total'] * 5 / $max);
$tagrow['tagnameenc'] = rawurlencode($tagrow['tagname']);
$randtaglist[] = $tagrow;
}
shuffle($randtaglist);
include template('tag');
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/tag.php
|
PHP
|
asf20
| 5,965
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: task.php 13890 2008-07-08 02:21:38Z liuqiang $
*/
define('NOROBOT', TRUE);
require_once './include/common.inc.php';
if(!$taskon && $adminid != 1) {
showmessage('task_close');
}
$discuz_action = 180;
$id = intval($id);
if(empty($action)) {
$multipage = '';
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$tasklist = $endtaskids = $magics = $magicids = $medals = $medalids = $groups = $groupids = array();
switch($item) {
case 'doing':
$sql = "mt.status='0'";
break;
case 'done':
$sql = "mt.status='1'";
break;
case 'failed':
$sql = "mt.status='-1'";
break;
default:
$item = 'new';
$sql = "(mt.taskid IS NULL OR (ABS(mt.status)='1' AND t.period>0 AND $timestamp-mt.dateline>=t.period*3600))";
break;
}
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}tasks t
LEFT JOIN {$tablepre}mytasks mt ON mt.taskid=t.taskid AND mt.uid='$discuz_uid'
WHERE $sql AND t.available='2'");
if($num) {
$updated = FALSE;
$multipage = multi($num, $tpp, $page, "task.php?item=$item");
$query = $db->query("SELECT t.*, mt.csc, mt.dateline FROM {$tablepre}tasks t
LEFT JOIN {$tablepre}mytasks mt ON mt.taskid=t.taskid AND mt.uid='$discuz_uid'
WHERE $sql AND t.available='2' ORDER BY displayorder, taskid DESC LIMIT $start_limit, $tpp");
while($task = $db->fetch_array($query)) {
if($task['reward'] == 'magic') {
$magicids[] = $task['prize'];
} elseif($task['reward'] == 'medal') {
$medalids[] = $task['prize'];
} elseif($task['reward'] == 'group') {
$groupids[] = $task['prize'];
}
if($task['available'] == '2' && ($task['starttime'] > $timestamp || ($task['endtime'] && $task['endtime'] <= $timestamp))) {
$endtaskids[] = $task['taskid'];
}
$csc = explode("\t", $task['csc']);
$task['csc'] = floatval($csc[0]);
$task['lastupdate'] = intval($csc[1]);
if(!$updated && $item == 'doing' && $task['csc'] < 100 && $timestamp - $task['lastupdate'] > 60) {
$updated = TRUE;
require_once DISCUZ_ROOT.'./include/tasks/'.$task['scriptname'].'.inc.php';
$task['applytime'] = $task['dateline'];
$result = task_csc($task);
if($result === TRUE) {
$task['csc'] = '100';
$db->query("UPDATE {$tablepre}mytasks SET csc='100' WHERE uid='$discuz_uid' AND taskid='$task[taskid]'");
} elseif($result === FALSE) {
$db->query("UPDATE {$tablepre}mytasks SET status='-1' WHERE uid='$discuz_uid' AND taskid='$task[taskid]'", 'UNBUFFERED');
} else {
$task['csc'] = floatval($result['csc']);
$db->query("UPDATE {$tablepre}mytasks SET csc='$task[csc]\t$timestamp' WHERE uid='$discuz_uid' AND taskid='$task[taskid]'", 'UNBUFFERED');
}
}
if(in_array($item, array('done', 'failed')) && $task['period']) {
$task['t'] = tasktimeformat($task['period'] * 3600 - $timestamp + $task['dateline']);
$task['allowapply'] = $timestamp - $task['dateline'] >= $task['period'] * 3600 ? 1 : 0;
}
$task['description'] = cutstr(strip_tags($task['description']), 120);
$task['icon'] = $task['icon'] ? $task['icon'] : 'task.gif';
$task['icon'] = strtolower(substr($task['icon'], 0, 7)) == 'http://' ? $task['icon'] : "images/tasks/$task[icon]";
$task['dateline'] = $task['dateline'] ? dgmdate("$dateformat $timeformat", $task['dateline'] + $timeoffset * 3600) : '';
$tasklist[] = $task;
}
}
if($magicids) {
$query = $db->query("SELECT magicid, name FROM {$tablepre}magics WHERE magicid IN (".implodeids($magicids).")");
while($magic = $db->fetch_array($query)) {
$magics[$magic['magicid']] = $magic['name'];
}
}
if($medalids) {
$query = $db->query("SELECT medalid, name FROM {$tablepre}medals WHERE medalid IN (".implodeids($medalids).")");
while($medal = $db->fetch_array($query)) {
$medals[$medal['medalid']] = $medal['name'];
}
}
if($groupids) {
$query = $db->query("SELECT groupid, grouptitle FROM {$tablepre}usergroups WHERE groupid IN (".implodeids($groupids).")");
while($group = $db->fetch_array($query)) {
$groups[$group['groupid']] = $group['grouptitle'];
}
}
if($item == 'doing' && ($doingtask xor $num)) {
if($num) {
$db->query("UPDATE {$tablepre}members SET prompt=prompt|2 WHERE uid='$discuz_uid'", 'UNBUFFERED');
} else {
$db->query("UPDATE {$tablepre}members SET prompt=prompt^2 WHERE uid='$discuz_uid' AND prompt=prompt|2", 'UNBUFFERED');
}
}
if($endtaskids) {
$db->query("UPDATE {$tablepre}tasks SET available='1' WHERE taskid IN (".implodeids($endtaskids).")", 'UNBUFFERED');
}
} elseif($action == 'view' && $id) {
if(!$task = $db->fetch_first("SELECT t.*, mt.status, mt.csc, mt.dateline, mt.dateline AS applytime FROM {$tablepre}tasks t LEFT JOIN {$tablepre}mytasks mt ON mt.uid='$discuz_uid' AND mt.taskid=t.taskid WHERE t.taskid='$id' AND t.available='2'")) {
showmessage('undefined_action');
}
if($task['reward'] == 'magic') {
$magicname = $db->result_first("SELECT name FROM {$tablepre}magics WHERE magicid='$task[prize]'");
} elseif($task['reward'] == 'medal') {
$medalname = $db->result_first("SELECT name FROM {$tablepre}medals WHERE medalid='$task[prize]'");
} elseif($task['reward'] == 'group') {
$grouptitle = $db->result_first("SELECT grouptitle FROM {$tablepre}usergroups WHERE groupid='$task[prize]'");
}
$task['icon'] = $task['icon'] ? $task['icon'] : 'task.gif';
$task['icon'] = strtolower(substr($task['icon'], 0, 7)) == 'http://' ? $task['icon'] : "images/tasks/$task[icon]";
$task['endtime'] = $task['endtime'] ? dgmdate("$dateformat $timeformat", $task['endtime'] + $timeoffset * 3600) : '';
$task['description'] = nl2br($task['description']);
$taskvars = array();
$query = $db->query("SELECT sort, name, description, variable, value FROM {$tablepre}taskvars WHERE taskid='$id'");
while($taskvar = $db->fetch_array($query)) {
if(!$taskvar['variable'] || $taskvar['value']) {
if(!$taskvar['variable']) {
$taskvar['value'] = $taskvar['description'];
} elseif($taskvar['variable'] == 'forumid') {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
} elseif($taskvar['variable'] == 'threadid') {
$subject = $db->result_first("SELECT subject FROM {$tablepre}threads WHERE tid='$taskvar[value]'");
$subject = $subject ? $subject : "TID $taskvar[value]";
} elseif($taskvar['variable'] == 'authorid') {
$author = $db->result_first("SELECT username FROM {$tablepre}members WHERE uid='$taskvar[value]'");
$author = $author ? $author : "TID $taskvar[value]";
}
if($taskvar['sort'] == 'apply') {
$taskvars['apply'][] = $taskvar;
} elseif($taskvar['sort'] == 'complete') {
$taskvars['complete'][$taskvar['variable']] = $taskvar;
}
}
}
$grouprequired = $comma = '';
$task['applyperm'] = $task['applyperm'] == 'all' ? '' : $task['applyperm'];
if(!in_array($task['applyperm'], array('', 'member', 'admin'))) {
$query = $db->query("SELECT grouptitle FROM {$tablepre}usergroups WHERE groupid IN (".str_replace("\t", ',', $task['applyperm']).")");
while($group = $db->fetch_array($query)) {
$grouprequired .= $comma.$group[grouptitle];
$comma = ', ';
}
}
if($task['relatedtaskid']) {
$taskrequired = $db->result_first("SELECT name FROM {$tablepre}tasks WHERE taskid='$task[relatedtaskid]'");
}
if($task['status'] == '-1') {
if($task['period']) {
$allowapply = $timestamp - $task['dateline'] >= $task['period'] * 3600 ? 3 : -7;
$task['t'] = tasktimeformat($task['period'] * 3600 - $timestamp + $task['dateline']);
} else {
$allowapply = -4;
}
} elseif($task['status'] == '0') {
$allowapply = -1;
$csc = explode("\t", $task['csc']);
$task['csc'] = floatval($csc[0]);
$task['lastupdate'] = intval($csc[1]);
if($task['csc'] < 100 && $timestamp - $task['lastupdate'] > 60) {
require_once DISCUZ_ROOT.'./include/tasks/'.$task['scriptname'].'.inc.php';
$result = task_csc($task);
if($result === TRUE) {
$task['csc'] = '100';
$db->query("UPDATE {$tablepre}mytasks SET csc='100' WHERE uid='$discuz_uid' AND taskid='$id'");
} elseif($result === FALSE) {
$db->query("UPDATE {$tablepre}mytasks SET status='-1' WHERE uid='$discuz_uid' AND taskid='$id'", 'UNBUFFERED');
dheader("Location: task.php?action=view&id=$id");
} else {
$task['csc'] = floatval($result['csc']);
$db->query("UPDATE {$tablepre}mytasks SET csc='$task[csc]\t$timestamp' WHERE uid='$discuz_uid' AND taskid='$id'", 'UNBUFFERED');
}
}
} elseif($task['status'] == '1') {
if($task['period']) {
$allowapply = $timestamp - $task['dateline'] >= $task['period'] * 3600 ? 2 : -6;
$task['t'] = tasktimeformat($task['period'] * 3600 - $timestamp + $task['dateline']);
} else {
$allowapply = -5;
}
} else {
$allowapply = 1;
}
if($allowapply > 0) {
if($task['applyperm'] && $task['applyperm'] != 'all' && !(($task['applyperm'] == 'member' && $adminid == '0') || ($task['applyperm'] == 'admin' && $adminid > '0') || forumperm($task['applyperm']))) {
$allowapply = -2;
} elseif($task['tasklimits'] && $task['achievers'] >= $task['tasklimits']) {
$allowapply = -3;
}
}
$task['dateline'] = dgmdate("$dateformat $timeformat", $task['dateline'] + $timeoffset * 3600);
} elseif($action == 'apply' && $id) {
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'NOPERM');
}
if(!$task = $db->fetch_first("SELECT * FROM {$tablepre}tasks WHERE taskid='$id' AND available='2'")) {
showmessage('task_nonexistence', NULL, 'HALTED');
} elseif(($task['starttime'] && $task['starttime'] > $timestamp) || ($task['endtime'] && $task['endtime'] <= $timestamp)) {
showmessage('task_offline', NULL, 'HALTED');
} elseif($task['tasklimits'] && $task['achievers'] >= $task['tasklimits']) {
showmessage('task_full', NULL, 'HALTED');
}
if($task['relatedtaskid'] && !$db->result_first("SELECT COUNT(*) FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND taskid='$task[relatedtaskid]' AND status='1'")) {
showmessage('task_relatedtask', 'task.php?action=view&id='.$task['relatedtaskid']);
} elseif($task['applyperm'] && $task['applyperm'] != 'all' && !(($task['applyperm'] == 'member' && $adminid == '0') || ($task['applyperm'] == 'admin' && $adminid > '0') || forumperm($task['applyperm']))) {
showmessage('task_grouplimit', 'task.php?item=new');
} else {
if(!$task['period'] && $db->result_first("SELECT COUNT(*) FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND taskid='$id'")) {
showmessage('task_duplicate', 'task.php?item=new');
} elseif($task['period'] && $db->result_first("SELECT COUNT(*) FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND taskid='$id' AND dateline>=$timestamp-$task[period]*3600")) {
showmessage('task_nextperiod', 'task.php?item=new');
}
}
require_once DISCUZ_ROOT.'./include/task.func.php';
task_apply($task);
showmessage('task_applied', "task.php?action=view&id=$id");
} elseif($action == 'draw' && $id) {
if(!$discuz_uid) {
showmessage('not_loggedin', NULL, 'NOPERM');
}
if(!$task = $db->fetch_first("SELECT t.*, mt.dateline AS applytime, mt.status FROM {$tablepre}tasks t, {$tablepre}mytasks mt WHERE mt.uid='$discuz_uid' AND mt.taskid=t.taskid AND t.taskid='$id' AND t.available='2'")) {
showmessage('task_nonexistence', NULL, 'HALTED');
} elseif($task['status'] != 0) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif($task['tasklimits'] && $task['achievers'] >= $task['tasklimits']) {
showmessage('task_up_to_limit', 'task.php');
}
require_once DISCUZ_ROOT.'./include/tasks/'.$task['scriptname'].'.inc.php';
$result = task_csc($task);
if($result === TRUE) {
if($task['reward']) {
require_once DISCUZ_ROOT.'./include/task.func.php';
$rewards = task_reward($task);
if($task['reward'] == 'magic') {
$magicname = $db->result_first("SELECT name FROM {$tablepre}magics WHERE magicid='$task[prize]'");
} elseif($task['reward'] == 'medal') {
$medalname = $db->result_first("SELECT name FROM {$tablepre}medals WHERE medalid='$task[prize]'");
} elseif($task['reward'] == 'group') {
$grouptitle = $db->result_first("SELECT grouptitle FROM {$tablepre}usergroups WHERE groupid='$task[prize]'");
}
sendpm($discuz_uid, 'task_reward_subject', 'task_reward_'.$task['reward'].'_message', 0);
}
task_sufprocess();
$db->query("UPDATE {$tablepre}mytasks SET status='1', csc='100', dateline='$timestamp' WHERE uid='$discuz_uid' AND taskid='$id'");
$db->query("UPDATE {$tablepre}tasks SET achievers=achievers+1 WHERE taskid='$id'", 'UNBUFFERED');
if(!$db->result_first("SELECT COUNT(*) FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND status='0'")) {
$db->query("UPDATE {$tablepre}members SET prompt=prompt^2 WHERE uid='$discuz_uid' AND prompt=prompt|2", 'UNBUFFERED');
}
if($inajax) {
taskmessage('100', $task['reward'] ? 'task_reward_'.$task['reward'] : 'task_completed');
} else {
showmessage('task_completed', 'task.php?item=done');
}
} elseif($result === FALSE) {
$db->query("UPDATE {$tablepre}mytasks SET status='-1' WHERE uid='$discuz_uid' AND taskid='$id'", 'UNBUFFERED');
$inajax ? taskmessage('-1', 'task_failed') : showmessage('task_failed', 'task.php?item=failed');
} else {
$result['t'] = tasktimeformat($result['remaintime']);
if($result['csc']) {
$db->query("UPDATE {$tablepre}mytasks SET csc='$result[csc]\t$timestamp' WHERE uid='$discuz_uid' AND taskid='$id'", 'UNBUFFERED');
$msg = $result['t'] ? 'task_doing_rt' : 'task_doing';
$inajax ? taskmessage($result['csc'], $msg) : showmessage($msg, "task.php?action=view&id=$id");
} else {
$msg = $result['t'] ? 'task_waiting_rt' : 'task_waiting';
$inajax ? taskmessage('0', $msg) : showmessage($msg, "task.php?action=view&id=$id");
}
}
} elseif($action == 'giveup' && $id && !empty($formhash)) {
if($formhash != FORMHASH) {
showmessage('undefined_action', NULL, 'HALTED');
} elseif(!$task = $db->fetch_first("SELECT t.taskid, mt.status FROM {$tablepre}tasks t LEFT JOIN {$tablepre}mytasks mt ON mt.taskid=t.taskid AND mt.uid='$discuz_uid' WHERE t.taskid='$id' AND t.available='2'")) {
showmessage('task_nonexistence', NULL, 'HALTED');
} elseif($task['status'] != '0') {
showmessage('undefined_action');
}
$db->query("DELETE FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND taskid='$id'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}tasks SET applicants=applicants-1 WHERE taskid='$id'", 'UNBUFFERED');
if(!$db->result_first("SELECT COUNT(*) FROM {$tablepre}mytasks WHERE uid='$discuz_uid' AND status='0'")) {
$db->query("UPDATE {$tablepre}members SET prompt=prompt^2 WHERE uid='$discuz_uid' AND prompt=prompt|2", 'UNBUFFERED');
}
showmessage('task_giveup', "task.php?item=view&id=$id");
} elseif($action == 'parter' && $id) {
$query = $db->query("SELECT * FROM {$tablepre}mytasks WHERE taskid='$id' ORDER BY dateline DESC LIMIT 0, 8");
while($parter = $db->fetch_array($query)) {
$parter['avatar'] = discuz_uc_avatar($parter['uid'], 'small');
$csc = explode("\t", $parter['csc']);
$parter['csc'] = floatval($csc[0]);
$parterlist[] = $parter;
}
include template('task_parter');
dexit();
} else {
showmessage('undefined_action', NULL, 'HALTED');
}
include template('task');
function taskmessage($csc, $msg) {
extract($GLOBALS, EXTR_SKIP);
include_once language('messages');
include template('header_ajax');
eval("\$msg = \"$language[$msg]\";");
echo "$csc|$msg";
include template('footer_ajax');
exit;
}
function tasktimeformat($t) {
global $dlang;
if($t) {
$h = floor($t / 3600);
$m = floor(($t - $h * 3600) / 60);
$s = floor($t - $h * 3600 - $m * 60);
return ($h ? "$h{$dlang[date][4]}" : '').($m ? "$m{$dlang[date][6]}" : '').($h || !$s ? '' : "$s{$dlang[date][7]}");
}
return '';
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/task.php
|
PHP
|
asf20
| 16,189
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: search_trade.inc.php 17492 2008-12-31 01:39:40Z monkey $
*/
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(!empty($searchid)) {
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$index = $db->fetch_first("SELECT searchstring, keywords, threads, tids FROM {$tablepre}searchindex WHERE searchid='$searchid'");
if(!$index) {
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'] = dgmdate("$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 {
!($exempt & 2) && 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) {
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}searchindex WHERE dateline>'$timestamp'-60") >= $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();
!($exempt & 2) && updatecredits($discuz_uid, $creditspolicy['search'], -1);
}
showmessage('search_redirect', "search.php?searchid=$searchid&srchtype=trade&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/search_trade.inc.php
|
PHP
|
asf20
| 7,828
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: advertisements.inc.php 16688 2008-11-14 06:41:07Z 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)) {
$thisgid = $forum['type'] == 'forum' ? $forum['fup'] : $_DCACHE['forums'][$forum['fup']]['fup'];
foreach($advs AS $type => $advitem) {
if($advitem = array_unique(array_merge((!empty($advitem['forum_'.$fid]) ? $advitem['forum_'.$fid] : array()), (!empty($advitem['forum_'.$thisgid]) ? $advitem['forum_'.$thisgid] : 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]];
}
if($insenz['hardadstatus'] && $insenz['hash'] && isset($advcodes[1])) {
foreach($advcodes[1] as $k => $v) {
if($v{0} == 'i') {
$advlist[$advtype][0] = $advitems[$v];
break;
}
}
}
} 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]];
if($insenz['hardadstatus'] && $insenz['hash'] && in_array($advtype, array('headerbanner', 'interthread', 'footerbanner1', 'footerbanner2', 'footerbanner3'))) {
foreach($advcodes as $k => $v) {
if($v{0} == 'i') {
$advlist[$advtype] = $advitems[$v];
break;
}
}
}
}
}
}
unset($_DCACHE['advs'], $advs, $advarray);
if(empty($advlist['intercat'])) {
unset($advitems);
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/advertisements.inc.php
|
PHP
|
asf20
| 3,920
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: task.func.php 17385 2008-12-17 05:05:02Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_apply($task = array()) {
global $db, $tablepre, $discuz_uid, $discuz_user, $timestamp;
require_once DISCUZ_ROOT.'./include/tasks/'.$task['scriptname'].'.inc.php';
if(!isset($task['newbie'])) {
task_condition();
}
$db->query("REPLACE INTO {$tablepre}mytasks (uid, username, taskid, csc, dateline)
VALUES ('$discuz_uid', '$discuz_user', '$task[taskid]', '0\t$timestamp', '$timestamp')");
$db->query("UPDATE {$tablepre}tasks SET applicants=applicants+1 WHERE taskid='$task[taskid]'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}members SET prompt=prompt|2 WHERE uid='$discuz_uid'", 'UNBUFFERED');
task_preprocess($task);
}
function task_reward($task = array()) {
switch($task['reward']) {
case 'credit': return task_reward_credit($task['prize'], $task['bonus']); break;
case 'magic': return task_reward_magic($task['prize'], $task['bonus']); break;
case 'medal': return task_reward_medal($task['prize'], $task['bonus']); break;
case 'invite': return task_reward_invite($task['bonus'], $task['prize']); break;
case 'group': return task_reward_group($task['prize'], $task['bonus']); break;
}
}
function task_reward_credit($extcreditid, $credits) {
global $db, $tablepre, $discuz_uid, $timestamp;
$creditsarray[$extcreditid] = $credits;
updatecredits($discuz_uid, $creditsarray);
$db->query("INSERT INTO {$tablepre}creditslog (uid, fromto, sendcredits, receivecredits, send, receive, dateline, operation) VALUES ('$discuz_uid', 'TASK REWARD', '$extcreditid', '$extcreditid', '0', '$credits', '$timestamp', 'RCV')");
}
function task_reward_magic($magicid, $num) {
global $db, $tablepre, $discuz_uid;
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}membermagics WHERE magicid='$magicid' AND uid='$discuz_uid'")) {
$db->query("UPDATE {$tablepre}membermagics SET num=num+'$num' WHERE magicid='$magicid' AND uid='$discuz_uid'", 'UNBUFFERED');
} else {
$db->query("INSERT INTO {$tablepre}membermagics (uid, magicid, num) VALUES ('$discuz_uid', '$magicid', '$num')");
}
}
function task_reward_medal($medalid, $day) {
global $db, $tablepre, $discuz_uid, $timestamp;
$medals = $db->result_first("SELECT medals FROM {$tablepre}memberfields WHERE uid='$discuz_uid'");
$medalsnew = $medals ? $medals."\t".$medalid : $medalid;
$db->query("UPDATE {$tablepre}memberfields SET medals='$medalsnew' WHERE uid='$discuz_uid'", 'UNBUFFERED');
$db->query("INSERT INTO {$tablepre}medallog (uid, medalid, type, dateline, expiration, status) VALUES ('$discuz_uid', '$medalid', '0', '$timestamp', '".($day ? $timestamp + $day * 86400 : '')."', '1')");
}
function task_reward_invite($day, $num) {
global $db, $tablepre, $discuz_uid, $timestamp, $onlineip;
$expiration = $timestamp + $day * 86400;
$invitecodes = $comma = '';
for($i = 1; $i <= $num; $i++) {
$invitecode = substr(md5($discuz_uid.$timestamp.random(6)), 0, 10).random(6);
$db->query("INSERT INTO {$tablepre}invites (uid, dateline, expiration, inviteip, invitecode) VALUES ('$discuz_uid', '$timestamp', '$expiration', '$onlineip', '$invitecode')", 'UNBUFFERED');
$invitecodes .= $comma.'[b]'.$invitecode.'[/b]';
$comma = "\n\t";
}
return $invitecodes;
}
function task_reward_group($gid, $day = 0) {
global $db, $tablepre, $discuz_uid, $timestamp;
$exists = FALSE;
if($extgroupids) {
$extgroupids = explode("\t", $extgroupids);
if(in_array($gid, $extgroupids)) {
$exists = TRUE;
} else {
$extgroupids[] = $gid;
}
$extgroupids = implode("\t", $extgroupids);
} else {
$extgroupids = $gid;
}
$db->query("UPDATE {$tablepre}members SET extgroupids='$extgroupids' WHERE uid='$discuz_uid'", 'UNBUFFERED');
if($day) {
$groupterms = $db->result_first("SELECT groupterms FROM {$tablepre}memberfields WHERE uid='$discuz_uid'");
$groupterms = $groupterms ? unserialize($groupterms) : array();
$groupterms['ext'][$gid] = $exists && $groupterms['ext'][$gid] ? max($groupterms['ext'][$gid], $timestamp + $day * 86400) : $timestamp + $day * 86400;
$db->query("UPDATE {$tablepre}memberfields SET groupterms='".addslashes(serialize($groupterms))."' WHERE uid='$discuz_uid'", 'UNBUFFERED');
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/task.func.php
|
PHP
|
asf20
| 4,457
|
<?php
function getswfattach($getcount = 1) {
global $db, $tablepre, $discuz_uid, $dateformat, $timeformat, $timeoffset;
require_once DISCUZ_ROOT.'./include/attachment.func.php';
$swfattachs = array();
if($getcount) {
$swfattachs = $db->result_first("SELECT count(*) FROM {$tablepre}attachments WHERE tid='0' AND pid='0' AND uid='$discuz_uid' ORDER BY dateline");
} else {
$query = $db->query("SELECT aid, filename, description, isimage, thumb, attachment, dateline, filesize, width FROM {$tablepre}attachments WHERE tid='0' AND pid='0' AND uid='$discuz_uid' ORDER BY dateline");
while($swfattach = $db->fetch_array($query)) {
$swfattach['filenametitle'] = $swfattach['filename'];
$swfattach['filename'] = cutstr($swfattach['filename'], 30);
$swfattach['attachsize'] = sizecount($swfattach['filesize']);
$swfattach['dateline'] = gmdate("$dateformat $timeformat", $swfattach['dateline'] + $timeoffset * 3600);
$swfattach['filetype'] = attachtype(fileext($swfattach['attachment'])."\t".$swfattach['filetype']);
$swfattachs[] = $swfattach;
}
}
return $swfattachs;
}
function updateswfattach() {
global $db, $tablepre, $attachsave, $attachdir, $discuz_uid, $postattachcredits, $tid, $pid, $swfattachnew, $swfattachdel, $allowsetattachperm, $maxprice, $updateswfattach, $watermarkstatus;
$imageexists = 0;
$swfattachnew = (array)$swfattachnew;
$query = $db->query("SELECT * FROM {$tablepre}attachments WHERE tid='0' AND pid='0' AND uid='$discuz_uid'");
if($db->num_rows($query) && $updateswfattach) {
$swfattachcount = 0;
$delaids = array();
while($swfattach = $db->fetch_array($query)) {
if(in_array($swfattach['aid'], $swfattachdel)) {
dunlink($swfattach['attachment'], $swfattach['thumb']);
$delaids[] = $swfattach['aid'];
continue;
}
$extension = strtolower(fileext($swfattach['filename']));
$attach_basename = basename($swfattach['attachment']);
$attach_src = $attachdir.'/'.$swfattach['attachment'];
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_descdir = $attachdir.'/'.$attach_subdir;
$swfattachnew[$swfattach['aid']]['attachment'] = $attach_subdir.'/'.$attach_basename;
} else {
$attach_descdir = $attachdir;
$swfattachnew[$swfattach['aid']]['attachment'] = $attach_basename;
}
$swfattachnew[$swfattach['aid']]['thumb'] = $swfattach['thumb'];
$attach_desc = $attach_descdir.'/'.$attach_basename;
if($swfattach['isimage'] && $watermarkstatus) {
require_once DISCUZ_ROOT.'./include/image.class.php';
$image = new Image($attach_src, $swfattach);
if($image->imagecreatefromfunc && $image->imagefunc) {
$image->Watermark();
$swfattach = $image->attach;
}
}
if(!is_dir($attach_descdir)) {
@mkdir($attach_descdir, 0777);
@fclose(fopen($attach_descdir.'/index.htm', 'w'));
}
if($swfattach['thumb'] == 1) {
if(!@rename($attach_src.'.thumb.jpg', $attach_desc.'.thumb.jpg') && @copy($attach_src.'.thumb.jpg', $attach_desc.'.thumb.jpg')) {
@unlink($attach_src.'.thumb.jpg');
}
}
if(!@rename($attach_src, $attach_desc) && @copy($attach_src, $attach_desc)) {
@unlink($attach_src);
}
if($swfattach['isimage']) {
$imageexists = 1;
}
$attachnew = $swfattachnew[$swfattach['aid']];
$attachnew['remote'] = ftpupload($attach_desc, $attachnew);
$attachnew['perm'] = $allowsetattachperm ? $attachnew['perm'] : 0;
$attachnew['description'] = cutstr(dhtmlspecialchars($attachnew['description']), 100);
$attachnew['price'] = $maxprice ? (intval($attachnew['price']) <= $maxprice ? intval($attachnew['price']) : $maxprice) : 0;
$db->query("UPDATE {$tablepre}attachments SET tid='$tid', pid='$pid', attachment='$attachnew[attachment]', description='$attachnew[description]', readperm='$attachnew[readperm]', price='$attachnew[price]', remote='$attachnew[remote]' WHERE aid='$swfattach[aid]'");
$swfattachcount++;
}
if($delaids) {
$db->query("DELETE FROM {$tablepre}attachments WHERE aid IN (".implodeids($delaids).")", 'UNBUFFERED');
}
$attachment = $imageexists ? 2 : 1;
if($swfattachcount) {
$db->query("UPDATE {$tablepre}threads SET attachment='$attachment' WHERE tid='$tid'", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}posts SET attachment='$attachment' WHERE pid='$pid'", 'UNBUFFERED');
updatecredits($discuz_uid, $postattachcredits, $swfattachcount);
}
}
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/swfupload.func.php
|
PHP
|
asf20
| 4,732
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: template.func.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function parse_template($tplfile, $templateid, $tpldir) {
global $language, $subtemplates, $timestamp;
$nest = 6;
$file = basename($tplfile, '.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]*)";
$subtemplates = array();
for($i = 1; $i<=3; $i++) {
if(strexists($template, '{subtemplate')) {
$template = preg_replace("/[\n\r\t]*\{subtemplate\s+([a-z0-9_]+)\}[\n\r\t]*/ies", "loadsubtemplate('\\1')", $template);
}
}
$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);
$headeradd = '';
if(!empty($subtemplates)) {
$headeradd .= "\n0\n";
foreach ($subtemplates as $fname) {
$headeradd .= "|| checktplrefresh('$tplfile', '$fname', $timestamp, '$templateid', '$tpldir')\n";
}
$headeradd .=";";
}
$template = "<? if(!defined('IN_DISCUZ')) exit('Access Denied'); {$headeradd}?>\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', '\\2')", $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 loadsubtemplate($file, $templateid = 0, $tpldir = '') {
global $subtemplates;
$tpldir = $tpldir ? $tpldir : TPLDIR;
$templateid = $templateid ? $templateid : TEMPLATEID;
$tplfile = DISCUZ_ROOT.'./'.$tpldir.'/'.$file.'.htm';
if($templateid != 1 && !file_exists($tplfile)) {
$tplfile = DISCUZ_ROOT.'./templates/default/'.$file.'.htm';
}
$content = @implode('', file($tplfile));
$subtemplates[] = $tplfile;
return $content;
}
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=faq&id='.$_DCACHE['faqs'][$var]['fpid'].'&messageid='.$_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, $extra) {
$extra = str_replace('\\"', '"', $extra);
$s = str_replace('&', '&', $s);
return "<script src=\"$s\" type=\"text/javascript\"$extra></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/51shangcheng.cn/htdocs/include/template.func.php
|
PHP
|
asf20
| 6,631
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.func.php 16688 2008-11-14 06:41:07Z 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=\"float:left; 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=\"float:left; 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'] = dgmdate("$dateformat $timeformat", $lastpost['dateline'] + $timeoffset * 3600);
$lastpost['authorusername'] = $lastpost['author'];
if($lastpost['author']) {
$lastpost['author'] = '<a href="space.php?username='.rawurlencode($lastpost['author']).'">'.$lastpost['author'].'</a>';
}
$forum['lastpost'] = $lastpost;
} else {
$forum['lastpost'] = $lastpost['authorusername'] = '';
}
$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, $selectedfid = 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'].'"'.($selectedfid && $selectedfid == $forum['fid'] ? ' selected' : '').'>'.$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'].'"'.($selectedfid && $selectedfid == $forum['fid'] ? ' selected' : '').'> '.$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, $sid;
$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 .= '<li><a href="forumdisplay.php?fid='.$fid.'&sid='.$sid.'">'.$_DCACHE['forums'][$fid]['name'].'</a></li>';
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;
}
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.' />';
}
}
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/forum.func.php
|
PHP
|
asf20
| 10,217
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_debate.inc.php 17198 2008-12-09 09:27:24Z zhaoxiongfei $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$debate = $thread;
$debate = $sdb->fetch_first("SELECT * FROM {$tablepre}debates WHERE tid='$tid'");
$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'] = dgmdate("$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);
if($debate['affirmvotes'] || $debate['negavotes']) {
if($debate['affirmvotes'] && $debate['affirmvotes'] > $debate['negavotes']) {
$debate['affirmvoteswidth'] = 100;
$debate['negavoteswidth'] = intval($debate['negavotes'] / $debate['affirmvotes'] * 100);
} elseif($debate['negavotes'] && $debate['negavotes'] > $debate['affirmvotes']) {
$debate['negavoteswidth'] = 100;
$debate['affirmvoteswidth'] = intval($debate['affirmvotes'] / $debate['negavotes'] * 100);
} else {
$debate['affirmvoteswidth'] = $debate['negavoteswidth'] = 100;
}
} else {
$debate['negavoteswidth'] = $debate['affirmvoteswidth'] = 0;
}
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']);
$query = $sdb->query("SELECT authorid FROM {$tablepre}posts p LEFT JOIN {$tablepre}debateposts dp ON p.pid=dp.pid WHERE p.tid='$tid' AND p.invisible='0' AND dp.stand='1' ORDER BY p.dateline DESC LIMIT 5");
while($affirmavatar = $sdb->fetch_array($query)) {
$debate['affirmavatars'] .= '<a target="_blank" href="space.php?uid='.$affirmavatar['authorid'].'">'.discuz_uc_avatar($affirmavatar['authorid'], 'small').'</a>';
}
$query = $sdb->query("SELECT authorid FROM {$tablepre}posts p LEFT JOIN {$tablepre}debateposts dp ON p.pid=dp.pid WHERE p.tid='$tid' AND p.invisible='0' AND dp.stand='2' ORDER BY p.dateline DESC LIMIT 5");
while($negaavatar = $sdb->fetch_array($query)) {
$debate['negaavatars'] .= '<a target="_blank" href="space.php?uid='.$negaavatar['authorid'].'">'.discuz_uc_avatar($negaavatar['authorid'], 'small').'</a>';
}
if($fastpost && $allowpostreply && $thread['closed'] == 0) {
$firststand = $sdb->result_first("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$discuz_uid' AND stand<>'0' ORDER BY dateline LIMIT 1");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/viewthread_debate.inc.php
|
PHP
|
asf20
| 3,082
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_reward.inc.php 16854 2008-11-24 14:15:05Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$bapid = 0;
$rewardprice = abs($thread['price']);
$bestpost = array();
if($thread['price'] < 0 && $page == 1) {
foreach($postlist as $key => $post) {
if(!$post['first']) {
$bapid = $key;
break;
}
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/viewthread_reward.inc.php
|
PHP
|
asf20
| 475
|
function validate() {
return checkusername($('form1').username.value)
&& checkpassword($('form1').password.value, $('form1').password2.value)
&& checkname($('form1').name.value)
&& checkidcard($('form1').idcard.value)
&& checkemail($('form1').email1.value, 'email1')
&& ($('form1').email2.value ? checkemail($('form1').email2.value, 'email2') : true)
&& checkqq($('form1').qq.value)
&& checktel($('form1').tel1.value, $('form1').tel2.value, $('form1').tel3.value, '电话号码')
&& ($('form1').fax2.value ? checktel($('form1').fax1.value, $('form1').fax2.value, $('form1').fax3.value, '传真号码') : true)
&& ($('form1').msn.value ? checkemail($('form1').msn.value, 'msn') : true)
&& checkmobile($('form1').mobile.value)
&& checkcpc($('form1').country.value, $('form1').province.value, $('form1').city.value)
&& checkaddress($('form1').address.value)
&& checkpostcode($('form1').postcode.value)
&& checkemail($('form1').alipay.value, 'alipay');
}
function checkusername(username) {
username = trim(username);
if(mb_strlen(username) < 4 || mb_strlen(username) > 20) {
return dalert('用户名长度不少于 4 字节不超过 20 字节!请重新填写', $('form1').username);
} else if(!preg_match(/^\w+$/i, username)) {
return dalert('用户名不合法!请重新填写', $('form1').username);
}
return true;
}
function checkpassword(password, password2) {
if(mb_strlen(password) < 6 || mb_strlen(password) > 20) {
return dalert('密码长度范围 6~20!请重新填写', $('form1').password);
} else if(!preg_match(/^\w+$/i, password)) {
return dalert('密码不能包含特殊字符!请重新填写', $('form1').password);
} else if(password != password2) {
return dalert('两次输入的密码不一致!请重新填写', $('form1').password2);
}
return true;
}
function checkname(name) {
name = trim(name);
if(mb_strlen(name) < 4 || mb_strlen(name) > 30) {
return dalert('姓名长度不少于 4 字节不超过 30 字节!请重新填写', $('form1').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' ? $('form1').email1 : (en == 'email2' ? $('form1').email2 : (en == 'msn' ? $('form1').msn : $('form1').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('身份证号码不合法!请重新填写', $('form1').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 + ' 不合法!请重新填写', $('form1').tel1);
}
return true;
}
function checkqq(qq) {
if(!(preg_match(/^([0-9]+)$/, qq) && mb_strlen(qq) >= 5 && mb_strlen(qq) <= 12)) {
return dalert('QQ 号码不合法!请重新填写', $('form1').qq);
}
return true;
}
function checkmobile(mobile) {
if(!preg_match(/^1(3|5)\d{9}$/, mobile)) {
return dalert('手机号码不合法!请重新填写', $('form1').mobile);
}
return true;
}
function checkcpc(country, province, city) {
country = parseInt(country);
if(country < 10000 || country > 70300) {
return dalert('请选择国家!', $('form1').country);
}
province = parseInt(province);
if(country == 10000 && (province < 10100 || province > 13100)) {
return dalert('请选择省份!', $('form1').province);
}
city = parseInt(city);
if(country == 10000 && (city < 10101 || city > 13107)) {
return dalert('请选择城市!', $('form1').city);
}
return true;
}
function checkaddress(address) {
address = trim(address);
if(mb_strlen(address) < 8) {
return dalert('请填写您的真实地址!', $('form1').address);
}
return true;
}
function checkpostcode(postcode) {
if(!preg_match(/^\d{6}$/, postcode)) {
return dalert('邮政编码不合法!请重新填写', $('form1').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/51shangcheng.cn/htdocs/include/js/insenz_reg.js
|
JavaScript
|
asf20
| 4,541
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: slide.js 16929 2008-11-28 00:59:14Z monkey $
*/
/*
var slideSpeed = 2500;
var slideImgsize = [140,140];
var slideTextBar = 0;
var slideBorderColor = '#C8DCEC';
var slideBgColor = '#FFF';
var slideImgs = new Array();
var slideImgLinks = new Array();
var slideImgTexts = new Array();
var slideSwitchBar = 1;
var slideSwitchColor = 'black';
var slideSwitchbgColor = 'white';
var slideSwitchHiColor = '#C8DCEC';
*/
var slide_curImg = 1;
var slide_timerId = -1;
var slide_interval = slideSpeed;
var slide_imgIsLoaded = false;
var slide_preload = new Array();
var slide_imgsize = new Array();
var slide_inited = 0;
var slide_opacity = 0;
var slide_st;
document.write('<style type="text/css">');
document.write('#slidetable { border: 1px solid ' + slideBorderColor + '; background: ' + slideBgColor + '; width: 100%; }');
document.write('#slidearea { height:' + (slideImgsize[1] + 6) + 'px; overflow: hidden; margin: 0 auto; text-align: center; }');
document.write('#slidefooter { ' + (slideSwitchBar != 0 ? '': '') + 'text-align: center; width:' + slideImgsize[0] + 'px; line-height: 22px; height: 21px; overflow: hidden; }');
if(slideSwitchBar != 0) {
document.write('#slideswitchtd { padding: 0; }');
document.write('#slideswitch div { filter: alpha(opacity=90);opacity: 0.9; float: left; width: 17px; height: 12px; font-weight: bold; text-align: center; cursor: pointer; font-size: 9px; padding: 0 0 5px; color: ' + slideSwitchColor + '; border-right: 1px solid ' + slideBorderColor + '; border-top: 1px solid ' + slideBorderColor + '; background-color: ' + slideSwitchbgColor + '; }');
document.write('#slideswitch div.current { background-color: ' + slideSwitchHiColor + '; }');
}
document.write('</style>');
document.write('<table cellspacing="0" cellpadding="2" id="slidetable"><tr><td id="slidearea" valign="middle"><img src="images/common/none.gif" width="' + slideImgsize[0] + '" height="' + slideImgsize[1] + '" />');
if(slideSwitchBar != 0) {
document.write('</td></tr><tr><td id="slideswitchtd"><div id="slideswitch">');
for(i = 1;i < slideImgs.length;i++) {
document.write('<div id="slide_' + i + '" onclick="slide_forward(' + i + ')">' + i + '</div>');
document.getElementById('slide_' + i).title = slideImgTexts[i];
}
document.write('</div>');
}
document.write('</td></tr></table>');
if(slideTextBar != 0) {
document.write('<div id="slidefooter"><p id="slidetext"><a href="' + slideImgLinks[slideImgs.length - 1] + '" target="_blank">' + slideImgTexts[slideImgs.length - 1] + '</a></div>')
}
function slide_init() {
if(slide_inited) {
return;
}
slide_inited = 1;
slide_imgPreload(1, slideImgs.length - 1);
slide_changeSlide();
slide_play();
}
function slide_imgPreload(intPic, intRange) {
for(var i=intPic; i<(intPic+intRange); i++) {
slide_preload[i] = new Image();
slide_preload[i].src = slideImgs[i];
slide_preload[i].i = i;
slide_preload[i].onload = function() {
slide_imgResize(this);
slide_imgsize[this.i] = 'width="' + this.width + '" height="' + this.height + '" ';
}
}
return false;
}
function slide_imgResize(obj) {
zr = obj.width / obj.height;
if(obj.width > slideImgsize[0]) {
obj.width = slideImgsize[0];
obj.height = obj.width / zr;
}
if(obj.height > slideImgsize[1]) {
obj.height = slideImgsize[1];
obj.width = obj.height * zr;
}
}
function slide_imgLoadNotify(obj, n) {
if(!slide_imgsize[n]) {
slide_imgResize(obj);
}
slide_imgIsLoaded = true;
}
function slide_changeSlide(n) {
if(!slide_preload[slide_curImg]) {
return;
}
if(!slide_preload[slide_curImg].complete) {
return;
}
if(slide_opacity <= 100) {
slide_changeopacity(1, n);
return;
}
slide_imgIsLoaded = false;
if(slideImgs.length !=0) {
var slideImage = '<a href="' + slideImgLinks[slide_curImg] + '" target="_blank"><img src="' + slideImgs[slide_curImg] + '" ' + (slide_imgsize[slide_curImg] ? slide_imgsize[slide_curImg] : '') + 'onload="slide_imgLoadNotify(this, ' + slide_curImg + ')" /></a>';
document.getElementById('slidearea').innerHTML = slideImage ;
if(slideTextBar != 0) {
var slideText = '<a href="' + slideImgLinks[slide_curImg] + '" target="_blank">' + slideImgTexts[slide_curImg] + '</a>';
document.getElementById('slidetext').innerHTML = slideText;
}
slide_opacity = 0;
slide_changeopacity(0);
if(slideSwitchBar != 0) {
document.getElementById('slide_' + slide_curImg).className = 'current';
}
}
}
function slide_changeopacity(op, n) {
if(slide_opacity <= 100) {
slide_opacity += 10;
setopacity = op ? 100 - slide_opacity : slide_opacity;
document.getElementById('slidearea').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + setopacity + ')';
document.getElementById('slidearea').style.opacity = setopacity / 100;
slide_st = setTimeout('slide_changeopacity(' + op + ',' + n + ')', op ? 10 : 50);
} else {
if(op) {
slide_changeSlide(n);
} else {
slide_opacity = 0;
}
}
}
function slide_forward(slide_n) {
slide_imgIsLoaded = false;
if(!document.getElementById('slide_' + slide_curImg)) {
return;
}
if(slideSwitchBar != 0) {
document.getElementById('slide_' + slide_curImg).className = '';
}
if(!slide_n) {
slide_curImg++;
if(slide_curImg >= slideImgs.length) {
slide_curImg = 1;
}
} else {
clearInterval(slide_timerId);
clearTimeout(slide_st);
slide_timerId = window.setInterval('slide_forward()', slide_interval);
slide_curImg = slide_n;
}
slide_changeSlide();
}
function slide_play() {
if(slide_timerId == -1) {
slide_timerId = window.setInterval('slide_forward()', slide_interval);
}
}
slide_init();
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/slide.js
|
JavaScript
|
asf20
| 5,867
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common.js 17535 2009-01-20 05:12:20Z monkey $
*/
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);
var is_mac = userAgent.indexOf('mac') != -1;
var ajaxdebug = 0;
var codecount = '-1';
var codehtml = new Array();
//FixPrototypeForGecko
if(is_moz && window.HTMLElement) {
HTMLElement.prototype.__defineSetter__('outerHTML', function(sHTML) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df,this);
return sHTML;
});
HTMLElement.prototype.__defineGetter__('outerHTML', function() {
var attr;
var attrs = this.attributes;
var str = '<' + this.tagName.toLowerCase();
for(var i = 0;i < attrs.length;i++){
attr = attrs[i];
if(attr.specified)
str += ' ' + attr.name + '="' + attr.value + '"';
}
if(!this.canHaveChildren) {
return str + '>';
}
return str + '>' + this.innerHTML + '</' + this.tagName.toLowerCase() + '>';
});
HTMLElement.prototype.__defineGetter__('canHaveChildren', function() {
switch(this.tagName.toLowerCase()) {
case 'area':case 'base':case 'basefont':case 'col':case 'frame':case 'hr':case 'img':case 'br':case 'input':case 'isindex':case 'link':case 'meta':case 'param':
return false;
}
return true;
});
HTMLElement.prototype.click = function(){
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}
Array.prototype.push = function(value) {
this[this.length] = value;
return this.length;
}
function $(id) {
return document.getElementById(id);
}
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
count = 0;
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;
if(e.checked) {
count++;
}
}
}
return count;
}
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)));
}
imggroup = new Array();
function thumbImg(obj, method) {
if(!obj) {
return;
}
obj.onload = null;
file = obj.src;
zw = obj.offsetWidth;
zh = obj.offsetHeight;
if(zw < 2) {
if(!obj.id) {
obj.id = 'img_' + Math.random();
}
setTimeout("thumbImg($('" + obj.id + "'), " + method + ")", 100);
return;
}
zr = zw / zh;
method = !method ? 0 : 1;
if(method) {
fixw = obj.getAttribute('_width');
fixh = obj.getAttribute('_height');
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
}
if(zh > fixh) {
zh = fixh;
zw = zh * zr;
}
} else {
var widthary = imagemaxwidth.split('%');
if(widthary.length > 1) {
fixw = $('wrap').clientWidth - 200;
if(widthary[0]) {
fixw = fixw * widthary[0] / 100;
} else if(widthary[1]) {
fixw = fixw < widthary[1] ? fixw : widthary[1];
}
} else {
fixw = widthary[0];
}
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
obj.style.cursor = 'pointer';
if(!obj.onclick) {
obj.onclick = function() {
zoom(obj, obj.src);
}
}
}
}
obj.width = zw;
obj.height = zh;
}
function imgzoom() {}
function attachimg() {}
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;
}
var clipboardswfdata;
function setcopy(text, alertmsg){
if(is_ie) {
clipboardData.setData('Text', text);
if(alertmsg) {
alert(alertmsg);
}
} else {
floatwin('open_clipboard', -1, 300, 110);
$('floatwin_clipboard_title').innerHTML = '剪贴板';
str = '<div style="text-decoration:underline;">点此复制到剪贴板</div>' +
AC_FL_RunContent('id', 'clipboardswf', 'name', 'clipboardswf', 'devicefont', 'false', 'width', '100', 'height', '20', 'src', 'images/common/clipboard.swf', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true', 'wmode', 'transparent', 'style' , 'margin-top:-20px');
$('floatwin_clipboard_content').innerHTML = str;
clipboardswfdata = text;
}
}
function dconfirm(msg, script, width, height) {
floatwin('open_confirm', -1, !width ? 300 : width, !height ? 110 : height);
$('floatwin_confirm_title').innerHTML = '提示信息';
$('floatwin_confirm_content').innerHTML = msg + '<br /><button onclick="' + script + ';floatwin(\'close_confirm\')"> 是 </button> <button onclick="floatwin(\'close_confirm\')"> 否 </button>';
}
function dnotice(msg, script, width, height) {
script = !script ? '' : script;
floatwin('open_confirm', -1, !width ? 400 : width, !height ? 110 : height);
$('floatwin_confirm_title').innerHTML = '提示信息';
$('floatwin_confirm_content').innerHTML = msg + (script ? '<br /><button onclick="' + script + ';floatwin(\'close_confirm\')">确定</button>' : '');
}
function setcopy_gettext() {
window.document.clipboardswf.SetVariable('str', clipboardswfdata)
}
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 mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : '';
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
expires.setTime(expires.getTime() + seconds * 1000);
domain = !domain ? cookiedomain : domain;
path = !path ? cookiepath : path;
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, complex, lang) {
var obj = $(objname);
if(obj) {
obj.style.display = obj.style.display == '' ? 'none' : '';
var collapsed = getcookie('discuz_collapse');
collapsed = updatestring(collapsed, objname, !obj.style.display);
setcookie('discuz_collapse', collapsed, (collapsed ? 2592000 : -2592000));
}
if(!noimg) {
var img = $(objname + '_img');
if(img.tagName != 'IMG') {
if(img.className.indexOf('_yes') == -1) {
img.className = img.className.replace(/_no/, '_yes');
if(lang) {
img.innerHTML = lang[0];
}
} else {
img.className = img.className.replace(/_yes/, '_no');
if(lang) {
img.innerHTML = lang[1];
}
}
} else {
img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif');
}
img.blur();
}
if(complex) {
var objc = $(objname + '_c');
objc.className = objc.className == 'c_header' ? 'c_header closenode' : 'c_header';
}
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('discuz_collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('discuz_collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function trim(str) {
return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function _attachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(eventobj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
var cssloaded= new Array();
function loadcss(cssname) {
if(!cssloaded[cssname]) {
css = document.createElement('link');
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = 'forumdata/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
var headNode = document.getElementsByTagName("head")[0];
headNode.appendChild(css);
cssloaded[cssname] = 1;
}
}
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]) jsmenu['timer'][ctrlobj.id] = setTimeout('hideMenu(' + layer + ')', timeout);
}
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]);
jsmenu['timer'][this.id] = null;
} else {
for(var id in jsmenu['timer']) {
if(jsmenu['timer'][id]) {
clearTimeout(jsmenu['timer'][id]);
jsmenu['timer'][id] = null;
}
}
}
}
}
}
function initMenu(ctrlid, menuobj, duration, timeout, layer, drag) {
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]);
jsmenu['timer'][ctrlid] = null;
}
}
if(duration != 1) {
menuobj.onmouseout = function() {
jsmenu['timer'][ctrlid] = setTimeout('hideMenu(' + layer + ')', timeout);
}
}
}
menuobj.style.zIndex = 999 + layer;
if(drag) {
menuobj.onmousedown = function(event) {try{menudrag(menuobj, event, 1);}catch(e){}};
menuobj.onmousemove = function(event) {try{menudrag(menuobj, event, 2);}catch(e){}};
menuobj.onmouseup = function(event) {try{menudrag(menuobj, event, 3);}catch(e){}};
}
}
}
var menudragstart = new Array();
function menudrag(menuobj, e, op) {
if(op == 1) {
if(in_array(is_ie ? event.srcElement.tagName : e.target.tagName, ['TEXTAREA', 'INPUT', 'BUTTON', 'SELECT'])) {
return;
}
menudragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
menudragstart[2] = parseInt(menuobj.style.left);
menudragstart[3] = parseInt(menuobj.style.top);
doane(e);
} else if(op == 2 && menudragstart[0]) {
var menudragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
menuobj.style.left = (menudragstart[2] + menudragnow[0] - menudragstart[0]) + 'px';
menuobj.style.top = (menudragstart[3] + menudragnow[1] - menudragstart[1]) + 'px';
doane(e);
} else if(op == 3) {
menudragstart = [];
doane(e);
}
}
function showMenu(ctrlid, click, offset, duration, timeout, layer, showid, maxh, drag) {
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 = 250;
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;
if(isUndefined(drag)) drag = false;
if(click && jsmenu['active'][layer] == menuobj) {
hideMenu(layer);
return;
} else {
hideMenu(layer);
}
var len = jsmenu['timer'].length;
if(len > 0) {
for(var i=0; i<len; i++) {
if(jsmenu['timer'][i]) clearTimeout(jsmenu['timer'][i]);
}
}
initCtrl(ctrlobj, click, duration, timeout, layer);
ctrlobjclassName = ctrlobj.className;
ctrlobj.className += ' hover';
initMenu(ctrlid, menuobj, duration, timeout, layer, drag);
menuobj.style.display = '';
if(!is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
setMenuPosition(showid, offset);
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'];
if($(InFloat) != null) {
var InFloate = InFloat.split('_');
if(!floatwinhandle[InFloate[1] + '_1']) {
floatwinnojspos = fetchOffset($('floatwinnojs'));
floatwinhandle[InFloate[1] + '_1'] = floatwinnojspos['left'];
floatwinhandle[InFloate[1] + '_2'] = floatwinnojspos['top'];
}
showobj.X = showobj.X - $(InFloat).scrollLeft - parseInt(floatwinhandle[InFloate[1] + '_1']);
showobj.Y = showobj.Y - $(InFloat).scrollTop - parseInt(floatwinhandle[InFloate[1] + '_2']);
InFloat = '';
}
showobj.w = showobj.offsetWidth;
showobj.h = showobj.offsetHeight;
menuobj.w = menuobj.offsetWidth;
menuobj.h = menuobj.offsetHeight;
if(offset < 3) {
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');
} else if(offset == 3) {
menuobj.style.left = (document.body.clientWidth - menuobj.clientWidth) / 2 + document.body.scrollLeft + 'px';
menuobj.style.top = (document.body.clientHeight - menuobj.clientHeight) / 2 + document.body.scrollTop + '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();
}
}
var Ajaxs = new Array();
var AjaxStacks = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
var attackevasive = isUndefined(attackevasive) ? 0 : attackevasive;
function Ajax(recvType, waitId) {
for(var stackId = 0; stackId < AjaxStacks.length && AjaxStacks[stackId] != 0; stackId++);
AjaxStacks[stackId] = 1;
var aj = new Object();
aj.loading = '加载中...';//public
aj.recvType = recvType ? recvType : 'XML';//public
aj.waitId = waitId ? $(waitId) : null;//public
aj.resultHandle = null;//private
aj.sendString = '';//private
aj.targetUrl = '';//private
aj.stackId = 0;
aj.stackId = stackId;
aj.setLoading = function(loading) {
if(typeof loading !== 'undefined' && loading !== null) aj.loading = loading;
}
aj.setRecvType = function(recvtype) {
aj.recvType = recvtype;
}
aj.setWaitId = function(waitid) {
aj.waitId = typeof waitid == 'object' ? waitid : $(waitid);
}
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) {}
}
}
return request;
}
aj.XMLHttpRequest = aj.createXMLHttpRequest();
aj.showLoading = function() {
if(aj.waitId && (aj.XMLHttpRequest.readyState != 4 || aj.XMLHttpRequest.status != 200)) {
aj.waitId.style.display = '';
aj.waitId.innerHTML = '<span><img src="' + IMGDIR + '/loading.gif"> ' + aj.loading + '</span>';
}
}
aj.processHandle = function() {
if(aj.XMLHttpRequest.readyState == 4 && aj.XMLHttpRequest.status == 200) {
for(k in Ajaxs) {
if(Ajaxs[k] == aj.targetUrl) {
Ajaxs[k] = null;
}
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
}
if(aj.recvType == 'HTML') {
aj.resultHandle(aj.XMLHttpRequest.responseText, aj);
} else if(aj.recvType == 'XML') {
if(aj.XMLHttpRequest.responseXML.lastChild) {
aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue, aj);
} else {
if(ajaxdebug) {
var error = mb_cutstr(aj.XMLHttpRequest.responseText.replace(/\r?\n/g, '\\n').replace(/"/g, '\\\"'), 200);
aj.resultHandle('<root>ajaxerror<script type="text/javascript" reload="1">alert(\'Ajax Error: \\n' + error + '\');</script></root>', aj);
}
}
}
AjaxStacks[aj.stackId] = 0;
}
}
aj.get = function(targetUrl, resultHandle) {
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
var delay = attackevasive & 1 ? (aj.stackId + 1) * 1001 : 100;
if(window.XMLHttpRequest) {
setTimeout(function(){
aj.XMLHttpRequest.open('GET', aj.targetUrl);
aj.XMLHttpRequest.send(null);}, delay);
} else {
setTimeout(function(){
aj.XMLHttpRequest.open("GET", targetUrl, true);
aj.XMLHttpRequest.send();}, delay);
}
}
aj.post = function(targetUrl, sendString, resultHandle) {
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.XMLHttpRequest.open('POST', targetUrl);
aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.XMLHttpRequest.send(aj.sendString);
}
return aj;
}
function newfunction(func){
var args = new Array();
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(event){
doane(event);
window[func].apply(window, args);
return false;
}
}
function display(id) {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
}
function display_opacity(id, n) {
if(!$(id)) {
return;
}
if(n >= 0) {
n -= 10;
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + n + ')';
$(id).style.opacity = n / 100;
setTimeout('display_opacity(\'' + id + '\',' + n + ')', 50);
} else {
$(id).style.display = 'none';
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
$(id).style.opacity = 1;
}
}
var evalscripts = new Array();
function evalscript(s) {
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) {
var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
var arr1 = new Array();
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}
function appendscript(src, text, reload, charset) {
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;
scriptNode.charset = charset ? charset : (is_moz ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
} else if(text){
scriptNode.text = text;
}
$('append_parent').appendChild(scriptNode);
} catch(e) {}
}
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}
function ajaxupdateevents(obj, tagName) {
tagName = tagName ? tagName : 'A';
var objs = obj.getElementsByTagName(tagName);
for(k in objs) {
var o = objs[k];
ajaxupdateevent(o);
}
}
function ajaxupdateevent(o) {
if(typeof o == 'object' && o.getAttribute) {
if(o.getAttribute('ajaxtarget')) {
if(!o.id) o.id = Math.random();
var ajaxevent = o.getAttribute('ajaxevent') ? o.getAttribute('ajaxevent') : 'click';
var ajaxurl = o.getAttribute('ajaxurl') ? o.getAttribute('ajaxurl') : o.href;
_attachEvent(o, ajaxevent, newfunction('ajaxget', ajaxurl, o.getAttribute('ajaxtarget'), o.getAttribute('ajaxwaitid'), o.getAttribute('ajaxloading'), o.getAttribute('ajaxdisplay')));
if(o.getAttribute('ajaxfunc')) {
o.getAttribute('ajaxfunc').match(/(\w+)\((.+?)\)/);
_attachEvent(o, ajaxevent, newfunction(RegExp.$1, RegExp.$2));
}
}
}
}
/*
*@ url: 需求请求的 url
*@ id : 显示的 id
*@ waitid: 等待的 id,默认为显示的 id,如果 waitid 为空字符串,则不显示 loading..., 如果为 null,则在 showid 区域显示
*@ linkid: 是哪个链接触发的该 ajax 请求,该对象的属性(如 ajaxdisplay)保存了一些 ajax 请求过程需要的数据。
*/
function ajaxget(url, showid, waitid, loading, display, recall) {
waitid = typeof waitid == 'undefined' || waitid === null ? showid : waitid;
var x = new Ajax();
x.setLoading(loading);
x.setWaitId(waitid);
x.display = typeof display == 'undefined' || display == null ? '' : display;
x.showId = $(showid);
if(x.showId) x.showId.orgdisplay = typeof x.showId.orgdisplay === 'undefined' ? x.showId.style.display : x.showId.orgdisplay;
if(url.substr(strlen(url) - 1) == '#') {
url = url.substr(0, strlen(url) - 1);
x.autogoto = 1;
}
var url = url + '&inajax=1&ajaxtarget=' + showid;
x.get(url, function(s, x) {
evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
x.showId.style.display = x.showId.orgdisplay;
x.showId.style.display = x.display;
x.showId.orgdisplay = x.showId.style.display;
ajaxinnerhtml(x.showId, s);
ajaxupdateevents(x.showId);
if(x.autogoto) scroll(0, x.showId.offsetTop);
}
}
if(!evaled)evalscript(s);
ajaxerror = null;
if(recall) {eval(recall);}
});
}
var ajaxpostHandle = 0;
function ajaxpost(formid, showid, waitid, showidclass, submitbtn) {
showloading();
var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');
var showidclass = !showidclass ? '' : showidclass;
if(ajaxpostHandle != 0) {
return false;
}
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
if(ajaxframe == null) {
if (is_ie && !is_opera) {
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_parent').appendChild(ajaxframe);
}
$(formid).target = ajaxframeid;
ajaxpostHandle = [showid, ajaxframeid, formid, $(formid).target, showidclass, submitbtn];
if(ajaxframe.attachEvent) {
ajaxframe.detachEvent ('onload', ajaxpost_load);
ajaxframe.attachEvent('onload', ajaxpost_load);
} else {
document.removeEventListener('load', ajaxpost_load, true);
ajaxframe.addEventListener('load', ajaxpost_load, false);
}
$(formid).action += '&inajax=1';
$(formid).submit();
return false;
}
function ajaxpost_load() {
showloading('none');
var s = '';
try {
if(is_ie) {
s = $(ajaxpostHandle[1]).contentWindow.document.XMLDocument.text;
} else {
s = $(ajaxpostHandle[1]).contentWindow.document.documentElement.firstChild.nodeValue;
}
} catch(e) {
if(ajaxdebug) {
var error = mb_cutstr($(ajaxpostHandle[1]).contentWindow.document.body.innerText.replace(/\r?\n/g, '\\n').replace(/"/g, '\\\"'), 200);
s = '<root>ajaxerror<script type="text/javascript" reload="1">alert(\'Ajax Error: \\n' + error + '\');</script></root>';
}
}
evaled = false;
if(s != '' && s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(ajaxpostHandle[4]) {
$(ajaxpostHandle[0]).className = ajaxpostHandle[4];
if(ajaxpostHandle[5]) {
ajaxpostHandle[5].disabled = false;
}
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
ajaxinnerhtml($(ajaxpostHandle[0]), s);
if(!evaled)evalscript(s);
setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);
setTimeout("hideMenu()", 3000);
}
ajaxerror = null;
if($(ajaxpostHandle[2])) {
$(ajaxpostHandle[2]).target = ajaxpostHandle[3];
}
ajaxpostHandle = 0;
}
function ajaxmenu(e, ctrlid, timeout, func, cache, duration, ismenu, divclass, optionclass) {
showloading();
if(jsmenu['active'][0] && jsmenu['active'][0].ctrlkey == ctrlid) {
hideMenu();
doane(e);
return;
} else if(is_ie && is_ie < 7 && document.readyState.toLowerCase() != 'complete') {
return;
}
if(isUndefined(timeout)) timeout = 3000;
if(isUndefined(func)) func = '';
if(isUndefined(cache)) cache = 1;
if(isUndefined(divclass)) divclass = 'popupmenu_popup';
if(isUndefined(optionclass)) optionclass = 'popupmenu_option';
if(isUndefined(ismenu)) ismenu = 1;
if(isUndefined(duration)) duration = timeout > 0 ? 0 : 3;
var div = $(ctrlid + '_menu');
if(cache && div) {
showMenu(ctrlid, e.type == 'click', 0, duration, timeout, 0, ctrlid, 400, 1);
if(func) setTimeout(func + '(' + ctrlid + ')', timeout);
doane(e);
} else {
if(!div) {
div = document.createElement('div');
div.ctrlid = ctrlid;
div.id = ctrlid + '_menu';
div.style.display = 'none';
div.className = divclass;
$('append_parent').appendChild(div);
}
var x = new Ajax();
var href = !isUndefined($(ctrlid).href) ? $(ctrlid).href : $(ctrlid).attributes['href'].value;
x.div = div;
x.etype = e.type;
x.optionclass = optionclass;
x.duration = duration;
x.timeout = timeout;
x.get(href + '&inajax=1&ajaxmenuid='+ctrlid+'_menu', function(s) {
evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
if(!cache && duration != 3 && x.div.id) setTimeout('$("append_parent").removeChild($(\'' + x.div.id + '\'))', timeout);
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.div) x.div.innerHTML = '<div class="' + x.optionclass + '">' + s + '</div>';
showMenu(ctrlid, x.etype == 'click', 0, x.duration, x.timeout, 0, ctrlid, 400, 1);
if(func) setTimeout(func + '("' + ctrlid + '")', x.timeout);
}
if(!evaled) evalscript(s);
ajaxerror = null;
showloading('none');
});
doane(e);
}
}
//得到一个定长的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 showloading(display, waiting) {
var display = display ? display : 'block';
var waiting = waiting ? waiting : '页面加载中...';
$('ajaxwaitid').innerHTML = waiting;
$('ajaxwaitid').style.display = display;
}
function ajaxinnerhtml(showid, s) {
if(showid.tagName != 'TBODY') {
showid.innerHTML = s;
} else {
while(showid.firstChild) {
showid.firstChild.parentNode.removeChild(showid.firstChild);
}
var div1 = document.createElement('DIV');
div1.id = showid.id+'_div';
div1.innerHTML = '<table><tbody id="'+showid.id+'_tbody">'+s+'</tbody></table>';
$('append_parent').appendChild(div1);
var trs = div1.getElementsByTagName('TR');
var l = trs.length;
for(var i=0; i<l; i++) {
showid.appendChild(trs[0]);
}
var inputs = div1.getElementsByTagName('INPUT');
var l = inputs.length;
for(var i=0; i<l; i++) {
showid.appendChild(inputs[0]);
}
div1.parentNode.removeChild(div1);
}
}
function AC_GetArgs(args, classid, mimeType) {
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i = 0; i < args.length; i = i + 2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":break;
case "pluginspage":ret.embedAttrs[args[i]] = 'http://www.macromedia.com/go/getflashplayer';break;
case "src":ret.embedAttrs[args[i]] = args[i+1];ret.params["movie"] = args[i+1];break;
case "codebase":ret.objAttrs[args[i]] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';break;
case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblclick":case "ondrag":case "ondragend":
case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":
case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":
case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":
case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":
case "id":ret.objAttrs[args[i]] = args[i+1];break;
case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":
case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;
default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if(mimeType) {
ret.embedAttrs["type"] = mimeType;
}
return ret;
}
function AC_FL_RunContent() {
var ret = AC_GetArgs(arguments, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
var str = '';
if(is_ie && !is_opera) {
str += '<object ';
for (var i in ret.objAttrs) {
str += i + '="' + ret.objAttrs[i] + '" ';
}
str += '>';
for (var i in ret.params) {
str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
}
str += '</object>';
} else {
str += '<embed ';
for (var i in ret.embedAttrs) {
str += i + '="' + ret.embedAttrs[i] + '" ';
}
str += '></embed>';
}
return str;
}
//PageScroll
function pagescroll_class(obj, pagewidth, pageheight) {
this.ctrlobj = $(obj);
this.speed = 2;
this.pagewidth = pagewidth;
this.times = 1;
this.pageheight = pageheight;
this.running = 0;
this.defaultleft = 0;
this.defaulttop = 0;
this.script = '';
this.start = function(times) {
if(this.running) return 0;
this.times = !times ? 1 : times;
this.scrollpx = 0;
return this.running = 1;
}
this.left = function(times, script) {
if(!this.start(times)) return;
this.stepv = -(this.step = this.pagewidth * this.times / this.speed);
this.script = !script ? '' : script;
setTimeout('pagescroll.h()', 1);
}
this.right = function(times, script) {
if(!this.start(times)) return;
this.stepv = this.step = this.pagewidth * this.times / this.speed;
this.script = !script ? '' : script;
setTimeout('pagescroll.h()', 1);
}
this.up = function(times, script) {
if(!this.start(times)) return;
this.stepv = -(this.step = this.pageheight * this.times / this.speed);
this.script = !script ? '' : script;
setTimeout('pagescroll.v()', 1);
}
this.down = function(times, script) {
if(!this.start(times)) return;
this.stepv = this.step = this.pageheight * this.times / this.speed;
this.script = !script ? '' : script;
setTimeout('pagescroll.v()', 1);
}
this.h = function() {
if(this.scrollpx <= this.pagewidth * this.times) {
this.scrollpx += Math.abs(this.stepv);
patch = this.scrollpx > this.pagewidth * this.times ? this.scrollpx - this.pagewidth * this.times : 0;
patch = patch > 0 && this.stepv < 0 ? -patch : patch;
oldscrollLeft = this.ctrlobj.scrollLeft;
this.ctrlobj.scrollLeft = this.ctrlobj.scrollLeft + this.stepv - patch;
if(oldscrollLeft != this.ctrlobj.scrollLeft) {
setTimeout('pagescroll.h()', 1);
return;
}
}
if(this.script) {
eval(this.script);
}
this.running = 0;
}
this.v = function() {
if(this.scrollpx <= this.pageheight * this.times) {
this.scrollpx += Math.abs(this.stepv);
patch = this.scrollpx > this.pageheight * this.times ? this.scrollpx - this.pageheight * this.times : 0;
patch = patch > 0 && this.stepv < 0 ? -patch : patch;
oldscrollTop = this.ctrlobj.scrollTop;
this.ctrlobj.scrollTop = this.ctrlobj.scrollTop + this.stepv - patch;
if(oldscrollTop != this.ctrlobj.scrollTop) {
setTimeout('pagescroll.v()', 1);
return;
}
}
if(this.script) {
eval(this.script);
}
this.running = 0;
}
this.init = function() {
this.ctrlobj.scrollLeft = this.defaultleft;
this.ctrlobj.scrollTop = this.defaulttop;
}
}
//LiSelect
var selectopen = null;
var hiddencheckstatus = 0;
function loadselect(id, showinput, pageobj, pos, method) {
var obj = $(id);
var objname = $(id).name;
var objoffset = fetchOffset(obj);
objoffset['width'] = is_ie ? (obj.offsetWidth ? obj.offsetWidth : parseInt(obj.currentStyle.width)) : obj.offsetWidth;
objoffset['height'] = is_ie ? (obj.offsetHeight ? obj.offsetHeight : parseInt(obj.currentStyle.height)) : obj.offsetHeight;
pageobj = !pageobj ? '' : pageobj;
showinput = !showinput ? 0 : showinput;
pos = !pos ? 0 : 1;
method = !method ? 0 : 1;
var maxlength = 0;
var defaultopt = '', defaultv = '';
var lis = '<ul onfocus="loadselect_keyinit(event, 1)" onblur="loadselect_keyinit(event, 2)" class="newselect" id="' + objname + '_selectmenu" style="' + (!pos ? 'z-index:999;position: absolute; width: ' + objoffset['width'] + 'px;' : '') + 'display: none">';
for(var i = 0;i < obj.options.length;i++){
lis += '<li ' + (obj.options[i].selected ? 'class="current" ' : '') + 'k_id="' + id + '" k_value="' + obj.options[i].value + '" onclick="loadselect_liset(\'' + objname + '\', ' + showinput + ', \'' + id + '\',' + (showinput ? 'this.innerHTML' : '\'' + obj.options[i].value + '\'') + ',this.innerHTML, ' + i + ')">' + obj.options[i].innerHTML + '</li>';
maxlength = obj.options[i].value.length > maxlength ? obj.options[i].value.length : maxlength;
if(obj.options[i].selected) {
defaultopt = obj.options[i].innerHTML;
defaultv = obj.options[i].value;
if($(objname)) {
$(objname).setAttribute('selecti', i);
}
}
}
lis += '</ul>';
if(showinput) {
inp = '<input autocomplete="off" class="newselect" id="' + objname + '_selectinput" onclick="loadselect_viewmenu(this, \'' + objname + '\', 0, \'' + pageobj + '\');doane(event)" onchange="loadselect_inputset(\'' + id + '\', this.value);loadselect_viewmenu(this, \'' + objname + '\', 0, \'' + pageobj + '\')" value="' + defaultopt + '" style="width: ' + objoffset['width'] + 'px;height: ' + objoffset['height'] + 'px;" tabindex="1" />';
} else {
inp = '<a href="javascript:;" hidefocus="true" class="loadselect" id="' + objname + '_selectinput"' + (!obj.disabled ? ' onfocus="loadselect_keyinit(event, 1)" onblur="loadselect_keyinit(event, 2)" onmouseover="this.focus()" onmouseout="this.blur()" onkeyup="loadselect_key(this, event, \'' + objname + '\', \'' + pageobj + '\')" onclick="loadselect_viewmenu(this, \'' + objname + '\', 0, \'' + pageobj + '\');doane(event)"' : '') + ' tabindex="1">' + defaultopt + '</a>';
}
obj.options.length = 0;
if(defaultopt) {
obj.options[0]= showinput ? new Option('', defaultopt) : new Option('', defaultv);
}
obj.style.width = objoffset['width'] + 'px';
obj.style.display = 'none';
if(!method) {
obj.outerHTML += inp + lis;
} else {
if(showinput) {
var inpobj = document.createElement("input");
} else {
var inpobj = document.createElement("a");
}
obj.parentNode.appendChild(inpobj);
inpobj.outerHTML = inp;
var lisobj = document.createElement("ul");
obj.parentNode.appendChild(lisobj);
lisobj.outerHTML = lis;
}
}
function loadselect_keyinit(e, a) {
if(a == 1) {
if(document.attachEvent) {
document.body.attachEvent('onkeydown', loadselect_keyhandle);
} else {
document.body.addEventListener('keydown', loadselect_keyhandle, false);
}
} else {
if(document.attachEvent) {
document.body.detachEvent('onkeydown', loadselect_keyhandle);
} else {
document.body.removeEventListener('keydown', loadselect_keyhandle, false);
}
}
}
function loadselect_keyhandle(e) {
e = is_ie ? event : e;
if(e.keyCode == 40 || e.keyCode == 38) doane(e);
}
function loadselect_key(ctrlobj, e, objname, pageobj) {
value = e.keyCode;
if(value == 40 || value == 38) {
if($(objname + '_selectmenu').style.display == 'none') {
loadselect_viewmenu(ctrlobj, objname, 0, pageobj);
} else {
lis = $(objname + '_selectmenu').getElementsByTagName('LI');
selecti = $(objname).getAttribute('selecti');
lis[selecti].className = '';
if(value == 40) {
selecti = parseInt(selecti) + 1;
} else if(value == 38) {
selecti = parseInt(selecti) - 1;
}
if(selecti < 0) {
selecti = lis.length - 1
} else if(selecti > lis.length - 1) {
selecti = 0;
}
lis[selecti].className = 'current';
$(objname).setAttribute('selecti', selecti);
lis[selecti].parentNode.scrollTop = lis[selecti].offsetTop;
}
} else if(value == 13) {
lis = $(objname + '_selectmenu').getElementsByTagName('LI');
for(i = 0;i < lis.length;i++) {
if(lis[i].className == 'current') {
loadselect_liset(objname, 0, lis[i].getAttribute('k_id'), lis[i].getAttribute('k_value'), lis[i].innerHTML, i);
break;
}
}
}
}
function loadselect_viewmenu(ctrlobj, objname, hidden, pageobj) {
if(!selectopen) {
if(document.attachEvent) {
document.body.attachEvent('onclick', loadselect_hiddencheck);
} else {
document.body.addEventListener('click', loadselect_hiddencheck, false);
}
}
var hidden = !hidden ? 0 : 1;
if($(objname + '_selectmenu').style.display == '' || hidden) {
$(objname + '_selectmenu').style.display = 'none';
} else {
if($(selectopen)) {
$(selectopen).style.display = 'none';
}
var objoffset = fetchOffset(ctrlobj);
if(pageobj) {
var InFloate = pageobj.split('_');
objoffset['left'] -= $(pageobj).scrollLeft + parseInt(floatwinhandle[InFloate[1] + '_1']);
objoffset['top'] -= $(pageobj).scrollTop + parseInt(floatwinhandle[InFloate[1] + '_2']);
}
objoffset['height'] = ctrlobj.offsetHeight;
$(objname + '_selectmenu').style.display = '';
selectopen = objname + '_selectmenu';
}
hiddencheckstatus = 1;
}
function loadselect_hiddencheck() {
if(hiddencheckstatus) {
if($(selectopen)) {
$(selectopen).style.display = 'none';
}
hiddencheckstatus = 0;
}
}
function loadselect_liset(objname, showinput, obj, v, opt, selecti) {
var change = 1;
if(showinput) {
if($(objname + '_selectinput').value != opt) {
$(objname + '_selectinput').value = opt;
} else {
change = 0;
}
} else {
if($(objname + '_selectinput').innerHTML != opt) {
$(objname + '_selectinput').innerHTML = opt;
} else {
change = 0;
}
}
lis = $(objname + '_selectmenu').getElementsByTagName('LI');
lis[$(objname).getAttribute('selecti')].className = '';
lis[selecti].className = 'current';
$(objname).setAttribute('selecti', selecti);
$(objname + '_selectmenu').style.display='none';
if(change) {
obj = $(obj);
obj.options.length=0;
obj.options[0]=new Option('', v);
eval(obj.getAttribute('change'));
}
}
function loadselect_inputset(obj, v) {
obj = $(obj);
obj.options.length=0;
obj.options[0]=new Option('', v);
eval(obj.getAttribute('change'));
}
//DetectCapsLock
var detectobj;
function detectcapslock(e, obj) {
detectobj = obj;
valueCapsLock = e.keyCode ? e.keyCode : e.which;
valueShift = e.shiftKey ? e.shiftKey : (valueCapsLock == 16 ? true : false);
detectobj.className = (valueCapsLock >= 65 && valueCapsLock <= 90 && !valueShift || valueCapsLock >= 97 && valueCapsLock <= 122 && valueShift) ? 'capslock txt' : 'txt';
if(is_ie) {
event.srcElement.onblur = detectcapslock_cleardetectobj;
} else {
e.target.onblur = detectcapslock_cleardetectobj;
}
}
function detectcapslock_cleardetectobj() {
detectobj.className = 'txt';
}
//FloatWin
var hiddenobj = new Array();
var floatwinhandle = new Array();
var floatscripthandle = new Array();
var floattabs = new Array();
var floatwins = new Array();
var InFloat = '';
var floatwinreset = 0;
var floatwinopened = 0;
function floatwin(action, script, w, h, scrollpos) {
var floatonly = !floatonly ? 0 : 1;
var actione = action.split('_');
action = actione[0];
if((!allowfloatwin || allowfloatwin == 0) && action == 'open' && in_array(actione[1], ['register','login','newthread','reply','edit']) && w >= 600) {
location.href = script;
return;
}
var handlekey = actione[1];
var layerid = 'floatwin_' + handlekey;
if(is_ie) {
var objs = $('wrap').getElementsByTagName("OBJECT");
} else {
var objs = $('wrap').getElementsByTagName("EMBED");
}
if(action == 'open') {
loadcss('float');
floatwinhandle[handlekey + '_0'] = layerid;
if(!floatwinopened) {
$('wrap').onkeydown = floatwin_wrapkeyhandle;
for(i = 0;i < objs.length; i ++) {
if(objs[i].style.visibility != 'hidden') {
objs[i].setAttribute("oldvisibility", objs[i].style.visibility);
objs[i].style.visibility = 'hidden';
}
}
}
scrollpos = !scrollpos ? '' : 'floatwin_scroll(\'' + scrollpos + '\');';
var clientWidth = document.body.clientWidth;
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
if(script && script != -1) {
if(script.lastIndexOf('/') != -1) {
script = script.substr(script.lastIndexOf('/') + 1);
}
var scriptfile = script.split('?');
scriptfile = scriptfile[0];
if(floatwinreset || floatscripthandle[scriptfile] && floatscripthandle[scriptfile][0] != script) {
if(!isUndefined(floatscripthandle[scriptfile])) {
$('append_parent').removeChild($(floatscripthandle[scriptfile][1]));
$('append_parent').removeChild($(floatscripthandle[scriptfile][1] + '_mask'));
}
floatwinreset = 0;
}
floatscripthandle[scriptfile] = [script, layerid];
}
if(!$(layerid)) {
floattabs[layerid] = new Array();
div = document.createElement('div');
div.className = 'floatwin';
div.id = layerid;
div.style.width = w + 'px';
div.style.height = h + 'px';
div.style.left = floatwinhandle[handlekey + '_1'] = ((clientWidth - w) / 2) + 'px';
div.style.position = 'absolute';
div.style.zIndex = '999';
div.onkeydown = floatwin_keyhandle;
$('append_parent').appendChild(div);
$(layerid).style.display = '';
$(layerid).style.top = floatwinhandle[handlekey + '_2'] = ((clientHeight - h) / 2 + scrollTop) + 'px';
$(layerid).innerHTML = '<div><h3 class="float_ctrl"><em><img src="' + IMGDIR + '/loading.gif"> 加载中...</em><span><a href="javascript:;" class="float_close" onclick="floatwinreset = 1;floatwin(\'close_' + handlekey + '\');"> </a></span></h3></div>';
divmask = document.createElement('div');
divmask.className = 'floatwinmask';
divmask.id = layerid + '_mask';
divmask.style.width = (parseInt($(layerid).style.width) + 14) + 'px';
divmask.style.height = (parseInt($(layerid).style.height) + 14) + 'px';
divmask.style.left = (parseInt($(layerid).style.left) - 6) + 'px';
divmask.style.top = (parseInt($(layerid).style.top) - 6) + 'px';
divmask.style.position = 'absolute';
divmask.style.zIndex = '998';
divmask.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=90,finishOpacity=100,style=0)';
divmask.style.opacity = 0.9;
$('append_parent').appendChild(divmask);
if(script && script != -1) {
script += (script.search(/\?/) > 0 ? '&' : '?') + 'infloat=yes&handlekey=' + handlekey;
try {
ajaxget(script, layerid, '', '', '', scrollpos);
} catch(e) {
setTimeout("ajaxget('" + script + "', '" + layerid + "', '', '', '', '" + scrollpos + "')", 1000);
}
} else if(script == -1) {
$(layerid).innerHTML = '<div><h3 class="float_ctrl"><em id="' + layerid + '_title"></em><span><a href="javascript:;" class="float_close" onclick="floatwinreset = 1;floatwin(\'close_' + handlekey + '\');"> </a></span></h3></div><div id="' + layerid + '_content"></div>';
$(layerid).style.zIndex = '1099';
$(layerid + '_mask').style.zIndex = '1098';
}
} else {
$(layerid).style.width = w + 'px';
$(layerid).style.height = h + 'px';
$(layerid).style.display = '';
$(layerid).style.top = floatwinhandle[handlekey + '_2'] = ((clientHeight - h) / 2 + scrollTop) + 'px';
$(layerid + '_mask').style.width = (parseInt($(layerid).style.width) + 14) + 'px';
$(layerid + '_mask').style.height = (parseInt($(layerid).style.height) + 14) + 'px';
$(layerid + '_mask').style.display = '';
$(layerid + '_mask').style.top = (parseInt($(layerid).style.top) - 6) + 'px';
}
floatwins[floatwinopened] = handlekey;
floatwinopened++;
} else if(action == 'close' && floatwinhandle[handlekey + '_0']) {
floatwinopened--;
for(i = 0;i < floatwins.length; i++) {
if(handlekey == floatwins[i]) {
floatwins[i] = null;
}
}
if(!floatwinopened) {
for(i = 0;i < objs.length; i ++) {
if(objs[i].attributes['oldvisibility']) {
objs[i].style.visibility = objs[i].attributes['oldvisibility'].nodeValue;
objs[i].removeAttribute('oldvisibility');
}
}
$('wrap').onkeydown = null;
}
hiddenobj = new Array();
$(layerid + '_mask').style.display = 'none';
$(layerid).style.display = 'none';
} else if(action == 'size' && floatwinhandle[handlekey + '_0']) {
if(!floatwinhandle[handlekey + '_3']) {
var clientWidth = document.body.clientWidth;
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var w = clientWidth > 800 ? clientWidth * 0.9 : 800;
var h = clientHeight * 0.9;
floatwinhandle[handlekey + '_3'] = $(layerid).style.left;
floatwinhandle[handlekey + '_4'] = $(layerid).style.top;
floatwinhandle[handlekey + '_5'] = $(layerid).style.width;
floatwinhandle[handlekey + '_6'] = $(layerid).style.height;
$(layerid).style.left = floatwinhandle[handlekey + '_1'] = ((clientWidth - w) / 2) + 'px';
$(layerid).style.top = floatwinhandle[handlekey + '_2'] = ((document.documentElement.clientHeight - h) / 2 + document.documentElement.scrollTop) + 'px';
$(layerid).style.width = w + 'px';
$(layerid).style.height = h + 'px';
} else {
$(layerid).style.left = floatwinhandle[handlekey + '_1'] = floatwinhandle[handlekey + '_3'];
$(layerid).style.top = floatwinhandle[handlekey + '_2'] = floatwinhandle[handlekey + '_4'];
$(layerid).style.width = floatwinhandle[handlekey + '_5'];
$(layerid).style.height = floatwinhandle[handlekey + '_6'];
floatwinhandle[handlekey + '_3'] = '';
}
$(layerid + '_mask').style.width = (parseInt($(layerid).style.width) + 14) + 'px';
$(layerid + '_mask').style.height = (parseInt($(layerid).style.height) + 14) + 'px';
$(layerid + '_mask').style.left = (parseInt($(layerid).style.left) - 6) + 'px';
$(layerid + '_mask').style.top = (parseInt($(layerid).style.top) - 6) + 'px';
}
}
function floatwin_scroll(pos) {
var pose = pos.split(',');
try {
pagescroll.defaultleft = pose[0];
pagescroll.defaulttop = pose[1];
pagescroll.init();
} catch(e) {}
}
function floatwin_wrapkeyhandle(e) {
e = is_ie ? event : e;
if(e.keyCode == 9) {
doane(e);
} else if(e.keyCode == 27) {
for(i = floatwins.length - 1;i >= 0; i--) {
floatwin('close_' + floatwins[i]);
}
}
}
function floatwin_keyhandle(e) {
e = is_ie ? event : e;
if(e.keyCode == 9) {
doane(e);
var obj = is_ie ? e.srcElement : e.target;
var srcobj = obj;
j = 0;
while(obj.className.indexOf('floatbox') == -1) {
obj = obj.parentNode;
}
obj.id = obj.id ? obj.id : 'floatbox_' + Math.random();
if(!floattabs[obj.id]) {
floattabs[obj.id] = new Array();
var alls = obj.getElementsByTagName("*");
for(i = 0;i < alls.length;i++) {
if(alls[i].getAttribute('tabindex') == 1) {
floattabs[obj.id][j] = alls[i];
j++;
}
}
}
if(floattabs[obj.id].length > 0) {
for(i = 0;i < floattabs[obj.id].length;i++) {
if(srcobj == floattabs[obj.id][i]) {
j = e.shiftKey ? i - 1 : i + 1;break;
}
}
if(j < 0) {
j = floattabs[obj.id].length - 1;
}
if(j > floattabs[obj.id].length - 1) {
j = 0;
}
do{
focusok = 1;
try{ floattabs[obj.id][j].focus(); } catch(e) {
focusok = 0;
}
if(!focusok) {
j = e.shiftKey ? j - 1 : j + 1;
if(j < 0) {
j = floattabs[obj.id].length - 1;
}
if(j > floattabs[obj.id].length - 1) {
j = 0;
}
}
} while(!focusok);
}
}
}
//ShowSelect
function showselect(obj, inpid, t, rettype) {
if(!obj.id) {
var t = !t ? 0 : t;
var rettype = !rettype ? 0 : rettype;
obj.id = 'calendarexp_' + Math.random();
div = document.createElement('div');
div.id = obj.id + '_menu';
div.style.display = 'none';
div.className = 'showselect_menu';
if($(InFloat) != null) {
$(InFloat).appendChild(div);
} else {
$('append_parent').appendChild(div);
}
s = '';
if(!t) {
s += showselect_row(inpid, '一天', 1, 0, rettype);
s += showselect_row(inpid, '一周', 7, 0, rettype);
s += showselect_row(inpid, '一个月', 30, 0, rettype);
s += showselect_row(inpid, '三个月', 90, 0, rettype);
s += showselect_row(inpid, '自定义', -2);
} else {
if($(t)) {
var lis = $(t).getElementsByTagName('LI');
for(i = 0;i < lis.length;i++) {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = this.innerHTML">' + lis[i].innerHTML + '</a><br />';
}
s += showselect_row(inpid, '自定义', -1);
} else {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'0\'">永久</a><br />';
s += showselect_row(inpid, '7 天', 7, 1, rettype);
s += showselect_row(inpid, '14 天', 14, 1, rettype);
s += showselect_row(inpid, '一个月', 30, 1, rettype);
s += showselect_row(inpid, '三个月', 90, 1, rettype);
s += showselect_row(inpid, '半年', 182, 1, rettype);
s += showselect_row(inpid, '一年', 365, 1, rettype);
s += showselect_row(inpid, '自定义', -1);
}
}
$(div.id).innerHTML = s;
}
showMenu(obj.id);
if(is_ie && is_ie < 7) {
doane(event);
}
}
function showselect_row(inpid, s, v, notime, rettype) {
if(v >= 0) {
if(!rettype) {
var notime = !notime ? 0 : 1;
t = today.getTime();
t += 86400000 * v;
d = new Date();
d.setTime(t);
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + (!notime ? ' ' + d.getHours() + ':' + d.getMinutes() : '') + '\'">' + s + '</a><br />';
} else {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + v + '\'">' + s + '</a><br />';
}
} else if(v == -1) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').focus()">' + s + '</a><br />';
} else if(v == -2) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').onclick()">' + s + '</a><br />';
}
}
//Smilies
function smilies_show(id, smcols, method, seditorkey) {
if(seditorkey && !$(seditorkey + 'smilies_menu')) {
var div = document.createElement("div");
div.id = seditorkey + 'smilies_menu';
div.style.display = 'none';
div.className = 'smilieslist';
$('append_parent').appendChild(div);
var div = document.createElement("div");
div.id = id;
div.style.overflow = 'hidden';
$(seditorkey + 'smilies_menu').appendChild(div);
}
if(typeof smilies_type == 'undefined') {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.charset = charset ? charset : (is_moz ? document.characterSet : document.charset);
scriptNode.src = 'forumdata/cache/smilies_var.js?' + VERHASH;
$('append_parent').appendChild(scriptNode);
if(is_ie) {
scriptNode.onreadystatechange = function() {
smilies_onload(id, smcols, method, seditorkey);
}
} else {
scriptNode.onload = function() {
smilies_onload(id, smcols, method, seditorkey);
}
}
} else {
smilies_onload(id, smcols, method, seditorkey);
}
}
var currentstype = null;
function smilies_onload(id, smcols, method, seditorkey) {
seditorkey = !seditorkey ? '' : seditorkey;
smile = getcookie('smile').split('D');
if(typeof smilies_type == 'object') {
if(smile[0] && smilies_array[smile[0]]) {
currentstype = smile[0];
} else {
for(i in smilies_array) {
currentstype = i; break;
}
}
smiliestype = '<div class="smiliesgroup" style="margin-right: 0"><ul>';
for(i in smilies_type) {
if(smilies_type[i][0]) {
smiliestype += '<li><a href="javascript:;" hidefocus="true" ' + (currentstype == i ? 'class="current"' : '') + ' id="stype_'+method+'_'+i+'" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', '+i+', 1, ' + method + ', \'' + seditorkey + '\');if(currentstype) {$(\'stype_'+method+'_\'+currentstype).className=\'\';}this.className=\'current\';currentstype='+i+';">'+smilies_type[i][0]+'</a></li>';
}
}
smiliestype += '</ul></div>';
$(id).innerHTML = smiliestype + '<div style="clear: both" class="float_typeid" id="' + id + '_data"></div><table class="smilieslist_table" id="' + id + '_preview_table" style="display: none"><tr><td class="smilieslist_preview" id="' + id + '_preview"></td></tr></table><div style="clear: both" class="smilieslist_page" id="' + id + '_page"></div>';
smilies_switch(id, smcols, currentstype, smile[1], method, seditorkey);
}
}
function smilies_switch(id, smcols, type, page, method, seditorkey) {
page = page ? page : 1;
if(!smilies_array[type] || !smilies_array[type][page]) return;
setcookie('smile', type + 'D' + page, 31536000);
smiliesdata = '<table id="' + id + '_table" cellpadding="0" cellspacing="0" style="clear: both"><tr>';
j = k = 0;
img = new Array();
for(i in smilies_array[type][page]) {
if(j >= smcols) {
smiliesdata += '<tr>';
j = 0;
}
s = smilies_array[type][page][i];
smilieimg = 'images/smilies/' + smilies_type[type][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smiliesdata += s && s[0] ? '<td onmouseover="smilies_preview(\'' + id + '\', this, ' + s[5] + ')" onmouseout="smilies_preview(\'' + id + '\')" onclick="' + (method ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
j++;k++;
}
smiliesdata += '</table>';
smiliespage = '';
if(smilies_array[type].length > 2) {
prevpage = ((prevpage = parseInt(page) - 1) < 1) ? smilies_array[type].length - 1 : prevpage;
nextpage = ((nextpage = parseInt(page) + 1) == smilies_array[type].length) ? 1 : nextpage;
smiliespage = '<div class="pags_act"><a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + prevpage + ', ' + method + ', \'' + seditorkey + '\')">上页</a>' +
'<a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + nextpage + ', ' + method + ', \'' + seditorkey + '\')">下页</a></div>' +
page + '/' + (smilies_array[type].length - 1);
}
$(id + '_data').innerHTML = smiliesdata;
$(id + '_page').innerHTML = smiliespage;
}
function smilies_preview(id, obj, v) {
if(!obj) {
$(id + '_preview_table').style.display = 'none';
} else {
$(id + '_preview_table').style.display = '';
$(id + '_preview').innerHTML = '<img width="' + v + '" src="' + obj.childNodes[0].src + '" />';
}
}
//SEditor
function seditor_ctlent(event, script) {
if(event.ctrlKey && event.keyCode == 13 || event.altKey && event.keyCode == 83) {
eval(script);
}
}
function parseurl(str, mode, parsecode) {
if(!parsecode) 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]');
if(!parsecode) {
for(var i = 0; i <= codecount; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
}
}
return str;
}
function codetag(text) {
codecount++;
if(typeof wysiwyg != 'undefined' && wysiwyg) text = text.replace(/<br[^\>]*>/ig, '\n').replace(/<(\/|)[A-Za-z].*?>/ig, '');
codehtml[codecount] = '[code]' + text + '[/code]';
return '[\tDISCUZ_CODE_' + codecount + '\t]';
}
function seditor_insertunit(key, text, textend, moveend) {
$(key + 'message').focus();
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($(key + 'message').selectionStart)) {
var opn = $(key + 'message').selectionStart + 0;
if(textend != '') {
text = text + $(key + 'message').value.substring($(key + 'message').selectionStart, $(key + 'message').selectionEnd) + textend;
}
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
if(!moveend) {
$(key + 'message').selectionStart = opn + strlen(text) - endlen;
$(key + 'message').selectionEnd = opn + strlen(text) - endlen;
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
$(key + 'message').value += text;
}
hideMenu();
}
function pmchecknew() {
ajaxget('pm.php?checknewpm=' + Math.random(), 'pm_ntc', 'ajaxwaitid');
}
function pmviewnew() {
if(!$('pm_ntc_menu')) {
var div = document.createElement("div");
div.id = 'pm_ntc_menu';
div.style.display = 'none';
$('append_parent').appendChild(div);
div.innerHTML = '<div id="pm_ntc_view"></div>';
}
showMenu('pm_ntc');
if($('pm_ntc_view').innerHTML == '') {
ajaxget('pm.php?action=viewnew', 'pm_ntc_view', 'ajaxwaitid');
}
}
function creditnoticewin() {
if(!(creditnoticedata = getcookie('discuz_creditnotice'))) {
return;
}
if(getcookie('discuz_creditnoticedisable')) {
return;
}
creditnoticearray = creditnoticedata.split('D');
if(creditnoticearray[9] != discuz_uid) {
return;
}
creditnames = creditnotice.split(',');
creditinfo = new Array();
for(i in creditnames) {
var e = creditnames[i].split('|');
creditinfo[e[0]] = [e[1], e[2]];
}
s = '';
for(i = 1;i <= 8;i++) {
if(creditnoticearray[i] != 0 && creditinfo[i]) {
s += '<span>' + creditinfo[i][0] + (creditnoticearray[i] > 0 ? '<em>+' : '<em class="desc">') + creditnoticearray[i] + '</em>' + creditinfo[i][1] + '</span>';
}
}
setcookie('discuz_creditnotice', '', -2592000);
if(s) {
noticewin(s, 2000, 1);
}
}
function noticewin(s, t, c) {
c = !c ? '' : c;
s = !c ? '<span style="font-style: normal;">'+s+'</span>' : s;
s = '<table cellspacing="0" cellpadding="0" class="popupcredit"><tr><td class="pc_l"> </td><td class="pc_c"><div class="pc_inner">' + s +
(c ? '<a class="pc_btn" href="javascript:;" onclick="display(\'ntcwin\');setcookie(\'discuz_creditnoticedisable\', 1, 31536000);" title="不要再提示我"><img src="' + IMGDIR + '/popupcredit_btn.gif" alt="不要再提示我" /></a>' : '') +
'</td><td class="pc_r"> </td></tr></table>';
if(!$('ntcwin')) {
var div = document.createElement("div");
div.id = 'ntcwin';
div.style.display = 'none';
div.style.position = 'absolute';
div.style.zIndex = '100000';
$('append_parent').appendChild(div);
}
$('ntcwin').innerHTML = s;
$('ntcwin').style.display = '';
$('ntcwin').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
$('ntcwin').style.opacity = 0;
pbegin = document.documentElement.scrollTop + (document.documentElement.clientHeight / 2);
pend = document.documentElement.scrollTop + (document.documentElement.clientHeight / 5);
setTimeout(function () {noticewin_show(pbegin, pend, 0, t)}, 10);
$('ntcwin').style.left = ((document.documentElement.clientWidth - $('ntcwin').clientWidth) / 2) + 'px';
$('ntcwin').style.top = pbegin + 'px';
}
function noticewin_show(b, e, a, t) {
step = (b - e) / 10;
newp = (parseInt($('ntcwin').style.top) - step);
if(newp > e) {
$('ntcwin').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + a + ')';
$('ntcwin').style.opacity = a / 100;
$('ntcwin').style.top = newp + 'px';
setTimeout(function () {noticewin_show(b, e, a += 10, t)}, 10);
} else {
$('ntcwin').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
$('ntcwin').style.opacity = 1;
setTimeout('display_opacity(\'ntcwin\', 100)', t);
}
}
function showimmestatus(imme) {
var lang = {'Online':'MSN 在线','Busy':'MSN 忙碌','Away':'MSN 离开','Offline':'MSN 脱机'};
$('imme_status_' + imme.id.substr(0, imme.id.indexOf('@'))).innerHTML = lang[imme.statusText];
}
var discuz_uid = isUndefined(discuz_uid) ? 0 : discuz_uid;
var creditnotice = isUndefined(creditnotice) ? '' : creditnotice;
var cookiedomain = isUndefined(cookiedomain) ? '' : cookiedomain;
var cookiepath = isUndefined(cookiepath) ? '' : cookiepath;
if(typeof IN_ADMINCP == 'undefined') {
if(discuz_uid && !getcookie('checkpm')) {
_attachEvent(window, 'load', pmchecknew, document);
}
if(creditnotice != '' && getcookie('discuz_creditnotice') && !getcookie('discuz_creditnoticedisable')) {
_attachEvent(window, 'load', function(){creditnoticewin()}, document);
}
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/common.js
|
JavaScript
|
asf20
| 68,273
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: floatadv.js 17449 2008-12-22 08:58:53Z cnteacher $
*/
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/51shangcheng.cn/htdocs/include/js/floatadv.js
|
JavaScript
|
asf20
| 2,039
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tree.js 17449 2008-12-22 08:58:53Z cnteacher $
*/
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/51shangcheng.cn/htdocs/include/js/tree.js
|
JavaScript
|
asf20
| 5,554
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: calendar.js 17449 2008-12-22 08:58:53Z cnteacher $
*/
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;
}
if($(InFloat)) {
var InFloate = InFloat.split('_');
r['x'] = r['x'] - $(InFloat).scrollLeft;
r['y'] = r['y'] - $(InFloat).scrollTop;
InFloat = '';
}
return r;
}
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:100000;" onclick="doane(event)">';
s += '<div style="width: 210px;"><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" class="txt" 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" class="txt" 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;z-index:100001;"><div class="col">';
for(var k = 2020; k >= 1931; k--) {
s += k != 2020 && 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;z-index:100001;">';
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();
}
loadcss('calendar');
loadcalendar();
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/calendar.js
|
JavaScript
|
asf20
| 9,444
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: post.js 17506 2009-01-05 04:57:02Z monkey $
*/
var postSubmited = false;
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']) && !validate($('postform'))) {
doane(event);
return;
}
postSubmited = true;
$('postsubmit').disabled = true;
$('postform').submit();
}
}
function ctltab(event) {
if(event.keyCode == 9) {
doane(event);
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
var showmessage = postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节' : '';
alert('\n当前长度: ' + mb_strlen(message) + ' 字节\n\n' + showmessage);
}
if(!tradepost) {
var tradepost = 0;
}
function validate(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
if(($('postsubmit').name != 'replysubmit' && !($('postsubmit').name == 'editsubmit' && !isfirstpost) && theform.subject.value == "") || !sortid && !special && message == "") {
dalert('请完成标题或内容栏。');
return false;
} else if(mb_strlen(theform.subject.value) > 80) {
dalert('您的标题超过 80 个字符的限制。');
return false;
}
if(tradepost) {
if(theform.item_name.value == '') {
dalert('对不起,请输入商品名称。');
return false;
} else if(theform.item_price.value == '') {
dalert('对不起,请输入商品现价。');
return false;
} else if(!parseInt(theform.item_price.value)) {
dalert('对不起,商品现价必须为有效数字。');
return false;
} else if(theform.item_costprice.value != '' && !parseInt(theform.item_costprice.value)) {
dalert('对不起,商品原价必须为有效数字。');
return false;
} else if(theform.item_number.value != '0' && !parseInt(theform.item_number.value)) {
dalert('对不起,商品数量必须为数字。');
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) {
dalert('请选择主题对应的分类。');
return false;
}
if(special == 3 && isfirstpost) {
if(theform.rewardprice.value == "") {
dalert('对不起,请输入悬赏积分。');
return false;
}
} else if(special == 4 && isfirstpost) {
if(theform.activityclass.value == "") {
dalert('对不起,请输入活动所属类别。');
return false;
} else if($('starttimefrom_0').value == "" && $('starttimefrom_1').value == "") {
dalert('对不起,请输入活动开始时间。');
return false;
} else if(theform.activityplace.value == "") {
dalert('对不起,请输入活动地点。');
return false;
}
} else if(special == 6 && isfirstpost && $('postsubmit').name == 'topicsubmit') {
if(theform.vid.value == '') {
dalert('您还没有上传视频,或者视频还在上传中,请稍侯重试。');
return false;
} else if(theform.vsubject.value == '') {
dalert('没有添加视频主题。');
return false;
} else if(theform.vtag.value == '') {
dalert('没有填写视频标签');
return false;
} else if($('vclass') == '') {
dalert('请您选择视频所属分类。');
return false;
}
}
}
if(!disablepostctrl && !sortid && !special && ((postminchars != 0 && mb_strlen(message) < postminchars) || (postmaxchars != 0 && mb_strlen(message) > postmaxchars))) {
alert('您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(message) + ' 字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节');
return false;
}
theform.message.value = message;
if($('postsubmit').name == 'editsubmit') {
if(!infloat) {
return true;
} else {
ajaxpost('postform', 'returnmessage', 'returnmessage', 'onerror', $('postsubmit'));
}
} else if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit'])) {
seccheck(theform, seccodecheck, secqaacheck);
return false;
}
}
function seccheck(theform, seccodecheck, secqaacheck) {
if(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') {
dalert(s);
$('seccodeverify').focus();
} else if(secqaacheck) {
checksecqaa(url, theform);
} else {
postsubmit(theform);
}
});
} else if(secqaacheck) {
checksecqaa(url, theform);
}
} else {
postsubmit(theform);
}
}
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') {
dalert(s);
$('secanswer').focus();
} else {
postsubmit(theform);
}
});
}
function postsubmit(theform) {
theform.replysubmit ? theform.replysubmit.disabled = true : (theform.editsubmit ? theform.editsubmit.disabled = true : theform.topicsubmit.disabled = true);
if(!infloat) {
theform.submit();
} else {
ajaxpost('postform', 'returnmessage', 'returnmessage', 'onerror', $('postsubmit'));
}
}
function loadData(quiet) {
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])) {
if(!quiet) {
alert('没有可以恢复的数据!');
}
return;
}
if(!quiet && !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
}
}
}
}
}
var autosaveDatai, autosaveDatatime;
function autosaveData(op) {
var autosaveInterval = 60;
obj = $(editorid + '_cmd_autosave');
if(op) {
if(op == 2) {
saveData(wysiwyg ? editdoc.body.innerHTML : textobj.value);
} else {
setcookie('disableautosave', '', -2592000);
}
autosaveDatatime = autosaveInterval;
autosaveDatai = setInterval(function() {
autosaveDatatime--;
if(autosaveDatatime == 0) {
saveData(wysiwyg ? editdoc.body.innerHTML : textobj.value);
autosaveDatatime = autosaveInterval;
}
if($('autsavet')) {
$('autsavet').innerHTML = '(' + autosaveDatatime + '秒' + ')';
}
}, 1000);
obj.onclick = function() { autosaveData(0); }
} else {
setcookie('disableautosave', 1, 2592000);
clearInterval(autosaveDatai);
$('autsavet').innerHTML = '(已停止)';
obj.onclick = function() { autosaveData(1); }
}
}
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' && $(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 deleteData() {
if(is_ie) {
saveData('', 'delete');
} else if(window.sessionStorage) {
try {
sessionStorage.removeItem('Discuz!');
} catch(e) {}
}
}
function setCaretAtEnd() {
if(typeof wysiwyg != 'undefined' && wysiwyg) {
editdoc.body.innerHTML += '';
} else {
editdoc.value += '';
}
}
function relatekw(subject, message, recall) {
if(isUndefined(recall)) recall = '';
if(isUndefined(subject) || subject == -1) subject = $('subject').value;
if(isUndefined(message) || message == -1) message = getEditorContents();
subject = (is_ie && document.charset == 'utf-8' ? encodeURIComponent(subject) : subject);
message = (is_ie && document.charset == 'utf-8' ? encodeURIComponent(message) : message);
message = message.replace(/&/ig, '', message).substr(0, 500);
ajaxget('relatekw.php?subjectenc=' + subject + '&messageenc=' + message, 'tagselect', '', '', '', recall);
}
function dalert(s) {
if(!infloat) {
alert(s);
} else {
$('returnmessage').className = 'onerror';
$('returnmessage').innerHTML = s;
messagehandle();
}
}
function pagescrolls(op) {
if(!infloat && op.substr(0, 6) == 'credit') {
window.open('faq.php?action=credits&fid=' + fid);
return;
}
switch(op) {
case 'credit1':hideMenu();$('moreconf').style.display = 'none';$('extcreditbox1').innerHTML = $('extcreditbox').innerHTML;pagescroll.left();break;
case 'credit2':$('moreconf').style.display = 'none';$('extcreditbox2').innerHTML = $('extcreditbox').innerHTML;pagescroll.left();break;
case 'credit3':hideMenu();$('moreconf').style.display = 'none';$('extcreditbox3').innerHTML = $('extcreditbox').innerHTML;pagescroll.left();break;
case 'return':if(!Editorwin) {hideMenu();$('custominfoarea').style.display=$('more_2').style.display='none';pagescroll.up(1, '$(\'more_1\').style.display=\'\'');}break;
case 'creditreturn':pagescroll.right(1, '$(\'moreconf\').style.display = \'\';');break;
case 'swf':hideMenu();$('moreconf').style.display = 'none';swfHandler(3);break;
case 'swfreturn':$('swfbox').style.display = 'none';if(!Editorwin) {pagescroll.left(1, '$(\'moreconf\').style.display = \'\';');}swfHandler(2);break;
case 'more':hideMenu();pagescroll.down(1, '$(\'more_1\').style.display=$(\'more_2\').style.display=$(\'custominfoarea\').style.display=\'none\'');break;
case 'editorreturn':$('more_1').style.display='none';pagescroll.up(1, '$(\'more_2\').style.display=$(\'custominfoarea\').style.display=\'\'');break;
case 'editor':$('more_1').style.display='none';pagescroll.down(1, '$(\'more_2\').style.display=\'\';$(\'custominfoarea\').style.display=\'\'');break;
}
}
function switchicon(iconid, obj) {
$('iconid').value = iconid;
$('icon_img').src = obj.src;
hideMenu();
}
var swfuploaded = 0;
function swfHandler(action) {
if(action == 1) {
swfuploaded = 1;
} else if(action == 2) {
if(Editorwin || !infloat) {
swfuploadwin();
} else {
$('swfbox').style.display = 'none';
pagescroll.left(1, '$(\'moreconf\').style.display=\'\';');
}
if(swfuploaded) {
swfattachlistupdate(action);
}
} else if(action == 3) {
swfuploaded = 0;
pagescroll.right(1, '$(\'swfuploadbox\').style.display = $(\'swfbox\').style.display = \'\';');
}
}
function swfattachlistupdate(action) {
ajaxget('ajax.php?action=swfattachlist', 'swfattachlist', 'swfattachlist', 'swfattachlist', null, '$(\'uploadlist\').scrollTop=10000');
attachlist('open');
$('postform').updateswfattach.value = 1;
}
function appendreply() {
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
$('postform').replysubmit.disabled = false;
creditnoticewin();
}
var Editorwin = 0;
function resizeEditorwin() {
var obj = $('resizeEditorwin');
floatwin('size_' + editoraction);
$('editorbox').style.height = $('floatlayout_' + editoraction).style.height = $('floatwin_' + editoraction).style.height;
if(!Editorwin) {
obj.className = 'float_min';
obj.title = obj.innerHTML = '还原大小';
$('editorbox').style.width = $('floatlayout_' + editoraction).style.width = (parseInt($('floatwin_' + editoraction).style.width) - 10)+ 'px';
$('editorbox').style.left = '0px';
$('editorbox').style.top = '0px';
$('swfuploadbox').style.display = $('custominfoarea').style.display = $('creditlink').style.display = $('morelink').style.display = 'none';
if(wysiwyg) {
$('e_iframe').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 150)+ 'px';
}
$('e_textarea').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 150)+ 'px';
attachlist('close');
Editorwin = 1;
} else {
obj.className = 'float_max';
obj.title = obj.innerHTML = '最大化';
$('editorbox').style.width = $('floatlayout_' + editoraction).style.width = '600px';
$('swfuploadbox').style.display = $('custominfoarea').style.display = $('creditlink').style.display = $('morelink').style.display = '';
if(wysiwyg) {
$('e_iframe').style.height = '';
}
$('e_textarea').style.height = '';
swfuploadwin();
Editorwin = 0;
}
}
function closeEditorwin() {
if(Editorwin) {
resizeEditorwin();
}
floatwin('close_' + editoraction);
}
function editorwindowopen(url) {
data = wysiwyg ? editdoc.body.innerHTML : textobj.value;
saveData(data);
url += '&cedit=' + (data !== '' ? 'yes' : 'no');
window.open(url);
}
function swfuploadwin() {
if(Editorwin) {
if($('swfuploadbox').style.display == 'none') {
$('swfuploadbox').className = 'floatbox floatbox1 floatboxswf floatwin swfwin';
$('swfuploadbox').style.position = 'absolute';
width = (parseInt($('floatlayout_' + editoraction).style.width) - 604) / 2;
$('swfuploadbox').style.left = width + 'px';
$('swfuploadbox').style.display = $('swfclosebtn').style.display = $('swfbox').style.display = '';
} else {
$('swfuploadbox').className = 'floatbox floatbox1 floatboxswf';
$('swfuploadbox').style.position = $('swfuploadbox').style.left = '';
$('swfuploadbox').style.display = $('swfclosebtn').style.display = 'none';
}
} else {
if(infloat) {
pagescrolls('swf');
} else {
if($('swfuploadbox').style.display == 'none') {
$('swfuploadbox').style.display = $('swfbox').style.display = $('swfclosebtn').style.display = '';
} else {
$('swfuploadbox').style.display = $('swfbox').style.display = $('swfclosebtn').style.display = 'none';
}
}
}
}
var editbox = editwin = editdoc = editcss = null;
var cursor = -1;
var stack = new Array();
var initialized = false;
function newEditor(mode, initialtext) {
wysiwyg = parseInt(mode);
if(!(is_ie || is_moz || (is_opera >= 9))) {
allowswitcheditor = wysiwyg = 0;
}
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 = 'javascript:;';
buttons[i].onclick = function(e) {discuzcode(this.id.substr(this.id.lastIndexOf('_cmd_') + 5))};
} else if(buttons[i].id == editorid + '_popup_media') {
buttons[i].href = 'javascript:;';
buttons[i].onclick = function(e) {discuzcode('media')};
} else if(buttons[i].id.indexOf(editorid + '_popup_') != -1) {
buttons[i].href = 'javascript:;';
buttons[i].onclick = function(e) {InFloat = InFloat_Editor;showMenu(this.id, true, 0, 2)};
}
}
setUnselectable($(editorid + '_controls'));
textobj.onkeydown = function(e) {ctlent(e ? e : event)};
}
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 && !(is_moz && is_moz >= 3)) {
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 = '';
editbox.className = textobj.className;
var headNode = editdoc.getElementsByTagName("head")[0];
if(!headNode.getElementsByTagName('link').length) {
editcss = editdoc.createElement('link');
editcss.type = 'text/css';
editcss.rel = 'stylesheet';
editcss.href = editorcss;
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.firstChild.style.background = 'none';
editdoc.body.style.backgroundColor = TABLEBG;
editdoc.body.style.textAlign = 'left';
editdoc.body.id = 'wysiwyg';
if(is_ie) {
try{$('subject').focus();} catch(e) {editwin.focus();}
}
} 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';
}
if(is_ie) {
try{$('subject').focus();} catch(e) {textobj.focus();}
}
}
}
function setEditorEvents() {
if(wysiwyg) {
if(is_moz || is_opera) {
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);ctltab(e);}, true);
} else {
if(editdoc.attachEvent) {
editdoc.body.attachEvent("onkeydown", ctlent);
editdoc.body.attachEvent("onkeydown", ctltab);
}
}
}
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();
if(cmd == 'createlink' && is_ie && wysiwyg && selection === undefined) {
applyFormat("createlink", true, null);
return;
}
var ctrlid = editorid + '_cmd_' + cmd;
var tag = cmd == 'createlink' ? 'url' : 'email';
var str = (tag == 'url' ? '请输入链接的地址:' : '请输入此链接的邮箱地址:') + '<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="txt" />';
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 ? ('<a href="' + (tag == 'email' ? 'mailto:' : '') + href + '">' + v + '</a>') : '[' + 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();
div.parentNode.removeChild(div);
}
}
function insertimage() {
InFloat = InFloat_Editor;
if(is_ie) $(editorid + '_cmd_insertimage_param_url').pos = getCaret();
showMenu(editorid + '_cmd_insertimage', true, 0, 3);
}
function insertimagesubmit() {
checkFocus();
if(is_ie) setCaret($(editorid + '_cmd_insertimage_param_url').pos);
if(wysiwyg) {
insertText('<img src='+$(editorid + '_cmd_insertimage_param_url').value+' border=0 /> ', false);
} else {
insertText('[img]'+$(editorid + '_cmd_insertimage_param_url').value+'[/img]');
}
hideMenu();
$(editorid + '_cmd_insertimage_param_url').value = '';
}
function insertSmiley(smilieid) {
checkFocus();
var src = $('smilie_' + smilieid).src;
var code = $('smilie_' + smilieid).alt;
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);
}
hideMenu();
}
function editorMenuEvent_onkeydown(e) {
e = e ? e : event;
try {
obj = is_ie ? event.srcElement : e.target;
var ctrlid = obj.id.substr(0, obj.id.lastIndexOf('_param_'));
if((obj.type == 'text' && e.keyCode == 13) || (obj.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
$(ctrlid + '_submit').click();
doane(e);
} else if(e.keyCode == 27) {
hideMenu();
$(ctrlid + '_menu').parentNode.removeChild($(ctrlid + '_menu'));
}
} catch(e) {}
}
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 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] : '请输入第 ' + i + ' 个参数:') + '<br /><input type="text" id="' + ctrlid + '_param_' + i + '" style="width: 98%" value="" class="txt" />' + (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();
div.parentNode.removeChild(div);
};
}
function editorMenu(ctrlid, str) {
var div = document.createElement('div');
div.id = ctrlid + '_menu';
div.style.display = 'none';
div.className = 'popupmenu_popup popupfix';
div.style.width = '300px';
$(editorid + '_controls').appendChild(div);
div.innerHTML = '<div class="popupmenu_option" unselectable="on">' + str + '<br /><center><input type="button" id="' + ctrlid + '_submit" value="提交" /> <input type="button" onClick="hideMenu();try{div.parentNode.removeChild(' + div.id + ')}catch(e){}" value="取消" /></center></div>';
InFloat = InFloat_Editor;
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 = '';
lang['e_quote'] = '请输入要插入的引用';
lang['e_code'] = '请输入要插入的代码';
lang['e_free'] = '请输入要插入的免费信息';
lang['e_hide'] = '请输入要插入的隐藏内容';
if(cmd != 'hide' || !selection) {
str += lang['e_' + cmd] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5"></textarea>';
}
str += cmd == 'hide' ? '<br /><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_1" class="txt" checked="checked" />只有当浏览者回复本帖时才显示<br /><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_2" class="txt" />只有当浏览者积分高于 <input type="text" size="3" id="' + ctrlid + '_param_2" class="txt" /> 时才显示' : '';
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;
if(wysiwyg) {
if(cmd == 'code') {
text = preg_replace(['<', '>'], ['<', '>'], text);
}
text = text.replace(/\r?\n/g, '<br />');
}
text = opentag + text + closetag;
insertText(text, strlen(opentag), strlen(closetag), false, sel);
hideMenu();
div.parentNode.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('输入一个列表项目.\r\n留空或者点击取消完成此列表.', '')) {
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') {
insertimage();
} else if(cmd == 'media') {
insertmedia();
} else if(cmd == 'table') {
if(wysiwyg) {
var selection = getSel();
if(is_ie) {
var pos = getCaret();
}
var ctrlid = editorid + '_cmd_table';
var str = '<p>表格行数: <input type="text" id="' + ctrlid + '_param_rows" size="2" value="2" class="txt" /> 表格列数: <input type="text" id="' + ctrlid + '_param_columns" size="2" value="2" class="txt" /></p><p>表格宽度: <input type="text" id="' + ctrlid + '_param_width" size="2" value="" class="txt" /> 背景颜色: <input type="text" id="' + ctrlid + '_param_bgcolor" size="2" class="txt" /></p>';
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() {
checkFocus();
if(is_ie) {
setCaret(pos);
}
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();
div.parentNode.removeChild(div);
}
}
return false;
} else if(cmd == 'floatleft' || cmd == 'floatright') {
if(wysiwyg) {
var selection = getSel();
if(selection) {
var ret = insertText('<br style="clear: both"><span style="float: ' + cmd.substr(5) + '">' + selection + '</span>', true);
}
} else {
var ret = applyFormat(cmd, false);
}
} else if(cmd == 'loadData') {
loadData();hideMenu();
} else if(cmd == 'saveData') {
autosaveData(2);hideMenu();
} else if(cmd == 'autosave') {
if(getcookie('disableautosave')) {
autosaveData(1);
} else {
autosaveData(0);
}
} else if(cmd == 'checklength') {
checklength($('postform'));hideMenu();
} else if(cmd == 'clearcontent') {
clearcontent();hideMenu();
} else {
try {
var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
} catch(e) {
var ret = false;
}
}
if(cmd != 'undo') {
addSnapshot(getEditorContents());
}
if(in_array(cmd, ['bold', 'italic', 'underline', 'fontname', 'fontsize', 'forecolor', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'floatleft', 'floatright', 'removeformat', 'unlink', 'undo', 'redo'])) {
hideMenu();
}
return ret;
}
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.id.indexOf(editorid + '_cmd_custom') == -1 ? '' : 'plugeditor';
control.state = false;
control.mode = 'normal';
} else if(control.id.indexOf(editorid + '_popup_') != -1) {
control.state = false;
}
}
}
cursor = -1;
stack = new Array();
var parsedtext = getEditorContents();
parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
wysiwyg = mode;
$(editorid + '_mode').value = mode;
newEditor(mode, parsedtext);
editwin.focus();
setCaretAtEnd();
}
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 insertmedia() {
InFloat = InFloat_Editor;
if(is_ie) $(editorid + '_mediaurl').pos = getCaret();
showMenu(editorid + '_popup_media', true, 0, 2);
}
function setmediacode(editorid) {
checkFocus();
if(is_ie) setCaret($(editorid + '_mediaurl').pos);
insertText('[media='+$(editorid + '_mediatype').value+
','+$(editorid + '_mediawidth').value+
','+$(editorid + '_mediaheight').value+']'+
$(editorid + '_mediaurl').value+'[/media]');
$(editorid + '_mediaurl').value = '';
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;
}
}
function clearcontent() {
if(wysiwyg) {
editdoc.body.innerHTML = is_moz ? '<br />' : '';
} else {
textobj.value = '';
}
}
var aid = 1;
var attachexts = new Array();
var attachwh = new Array();
function delAttach(id) {
$('attachbody').removeChild($('localno_' + id).parentNode.parentNode);
$('attachbtn').removeChild($('attachnew_' + id).parentNode);
$('attachbody').innerHTML == '' && addAttach();
$('localimgpreview_' + id) ? document.body.removeChild($('localimgpreview_' + id)) : null;
}
function delSWFAttach(id) {
$('swfattach_' + id).style.display = 'none';
$('delswfattach_' + id).checked = true;
}
function delEditAttach(id) {
$('attach_' + id).style.display = 'none';
$('delattach_' + id).checked = true;
}
function addAttach() {
var id = aid;
var tags, newnode, i;
newnode = $('attachbtnhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach[]') {
tags[i].id = 'attachnew_' + id;
tags[i].onchange = function() {insertAttach(id)};
tags[i].unselectable = 'on';
}
}
$('attachbtn').appendChild(newnode);
newnode = $('attachbodyhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
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;
} else if(tags[i].id == 'cpadd[]') {
tags[i].id = 'cpadd_' + id;
} else if(tags[i].id == 'cpdel[]') {
tags[i].id = 'cpdel_' + id;
} else if(tags[i].id == 'localno[]') {
tags[i].id = 'localno_' + id;
} else if(tags[i].id == 'deschidden[]') {
tags[i].id = 'deschidden_' + id;
}
}
aid++;
newnode.style.display = 'none';
$('attachbody').appendChild(newnode);
$('uploadlist').scrollTop = 10000;
}
function insertAttach(id) {
var localimgpreview = '';
var path = $('attachnew_' + id).value;
var extpos = path.lastIndexOf('.');
var ext = extpos == -1 ? '' : path.substr(extpos + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $('attachnew_' + id).value.substr($('attachnew_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
var filename = mb_cutstr(localfile, 30);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类扩展名的附件。');
return;
}
attachexts[id] = is_ie && is_ie < 8 && in_array(ext, ['gif', 'jpeg', 'jpg', 'png', 'bmp']) ? 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 = $('attachnew_' + id).value;
} catch (e) {
alert('无效的图片文件。');
delAttach(id);
return;
}
var wh = {'w' : $('img_hidden').offsetWidth, 'h' : $('img_hidden').offsetHeight};
var aid = $('img_hidden').alt;
if(wh['w'] >= 180 || wh['h'] >= 150) {
wh = attachthumbImg(wh['w'], wh['h'], 180, 150);
}
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;
div.style.display = 'none';
document.body.appendChild(div);
div.innerHTML = '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + $('attachnew_' + id).value+'\');width:'+wh['w']+';height:'+wh['h']+'" src=\'images/common/none.gif\' border="0" aid="attach_'+ aid +'" alt="" />';
}
$('cpdel_' + id).innerHTML = '<a href="###" class="deloption" onclick="delAttach(' + id + ')">删除</a>';
$('cpadd_' + id).innerHTML = '<a href="###" title="点击这里将本附件插入帖子内容中当前光标的位置"' + 'onclick="insertAttachtext(' + id + ');return false;">插入</a>';
$('localfile_' + id).innerHTML = '<span' + (attachexts[id] == 2 ? ' onmouseover="showpreview(this, \'localimgpreview_' + id + '\')" ' : '') + '>' + filename + '</span>';
$('attachnew_' + id).style.display = 'none';
$('deschidden_' + id).style.display = '';
$('deschidden_' + id).title = localfile;
$('localno_' + id).parentNode.parentNode.style.display = '';
addAttach();
attachlist('open');
}
function attachlist(op) {
if(!op) {
op = textobj.className == 'autosave' ? 'close' : 'open';
}
if(op == 'open') {
textobj.className = 'autosave';
if(editbox) {
editbox.className = 'autosave';
}
$('attachlist').style.display = '';
if(Editorwin) {
if(wysiwyg) {
$('e_iframe').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 329)+ 'px';
}
$('e_textarea').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 329)+ 'px';
}
} else {
textobj.className = 'autosave max';
if(editbox) {
editbox.className = 'autosave max';
}
$('attachlist').style.display = 'none';
if(Editorwin) {
if(wysiwyg) {
$('e_iframe').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 150)+ 'px';
}
$('e_textarea').style.height = (parseInt($('floatwin_' + editoraction).style.height) - 150)+ 'px';
}
}
}
lastshowpreview = null;
function showpreview(ctrlobj, showid) {
if(lastshowpreview) {
lastshowpreview.id = '';
}
if(!ctrlobj.onmouseout) {
ctrlobj.onmouseout = function() { hideMenu(); }
}
ctrlobj.id = 'imgpreview';
lastshowpreview = ctrlobj;
$('imgpreview_menu').innerHTML = '<table width="100%" height="100%"><tr><td align="center" valign="middle">' + $(showid).innerHTML + '</td></tr></table>';
InFloat='floatlayout_' + editoraction;
showMenu('imgpreview', false, 2, 1, 0);
$('imgpreview_menu').style.top = (parseInt($('imgpreview_menu').style.top) - $('uploadlist').scrollTop) + 'px';
}
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('无效的图片文件。');
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) {
wysiwyg ? insertText($('localimgpreview_' + id).innerHTML, false) : AddText('[localimg=' + attachwh[id]['w'] + ',' + attachwh[id]['h'] + ']' + id + '[/localimg]');
} else {
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 attachupdate(aid, ctrlobj) {
objupdate = $('attachupdate'+aid);
obj = $('attach'+aid);
if(!objupdate.innerHTML) {
obj.style.display = 'none';
objupdate.innerHTML = '<input type="file" name="attachupdate[paid' + aid + ']">';
ctrlobj.innerHTML = '取消';
} else {
obj.style.display = '';
objupdate.innerHTML = '';
ctrlobj.innerHTML = '更新';
}
}
function insertAttachTag(aid) {
if(wysiwyg) {
insertText('[attach]' + aid + '[/attach]', false);
} else {
AddText('[attach]' + aid + '[/attach]');
}
}
function insertAttachimgTag(aid) {
if(wysiwyg) {
eval('var attachimg = $(\'preview_' + aid + '\')');
insertText('<img src="' + attachimg.src + '" border="0" aid="attachimg_' + aid + '" width="180" alt="" />', false);
} else {
AddText('[attachimg]' + aid + '[/attachimg]');
}
}
openEditor();
if(allowpostattach) {
addAttach();
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/post.js
|
JavaScript
|
asf20
| 57,051
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread.js 17535 2009-01-20 05:12:20Z monkey $
*/
var replyreload = '';
function attachimgshow(pid) {
aimgs = aimgcount[pid];
aimgcomplete = 0;
loadingcount = 0;
for(i = 0;i < aimgs.length;i++) {
obj = $('aimg_' + aimgs[i]);
if(!obj) {
break;
}
if(!obj.status) {
obj.status = 1;
obj.src = obj.getAttribute('file');
loadingcount++;
} else if(obj.status == 1) {
if(obj.complete) {
obj.status = 2;
} else {
loadingcount++;
}
} else if(obj.status == 2) {
aimgcomplete++;
if(obj.getAttribute('thumbImg')) {
thumbImg(obj);
}
}
if(loadingcount >= 10) {
break;
}
}
if(aimgcomplete < aimgs.length) {
setTimeout("attachimgshow('" + pid + "')", 100);
}
}
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) {
setcopy(is_ie ? obj.innerText.replace(/\r\n\r\n/g, '\r\n') : obj.textContent, '代码已复制到剪贴板');
}
function signature(obj) {
if(obj.style.maxHeightIE != '') {
var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight + 'px';
if(obj.innerHTML.indexOf('<IMG ') == -1) {
obj.style.maxHeightIE = '';
}
return height;
}
}
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.zIndex = '998';
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.style.padding = 0;
$('append_parent').appendChild(div);
}
zoomobj['srcinfo'] = fetchOffset(obj);
zoomobj['srcobj'] = obj;
zoomobj['zimg'] = zimg;
zoomobj['id'] = 'zoom_' + Math.random();
$('zoomimglayer').setAttribute('pid', obj.getAttribute('pid'));
$('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)';
$('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;display:none"><img id="' + zoomobj['id'] + '" src="' + zoomobj['zimg'] + '"></div>';
setTimeout('zoomimgresize($(\'' + zoomobj['id'] + '\'))', 100);
if(is_ie) {
doane(event);
}
}
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';
c++;
if(c <= 5) {
setTimeout('zoomST(' + c + ')', 1);
} else {
$('zoomimglayer').style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100,style=0)';
$('zoomimglayer').style.opacity = 1;
zoomadjust = 1;
$('zoomimglayer').style.filter = '';
$('zoomimglayer_bg').style.display = '';
$('zoomimglayer').innerHTML = '<div class="zoominner"><p><span class="right"><a href="' + zoomobj['zimg'] + '" class="imglink" target="_blank" title="在新窗口打开">在新窗口打开</a><a href="javascipt:;" onclick="zoomimgadjust(event, 1)" class="imgadjust" title="实际大小">实际大小</a><a href="javascript:;" onclick="zoomclose()" class="imgclose" title="关闭">关闭</a></span>鼠标滚轮缩放图片</p><div id="zoomimgbox"><img id="zoomimg" style="cursor: move;" src="' + zoomobj['zimg'] + '" width="' + parseInt($('zoomimglayer').style.width) + '" height="' + parseInt($('zoomimglayer').style.height) + '"></div></div>';
$('zoomimglayer').style.overflow = 'visible';
$('zoomimglayer').style.width = (parseInt($('zoomimg').width < 300 ? 300 : parseInt($('zoomimg').width)) + 20) + 'px';
$('zoomimglayer').style.height = (parseInt($('zoomimg').height) + 20) + 'px';
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) {
if(!obj.complete) {
setTimeout('zoomimgresize($(\'' + obj.id + '\'))', 100);
return;
}
obj.parentNode.style.display = '';
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;
$('zoomimglayer').style.width = (parseInt($('zoomimg').width < 300 ? 300 : parseInt($('zoomimg').width)) + 20) + 'px';
$('zoomimglayer').style.height = (parseInt($('zoomimg').height) + 20) + 'px';
doane(e);
}
function zoomclose() {
$('zoomimglayer').innerHTML = '';
$('zoomimglayer').style.display = 'none';
$('zoomimglayer_bg').style.display = 'none';
}
function v_onPlayStart(videoId, isAvailability, length) {
ajaxget('video.php?action=updatevideoinfo&vid=' + videoId, '');
}
function parsetag(pid) {
if(!$('postmessage_'+pid)) {
return;
}
var havetag = false;
var tagfindarray = new Array();
var str = $('postmessage_'+pid).innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3, $4) {
for(i in tagarray) {
if(tagarray[i] && $3.indexOf(tagarray[i]) != -1) {
havetag = true;
$3 = $3.replace(tagarray[i], '<h_ ' + i + '>');
tmp = $3.replace(/&[a-z]*?<h_ \d+>[a-z]*?;/ig, '');
if(tmp != $3) {
$3 = tmp;
} else {
tagfindarray[i] = tagarray[i];
tagarray[i] = '';
}
}
}
return $2 + $3;
});
if(havetag) {
$('postmessage_'+pid).innerHTML = str.replace(/<h_ (\d+)>/ig, function($1, $2) {
return '<span href=\"tag.php?name=' + tagencarray[$2] + '\" onclick=\"tagshow(event)\" class=\"t_tag\">' + tagfindarray[$2] + '</span>';
});
}
}
function setanswer(pid){
if(confirm('您确认要把该回复选为“最佳答案”吗?')){
if(is_ie) {
doane(event);
}
$('modactions').action='misc.php?action=bestanswer&tid=' + tid + '&pid=' + pid + '&bestanswersubmit=yes';
$('modactions').submit();
}
}
var authort;
function showauthor(obj, id) {
authort = setTimeout("$('" + id + "').style.display = 'block';", 500);
if(!$(id).onmouseover) {
$(id + '_ma').innerHTML = $(id + '_a').innerHTML;
$(id).onmouseover = function() {
$(id).style.display = 'block';
}
$(id).onmouseout = function() {
$(id).style.display = 'none';
}
}
if(!obj.onmouseout) {
obj.onmouseout = function() {
clearTimeout(authort);
}
}
}
function fastpostvalidate(theform) {
s = '';
if(theform.message.value == '' && theform.subject.value == '') {
s = '请完成标题或内容栏。';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = '您的标题超过 80 个字符的限制。';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = '您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(theform.message.value) + ' ' + '字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节';
}
if(s) {
$('fastpostreturn').className = 'onerror';
$('fastpostreturn').innerHTML = s;
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = parseurl(theform.message.value);
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('replysubmit'));
return false;
}
function fastpostappendreply() {
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
$('fastpostsubmit').disabled = false;
$('fastpostmessage').value = '';
if($('secanswer3')) {
$('checksecanswer3').innerHTML = '<img src="images/common/none.gif" width="17" height="17">';
$('secanswer3').value = '';
secclick3['secanswer3'] = 0;
}
if($('seccodeverify3')) {
$('checkseccodeverify3').innerHTML = '<img src="images/common/none.gif" width="17" height="17">';
$('seccodeverify3').value = '';
secclick3['seccodeverify3'] = 0;
}
creditnoticewin();
}
function submithandle_fastpost(locationhref) {
var pid = locationhref.lastIndexOf('#pid');
if(pid != -1) {
pid = locationhref.substr(pid + 4);
ajaxget('viewthread.php?tid=' + tid + '&viewpid=' + pid, 'post_new', 'ajaxwaitid', '', null, 'fastpostappendreply()');
if(replyreload) {
var reloadpids = replyreload.split(',');
for(i = 1;i < reloadpids.length;i++) {
ajaxget('viewthread.php?tid=' + tid + '&viewpid=' + reloadpids[i], 'post_' + reloadpids[i]);
}
}
$('fastpostreturn').className = '';
} else {
$('post_new').style.display = $('fastpostmessage').value = $('fastpostreturn').className = '';
$('fastpostreturn').innerHTML = '本版回帖需要审核,您的帖子将在通过审核后显示';
}
}
function messagehandle_fastpost() {
$('fastpostsubmit').disabled = false;
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/viewthread.js
|
JavaScript
|
asf20
| 14,745
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: bbcode.js 17473 2008-12-25 02:10:55Z monkey $
*/
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', false);
}
}
if(!fetchCheckbox('smileyoff') && allowsmilies) {
if(typeof smilies_type == 'object') {
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
re = new RegExp(addslashes(smilies_array[typeid][page][i][1]), "g");
str = str.replace(re, '<img src="./images/smilies/' + smilies_type[typeid][1] + '/' + smilies_array[typeid][page][i][2] + '" border="0" smilieid="' + smilies_array[typeid][page][i][0] + '" alt="' + smilies_array[typeid][page][i][1] + '" />');
}
}
}
}
}
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 class="litype_1">', '<ul type=a class="litype_2">',
'<ul type=A class="litype_3">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
], str, 'g');
}
if(!fetchCheckbox('bbcodeoff')) {
if(allowimgcode) {
str = str.replace(/\[localimg=(\d{1,4}),(\d{1,4})\](\d+)\[\/localimg\]/ig, function ($1, $2, $3, $4) {if($('attachnew_' + $4)) {var src = $('attachnew_' + $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 + '\')');width = is_ie ? parseInt(attachimg.currentStyle.width) : attachimg.width;return '<img src="' + attachimg.src + '" border="0" aid="attachimg_' + $2 + '" width="' + width + '" 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[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
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', false);
}
str = str.replace(/<br\s+?style=(["']?)clear: both;?(\1)[^\>]*>/ig, '');
str = str.replace(/<br[^\>]*>/ig, "\n");
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 smileycode($3);});
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 = 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(['&', '<', '>', '"'], ['&', '<', '>', '"'], 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++;
codehtml[codecount] = '[code]' + htmlspecialchars(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, regswitch) {
var regswitch = !regswitch ? 'ig' : regswitch;
var len = search.length;
for(var i = 0; i < len; i++) {
re = new RegExp(search[i], regswitch);
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 smileycode(smileyid) {
if(typeof smilies_type != 'object') return;
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
if(smilies_array[typeid][page][i][0] == smileyid) {
return smilies_array[typeid][page][i][1];
break;
}
}
}
}
}
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/51shangcheng.cn/htdocs/include/js/bbcode.js
|
JavaScript
|
asf20
| 20,520
|
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.createElement||!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
//this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.skipDetect=true;
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
if(c){this.addParam("bgcolor",c);}else{this.addParam("wmode","transparent");}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){
_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+=" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"/>";
}else{
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();
return true;
}else{
if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
var _25=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=15;i>6;i--){
try{
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
_25=new deconcept.PlayerVersion([i,0,0]);
break;}
catch(e){}}}
catch(e){}
if(_23&&_25.major>_23.major){return _25;}
if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
catch(e){}}}
return _25;};
deconcept.PlayerVersion=function(_29){
this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
this.minor=parseInt(_29[1])||0;
this.rev=parseInt(_29[2])||0;};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}return true;};
deconcept.util={getRequestParameter:function(_2b){
var q=document.location.search||document.location.hash;
if(q){
var _2d=q.indexOf(_2b+"=");
var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
if(q.length>1&&_2d>-1){
return q.substring(q.indexOf("=",_2d)+1,_2e);
}}return "";}};
if(Array.prototype.push==null){
Array.prototype.push=function(_2f){
this[this.length]=_2f;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject; // for backwards compatibility
var SWFObject=deconcept.SWFObject;
if(typeof video_uploader_show == 'function') {
video_uploader_show();
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/video.js
|
JavaScript
|
asf20
| 6,054
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: md5.js 16688 2008-11-14 06:41:07Z cnteacher $
*/
var hexcase = 0;
var chrsz = 8;
function hex_md5(s){
return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}
function core_md5(x, len) {
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/md5.js
|
JavaScript
|
asf20
| 5,334
|
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" class="txt" size="20" name="q" id="q" maxlength="255" value=""></input>');
document.writeln('<select name="site">');
document.writeln('<option value="0"' + google_default_0 + '>网页搜索</option>');
document.writeln('<option value="1"' + google_default_1 + '>站内搜索</option>');
document.writeln('</select>');
document.writeln(' <button type="submit" name="sa" value="true">搜索</button>');
document.writeln('</form>');
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/js/google.js
|
JavaScript
|
asf20
| 2,095
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: qihoo.js 17449 2008-12-22 08:58:53Z cnteacher $
*/
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?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/51shangcheng.cn/htdocs/include/js/qihoo.js
|
JavaScript
|
asf20
| 2,508
|
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: iframe.js 17449 2008-12-22 08:58:53Z cnteacher $
*/
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/51shangcheng.cn/htdocs/include/js/iframe.js
|
JavaScript
|
asf20
| 580
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cron.func.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function runcron($cronid = 0) {
global $timestamp, $db, $tablepre, $_DCACHE;
if($cron = $db->fetch_first("SELECT * FROM {$tablepre}crons WHERE ".($cronid ? "cronid='$cronid'" : "available>'0' AND nextrun<='$timestamp'")." ORDER BY nextrun LIMIT 1")) {
$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);
}
$nextrun = $db->result_first("SELECT nextrun FROM {$tablepre}crons WHERE available>'0' ORDER BY nextrun LIMIT 1");
if(!$nextrun === FALSE) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
$_DCACHE['settings']['cronnextrun'] = $nextrun;
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 ? $cron['minute'] : 0, 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/51shangcheng.cn/htdocs/include/cron.func.php
|
PHP
|
asf20
| 4,801
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_activity.inc.php 17393 2008-12-17 07:30:46Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$sdb = loadmultiserver();
$applylist = array();
$activity = $sdb->fetch_first("SELECT * FROM {$tablepre}activities WHERE tid='$tid'");
$activityclose = $activity['expiration'] ? ($activity['expiration'] > $timestamp - date('Z') ? 0 : 1) : 0;
$activity['starttimefrom'] = dgmdate("$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;
}
}
$query = $db->query("SELECT aa.username, aa.uid, aa.dateline, aa.message, aa.payment, aa.contact, m.groupid FROM {$tablepre}activityapplies aa
LEFT JOIN {$tablepre}members m USING(uid)
LEFT JOIN {$tablepre}memberfields mf USING(uid)
WHERE aa.tid='$tid' AND aa.verified=1 ORDER BY aa.dateline DESC LIMIT 9");
while($activityapplies = $db->fetch_array($query)) {
$activityapplies['dateline'] = dgmdate("$dateformat $timeformat", $activityapplies['dateline'] + $timeoffset * 3600);
$applylist[] = $activityapplies;
}
if($thread['authorid'] == $discuz_uid) {
$applylistverified = array();
$query = $db->query("SELECT aa.username, aa.uid, aa.dateline, aa.message, aa.payment, aa.contact, m.groupid FROM {$tablepre}activityapplies aa
LEFT JOIN {$tablepre}members m USING(uid)
LEFT JOIN {$tablepre}memberfields mf USING(uid)
WHERE aa.tid='$tid' AND aa.verified=0 ORDER BY aa.dateline DESC LIMIT 9");
while($activityapplies = $db->fetch_array($query)) {
$activityapplies['dateline'] = dgmdate("$dateformat $timeformat", $activityapplies['dateline'] + $timeoffset * 3600);
$applylistverified[] = $activityapplies;
}
}
$applynumbers = $db->result_first("SELECT COUNT(*) FROM {$tablepre}activityapplies WHERE tid='$tid' AND verified=1");
$aboutmembers = $activity['number'] >= $applynumbers ? $activity['number'] - $applynumbers : 0;
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/viewthread_activity.inc.php
|
PHP
|
asf20
| 2,518
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: seccode.class.php 16698 2008-11-14 07:58:56Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class seccode {
var $code;
var $type = 0;
var $width = 150;
var $height = 60;
var $background = 1;
var $adulterate = 1;
var $ttf = 0;
var $angle = 0;
var $color = 1;
var $size = 0;
var $shadow = 1;
var $animator = 0;
var $fontpath = '';
var $datapath = '';
var $includepath= '';
var $fontcolor;
var $im;
function display() {
$this->type == 2 && !extension_loaded('ming') && $this->type = 0;
$this->width = $this->width >= 100 && $this->width <= 200 ? $this->width : 150;
$this->height = $this->height >= 50 && $this->height <= 80 ? $this->height : 60;
seccodeconvert($this->code);
if($this->type < 2 && function_exists('imagecreate') && function_exists('imagecolorset') && function_exists('imagecopyresized') &&
function_exists('imagecolorallocate') && function_exists('imagechar') && function_exists('imagecolorsforindex') &&
function_exists('imageline') && function_exists('imagecreatefromstring') && (function_exists('imagegif') || function_exists('imagepng') || function_exists('imagejpeg'))) {
$this->image();
} elseif($this->type == 2 && extension_loaded('ming')) {
$this->flash();
} elseif($this->type == 3) {
$this->audio();
} else {
$this->bitmap();
}
}
function image() {
$bgcontent = $this->background();
if($this->animator == 1 && function_exists('imagegif')) {
include_once $this->includepath.'gifmerge.class.php';
$trueframe = mt_rand(1, 9);
for($i = 0; $i <= 9; $i++) {
$this->im = imagecreatefromstring($bgcontent);
$x[$i] = $y[$i] = 0;
$this->adulterate && $this->adulterate();
if($i == $trueframe) {
$this->ttf && function_exists('imagettftext') || $this->type == 1 ? $this->ttffont() : $this->giffont();
$d[$i] = mt_rand(250, 400);
} else {
$this->adulteratefont();
$d[$i] = mt_rand(5, 15);
}
ob_start();
imagegif($this->im);
imagedestroy($this->im);
$frame[$i] = ob_get_contents();
ob_end_clean();
}
$anim = new GifMerge($frame, 255, 255, 255, 0, $d, $x, $y, 'C_MEMORY');
dheader('Content-type: image/gif');
echo $anim->getAnimation();
} else {
$this->im = imagecreatefromstring($bgcontent);
$this->adulterate && $this->adulterate();
$this->ttf && function_exists('imagettftext') || $this->type == 1 ? $this->ttffont() : $this->giffont();
if(function_exists('imagepng')) {
dheader('Content-type: image/png');
imagepng($this->im);
} else {
dheader('Content-type: image/jpeg');
imagejpeg($this->im, '', 100);
}
imagedestroy($this->im);
}
}
function background() {
$this->im = imagecreatetruecolor($this->width, $this->height);
$backgroundcolor = imagecolorallocate($this->im, 255, 255, 255);
$backgrounds = $c = array();
if($this->background && function_exists('imagecreatefromjpeg') && function_exists('imagecolorat') && function_exists('imagecopymerge') &&
function_exists('imagesetpixel') && function_exists('imageSX') && function_exists('imageSY')) {
if($handle = @opendir($this->datapath.'background/')) {
while($bgfile = @readdir($handle)) {
if(preg_match('/\.jpg$/i', $bgfile)) {
$backgrounds[] = $this->datapath.'background/'.$bgfile;
}
}
@closedir($handle);
}
if($backgrounds) {
$imwm = imagecreatefromjpeg($backgrounds[array_rand($backgrounds)]);
$colorindex = imagecolorat($imwm, 0, 0);
$this->c = imagecolorsforindex($imwm, $colorindex);
$colorindex = imagecolorat($imwm, 1, 0);
imagesetpixel($imwm, 0, 0, $colorindex);
$c[0] = $c['red'];$c[1] = $c['green'];$c[2] = $c['blue'];
imagecopymerge($this->im, $imwm, 0, 0, mt_rand(0, 200 - $this->width), mt_rand(0, 80 - $this->height), imageSX($imwm), imageSY($imwm), 100);
imagedestroy($imwm);
}
}
if(!$this->background || !$backgrounds) {
for($i = 0;$i < 3;$i++) {
$start[$i] = mt_rand(200, 255);$end[$i] = mt_rand(100, 150);$step[$i] = ($end[$i] - $start[$i]) / $this->width;$c[$i] = $start[$i];
}
for($i = 0;$i < $this->width;$i++) {
$color = imagecolorallocate($this->im, $c[0], $c[1], $c[2]);
imageline($this->im, $i, 0, $i-$angle, $this->height, $color);
$c[0] += $step[0];$c[1] += $step[1];$c[2] += $step[2];
}
$c[0] -= 20;$c[1] -= 20;$c[2] -= 20;
}
ob_start();
if(function_exists('imagepng')) {
imagepng($this->im);
} else {
imagejpeg($this->im, '', 100);
}
imagedestroy($this->im);
$bgcontent = ob_get_contents();
ob_end_clean();
$this->fontcolor = $c;
return $bgcontent;
}
function adulterate() {
$linenums = $this->height / 10;
for($i=0; $i <= $linenums; $i++) {
$color = $this->color ? imagecolorallocate($this->im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)) : imagecolorallocate($this->im, $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
$x = mt_rand(0, $this->width);
$y = mt_rand(0, $this->height);
if(mt_rand(0, 1)) {
imagearc($this->im, $x, $y, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, 360), mt_rand(0, 360), $color);
} else {
imageline($this->im, $x, $y, $linex + mt_rand(0, $linemaxlong), $liney + mt_rand(0, mt_rand($this->height, $this->width)), $color);
}
}
}
function adulteratefont() {
$seccodeunits = 'BCEFGHJKMPQRTVWXY2346789';
$x = $this->width / 4;
$y = $this->height / 10;
$text_color = imagecolorallocate($this->im, $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
for($i = 0; $i <= 3; $i++) {
$adulteratecode = $seccodeunits[mt_rand(0, 23)];
imagechar($this->im, 5, $x * $i + mt_rand(0, $x - 10), mt_rand($y, $this->height - 10 - $y), $adulteratecode, $text_color);
}
}
function ttffont() {
$seccode = $this->code;
$charset = $GLOBALS['charset'];
$seccoderoot = $this->type ? $this->fontpath.'ch/' : $this->fontpath.'en/';
$dirs = opendir($seccoderoot);
$seccodettf = array();
while($entry = readdir($dirs)) {
if($entry != '.' && $entry != '..' && in_array(strtolower(fileext($entry)), array('ttf', 'ttc'))) {
$seccodettf[] = $entry;
}
}
if(empty($seccodettf)) {
$this->giffont();
return;
}
$seccodelength = 4;
if($this->type && !empty($seccodettf)) {
if(strtoupper($charset) != 'UTF-8') {
include $this->includepath.'chinese.class.php';
$cvt = new Chinese($charset, 'utf8');
$seccode = $cvt->Convert($seccode);
}
$seccode = array(substr($seccode, 0, 3), substr($seccode, 3, 3));
$seccodelength = 2;
}
$widthtotal = 0;
for($i = 0; $i < $seccodelength; $i++) {
$font[$i]['font'] = $seccoderoot.$seccodettf[array_rand($seccodettf)];
$font[$i]['angle'] = $this->angle ? mt_rand(-30, 30) : 0;
$font[$i]['size'] = $this->type ? $this->width / 7 : $this->width / 6;
$this->size && $font[$i]['size'] = mt_rand($font[$i]['size'] - $this->width / 40, $font[$i]['size'] + $this->width / 20);
$box = imagettfbbox($font[$i]['size'], 0, $font[$i]['font'], $seccode[$i]);
$font[$i]['zheight'] = max($box[1], $box[3]) - min($box[5], $box[7]);
$box = imagettfbbox($font[$i]['size'], $font[$i]['angle'], $font[$i]['font'], $seccode[$i]);
$font[$i]['height'] = max($box[1], $box[3]) - min($box[5], $box[7]);
$font[$i]['hd'] = $font[$i]['height'] - $font[$i]['zheight'];
$font[$i]['width'] = (max($box[2], $box[4]) - min($box[0], $box[6])) + mt_rand(0, $this->width / 8);
$font[$i]['width'] = $font[$i]['width'] > $this->width / $seccodelength ? $this->width / $seccodelength : $font[$i]['width'];
$widthtotal += $font[$i]['width'];
}
$x = mt_rand($font[0]['angle'] > 0 ? cos(deg2rad(90 - $font[0]['angle'])) * $font[0]['zheight'] : 1, $this->width - $widthtotal);
!$this->color && $text_color = imagecolorallocate($this->im, $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
for($i = 0; $i < $seccodelength; $i++) {
if($this->color) {
$this->fontcolor = array(mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
$this->shadow && $text_shadowcolor = imagecolorallocate($this->im, 255 - $this->fontcolor[0], 255 - $this->fontcolor[1], 255 - $this->fontcolor[2]);
$text_color = imagecolorallocate($this->im, $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
} elseif($this->shadow) {
$text_shadowcolor = imagecolorallocate($this->im, 255 - $this->fontcolor[0], 255 - $this->fontcolor[1], 255 - $this->fontcolor[2]);
}
$y = $font[0]['angle'] > 0 ? mt_rand($font[$i]['height'], $this->height) : mt_rand($font[$i]['height'] - $font[$i]['hd'], $this->height - $font[$i]['hd']);
$this->shadow && imagettftext($this->im, $font[$i]['size'], $font[$i]['angle'], $x + 1, $y + 1, $text_shadowcolor, $font[$i]['font'], $seccode[$i]);
imagettftext($this->im, $font[$i]['size'], $font[$i]['angle'], $x, $y, $text_color, $font[$i]['font'], $seccode[$i]);
$x += $font[$i]['width'];
}
}
function giffont() {
$seccode = $this->code;
$seccodedir = array();
if(function_exists('imagecreatefromgif')) {
$seccoderoot = $this->datapath.'gif/';
$dirs = opendir($seccoderoot);
while($dir = readdir($dirs)) {
if($dir != '.' && $dir != '..' && file_exists($seccoderoot.$dir.'/9.gif')) {
$seccodedir[] = $dir;
}
}
}
$widthtotal = 0;
for($i = 0; $i <= 3; $i++) {
$this->imcodefile = $seccodedir ? $seccoderoot.$seccodedir[array_rand($seccodedir)].'/'.strtolower($seccode[$i]).'.gif' : '';
if(!empty($this->imcodefile) && file_exists($this->imcodefile)) {
$font[$i]['file'] = $this->imcodefile;
$font[$i]['data'] = getimagesize($this->imcodefile);
$font[$i]['width'] = $font[$i]['data'][0] + mt_rand(0, 6) - 4;
$font[$i]['height'] = $font[$i]['data'][1] + mt_rand(0, 6) - 4;
$font[$i]['width'] += mt_rand(0, $this->width / 5 - $font[$i]['width']);
$widthtotal += $font[$i]['width'];
} else {
$font[$i]['file'] = '';
$font[$i]['width'] = 8 + mt_rand(0, $this->width / 5 - 5);
$widthtotal += $font[$i]['width'];
}
}
$x = mt_rand(1, $this->width - $widthtotal);
for($i = 0; $i <= 3; $i++) {
$this->color && $this->fontcolor = array(mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
if($font[$i]['file']) {
$this->imcode = imagecreatefromgif($font[$i]['file']);
if($this->size) {
$font[$i]['width'] = mt_rand($font[$i]['width'] - $this->width / 20, $font[$i]['width'] + $this->width / 20);
$font[$i]['height'] = mt_rand($font[$i]['height'] - $this->width / 20, $font[$i]['height'] + $this->width / 20);
}
$y = mt_rand(0, $this->height - $font[$i]['height']);
if($this->shadow) {
$this->imcodeshadow = $this->imcode;
imagecolorset($this->imcodeshadow, 0 , 255 - $this->fontcolor[0], 255 - $this->fontcolor[1], 255 - $this->fontcolor[2]);
imagecopyresized($this->im, $this->imcodeshadow, $x + 1, $y + 1, 0, 0, $font[$i]['width'], $font[$i]['height'], $font[$i]['data'][0], $font[$i]['data'][1]);
}
imagecolorset($this->imcode, 0 , $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
imagecopyresized($this->im, $this->imcode, $x, $y, 0, 0, $font[$i]['width'], $font[$i]['height'], $font[$i]['data'][0], $font[$i]['data'][1]);
} else {
$y = mt_rand(0, $this->height - 20);
if($this->shadow) {
$text_shadowcolor = imagecolorallocate($this->im, 255 - $this->fontcolor[0], 255 - $this->fontcolor[1], 255 - $this->fontcolor[2]);
imagechar($this->im, 5, $x + 1, $y + 1, $seccode[$i], $text_shadowcolor);
}
$text_color = imagecolorallocate($this->im, $this->fontcolor[0], $this->fontcolor[1], $this->fontcolor[2]);
imagechar($this->im, 5, $x, $y, $seccode[$i], $text_color);
}
$x += $font[$i]['width'];
}
}
function flash() {
$spacing = 5;
$codewidth = ($this->width - $spacing * 5) / 4;
$strforswdaction = '';
for($i = 0; $i <= 3; $i++) {
$strforswdaction .= $this->swfcode($codewidth, $spacing, $this->code[$i], $i+1);
}
ming_setScale(20.00000000);
ming_useswfversion(6);
$movie = new SWFMovie();
$movie->setDimension($this->width, $this->height);
$movie->setBackground(255, 255, 255);
$movie->setRate(31);
$fontcolor = '0x'.(sprintf('%02s', dechex (mt_rand(0, 255)))).(sprintf('%02s', dechex (mt_rand(0, 128)))).(sprintf('%02s', dechex (mt_rand(0, 255))));
$strAction = "
_root.createEmptyMovieClip ( 'triangle', 1 );
with ( _root.triangle ) {
lineStyle( 3, $fontcolor, 100 );
$strforswdaction
}
";
$movie->add(new SWFAction( str_replace("\r", "", $strAction) ));
header('Content-type: application/x-shockwave-flash');
$movie->output();
}
function swfcode($width, $d, $code, $order) {
$str = '';
$height = $this->height - $d * 2;
$x_0 = ($order * ($width + $d) - $width);
$x_1 = $x_0 + $width / 2;
$x_2 = $x_0 + $width;
$y_0 = $d;
$y_2 = $y_0 + $height;
$y_1 = $y_2 / 2;
$y_0_5 = $y_2 / 4;
$y_1_5 = $y_1 + $y_0_5;
switch($code) {
case 'B':$str .= 'moveTo('.$x_1.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_1.', '.$y_2.');lineTo('.$x_2.', '.$y_1_5.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_0_5.');lineTo('.$x_1.', '.$y_0.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');';break;
case 'C':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');';break;
case 'E':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');';break;
case 'F':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');';break;
case 'G':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_2.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');';break;
case 'H':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');moveTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_2.', '.$y_1.');';break;
case 'J':$str .= 'moveTo('.$x_1.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_0.', '.$y_1_5.');';break;
case 'K':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_0.', '.$y_1.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');moveTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_2.');';break;
case 'M':$str .= 'moveTo('.$x_0.', '.$y_2.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');';break;
case 'P':$str .= 'moveTo('.$x_0.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_0_5.');lineTo('.$x_1.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');';break;
case 'Q':$str .= 'moveTo('.$x_2.', '.$y_2.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_1.', '.$y_1.');';break;
case 'R':$str .= 'moveTo('.$x_0.', '.$y_1.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_0_5.');lineTo('.$x_1.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');moveTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_2.');';break;
case 'T':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');moveTo('.$x_1.', '.$y_0.');lineTo('.$x_1.', '.$y_2.');';break;
case 'V':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_1.', '.$y_2.');lineTo('.$x_2.', '.$y_0.');';break;
case 'W':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_2.', '.$y_0.');';break;
case 'X':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');';break;
case 'Y':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_1.', '.$y_1.');lineTo('.$x_2.', '.$y_0.');moveTo('.$x_1.', '.$y_1.');lineTo('.$x_1.', '.$y_2.');';break;
case '2':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_1.');lineTo('.$x_0.', '.$y_1.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');';break;
case '3':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_0.', '.$y_2.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_2.', '.$y_1.');';break;
case '4':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');moveTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_1.');lineTo('.$x_2.', '.$y_1.');';break;
case '6':$str .= 'moveTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_2.', '.$y_1.');lineTo('.$x_0.', '.$y_1.');';break;
case '7':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');';break;
case '8':$str .= 'moveTo('.$x_0.', '.$y_0.');lineTo('.$x_0.', '.$y_2.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_0.', '.$y_0.');moveTo('.$x_0.', '.$y_1.');lineTo('.$x_2.', '.$y_1.');';break;
case '9':$str .= 'moveTo('.$x_2.', '.$y_1.');lineTo('.$x_0.', '.$y_1.');lineTo('.$x_0.', '.$y_0.');lineTo('.$x_2.', '.$y_0.');lineTo('.$x_2.', '.$y_2.');lineTo('.$x_0.', '.$y_2.');';break;
}
return $str;
}
function audio() {
header('Content-type: audio/mpeg');
for($i = 0;$i <= 3; $i++) {
readfile($this->datapath.'sound/'.strtolower($this->code[$i]).'.mp3');
}
}
function bitmap() {
$numbers = array
(
'B' => array('00','fc','66','66','66','7c','66','66','fc','00'),
'C' => array('00','38','64','c0','c0','c0','c4','64','3c','00'),
'E' => array('00','fe','62','62','68','78','6a','62','fe','00'),
'F' => array('00','f8','60','60','68','78','6a','62','fe','00'),
'G' => array('00','78','cc','cc','de','c0','c4','c4','7c','00'),
'H' => array('00','e7','66','66','66','7e','66','66','e7','00'),
'J' => array('00','f8','cc','cc','cc','0c','0c','0c','7f','00'),
'K' => array('00','f3','66','66','7c','78','6c','66','f7','00'),
'M' => array('00','f7','63','6b','6b','77','77','77','e3','00'),
'P' => array('00','f8','60','60','7c','66','66','66','fc','00'),
'Q' => array('00','78','cc','cc','cc','cc','cc','cc','78','00'),
'R' => array('00','f3','66','6c','7c','66','66','66','fc','00'),
'T' => array('00','78','30','30','30','30','b4','b4','fc','00'),
'V' => array('00','1c','1c','36','36','36','63','63','f7','00'),
'W' => array('00','36','36','36','77','7f','6b','63','f7','00'),
'X' => array('00','f7','66','3c','18','18','3c','66','ef','00'),
'Y' => array('00','7e','18','18','18','3c','24','66','ef','00'),
'2' => array('fc','c0','60','30','18','0c','cc','cc','78','00'),
'3' => array('78','8c','0c','0c','38','0c','0c','8c','78','00'),
'4' => array('00','3e','0c','fe','4c','6c','2c','3c','1c','1c'),
'6' => array('78','cc','cc','cc','ec','d8','c0','60','3c','00'),
'7' => array('30','30','38','18','18','18','1c','8c','fc','00'),
'8' => array('78','cc','cc','cc','78','cc','cc','cc','78','00'),
'9' => array('f0','18','0c','6c','dc','cc','cc','cc','78','00')
);
foreach($numbers as $i => $number) {
for($j = 0; $j < 6; $j++) {
$a1 = substr('012', mt_rand(0, 2), 1).substr('012345', mt_rand(0, 5), 1);
$a2 = substr('012345', mt_rand(0, 5), 1).substr('0123', mt_rand(0, 3), 1);
mt_rand(0, 1) == 1 ? array_push($numbers[$i], $a1) : array_unshift($numbers[$i], $a1);
mt_rand(0, 1) == 0 ? array_push($numbers[$i], $a1) : array_unshift($numbers[$i], $a2);
}
}
$bitmap = array();
for($i = 0; $i < 20; $i++) {
for($j = 0; $j <= 3; $j++) {
$bytes = $numbers[$this->code[$j]][$i];
$a = mt_rand(0, 14);
array_push($bitmap, $bytes);
}
}
for($i = 0; $i < 8; $i++) {
$a = substr('012345', mt_rand(0, 2), 1) . substr('012345', mt_rand(0, 5), 1);
array_unshift($bitmap, $a);
array_push($bitmap, $a);
}
$image = pack('H*', '424d9e000000000000003e000000280000002000000018000000010001000000'.
'0000600000000000000000000000000000000000000000000000FFFFFF00'.implode('', $bitmap));
dheader('Content-Type: image/bmp');
echo $image;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/seccode.class.php
|
PHP
|
asf20
| 20,720
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Technology Ltd.
This is NOT a freeware, use is subject to license terms
$Id: ec_credit.func.php 16688 2008-11-14 06:41:07Z 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;
}
if($cache = $db->fetch_first("SELECT value, expiration FROM {$tablepre}spacecaches WHERE uid='$uid' AND variable='$type'")) {
$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/51shangcheng.cn/htdocs/include/ec_credit.func.php
|
PHP
|
asf20
| 3,023
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: xmlparser.class.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/xmlparser.class.php
|
PHP
|
asf20
| 2,451
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: threadpay.inc.php 17362 2008-12-16 03:30:55Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!isset($extcredits[$creditstransextra[1]])) {
showmessage('credits_transaction_disabled');
}
$payment = $db->fetch_first("SELECT COUNT(*) AS payers, SUM(netamount) AS income FROM {$tablepre}paymentlog WHERE tid='$tid'");
$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 ? dgmdate("$dateformat $timeformat", $thread['dateline'] + $maxchargespan * 3600 + $timeoffset * 3600) : 0;
$firstpost = $db->fetch_first("SELECT * FROM {$tablepre}posts WHERE tid='$tid' AND first='1' LIMIT 1");
$pid = $firstpost['pid'];
$freemessage = array();
$freemessage[$pid]['message'] = '';
if(preg_match_all("/\[free\](.+?)\[\/free\]/is", $firstpost['message'], $matches)) {
foreach($matches[1] AS $match) {
$freemessage[$pid]['message'] .= discuzcode($match, $firstpost['smileyoff'], $firstpost['bbcodeoff'], sprintf('%00b', $firstpost['htmlon']), $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'], $forum['allowhtml'], 0).'<br />';
}
}
$attachtags = array();
if($allowgetattach) {
if(preg_match_all("/\[attach\](\d+)\[\/attach\]/i", $freemessage[$pid]['message'], $matchaids)) {
$attachtags[$pid] = $matchaids[1];
}
}
if($attachtags) {
require_once DISCUZ_ROOT.'./include/attachment.func.php';
parseattach($pid, $attachtags, $freemessage, $showimages);
}
$thread['freemessage'] = $freemessage[$pid]['message'];
unset($freemessage);
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/threadpay.inc.php
|
PHP
|
asf20
| 1,872
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forumselect.inc.php 16698 2008-11-14 07:58:56Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!isset($_DCACHE['forums'])) {
require_once DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';
}
$grouplist = $commonlist = '';
$forumlist = $subforumlist = array();
$i = array();
$commonfids = explode('D', $_DCOOKIE['visitedfid']);
if($discuz_uid) {
$query = $db->query("SELECT fid FROM {$tablepre}favorites WHERE uid='$discuz_uid' AND fid>0");
while($fav = $db->fetch_array($query)) {
$commonfids[] = $fav['fid'];
}
}
foreach($commonfids as $k => $fid) {
if($_DCACHE['forums'][$fid]['type'] == 'sub') {
$commonfids[] = $_DCACHE['forums'][$fid]['fup'];
unset($commonfids[$k]);
}
}
$commonfids = array_unique($commonfids);
foreach($commonfids as $fid) {
$commonlist .= '<li fid="'.$fid.'">'.$_DCACHE['forums'][$fid]['name'].'</li>';
}
foreach($_DCACHE['forums'] as $forum) {
if($forum['type'] == 'group') {
$grouplist .= '<li fid="'.$forum['fid'].'">'.$forum['name'].'</li>';
$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"))) {
$forumlist[$forum['fup']] .= '<li fid="'.$forum['fid'].'">'.$forum['name'].'</li>';
$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"))) {
$subforumlist[$forum['fup']] .= '<li fid="'.$forum['fid'].'">'.$forum['name'].'</li>';
}
}
include template('post_forumselect');
exit;
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/forumselect.inc.php
|
PHP
|
asf20
| 1,883
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editor.func.php 17417 2008-12-19 06:16:25Z liuqiang $
*/
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",
"/<span\s+?style=\"float:\s+(left|right);\">(.+?)<\/span>/is",
);
$pregreplace = array(
'',
'',
'',
"tabletag('\\1')",
'[table]',
'[tr]',
'[td]',
"tdtag('\\1')",
'[/td]',
'[/tr]',
'[/table]',
"[size=\\1]\\2[/size]\n\n",
"smileycode('\\1')",
"imgtag('\\1')",
'\1',
"\n",
"[float=\\1]\\2[/float]",
);
$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['smileycodes'])) {
@include DISCUZ_ROOT.'./forumdata/cache/cache_post.php';
}
foreach($_DCACHE['smileycodes'] as $id => $code) {
if($smileyid == $id) {
return $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/51shangcheng.cn/htdocs/include/editor.func.php
|
PHP
|
asf20
| 12,713
|
<?
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: image.class.php 17503 2009-01-05 02:21:45Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class Image {
var $attachinfo = '';
var $targetfile = '';
var $imagecreatefromfunc = '';
var $imagefunc = '';
var $attach = array();
var $animatedgif = 0;
var $error = 0;
function Image($targetfile, $attach = array()) {
global $imagelib, $watermarktext, $imageimpath;
$this->targetfile = $targetfile;
$this->attach = $attach;
$this->attachinfo = @getimagesize($targetfile);
if(!$imagelib || !$imageimpath) {
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') {
if($this->imagecreatefromfunc && !@imagecreatefromgif($targetfile)) {
$this->error = 1;
$this->imagecreatefromfunc = $this->imagefunc = '';
return FALSE;
}
$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->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, $thumbquality;
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)) {
if($thumbstatus != 3) {
$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';
$cx = $img_w;
$cy = $img_h;
} else {
$attach_photo = $imagecreatefromfunc($this->targetfile);
$imgratio = $img_w / $img_h;
$thumbratio = $thumbwidth / $thumbheight;
if($imgratio >= 1 && $imgratio >= $thumbratio || $imgratio < 1 && $imgratio > $thumbratio) {
$cuty = $img_h;
$cutx = $cuty * $thumbratio;
} elseif($imgratio >= 1 && $imgratio <= $thumbratio || $imgratio < 1 && $imgratio < $thumbratio) {
$cutx = $img_w;
$cuty = $cutx / $thumbratio;
}
$dst_photo = imagecreatetruecolor($cutx, $cuty);
imageCopyMerge($dst_photo, $attach_photo, 0, 0, 0, 0, $cutx, $cuty, 100);
$thumb['width'] = $thumbwidth;
$thumb['height'] = $thumbheight;
$targetfile = !$preview ? $this->targetfile.'.thumb.jpg' : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
$cx = $cutx;
$cy = $cuty;
}
$thumb_photo = imagecreatetruecolor($thumb['width'], $thumb['height']);
imageCopyreSampled($thumb_photo, $attach_photo ,0, 0, 0, 0, $thumb['width'], $thumb['height'], $cx, $cy);
clearstatcache();
if($this->attachinfo['mime'] == 'image/jpeg') {
$imagefunc($thumb_photo, $targetfile, $thumbquality);
} else {
$imagefunc($thumb_photo, $targetfile);
}
$this->attach['thumb'] = $thumbstatus == 1 || $thumbstatus == 3 ? 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';
clearstatcache();
if($this->attachinfo['mime'] == 'image/jpeg') {
$imagefunc($dst_photo, $targetfile, $watermarkquality);
} else {
$imagefunc($dst_photo, $targetfile);
}
$this->attach['size'] = filesize($targetfile);
}
}
}
function Thumb_IM($thumbwidth, $thumbheight, $preview = 0) {
global $thumbstatus, $imageimpath, $thumbquality;
if($thumbstatus) {
list($img_w, $img_h) = $this->attachinfo;
$targetfile = !$preview ? ($thumbstatus == 1 || $thumbstatus == 3 ? $this->targetfile.'.thumb.jpg' : $this->targetfile) : DISCUZ_ROOT.'./forumdata/watermark_temp.jpg';
if(!$this->animatedgif && ($img_w >= $thumbwidth || $img_h >= $thumbheight)) {
if($thumbstatus != 3) {
$exec_str = $imageimpath.'/convert -quality '.intval($thumbquality).' -geometry '.$thumbwidth.'x'.$thumbheight.' '.$this->targetfile.' '.$targetfile;
@exec($exec_str, $output, $return);
if(empty($return) && empty($output)) {
$this->attach['thumb'] = $thumbstatus == 1 ? 1 : 0;
}
} else {
$imgratio = $img_w / $img_h;
$thumbratio = $thumbwidth / $thumbheight;
if($imgratio >= 1 && $imgratio >= $thumbratio || $imgratio < 1 && $imgratio > $thumbratio) {
$cuty = $img_h;
$cutx = $cuty * $thumbratio;
} elseif($imgratio >= 1 && $imgratio <= $thumbratio || $imgratio < 1 && $imgratio < $thumbratio) {
$cutx = $img_w;
$cuty = $cutx / $thumbratio;
}
$exec_str = $imageimpath.'/convert -crop '.$cutx.'x'.$cuty.'+0+0 '.$this->targetfile.' '.$targetfile;
@exec($exec_str, $output, $return);
$exec_str = $imageimpath.'/convert -quality '.intval($thumbquality).' -geometry '.$thumbwidth.'x'.$thumbheight.' '.$targetfile.' '.$targetfile;
@exec($exec_str, $output, $return);
if(empty($return) && empty($output)) {
$this->attach['thumb'] = $thumbstatus == 1 || $thumbstatus == 3 ? 1 : 0;
}
}
}
}
}
function Watermark_IM($preview = 0) {
global $watermarkstatus, $watermarktype, $watermarktrans, $watermarkquality, $watermarktext, $imageimpath;
$watermarkstatus = $GLOBALS['forum']['disablewatermark'] ? 0 : $watermarkstatus;
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.'%' : '').
' -quality '.$watermarkquality.
' -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'.
' -quality '.$watermarkquality.
' -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/51shangcheng.cn/htdocs/include/image.class.php
|
PHP
|
asf20
| 13,865
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: gift.inc.php 17385 2008-12-17 05:05:02Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_install() {
global $db, $tablepre;
}
function task_uninstall() {
global $db, $tablepre;
}
function task_upgrade() {
global $db, $tablepre;
}
function task_condition() {
}
function task_preprocess($task = array()) {
if(!isset($task['newbie'])) {
dheader("Location: task.php?action=draw&id=$task[taskid]");
}
}
function task_csc($task = array()) {
return true;
}
function task_sufprocess() {
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/gift.inc.php
|
PHP
|
asf20
| 685
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: post.inc.php 17326 2008-12-15 03:09:58Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_condition() {
}
function task_preprocess() {
}
function task_csc($task = array()) {
global $db, $tablepre, $discuz_uid, $timestamp;
$taskvars = array('num' => 0);
$query = $db->query("SELECT variable, value FROM {$tablepre}taskvars WHERE taskid='$task[taskid]'");
while($taskvar = $db->fetch_array($query)) {
if($taskvar['value']) {
$taskvars[$taskvar['variable']] = $taskvar['value'];
}
}
$tbladd = $sqladd = '';
if($taskvars['threadid']) {
$sqladd .= " AND p.tid='$taskvars[threadid]'";
} else {
if($taskvars['forumid']) {
$sqladd .= " AND p.fid='$taskvars[forumid]'";
}
if($taskvars['authorid']) {
$tbladd .= ", {$tablepre}threads t";
$sqladd .= " AND p.tid=t.tid AND t.authorid='$taskvars[authorid]'";
}
}
if($taskvars['act']) {
if($taskvars['act'] == 'newthread') {
$sqladd .= " AND p.first='1'";
} elseif($taskvars['act'] == 'newreply') {
$sqladd .= " AND p.first='0'";
}
}
$sqladd .= ($taskvars['time'] = floatval($taskvars['time'])) ? " AND p.dateline BETWEEN $task[applytime] AND $task[applytime]+3600*$taskvars[time]" : " AND p.dateline>$task[applytime]";
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}posts p $tbladd WHERE p.authorid='$discuz_uid' $sqladd");
if($num && $num >= $taskvars['num']) {
return TRUE;
} elseif($taskvars['time'] && $timestamp >= $task['applytime'] + 3600 * $taskvars['time'] && (!$num || $num < $taskvars['num'])) {
return FALSE;
} else {
return array('csc' => $num > 0 && $taskvars['num'] ? sprintf("%01.2f", $num / $taskvars['num'] * 100) : 0, 'remaintime' => $taskvars['time'] ? $task['applytime'] + $taskvars['time'] * 3600 - $timestamp : 0);
}
}
function task_sufprocess() {
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/post.inc.php
|
PHP
|
asf20
| 2,006
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: mod.inc.php 16697 2008-11-14 07:36:51Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_condition() {
}
function task_preprocess() {
}
function task_csc($task = array()) {
return true;
}
function task_sufprocess() {
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/mod.inc.php
|
PHP
|
asf20
| 395
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: avatar.inc.php 17065 2008-12-05 01:30:57Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_install() {
global $db, $tablepre;
}
function task_uninstall() {
global $db, $tablepre;
}
function task_upgrade() {
global $db, $tablepre;
}
function task_condition() {
global $discuz_uid;
include_once DISCUZ_ROOT.'./uc_client/client.php';
include language('tasks');
if(uc_check_avatar($discuz_uid)) {
showmessage($tasklang['avatar_apply_var_desc_noavatar']);
}
}
function task_preprocess() {
}
function task_csc($task = array()) {
global $discuz_uid;
include_once DISCUZ_ROOT.'./uc_client/client.php';
if(uc_check_avatar($discuz_uid)) {
return true;
}
return array('csc' => 0, 'remaintime' => 0);
}
function task_sufprocess() {
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/avatar.inc.php
|
PHP
|
asf20
| 947
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: gift.cfg.php 16697 2008-11-14 07:36:51Z monkey $
*/
$task_name = $tasklang['gift_name'];
$task_description = $tasklang['gift_desc'];
$task_icon = 'gift.gif';
$task_period = '';
$task_conditions = array(
array('sort' => '', 'name' => '', 'description' => '', 'variable' => '', 'value' => '', 'type' => '', 'extra' => ''),
);
$task_version = '1.0';
$task_copyright = $tasklang['gift_copyright'];
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/gift.cfg.php
|
PHP
|
asf20
| 550
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: avatar.cfg.php 16697 2008-11-14 07:36:51Z monkey $
*/
$task_name = $tasklang['avatar_name'];
$task_description = $tasklang['avatar_desc'];
$task_icon = '';
$task_period = '';
$task_conditions = array(
array('sort' => 'apply', 'name' => $tasklang['avatar_apply_var_name_noavatar'], 'description' => $tasklang['avatar_apply_var_desc_noavatar'], 'variable' => '', 'value' => '', 'type' => '', 'extra' => ''),
array('sort' => 'complete', 'name' => $tasklang['avatar_complete_var_name_uploadavatar'], 'description' => $tasklang['avatar_complete_var_desc_uploadavatar'], 'variable' => '', 'value' => '', 'type' => '', 'extra' => '')
);
$task_version = '1.0';
$task_copyright = $task_copyright = $tasklang['avatar_copyright'];
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/avatar.cfg.php
|
PHP
|
asf20
| 879
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: member.inc.php 17090 2008-12-05 05:15:08Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_condition() {
}
function task_preprocess() {
global $db, $tablepre, $task, $discuz_uid, $timestamp;
$act = $db->result_first("SELECT value FROM {$tablepre}taskvars WHERE taskid='$task[taskid]' AND variable='act'");
if($act == 'buddy') {
include_once DISCUZ_ROOT.'./uc_client/client.php';
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$discuz_uid', 'buddy$task[taskid]', '".(uc_friend_totalnum($discuz_uid, 1) + uc_friend_totalnum($discuz_uid, 3))."', '$timestamp')");
} elseif($act == 'favorite') {
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$discuz_uid', 'favorite$task[taskid]', '".$db->result_first("SELECT COUNT(*) FROM {$tablepre}favorites WHERE uid='$discuz_uid' AND tid>'0'")."', '$timestamp')");
}
}
function task_csc($task = array()) {
global $db, $tablepre, $discuz_uid, $timestamp;
$taskvars = array('num' => 0);
$num = 0;
$query = $db->query("SELECT variable, value FROM {$tablepre}taskvars WHERE taskid='$task[taskid]'");
while($taskvar = $db->fetch_array($query)) {
if($taskvar['value']) {
$taskvars[$taskvar['variable']] = $taskvar['value'];
}
}
$taskvars['time'] = floatval($taskvars['time']);
if($taskvars['act'] == 'buddy') {
include_once DISCUZ_ROOT.'./uc_client/client.php';
$num = uc_friend_totalnum($discuz_uid, 1) + uc_friend_totalnum($discuz_uid, 3) - $db->result_first("SELECT value FROM {$tablepre}spacecaches WHERE uid='$discuz_uid' AND variable='buddy$task[taskid]'");
} elseif($taskvars['act'] == 'favorite') {
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}favorites WHERE uid='$discuz_uid' AND tid>'0'") - $db->result_first("SELECT value FROM {$tablepre}spacecaches WHERE uid='$discuz_uid' AND variable='favorite$task[taskid]'");
} elseif($taskvars['act'] == 'magic') {
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}magiclog WHERE action='2' AND uid='$discuz_uid'".($taskvars['time'] ? " AND dateline BETWEEN $task[applytime] AND $task[applytime]+3600*$taskvars[time]" : " AND dateline>$task[applytime]"));
}
if($num && $num >= $taskvars['num']) {
if(in_array($taskvars['act'], array('buddy', 'favorite'))) {
$db->query("DELETE FROM {$tablepre}spacecaches WHERE uid='$discuz_uid' AND variable='$taskvars[act]$task[taskid]'");
}
return TRUE;
} elseif($taskvars['time'] && $timestamp >= $task['applytime'] + 3600 * $taskvars['time'] && (!$num || $num < $taskvars['num'])) {
return FALSE;
} else {
return array('csc' => $num > 0 && $taskvars['num'] ? sprintf("%01.2f", $num / $taskvars['num'] * 100) : 0, 'remaintime' => $taskvars['time'] ? $task['applytime'] + $taskvars['time'] * 3600 - $timestamp : 0);
}
}
function task_sufprocess() {
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/member.inc.php
|
PHP
|
asf20
| 3,055
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: promotion.inc.php 17523 2009-01-12 03:41:50Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function task_install() {
global $db, $tablepre;
}
function task_uninstall() {
global $db, $tablepre;
}
function task_upgrade() {
global $db, $tablepre;
}
function task_condition() {
}
function task_preprocess() {
global $db, $tablepre, $discuz_uid, $timestamp, $task;
$promotions = $db->result_first("SELECT COUNT(*) FROM {$tablepre}promotions WHERE uid='$discuz_uid'");
$db->query("REPLACE INTO {$tablepre}spacecaches (uid, variable, value, expiration) VALUES ('$discuz_uid', 'promotion$task[taskid]', '$promotions', '$timestamp')");
}
function task_csc($task = array()) {
global $db, $tablepre, $discuz_uid;
$num = $db->result_first("SELECT COUNT(*) FROM {$tablepre}promotions WHERE uid='$discuz_uid'") - $db->result_first("SELECT value FROM {$tablepre}spacecaches WHERE uid='$discuz_uid' AND variable='promotion$task[taskid]'");
$numlimit = $db->result_first("SELECT value FROM {$tablepre}taskvars WHERE taskid='$task[taskid]' AND variable='num'");
if($num && $num >= $numlimit) {
return TRUE;
} else {
return array('csc' => $num > 0 && $numlimit ? sprintf("%01.2f", $num / $numlimit * 100) : 0, 'remaintime' => 0);
}
}
function task_sufprocess() {
global $db, $tablepre, $discuz_uid, $task;
$db->query("DELETE FROM {$tablepre}spacecaches WHERE uid='$discuz_uid' AND variable='promotion$task[taskid]'");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/promotion.inc.php
|
PHP
|
asf20
| 1,619
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: promotion.cfg.php 16697 2008-11-14 07:36:51Z monkey $
*/
$task_name = $tasklang['promotion_name'];
$task_description = $tasklang['promotion_desc'];
$task_icon = '';
$task_period = '';
$task_conditions = array(
array('sort' => 'complete', 'name' => $tasklang['promotion_complete_var_name_iplimit'], 'description' => $tasklang['promotion_complete_var_desc_iplimit'], 'variable' => 'num', 'value' => '100', 'type' => 'number', 'extra' => ''),
);
$task_version = '1.0';
$task_copyright = $tasklang['promotion_copyright'];
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/tasks/promotion.cfg.php
|
PHP
|
asf20
| 674
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: newthread.inc.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$discuz_action = 11;
if(($special == 1 && !$allowpostpoll) || ($special == 2 && !$allowposttrade) || ($special == 3 && !$allowpostreward) || ($special == 4 && !$allowpostactivity) || ($special == 5 && !$allowpostdebate) || ($special == 6 && !$allowpostvideo)) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if($special == 6) {
require_once DISCUZ_ROOT.'./api/video.php';
require_once DISCUZ_ROOT.'./include/insenz.func.php';
}
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');
}
} elseif($forum['allowpost'] == -1) {
showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
}
if($url && !empty($qihoo['relate']['webnum'])) {
$from = in_array($from, array('direct', 'iframe')) ? $from : '';
if($data = @implode('', file("http://search.qihoo.com/sint/content.html?surl=$url&md5=$md5&ocs=$charset&ics=$charset&from=$from"))) {
preg_match_all("/(\w+):([^\>]+)/i", $data, $data);
if(!$data[2][1]) {
$subject = trim($data[2][3]);
$message = !$editormode ? str_replace('[br]', "\n", trim($data[2][4])) : str_replace('[br]', '<br />', trim($data[2][4]));
} else {
showmessage('reprint_invalid');
}
}
}
checklowerlimit($postcredits);
if(!submitcheck('topicsubmit', 0, $seccodecheck, $secqaacheck)) {
$modelid = $modelid ? intval($modelid) : '';
$isfirstpost = 1;
$tagoffcheck = '';
$showthreadsorts = !empty($sortid);
$icons = '';
if(!$special && is_array($_DCACHE['icons'])) {
$key = 1;
foreach($_DCACHE['icons'] as $id => $icon) {
$icons .= ' <input class="radio" type="radio" name="iconid" value="'.$id.'" /><img src="images/icons/'.$icon.'" alt="" />';
$icons .= !(++$key % 10) ? '<br />' : '';
}
}
if($special == 2 && $allowposttrade) {
$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));
$forum['tradetypes'] = $forum['tradetypes'] == '' ? -1 : unserialize($forum['tradetypes']);
} elseif($special == 6 && $allowpostvideo) {
$videoAccount = new VideoClient_Util($appid, $siteid, $sitekey);
$videoupload = $videoAccount->createUploadFrom($option, array('url' => 'data.php'));
$query = $db->query("SELECT value FROM {$tablepre}settings WHERE variable='videoinfo'");
$settings = unserialize($db->result($query, 0));
if($settings['videotype'] && is_array($settings['videotype'])) {
$vtypeselect = '<select name="vclass">';
foreach($settings['videotype'] as $key => $type) {
if($type['able']) {
$vtypeselect .= '<option value="'.$key.'"> '.$type['name'].'</option>';
}
}
$vtypeselect .= '</select>';
}
}
if($special == 4) {
$activitytypelist = $activitytype ? explode("\n", trim($activitytype)) : '';
}
include template('post');
} else {
if($subject == '') {
showmessage('post_sm_isnull');
}
if(!$sortid && !$special && $message == '') {
showmessage('post_sm_isnull');
}
if($post_invalid = checkpost($special)) {
showmessage($post_invalid);
}
if(checkflood()) {
showmessage('post_flood_ctrl');
}
if($allowpostattach && is_array($_FILES['attach'])) {
foreach($_FILES['attach']['name'] as $attachname) {
if($attachname != '') {
checklowerlimit($postattachcredits);
break;
}
}
}
$typeid = isset($typeid) && isset($forum['threadtypes']['types'][$typeid]) ? $typeid : 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;
$readperm = $allowsetreadperm ? $readperm : 0;
$isanonymous = $isanonymous && $allowanonymous ? 1 : 0;
$price = intval($price);
$price = $maxprice && !$special ? ($price <= $maxprice ? $price : $maxprice) : 0;
if(!$typeid && $forum['threadtypes']['required'] && !$special) {
showmessage('post_type_isnull');
}
if(!$sortid && $forum['threadsorts']['required'] && !$special) {
showmessage('post_sort_isnull');
}
if($price > 0 && floor($price * (1 - $creditstax)) == 0) {
showmessage('post_net_price_iszero');
}
if($special == 1) {
$pollarray = array();
foreach($polloption as $key => $value) {
if(trim($value) === '') {
unset($polloption[$key]);
}
}
if(count($polloption) > $maxpolloptions) {
showmessage('post_poll_option_toomany');
} elseif(count($polloption) < 2) {
showmessage('post_poll_inputmore');
}
$maxchoices = !empty($multiplepoll) ? (!$maxchoices || $maxchoices >= count($polloption) ? count($polloption) : $maxchoices) : '';
$pollarray['options'] = $polloption;
$pollarray['multiple'] = !empty($multiplepoll);
$pollarray['visible'] = empty($visibilitypoll);
$pollarray['overt'] = !empty($overt);
if(preg_match("/^\d*$/", trim($maxchoices)) && preg_match("/^\d*$/", trim($expiration))) {
if(!$pollarray['multiple']) {
$pollarray['maxchoices'] = 1;
} elseif(empty($maxchoices)) {
$pollarray['maxchoices'] = 0;
} elseif($maxchoices == 1) {
$pollarray['multiple'] = 0;
$pollarray['maxchoices'] = $maxchoices;
} else {
$pollarray['maxchoices'] = $maxchoices;
}
if(empty($expiration)) {
$pollarray['expiration'] = 0;
} else {
$pollarray['expiration'] = $timestamp + 86400 * $expiration;
}
} else {
showmessage('poll_maxchoices_expiration_invalid');
}
} elseif($special == 3) {
$rewardprice = intval($rewardprice);
if($rewardprice < 1) {
showmessage('reward_credits_please');
} elseif($rewardprice > 32767) {
showmessage('reward_credits_overflow');
} elseif($rewardprice < $minrewardprice || ($maxrewardprice > 0 && $rewardprice > $maxrewardprice)) {
if($maxrewardprice > 0) {
showmessage('reward_credits_between');
} else {
showmessage('reward_credits_lower');
}
} elseif(($realprice = $rewardprice + ceil($rewardprice * $creditstax)) > $_DSESSION["extcredits$creditstransextra[2]"]) {
showmessage('reward_credits_shortage');
}
$price = $rewardprice;
$db->query("UPDATE {$tablepre}members SET extcredits$creditstransextra[2]=extcredits$creditstransextra[2]-$realprice WHERE uid='$discuz_uid'");
} elseif($special == 4) {
$activitytime = intval($activitytime);
if(empty($starttimefrom[$activitytime])) {
showmessage('activity_fromtime_please');
} elseif(@strtotime($starttimefrom[$activitytime]) === -1 || @strtotime($starttimefrom[$activitytime]) === FALSE) {
showmessage('activity_fromtime_error');
} 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;
}
if(trim($activitycity)) {
$subject .= '['.dhtmlspecialchars(trim($activitycity)).']';
}
} elseif($special == 5) {
if(empty($affirmpoint) || empty($negapoint)) {
showmessage('debate_position_nofound');
} elseif(!empty($endtime) && (!($endtime = @strtotime($endtime)) || $endtime < $timestamp)) {
showmessage('debate_endtime_invalid');
} elseif(!empty($umpire)) {
if(!$db->result_first("SELECT COUNT(*) FROM {$tablepre}members WHERE username='$umpire'")) {
$umpire = dhtmlspecialchars($umpire);
showmessage('debate_umpire_invalid');
}
}
$affirmpoint = dhtmlspecialchars($affirmpoint);
$negapoint = dhtmlspecialchars($negapoint);
$stand = intval($stand);
} elseif($special == 6) {
if(empty($vid) || empty($vsubject) || empty($vtag)) {
showmessage('video_required_invalid');
}
}
$sortid = $special && $forum['threadsorts']['types'][$sortid] ? 0 : $sortid;
$typeexpiration = intval($typeexpiration);
if($forum['threadsorts']['expiration'][$typeid] && !$typeexpiration) {
showmessage('threadtype_expiration_invalid');
}
$optiondata = array();
if($forum['threadsorts']['types'][$sortid] && !$forum['allowspecialonly']) {
$optiondata = threadsort_validator($typeoption);
}
$author = !$isanonymous ? $discuz_user : '';
$moderated = $digest || $displayorder > 0 ? 1 : 0;
$attachment = ($allowpostattach && $attachments = attach_upload()) ? ($imageexists ? 2 : 1) : 0;
$subscribed = !empty($emailnotify) && $discuz_uid ? 1 : 0;
$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, sortid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, special, attachment, subscribed, moderated)
VALUES ('$fid', '$readperm', '$price', '$iconid', '$typeid', '$sortid', '$author', '$discuz_uid', '$subject', '$timestamp', '$timestamp', '$author', '$displayorder', '$digest', '$special', '$attachment', '$subscribed', '$moderated')");
$tid = $db->insert_id();
if($subscribed) {
$db->query("REPLACE INTO {$tablepre}subscriptions (uid, tid, lastpost, lastnotify)
VALUES ('$discuz_uid', '$tid', '$timestamp', '$timestamp')", 'UNBUFFERED');
}
if($special == 3 && $allowpostreward) {
$db->query("INSERT INTO {$tablepre}rewardlog (tid, authorid, netamount, dateline) VALUES ('$tid', '$discuz_uid', $realprice, '$timestamp')");
}
$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);
}
if($special == 1) {
$db->query("INSERT INTO {$tablepre}polls (tid, multiple, visible, maxchoices, expiration, overt)
VALUES ('$tid', '$pollarray[multiple]', '$pollarray[visible]', '$pollarray[maxchoices]', '$pollarray[expiration]', '$pollarray[overt]')");
foreach($pollarray['options'] as $polloptvalue) {
$polloptvalue = dhtmlspecialchars(trim($polloptvalue));
$db->query("INSERT INTO {$tablepre}polloptions (tid, polloption) VALUES ('$tid', '$polloptvalue')");
}
} elseif($special == 4 && $allowpostactivity) {
$db->query("INSERT INTO {$tablepre}activities (tid, uid, cost, starttimefrom, starttimeto, place, class, gender, number, expiration)
VALUES ('$tid', '$discuz_uid', '$activity[cost]', '$activity[starttimefrom]', '$activity[starttimeto]', '$activity[place]', '$activity[class]', '$activity[gender]', '$activity[number]', '$activity[expiration]')");
} elseif($special == 5 && $allowpostdebate) {
$db->query("INSERT INTO {$tablepre}debates (tid, uid, starttime, endtime, affirmdebaters, negadebaters, affirmvotes, negavotes, umpire, winner, bestdebater, affirmpoint, negapoint, umpirepoint)
VALUES ('$tid', '$discuz_uid', '$timestamp', '$endtime', '0', '0', '0', '0', '$umpire', '', '', '$affirmpoint', '$negapoint', '')");
} elseif($special == 6 && $allowpostvideo) {
$vid = dhtmlspecialchars($vid);
$vsubject = dhtmlspecialchars($vsubject);
$vclass = intval($vclass);
$visup = intval($visup);
$vlength = intval($vlength);
$vautoplay = $vautoplay ? intval($vautoplay) : 2;
$vshare = $vshare ? intval($vshare) : 1;
$videoAccount = new VideoClient_VideoService($appid, $siteid, $sitekey);
$result = $videoAccount->upload($vid, $tid, $visup, insenz_convert($vsubject, 1), insenz_convert($vtag, 1), '', $vclass, $vautoplay, $vshare);
$query = $db->query("INSERT INTO {$tablepre}videos (vid, tid, uid, dateline, vthumb, vtitle, vclass, vtime, visup, vautoplay)
VALUES ('$vid', '$tid', '$discuz_uid', '$timestamp', '', '$vsubject', '$vclass', '$vlength', '$visup', '$vautoplay')", 'SILENT');
}
if($forum['threadsorts']['types'][$sortid] && !empty($optiondata) && is_array($optiondata)) {
foreach($optiondata as $optionid => $value) {
$db->query("INSERT INTO {$tablepre}typeoptionvars (sortid, tid, optionid, value, expiration)
VALUES ('$sortid', '$tid', '$optionid', '$value', '".($typeexpiration ? $timestamp + $typeexpiration : 0)."')");
}
}
$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;
$message = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $message);
$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', '$message', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '$attachment')");
$pid = $db->insert_id();
if($tagstatus && $tags != '') {
$tags = str_replace(array(chr(0xa3).chr(0xac), chr(0xa1).chr(0x41), chr(0xef).chr(0xbc).chr(0x8c)), ',', censor($tags));
if(strexists($tags, ',')) {
$tagarray = array_unique(explode(',', $tags));
} else {
$tags = str_replace(array(chr(0xa1).chr(0xa1), chr(0xa1).chr(0x40), chr(0xe3).chr(0x80).chr(0x80)), ' ', $tags);
$tagarray = array_unique(explode(' ', $tags));
}
$tagcount = 0;
foreach($tagarray as $tagname) {
$tagname = trim($tagname);
if(preg_match('/^([\x7f-\xff_-]|\w|\s){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;
}
}
}
}
$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, width)
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]', '$attach[width]')");
$searcharray[] = '[local]'.$localid[$key].'[/local]';
$pregarray[] = '/\[localimg=(\d{1,3}),(\d{1,3})\]'.$localid[$key].'\[\/localimg\]/is';
$replacearray[] = '[attach]'.$db->insert_id().'[/attach]';
}
$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));
}
if($swfupload) {
updateswfattach();
}
if($modnewthreads) {
$db->query("UPDATE {$tablepre}forums SET todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
showmessage('post_newthread_mod_succeed', "forumdisplay.php?fid=$fid");
} else {
$feed = array(
'icon' => '',
'title_template' => '',
'title_data' => array(),
'body_template' => '',
'body_data' => array(),
'title_data'=>array(),
'images'=>array()
);
if($addfeed && $forum['allowfeed']) {
if($special == 0) {
$feed['icon'] = 'thread';
$feed['title_template'] = 'feed_thread_title';
$feed['body_template'] = 'feed_thread_message';
$feed['body_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
);
} elseif($special > 0) {
if($special == 1) {
$feed['icon'] = 'poll';
$feed['title_template'] = 'feed_thread_poll_title';
$feed['body_template'] = 'feed_thread_poll_message';
$feed['body_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
);
} elseif($special == 3) {
$feed['icon'] = 'reward';
$feed['title_template'] = 'feed_thread_reward_title';
$feed['body_template'] = 'feed_thread_reward_message';
$feed['body_data'] = array(
'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'rewardprice'=> $rewardprice,
'extcredits' => $extcredits[$creditstransextra[2]]['title'],
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
);
} elseif($special == 4) {
$feed['icon'] = 'activity';
$feed['title_template'] = 'feed_thread_activity_title';
$feed['body_template'] = 'feed_thread_activity_message';
$feed['body_data'] = array(
'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'starttimefrom' => $starttimefrom[$activitytime],
'activityplace'=> $activityplace,
'cost'=> $cost,
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150)
);
} elseif($special == 5) {
$feed['icon'] = 'debate';
$feed['title_template'] = 'feed_thread_debate_title';
$feed['body_template'] = 'feed_thread_debate_message';
$feed['body_data'] = array(
'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150),
'affirmpoint'=> cutstr(strip_tags(preg_replace("/\[.+?\]/is", '', $affirmpoint)), 150),
'negapoint'=> cutstr(strip_tags(preg_replace("/\[.+?\]/is", '', $negapoint)), 150)
);
} elseif($special == 6) {
$feed['icon'] = 'video';
$feed['title_template'] = 'feed_thread_video_title';
$feed['body_template'] = 'feed_thread_video_message';
$feed['body_data'] = array(
'subject'=> "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$subject</a>",
'play' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\" class=\"playbutton\">Play</a>",
'message' => cutstr(strip_tags(preg_replace(array("/\[hide=?\d*\].+?\[\/hide\]/is", "/\[.+?\]/is"), array('', ''), $message)), 150),
'vlength'=> sprintf("%02d", intval($vlength / 60)).':'.sprintf("%02d", intval($vlength % 60)),
);
}
}
if($special == 6) {
$feed['images'][] = array('url' => VideoClient_Util::getThumbUrl($vid, 'small'), 'link' => "{$boardurl}viewthread.php?tid=$tid");
} else {
if(in_array($attachments[1]['type'], array('image/gif', 'image/jpeg', 'image/png'))) {
$attachurl = preg_match("/^((https?|ftps?):\/\/|www\.)/i", $attachurl) ? $attachurl : $boardurl.$attachurl;
$imgurl = $attachurl.'/'.$attachments[1]['attachment'].($attachments[1]['thumb'] && $attachments[1]['type'] != 'image/gif' ? '.thumb.jpg' : '');
$feed['images'][] = $attachments[1]['attachment'] ? array('url' => $imgurl, 'link' => "{$boardurl}viewthread.php?tid=$tid") : array();
}
}
if($feed) {
postfeed($feed);
}
}
if($digest) {
foreach($digestcredits as $id => $addcredits) {
$postcredits[$id] = (isset($postcredits[$id]) ? $postcredits[$id] : 0) + $addcredits;
}
}
updatepostcredits('+', $discuz_uid, $postcredits);
$subject = str_replace("\t", ' ', $subject);
$lastpost = "$tid\t$subject\t$timestamp\t$author";
$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');
}
showmessage('post_newthread_succeed', "viewthread.php?tid=$tid&extra=$extra");
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/newthread.inc.php
|
PHP
|
asf20
| 22,378
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: post.func.php 17503 2009-01-05 02:21:45Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function attach_upload($varname = 'attach', $swfupload = 0) {
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, $imageexists;
$attachments = $attacharray = array();
$imageexists = 0;
static $safeext = array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp', 'txt', 'zip', 'rar', 'doc', 'mp3');
static $imgext = array('jpg', 'jpeg', 'gif', 'png', 'bmp');
if(!$swfupload) {
if(isset($_FILES[$varname]) && is_array($_FILES[$varname])) {
foreach($_FILES[$varname] as $key => $var) {
foreach($var as $id => $val) {
$attachments[$id][$key] = $val;
}
}
}
} else {
$attachments[0] = $_FILES[$varname];
}
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;
$imageexists = 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);
}
if($type = $db->fetch_first("SELECT maxsize FROM {$tablepre}attachtypes WHERE extension='".addslashes($attach['ext'])."'")) {
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)) {
$todaysize = intval($db->result_first("SELECT SUM(filesize) FROM {$tablepre}attachments
WHERE uid='$GLOBALS[discuz_uid]' AND dateline>'$GLOBALS[timestamp]'-86400"));
}
$todaysize += $attach['size'];
if($todaysize >= $maxsizeperday) {
$maxsizeperday = $maxsizeperday / 1048576 >= 1 ? round(($maxsizeperday / 1048576), 1).'M' : round(($maxsizeperday / 1024)).'K';
upload_error('post_attachment_quota_exceed', $attacharray);
}
}
if($attachsave) {
if(!$swfupload) {
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;
}
} else {
$attach_subdir = 'swfupload';
}
$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('ymdHi').substr(md5($filename.microtime().random(6)), 8, 16).'.'.$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);
$width = $height = $type = 0;
if($attach['isimage'] || $attach['ext'] == 'swf') {
$imagesize = @getimagesize($target);
list($width, $height, $type) = (array)$imagesize;
$size = $width * $height;
if($size > 16777216 || $size < 4 || empty($type) || ($attach['isimage'] && !in_array($type, array(1,2,3,6,13)))) {
@unlink($target);
upload_error('post_attachment_image_checkerror', $attacharray);
}
}
if($attach['isimage'] && ($thumbstatus || $watermarkstatus)) {
require_once DISCUZ_ROOT.'./include/image.class.php';
$image = new Image($target, $attach);
if($image->imagecreatefromfunc && $image->imagefunc) {
$image->Thumb($thumbwidth, $thumbheight);
!$swfupload && $image->Watermark();
$attach = $image->attach;
}
}
$attach['width'] = 0;
if($attach['isimage'] || $attach['ext'] == 'swf') {
$imagesize = @getimagesize($target);
list($width) = (array)$imagesize;
$attach['width'] = $width;
}
$attach['remote'] = !$swfupload ? ftpupload($target, $attach) : 0;
$attach['perm'] = $allowsetattachperm ? intval($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);
}
function ftpupload($source, $attach) {
global $authkey, $ftp;
$ftp['pwd'] = isset($ftp['pwd']) ? $ftp['pwd'] : FALSE;
$dest = $attach['attachment'];
if($ftp['on'] && ((!$ftp['allowedexts'] && !$ftp['disallowedexts']) || ($ftp['allowedexts'] && in_array($attach['ext'], explode("\n", strtolower($ftp['allowedexts'])))) || ($ftp['disallowedexts'] && !in_array($attach['ext'], explode("\n", strtolower($ftp['disallowedexts']))))) && (!$ftp['minsize'] || $attach['size'] >= $ftp['minsize'] * 1024)) {
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']))) {
if($ftp['mirror'] == 1) {
ftpupload_error($source, $attach);
} else {
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);
if($ftp['mirror'] == 1) {
ftpupload_error($source, $attach);
} else {
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);
if($ftp['mirror'] == 1) {
ftpupload_error($source, $attach);
} else {
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($attach['thumb']) {
if(dftp_put($ftp['connid'], $dest.'.thumb.jpg', $source.'.thumb.jpg', FTP_BINARY)) {
if($ftp['mirror'] != 2) {
@unlink($source);
@unlink($source.'.thumb.jpg');
}
return 1;
} else {
dftp_delete($ftp['connid'], $dest);
}
} else {
if($ftp['mirror'] != 2) {
@unlink($source);
}
return 1;
}
}
errorlog('FTP', "Upload '$source' error.", 0);
$ftp['mirror'] == 1 && ftpupload_error($source, $attach);
}
return 0;
}
function ftpupload_error($source, $attach) {
@unlink($source);
if($attach['thumb']) {
@unlink($source.'.thumb.jpg');
}
showmessage('post_attachment_remote_save_error');
}
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($special = 0) {
global $subject, $message, $disablepostctrl, $minpostsize, $maxpostsize;
if(strlen($subject) > 80) {
return 'post_subject_toolong';
}
if(!$disablepostctrl && !$special) {
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 && !strpos($message, '[/') ? -1 : $bbcodeoff;
}
function checksmilies($message, $smileyoff) {
global $_DCACHE;
if($smileyoff) {
return 1;
} else {
if(!empty($_DCACHE['smileycodes']) && is_array($_DCACHE['smileycodes'])) {
$message = stripslashes($message);
foreach($_DCACHE['smileycodes'] as $id => $code) {
if(strpos($message, $code) !== FALSE) {
return 0;
}
}
}
return -1;
}
}
function updatepostcredits($operator, $uidarray, $creditsarray) {
global $db, $tablepre, $discuz_uid, $timestamp, $creditnotice, $cookiecredits;
$membersarray = $postsarray = array();
$self = $creditnotice && $uidarray == $discuz_uid;
foreach((is_array($uidarray) ? $uidarray : array($uidarray)) as $id) {
$membersarray[intval(trim($id))]++;
}
foreach($membersarray as $uid => $posts) {
$postsarray[$posts][] = $uid;
}
$lastpostadd = $self ? ", lastpost='$timestamp'" : '';
$creditsadd1 = '';
if(is_array($creditsarray)) {
if($self && !isset($cookiecredits)) {
$cookiecredits = !empty($_COOKIE['discuz_creditnotice']) ? explode('D', $_COOKIE['discuz_creditnotice']) : array_fill(0, 9, 0);
}
foreach($creditsarray as $id => $addcredits) {
$creditsadd1 .= ", extcredits$id=extcredits$id$operator($addcredits)*\$posts";
if($self) {
eval("\$cookiecredits[$id] += $operator($addcredits)*\$posts;");
}
}
if($self) {
dsetcookie('discuz_creditnotice', implode('D', $cookiecredits).'D'.$discuz_uid, 43200, 0);
}
}
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;
extract($db->fetch_first("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'"));
$thread = $db->fetch_first("SELECT tid, subject, author, lastpost, lastposter FROM {$tablepre}threads
WHERE fid='$fid' AND displayorder>='0' ORDER BY lastpost DESC LIMIT 1");
$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;
$replycount = $db->result_first("SELECT COUNT(*) FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0'") - 1;
$lastpost = $db->fetch_first("SELECT author, anonymous, dateline FROM {$tablepre}posts WHERE tid='$tid' AND invisible='0' ORDER BY dateline DESC LIMIT 1");
$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 threadsort_checkoption($unchangeable = 1, $trade = 0) {
global $selectsortid, $optionlist, $trade_create, $tradetypeid, $sortid, $_DTYPE, $checkoption, $forum, $action;
if($trade) {
$selectsortid = $tradetypeid ? intval($tradetypeid) : '';
} else {
$selectsortid = $sortid ? intval($sortid) : '';
}
@include_once DISCUZ_ROOT.'./forumdata/cache/threadsort_'.$selectsortid.'.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 threadsort_optiondata() {
global $db, $tablepre, $tid, $pid, $tradetype, $_DTYPE, $_DTYPEDESC, $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]['unchangeable'] = $_DTYPE[$optionid]['unchangeable'] ? 'readonly' : '';
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 (sortid, $field, optionid)
VALUES ('$thread[sortid]', '$id', '$optionid')");
}
}
}
}
function threadsort_validator($sortoption) {
global $checkoption, $var, $selectsortid, $fid, $tid, $pid;
$postaction = $tid && $pid ? "edit&tid=$tid&pid=$pid" : 'newthread';
$optiondata = array();
foreach($checkoption as $var => $option) {
if($checkoption[$var]['required'] && !$sortoption[$var]) {
showmessage('threadtype_required_invalid', "post.php?action=$postaction&fid=$fid&sortid=$selectsortid");
} elseif($sortoption[$var] && ($checkoption[$var]['type'] == 'number' && !is_numeric($sortoption[$var]) || $checkoption[$var]['type'] == 'email' && !isemail($sortoption[$var]))){
showmessage('threadtype_format_invalid', "post.php?action=$postaction&fid=$fid&sortid=$selectsortid");
} elseif($sortoption[$var] && $checkoption[$var]['maxlength'] && strlen($typeoption[$var]) > $checkoption[$var]['maxlength']) {
showmessage('threadtype_toolong_invalid', "post.php?action=$postaction&fid=$fid&sortid=$selectsortid");
} elseif($sortoption[$var] && (($checkoption[$var]['maxnum'] && $sortoption[$var] >= $checkoption[$var]['maxnum']) || ($checkoption[$var]['minnum'] && $sortoption[$var] < $checkoption[$var]['minnum']))) {
showmessage('threadtype_num_invalid', "post.php?action=$postaction&fid=$fid&sortid=$selectsortid");
} elseif($sortoption[$var] && $checkoption[$var]['unchangeable'] && !($tid && $pid)) {
showmessage('threadtype_unchangeable_invalid', "post.php?action=$postaction&fid=$fid&sortid=$selectsortid");
}
if($checkoption[$var]['type'] == 'checkbox') {
$sortoption[$var] = $sortoption[$var] ? implode("\t", $sortoption[$var]) : '';
} elseif($checkoption[$var]['type'] == 'url') {
$sortoption[$var] = $sortoption[$var] ? (substr(strtolower($sortoption[$var]), 0, 4) == 'www.' ? 'http://'.$sortoption[$var] : $sortoption[$var]) : '';
}
$sortoption[$var] = dhtmlspecialchars(censor(trim($sortoption[$var])));
$optiondata[$checkoption[$var]['optionid']] = $sortoption[$var];
}
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')");
}
function disuploadedfile($file) {
return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}
function postfeed($feed) {
global $discuz_uid, $discuz_user;
require_once DISCUZ_ROOT.'./templates/default/feed.lang.php';
require_once DISCUZ_ROOT.'./uc_client/client.php';
$feed['title_template'] = $feed['title_template'] ? $language[$feed['title_template']] : '';
$feed['body_template'] = $feed['title_template'] ? $language[$feed['body_template']] : '';
uc_feed_add($feed['icon'], $discuz_uid, $discuz_user, $feed['title_template'], $feed['title_data'], $feed['body_template'], $feed['body_data'], '', '', $feed['images']);
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/post.func.php
|
PHP
|
asf20
| 22,011
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: counter.inc.php 17367 2008-12-16 06:13:26Z monkey $
*/
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(strexists($visitor['agent'], 'Netscape')) {
$visitor['browser'] = 'Netscape';
} elseif(strexists($visitor['agent'], 'Lynx')) {
$visitor['browser'] = 'Lynx';
} elseif(strexists($visitor['agent'], 'Opera')) {
$visitor['browser'] = 'Opera';
} elseif(strexists($visitor['agent'], 'Konqueror')) {
$visitor['browser'] = 'Konqueror';
} elseif(strexists($visitor['agent'], 'MSIE')) {
$visitor['browser'] = 'MSIE';
} elseif(strexists($visitor['agent'], 'Firefox')) {
$visitor['browser'] = 'Firefox';
} elseif(strexists($visitor['agent'], 'Safari')) {
$visitor['browser'] = 'Safari';
} elseif(strexists($visitor['agent'], 0, 7) == 'Mozilla') {
$visitor['browser'] = 'Mozilla';
} else {
$visitor['browser'] = 'Other';
}
if(strexists($visitor['agent'], 'Win')) {
$visitor['os'] = 'Windows';
} elseif(strexists($visitor['agent'], 'Mac')) {
$visitor['os'] = 'Mac';
} elseif(strexists($visitor['agent'], 'Linux')) {
$visitor['os'] = 'Linux';
} elseif(strexists($visitor['agent'], 'FreeBSD')) {
$visitor['os'] = 'FreeBSD';
} elseif(strexists($visitor['agent'], 'SunOS')) {
$visitor['os'] = 'SunOS';
} elseif(strexists($visitor['agent'], 'OS/2')) {
$visitor['os'] = 'OS/2';
} elseif(strexists($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/51shangcheng.cn/htdocs/include/counter.inc.php
|
PHP
|
asf20
| 2,688
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_trade.inc.php 17493 2008-12-31 01:48:20Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(empty($do) || $do == 'tradeinfo') {
if($do == 'tradeinfo') {
$tradelistadd = "AND pid = '$pid'";
} else {
$tradelistadd = '';
!$tradenum && $allowpostreply = FALSE;
}
$query = $db->query("SELECT * FROM {$tablepre}trades WHERE tid='$tid' $tradelistadd ORDER BY displayorder");
$trades = $tradesstick = array();$tradelist = 0;
if(empty($do)) {
$sellerid = 0;
$listcount = $db->num_rows($query);
$tradelist = $tradenum - $listcount;
}
$tradesaids = $tradesaids = array();
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'];
if($trade['displayorder'] < 0) {
$trades[$trade['pid']] = $trade;
} else {
$tradesstick[$trade['pid']] = $trade;
}
}
$trades = $tradesstick + $trades;
$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);
$post = $db->fetch_first("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, mf.nickname, mf.site,
mf.icq, mf.qq, mf.yahoo, mf.msn, mf.taobao, mf.alipay, mf.location, mf.medals,
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'");
$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/threadsort_'.$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');
exit;
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/viewthread_trade.inc.php
|
PHP
|
asf20
| 5,949
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: chinese.class.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/chinese.class.php
|
PHP
|
asf20
| 7,047
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: insenz_cron.func.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
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 vfid, c.tid, c.status, c.begintime, c.starttime, c.endtime, t.fid, t.authorid, t.author, t.subject, t.lastpost, t.displayorder, t.digest 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, expiration=expiration+starttime-begintime WHERE id='$c[id]' AND type='$c[type]'", 'UNBUFFERED');
$lastpost = addslashes("$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, expiration=expiration+starttime-begintime WHERE id='$c[id]' AND type=4", 'UNBUFFERED');
$db->query("UPDATE {$tablepre}virtualforums SET status='1' WHERE fid='$c[vfid]'", 'UNBUFFERED');
$_DCACHE['settings']['insenz']['vfstatus'] += 1;
}
} 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;
}
}
if($c['digest'] == -2) {
$db->query("UPDATE {$tablepre}threads SET views='0', replies='0', digest='-1' WHERE tid='$c[tid]'", 'UNBUFFERED');
}
} else {
$db->query("UPDATE {$tablepre}virtualforums SET status='0' WHERE fid='$c[vfid]'", 'UNBUFFERED');
$_DCACHE['settings']['insenz']['vfstatus'] -= 1;
}
$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');
} else {
$db->query("DELETE FROM {$tablepre}virtualforums WHERE fid='$c[vfid]'", '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);
$_DCACHE['settings']['insenz']['vfstatus'] = max(0, intval($_DCACHE['settings']['insenz']['vfstatus']));
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_first("SELECT COUNT(*) FROM {$tablepre}sessions WHERE lastactivity>=($timestamp-900)");
$db->query("REPLACE INTO {$tablepre}statvars (type, variable, value) VALUES ('houronlines', '".gmdate('ymdH', $timestamp + 8 * 3600)."', '$onlinenum')");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/insenz_cron.func.php
|
PHP
|
asf20
| 5,294
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: moderation.inc.php 17453 2008-12-23 00:36:47Z monkey $
*/
if(!empty($tid)) {
$moderate = array($tid);
}
if(!defined('IN_DISCUZ') || CURSCRIPT != 'topicadmin') {
exit('Access Denied');
}
if($operations && $operations != array_intersect($operations, array('delete', 'highlight', 'open', 'close', 'stick', 'digest', 'bump', 'down', 'recommend', 'type', 'move')) || (!$allowdelpost && in_array('delete', $operations)) || (!$allowstickthread && in_array('stick', $operations))) {
showmessage('admin_moderate_invalid');
}
$threadlist = $loglist = array();
if($tids = implodeids($moderate)) {
$query = $db->query("SELECT * FROM {$tablepre}threads WHERE tid IN ($tids) AND fid='$fid' AND displayorder>='0' AND digest>='0' LIMIT $tpp");
while($thread = $db->fetch_array($query)) {
$thread['lastposterenc'] = rawurlencode($thread['lastposter']);
$thread['dblastpost'] = $thread['lastpost'];
$thread['lastpost'] = dgmdate("$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;
if($frommodcp) {
$referer = "modcp.php?action=threads&fid=$fid&op=threads&do=".($frommodcp == 1 ? '' : 'list');
} else {
$referer = "forumdisplay.php?fid=$fid&".rawurldecode($listextra);
}
if(!submitcheck('modsubmit')) {
if($optgroup == 1 && $single) {
$stickcheck = $digestcheck = array();
empty($threadlist[$tid]['displayorder']) ? $stickcheck[0] ='selected="selected"' : $stickcheck[$threadlist[$tid]['displayorder']] = 'selected="selected"';
empty($threadlist[$tid]['digest']) ? $digestcheck[0] = 'selected="selected"' : $digestcheck[$threadlist[$tid]['digest']] = 'selected="selected"';
$string = sprintf('%02d', $threadlist[$tid]['highlight']);
$stylestr = sprintf('%03b', $string[0]);
for($i = 1; $i <= 3; $i++) {
$stylecheck[$i] = $stylestr[$i - 1] ? 1 : 0;
}
$colorcheck = $string[1];
$forum['modrecommend'] = $forum['modrecommend'] ? unserialize($forum['modrecommend']) : array();
} elseif($optgroup == 2) {
require_once DISCUZ_ROOT.'./include/forum.func.php';
$forumselect = forumselect(FALSE, 0, $single ? $threadlist[$tid]['fid'] : 0);
$typeselect = typeselect($single ? $threadlist[$tid]['typeid'] : 0);
} elseif($optgroup == 4 && $single) {
$closecheck = array();
empty($threadlist[$tid]['closed']) ? $closecheck[0] = 'checked="checked"' : $closecheck[1] = 'checked="checked"';
}
$defaultcheck[$operation] = 'checked="checked"';
include template('topicadmin');
} else {
$moderatetids = implodeids(array_keys($threadlist));
checkreasonpm();
if(empty($operations)) {
showmessage('admin_nonexistence');
} else {
foreach($operations as $operation) {
$updatemodlog = TRUE;
if($operation == 'stick') {
$expiration = checkexpiration($expirationstick);
$sticklevel = intval($sticklevel);
if($sticklevel < 0 || $sticklevel > 3 || $sticklevel > $allowstickthread) {
showmessage('undefined_action');
}
$expirationstick = $sticklevel ? $expirationstick : 0;
$db->query("UPDATE {$tablepre}threads SET displayorder='$sticklevel', moderated='1' WHERE tid IN ($moderatetids)");
$stickmodify = 0;
foreach($threadlist as $thread) {
$stickmodify = (in_array($thread['displayorder'], array(2, 3)) || in_array($sticklevel, array(2, 3))) && $sticklevel != $thread['displayorder'] ? 1 : $stickmodify;
}
if($globalstick && $stickmodify) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
$modaction = $sticklevel ? ($expiration ? 'EST' : 'STK') : 'UST';
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('STK', 'UST', 'EST', 'UES')", 'UNBUFFERED');
} elseif($operation == 'highlight') {
$expiration = checkexpiration($expirationhighlight);
$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')", 'UNBUFFERED');
} elseif($operation == 'digest') {
$expiration = checkexpiration($expirationdigest);
$db->query("UPDATE {$tablepre}threads SET digest='$digestlevel', moderated='1' WHERE tid IN ($moderatetids)");
foreach($threadlist as $thread) {
if($thread['digest'] != $digestlevel) {
$digestpostsadd = ($thread['digest'] > 0 && $digestlevel == 0) || ($thread['digest'] == 0 && $digestlevel > 0) ? 'digestposts=digestposts'.($digestlevel == 0 ? '-' : '+').'1' : '';
updatecredits($thread['authorid'], $digestcredits, $digestlevel - $thread['digest'], $digestpostsadd);
}
}
$modaction = $digestlevel ? ($expiration ? 'EDI' : 'DIG') : 'UDG';
$db->query("UPDATE {$tablepre}threadsmod SET status='0' WHERE tid IN ($moderatetids) AND action IN ('DIG', 'UDI', 'EDI', 'UED')", 'UNBUFFERED');
} elseif($operation == 'recommend') {
$expiration = checkexpiration($expirationrecommend);
$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')", 'UNBUFFERED');
if($isrecommend) {
$addthread = $comma = '';
foreach($threadlist as $thread) {
$addthread .= $comma."('$thread[fid]', '$thread[tid]', '0', '".addslashes($thread['subject'])."', '".addslashes($thread['author'])."', '$thread[authorid]', '$discuz_uid', '$expiration')";
$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)");
}
} elseif($operation == 'bump') {
$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'");
$forum['threadcaches'] && deletethreadcaches($thread['tid']);
} elseif($operation == 'down') {
$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 == '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');
}
$updatemodlog = FALSE;
}
if($globalstick && $stickmodify) {
require_once DISCUZ_ROOT.'./include/cache.func.php';
updatecache('globalstick');
}
updateforumcount($fid);
} elseif($operation == 'close') {
$expiration = checkexpiration($expirationclose);
$modaction = $expiration ? 'ECL' : 'CLS';
$db->query("UPDATE {$tablepre}threads SET closed='1', 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')", 'UNBUFFERED');
} elseif($operation == 'open') {
$expiration = checkexpiration($expirationopen);
$modaction = $expiration ? 'EOP' : 'OPN';
$db->query("UPDATE {$tablepre}threads SET closed='0', 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')", 'UNBUFFERED');
} elseif($operation == 'move') {
$toforum = $db->fetch_first("SELECT fid, name, modnewposts, allowpostspecial FROM {$tablepre}forums WHERE fid='$moveto' AND status>0 AND type<>'group'");
if(!$toforum) {
showmessage('admin_move_invalid');
} elseif($fid == $toforum['fid']) {
continue;
} 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'";
}
$priv = $db->fetch_first("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'");
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') {
$thread = daddslashes($thread, 1);
$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]', '".addslashes($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 == 'type') {
if(!isset($forum['threadtypes']['types'][$typeid]) && ($typeid != 0 || $forum['threadtypes']['required'])) {
showmessage('admin_type_invalid');
}
$db->query("UPDATE {$tablepre}threads SET typeid='$typeid', moderated='1' WHERE tid IN ($moderatetids)");
$modaction = 'TYP';
}
if($updatemodlog) {
updatemodlog($moderatetids, $modaction, $expiration);
}
updatemodworks($modaction, $modpostsnum);
foreach($threadlist as $thread) {
modlog($thread, $modaction);
}
if($sendreasonpm) {
include_once language('modactions');
$modaction = $modactioncode[$modaction];
foreach($threadlist as $thread) {
sendreasonpm('thread', $operation == 'move' ? 'reason_move' : 'reason_moderate');
}
}
procreportlog($moderatetids, '', $operation == 'delete');
}
showmessage('admin_succeed', $referer);
}
}
function checkexpiration($expiration) {
global $operation, $timestamp, $timeoffset;
if(!empty($expiration) && in_array($operation, array('recommend', '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;
}
return $expiration;
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/moderation.inc.php
|
PHP
|
asf20
| 15,825
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: search_sort.inc.php 17492 2008-12-31 01:39:40Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if(!empty($searchid)) {
$page = max(1, intval($page));
$start_limit = ($page - 1) * $tpp;
$index = $db->fetch_first("SELECT searchstring, keywords, threads, threadsortid, tids FROM {$tablepre}searchindex WHERE searchid='$searchid' AND threadsortid='$sortid'");
if(!$index) {
showmessage('search_id_invalid');
}
$threadlist = $typelist = $resultlist = $optionlist = array();
$query = $db->query("SELECT tid, subject, dateline, iconid 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']]['icon'] = isset($GLOBALS['_DCACHE']['icons'][$info['iconid']]) ? '<img src="images/icons/'.$GLOBALS['_DCACHE']['icons'][$info['iconid']].'" alt="Icon'.$info['iconid'].'" class="icon" />' : ' ';
$threadlist[$info['tid']]['dateline'] = dgmdate("$dateformat $timeformat", $info['dateline'] + $timeoffset * 3600);
$threadlist[$info['tid']]['subject'] = $info['subject'];
}
@include_once DISCUZ_ROOT.'./forumdata/cache/threadsort_'.$index['threadsortid'].'.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 = array();
foreach($threadlist as $tid => $thread) {
$resultlist[$tid]['icon'] = $thread['icon'];
$resultlist[$tid]['subject'] = $thread['subject'];
$resultlist[$tid]['dateline'] = $thread['dateline'];
if(is_array($typelist[$tid])) {
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[$tid] .= $_DTYPE[$optionid]['choices'][$choiceid].' ';
}
$resultlist[$tid]['option'][] = $choiceshow[$tid];
} 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=threadsort&sortid=$index[threadsortid]&searchsubmit=yes");
$url_forward = 'search.php?'.$_SERVER['QUERY_STRING'];
include template('search_sort');
} else {
!($exempt & 2) && 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=threadsort&sortid=$selectsortid&srchfid=$fid");
}
}
if($searchindex['id']) {
$searchid = $searchindex['id'];
} else {
if((!$searchoption || !is_array($searchoption)) && !$selectsortid) {
showmessage('search_threadtype_invalid', "search.php?srchtype=threadsort&sortid=$selectsortid&srchfid=$fid");
} elseif(isset($srchfid) && $srchfid != 'all' && !(is_array($srchfid) && in_array('all', $srchfid)) && empty($forumsarray)) {
showmessage('search_forum_invalid', "search.php?srchtype=threadsort&sortid=$selectsortid&srchfid=$fid");
} elseif(!$fids) {
showmessage('group_nopermission', NULL, 'NOPERM');
}
if($maxspm) {
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}searchindex WHERE dateline>'$timestamp'-60") >= $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, sortid FROM {$tablepre}typeoptionvars WHERE (expiration='0' OR expiration>'$timestamp') ".($sqlsrch ? 'AND '.$sqlsrch : '')."");
while($post = $db->fetch_array($query)) {
if($post['sortid'] == $selectsortid) {
$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, threadsortid, tids)
VALUES ('$keywords', '$searchstring', '$onlineip', '$discuz_uid', '$timestamp', '$expiration', '$threads', '$selectsortid', '$tids')");
$searchid = $db->insert_id();
!($exempt & 2) && updatecredits($discuz_uid, $creditspolicy['search'], -1);
}
showmessage('search_redirect', "search.php?searchid=$searchid&srchtype=threadsort&sortid=$selectsortid&searchsubmit=yes");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/search_sort.inc.php
|
PHP
|
asf20
| 8,051
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: category.inc.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$gquery = $db->query("SELECT f.fid, f.fup, f.type, f.name, ff.moderators FROM {$tablepre}forums f LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid WHERE f.fid='$gid'");
$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.fup='$gid' AND f.status>0 AND f.type='forum' ORDER BY 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.fup='$gid' AND f.status>0 AND f.type='forum' ORDER BY f.displayorder";
$query = $db->query($sql);
if(!$db->num_rows($gquery) || !$db->num_rows($query)) {
showmessage('forum_nonexistence', NULL, 'HALTED');
}
while(($forum = $db->fetch_array($gquery)) || ($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' ORDER BY displayorder");
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/51shangcheng.cn/htdocs/include/category.inc.php
|
PHP
|
asf20
| 2,825
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: global.func.php 17460 2008-12-24 01:46:38Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
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, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
function clearcookies() {
global $discuz_uid, $discuz_user, $discuz_pw, $discuz_secques, $adminid, $credits;
foreach(array('sid', 'auth', 'visitedfid', 'onlinedetail', 'loginuser', 'activationauth') as $k) {
dsetcookie($k);
}
$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 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 checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $tpldir) {
global $tplrefresh;
if(empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($GLOBALS['timestamp'] % $tplrefresh))) {
if(empty($timecompare) || @filemtime($subtpl) > $timecompare) {
require_once DISCUZ_ROOT.'./include/template.func.php';
parse_template($maintpl, $templateid, $tpldir);
return TRUE;
}
}
return FALSE;
}
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 dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
$return = '';
$matches = parse_url($url);
$host = $matches['host'];
$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
$port = !empty($matches['port']) ? $matches['port'] : 80;
if($post) {
$out = "POST $path HTTP/1.0\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 .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\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 $path HTTP/1.0\r\n";
$out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
}
$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
if(!$fp) {
return '';
} else {
stream_set_blocking($fp, $block);
stream_set_timeout($fp, $timeout);
@fwrite($fp, $out);
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
$return .= $data;
if($limit) {
$limit -= strlen($data);
$stop = $limit <= 0;
}
}
}
@fclose($fp);
return $return;
}
}
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}));)/', '&\\1',
//$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 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, $httponly = false) {
global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
$var = ($prefix ? $cookiepre : '').$var;
if($value == '' || $life < 0) {
$value = '';
$life = -1;
}
$life = $life > 0 ? $timestamp + $life : ($life < 0 ? $timestamp - 31536000 : 0);
$path = $httponly && PHP_VERSION < '5.2.0' ? "$cookiepath; HttpOnly" : $cookiepath;
$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
if(PHP_VERSION < '5.2.0') {
setcookie($var, $value, $life, $path, $cookiedomain, $secure);
} else {
setcookie($var, $value, $life, $path, $cookiedomain, $secure, $httponly);
}
}
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 dgmdate($format, $timestamp, $convert = 1) {
$s = gmdate($format, $timestamp);
if($GLOBALS['dateconvert'] && $convert) {
if($GLOBALS['discuz_uid']) {
if(!isset($GLOBALS['disableddateconvert'])) {
$customshow = str_pad(base_convert($GLOBALS['customshow'], 10, 3), 4, '0', STR_PAD_LEFT);
$GLOBALS['disableddateconvert'] = $customshow{0};
}
if($GLOBALS['disableddateconvert']) {
return $s;
}
}
if(!isset($GLOBALS['todaytimestamp'])) {
$GLOBALS['todaytimestamp'] = $GLOBALS['timestamp'] - ($GLOBALS['timestamp'] + $GLOBALS['timeoffset'] * 3600) % 86400 + $GLOBALS['timeoffset'] * 3600;
}
$lang = $GLOBALS['dlang']['date'];
$time = $GLOBALS['timestamp'] + $GLOBALS['timeoffset'] * 3600 - $timestamp;
if($timestamp >= $GLOBALS['todaytimestamp']) {
if($time > 3600) {
return '<span title="'.$s.'">'.intval($time / 3600).' '.$lang[4].$lang[0].'</span>';
} elseif($time > 1800) {
return '<span title="'.$s.'">'.$lang[5].$lang[4].$lang[0].'</span>';
} elseif($time > 60) {
return '<span title="'.$s.'">'.intval($time / 60).' '.$lang[6].$lang[0].'</span>';
} elseif($time > 0) {
return '<span title="'.$s.'">'.$time.' '.$lang[7].$lang[0].'</span>';
} elseif($time == 0) {
return '<span title="'.$s.'">'.$lang[8].'</span>';
} else {
return $s;
}
} elseif(($days = intval(($GLOBALS['todaytimestamp'] - $timestamp) / 86400)) >= 0 && $days < 7) {
if($days == 0) {
return '<span title="'.$s.'">'.$lang[2].' '.gmdate($GLOBALS['timeformat'], $timestamp).'</span>';
} elseif($days == 1) {
return '<span title="'.$s.'">'.$lang[3].' '.gmdate($GLOBALS['timeformat'], $timestamp).'</span>';
} else {
return '<span title="'.$s.'">'.($days + 1).' '.$lang[1].$lang[0].' '.gmdate($GLOBALS['timeformat'], $timestamp).'</span>';
}
} else {
return $s;
}
} else {
return $s;
}
}
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 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 formulaperm($formula, $type = 0) {
global $_DSESSION, $extcredits, $formulamessage, $usermsg, $forum, $language;
if((!$formula || $_DSESSION['adminid'] == 1 || $forum['ismoderator']) && !$type) {
return;
}
$formula = unserialize($formula);$formula = $formula[1];
if(!$formula) {
return;
}
@eval("\$formulaperm = ($formula) ? TRUE : FALSE;");
if(!$formulaperm || $type == 2) {
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);
if($type == 1) {
showmessage('medal_permforum_nopermission', NULL, 'NOPERM');
} elseif($type == 2) {
return $formulamessage;
} else {
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 getrobot() {
if(!defined('IS_ROBOT')) {
$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
if(!strexists($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
define('IS_ROBOT', FALSE);
} elseif(preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
define('IS_ROBOT', TRUE);
} else {
define('IS_ROBOT', FALSE);
}
}
return IS_ROBOT;
}
function get_home($uid) {
$uid = sprintf("%05d", $uid);
$dir1 = substr($uid, 0, -4);
$dir2 = substr($uid, -4, 2);
$dir3 = substr($uid, -2, 2);
return $dir1.'/'.$dir2.'/'.$dir3;
}
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 implodeids($array) {
if(!empty($array)) {
return "'".implode("','", is_array($array) ? $array : array($array))."'";
} else {
return '';
}
}
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 modthreadkey($tid) {
global $adminid, $discuz_user, $discuz_uid, $discuz_pw, $timestamp, $discuz_auth_key;
return $adminid > 0 ? md5($discuz_user.$discuz_uid.$discuz_auth_key.substr($timestamp, 0, -7).$tid) : '';
}
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
global $maxpage;
$ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".dhtmlspecialchars($_GET['ajaxtarget'])."\" " : '';
if(defined('IN_ADMINCP')) {
$shownum = $showkbd = TRUE;
$lang['prev'] = '‹‹';
$lang['next'] = '››';
} else {
$shownum = $showkbd = FALSE;
$lang['prev'] = ' ';
$lang['next'] = $GLOBALS['dlang']['nextpage'];
}
$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.'>'.$lang['prev'].'</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 .= ($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>'.$lang['next'].'</a>' : '').
($showkbd && !$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">'.($shownum && !$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 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 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 random($length, $numeric = 0) {
PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
$hash = '';
$max = strlen($seed) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $seed[mt_rand(0, $max)];
}
return $hash;
}
function request($cachekey, $fid = 0, $type = 0, $return = 0) {
global $timestamp, $_DCACHE;
$datalist = '';
if($fid && CURSCRIPT == 'forumdisplay') {
$specialfid = $GLOBALS['forum']['fid'];
$key = $cachekey = empty($GLOBALS['infosidestatus']['f'.$specialfid][$type]) ? $GLOBALS['infosidestatus'][$type] : $GLOBALS['infosidestatus']['f'.$specialfid][$type];
$cachekey .= '_fid'.$specialfid;
} else {
$specialfid = 0;
if(!$type) {
$key = $cachekey;
} else {
$key = $cachekey = $cachekey[$type];
}
}
$cachefile = DISCUZ_ROOT.'./forumdata/cache/request_'.md5($cachekey).'.php';
if((@!include($cachefile)) || $expiration < $timestamp) {
include_once DISCUZ_ROOT.'./forumdata/cache/cache_request.php';
require_once DISCUZ_ROOT.'./include/request.func.php';
parse_str($_DCACHE['request'][$key]['url'], $requestdata);
$datalist = parse_request($requestdata, $cachefile, 0, $specialfid, $key);
}
if(!empty($nocachedata)) {
include_once DISCUZ_ROOT.'./forumdata/cache/cache_request.php';
require_once DISCUZ_ROOT.'./include/request.func.php';
foreach($nocachedata as $key => $v) {
$cachefile = DISCUZ_ROOT.'./forumdata/cache/request_'.md5($key).'.php';
parse_str($_DCACHE['request'][$key]['url'], $requestdata);
$datalist = str_replace($v, parse_request($requestdata, $cachefile, 0, $specialfid, $key), $datalist);
}
}
if(!$return) {
echo $datalist;
} else {
return $datalist;
}
}
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 = '') {
extract($GLOBALS, EXTR_SKIP);
include language('pms');
require_once DISCUZ_ROOT.'./uc_client/client.php';
if(isset($language[$subject])) {
eval("\$subject = addslashes(\"".$language[$subject]."\");");
}
if(isset($language[$message])) {
eval("\$message = addslashes(\"".$language[$message]."\");");
}
if($fromid === '') {
$fromid = $discuz_uid;
}
uc_pm_send($fromid, $toid, $subject, $message);
}
function showmessage($message, $url_forward = '', $extra = '', $forwardtype = 0) {
extract($GLOBALS, EXTR_SKIP);
global $extrahead, $discuz_uid, $discuz_action, $debuginfo, $seccode, $seccodestatus, $fid, $tid, $charset, $show_message, $inajax, $_DCACHE, $advlist;
define('CACHE_FORBIDDEN', TRUE);
$show_message = $message;$messagehandle = 0;
$msgforward = unserialize($_DCACHE['settings']['msgforward']);
$refreshtime = intval($msgforward['refreshtime']);
$refreshtime = empty($forwardtype) ? $refreshtime : ($refreshtime ? $refreshtime : 3);
$msgforward['refreshtime'] = $refreshtime * 1000;
$url_forward = empty($url_forward) ? '' : (empty($_DCOOKIE['sid']) && $transsidstatus ? transsid($url_forward) : $url_forward);
$seccodecheck = $seccodestatus & 2;
if($url_forward && (!empty($quickforward) || empty($inajax) && $msgforward['quick'] && $msgforward['messages'] && @in_array($message, $msgforward['messages']))) {
updatesession();
dheader("location: ".str_replace('&', '&', $url_forward));
}
if(!empty($infloat)) {
if($extra) {
$messagehandle = $extra;
}
$extra = '';
}
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 = $inajax ? 'ajax_' : '';
eval("\$show_message = \"".(isset($language[$pre.$message]) ? $language[$pre.$message] : $language[$message])."\";");
unset($pre);
}
if(empty($infloat)) {
$show_message .= $url_forward && empty($inajax) ? '<script>setTimeout("window.location.href =\''.$url_forward.'\';", '.$msgforward['refreshtime'].');</script>' : '';
} elseif($handlekey) {
$show_message = str_replace("'", "\'", $show_message);
if($url_forward) {
$show_message = "<script type=\"text/javascript\" reload=\"1\">\nif($('return_$handlekey')) $('return_$handlekey').className = 'onright';\nif(typeof submithandle_$handlekey =='function') {submithandle_$handlekey('$url_forward', '$show_message');} else {location.href='$url_forward'}\n</script>";
} else {
$show_message .= "<script type=\"text/javascript\" reload=\"1\">\nif(typeof messagehandle_$handlekey =='function') {messagehandle_$handlekey('$messagehandle', '$show_message');}\n</script>";
}
}
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') {
include template('nopermission');
} else {
include template('showmessage');
}
dexit();
}
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);
}
return;
} elseif($seccodedata['type'] == 3) {
$s = sprintf('%04s', base_convert($seccode, 10, 20));
$seccodeunits = 'CEFHKLMNOPQRSTUVWXYZ';
} else {
$s = sprintf('%04s', base_convert($seccode, 10, 24));
$seccodeunits = 'BCEFGHJKMPQRTVWXY2346789';
}
$seccode = '';
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, $seclevel, $seccode, $seccodedata, $seccodeverify, $secanswer, $_DCACHE, $_DCOOKIE, $timestamp, $discuz_uid;
if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && $GLOBALS['formhash'] == formhash() && empty($_SERVER['HTTP_X_FLASH_VERSION']) && (empty($_SERVER['HTTP_REFERER']) ||
preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
if($seccodecheck) {
if(!$seclevel) {
$key = $seccodedata['type'] != 3 ? '' : $_DCACHE['settings']['authkey'].date('Ymd');
list($seccode, $expiration, $seccodeuid) = explode("\t", authcode($_DCOOKIE['secc'], 'DECODE', $key));
if($seccodeuid != $discuz_uid || $timestamp - $expiration > 600) {
showmessage('submit_seccode_invalid');
}
dsetcookie('secc', '');
} else {
$tmp = substr($seccode, 0, 1);
}
seccodeconvert($seccode);
if(strtoupper($seccodeverify) != $seccode) {
showmessage('submit_seccode_invalid');
}
$seclevel && $seccode = random(6, 1) + $tmp * 1000000;
}
if($secqaacheck) {
if(!$seclevel) {
list($seccode, $expiration, $seccodeuid) = explode("\t", authcode($_DCOOKIE['secq'], 'DECODE'));
if($seccodeuid != $discuz_uid || $timestamp - $expiration > 600) {
showmessage('submit_secqaa_invalid');
}
dsetcookie('secq', '');
}
require_once DISCUZ_ROOT.'./forumdata/cache/cache_secqaa.php';
if(md5($secanswer) != $_DCACHE['secqaa'][substr($seccode, 0, 1)]['answer']) {
showmessage('submit_secqaa_invalid');
}
$seclevel && $seccode = random(1, 1) * 1000000 + substr($seccode, -6);
}
return TRUE;
} else {
showmessage('submit_invalid');
}
}
}
function template($file, $templateid = 0, $tpldir = '') {
global $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 && !file_exists($tplfile)) {
$tplfile = DISCUZ_ROOT.'./templates/default/'.$file.'.htm';
}
@checktplrefresh($tplfile, $tplfile, filemtime($objfile), $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) {
if($threadtypes = $GLOBALS['forum']['threadtypes']) {
$html = '<select name="typeid" id="typeid"><option value="0"> </option>';
foreach($threadtypes['types'] as $typeid => $name) {
$html .= '<option value="'.$typeid.'" '.($curtypeid == $typeid ? 'selected' : '').'>'.strip_tags($name).'</option>';
}
$html .= '</select>';
return $html;
} else {
return '';
}
}
function sortselect($cursortid = 0, $modelid = 0, $onchange = '') {
global $fid, $sid, $extra;
if($threadsorts = $GLOBALS['forum']['threadsorts']) {
$onchange = $onchange ? $onchange : "onchange=\"ajaxget('post.php?action=threadsorts&sortid='+this.options[this.selectedIndex].value+'&fid=$fid&sid=$sid', 'threadsorts', 'threadsortswait')\"";
$selecthtml = '';
foreach($threadsorts['types'] as $sortid => $name) {
$sorthtml = '<option value="'.$sortid.'" '.($cursortid == $sortid ? 'selected="selected"' : '').' class="special">'.strip_tags($name).'</option>';
$selecthtml .= $modelid ? ($threadsorts['modelid'][$sortid] == $modelid ? $sorthtml : '') : $sorthtml;
}
$hiddeninput = $cursortid ? '<input type="hidden" name="sortid" value="'.$cursortid.'" />' : '';
$html = '<select name="sortid" '.$onchange.'><option value="0"> </option>'.$selecthtml.'</select><span id="threadsortswait"></span>'.$hiddeninput;
return $html;
} else {
return '';
}
}
function updatecredits($uids, $creditsarray, $coef = 1, $extrasql = '') {
if($uids && ((!empty($creditsarray) && is_array($creditsarray)) || $extrasql)) {
global $db, $tablepre, $discuz_uid, $creditnotice, $cookiecredits;
$self = $creditnotice && $uids == $discuz_uid;
if($self && !isset($cookiecredits)) {
$cookiecredits = !empty($_COOKIE['discuz_creditnotice']) ? explode('D', $_COOKIE['discuz_creditnotice']) : array_fill(0, 9, 0);
}
$creditsadd = $comma = '';
foreach($creditsarray as $id => $addcredits) {
$creditsadd .= $comma.'extcredits'.$id.'=extcredits'.$id.'+('.intval($addcredits).')*('.$coef.')';
$comma = ', ';
if($self) {
$cookiecredits[$id] += intval($addcredits) * $coef;
}
}
if($self) {
dsetcookie('discuz_creditnotice', implode('D', $cookiecredits).'D'.$discuz_uid, 43200, 0);
}
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;
$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' $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)
VALUES ('$sid', '$ips[0]', '$ips[1]', '$ips[2]', '$ips[3]', '$discuz_uid', '$discuz_user', '$groupid', '$styleid', '$invisible', '$discuz_action', '$timestamp', '$lastolupdate', '$seccode', '$fid', '$tid')", '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 wipespecial($str) {
return str_replace(array( "\n", "\r", '..'), array('', '', ''), $str);
}
function discuz_uc_avatar($uid, $size = '', $returnsrc = FALSE) {
if($uid > 0) {
$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
$uid = abs(intval($uid));
if(empty($GLOBALS['avatarmethod'])) {
return $returnsrc ? UC_API.'/avatar.php?uid='.$uid.'&size='.$size : '<img src="'.UC_API.'/avatar.php?uid='.$uid.'&size='.$size.'" />';
} else {
$uid = sprintf("%09d", $uid);
$dir1 = substr($uid, 0, 3);
$dir2 = substr($uid, 3, 2);
$dir3 = substr($uid, 5, 2);
$file = UC_API.'/data/avatar/'.$dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).'_avatar_'.$size.'.jpg';
return $returnsrc ? $file : '<img src="'.$file.'" onerror="this.onerror=null;this.src=\''.UC_API.'/images/noavatar_'.$size.'.gif\'" />';
}
} else {
$file = $GLOBALS['boardurl'].IMGDIR.'/syspm.gif';
return $returnsrc ? $file : '<img src="'.$file.'" />';
}
}
function loadmultiserver($type = '') {
global $db, $dbcharset, $multiserver;
$type = empty($type) && defined('CURSCRIPT') ? CURSCRIPT : $type;
static $sdb = null;
if($type && !empty($multiserver['enable'][$type])) {
if(!is_a($sdb, 'dbstuff')) $sdb = new dbstuff();
if($sdb->link > 0) {
return $sdb;
} elseif($sdb->link === null && (!empty($multiserver['slave']['dbhost']) || !empty($multiserver[$type]['dbhost']))) {
$setting = !empty($multiserver[$type]['host']) ? $multiserver[$type] : $multiserver['slave'];
$sdb->connect($setting['dbhost'], $setting['dbuser'], $setting['dbpw'], $setting['dbname'], $setting['pconnect'], false, $dbcharset);
if($sdb->link) {
return $sdb;
} else {
$sdb->link = -32767;
}
}
}
return $db;
}
function swapclass($classname) {
global $swapc;
$swapc = isset($swapc) && $swapc != $classname ? $classname : '';
return $swapc;
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/global.func.php
|
PHP
|
asf20
| 43,632
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: ftp.func.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/ftp.func.php
|
PHP
|
asf20
| 3,711
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: discuzcode.func.php 17473 2008-12-25 02:10:55Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
include template('discuzcode');
$discuzcodes = array(
'pcodecount' => -1,
'codecount' => 0,
'codehtml' => '',
'smiliesreplaced' => 0,
'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';
}
mt_srand((double)microtime() * 1000000);
function attachtag($pid, $aid, &$postlist, $sidauth) {
global $attachrefcheck, $thumbstatus, $extcredits, $creditstrans, $creditstransextra, $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, $sidauth);
}
function censor($message) {
global $_DCACHE;
require_once(DISCUZ_ROOT.'/forumdata/cache/cache_censor.php');
if($_DCACHE['censor']['banned']) {
$bbcodes = 'b|i|u|color|size|font|align|list|indent|url|email|hide|quote|code|free|table|tr|td|img|swf|attach|payto|float'.($_DCACHE['bbcodes_display'] ? '|'.implode('|', array_keys($_DCACHE['bbcodes_display'])) : '');
if(preg_match($_DCACHE['censor']['banned'], @preg_replace(array("/\[($bbcodes)=?.*\]/iU", "/\[\/($bbcodes)\]/i"), '', $message).$message)) {
showmessage('word_banned');
}
}
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] = 0;
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 = dhtmlspecialchars(str_replace('\\"', '"', preg_replace("/^[\n\r]*(.+?)[\n\r]*$/is", "\\1", $code)));
$code = str_replace("\n", "<li>", $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 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 && (strpos($message, '[/code]') || strpos($message, '[/CODE]')) !== FALSE) {
$message = preg_replace("/\s*\[code\](.+?)\[\/code\]\s*/ies", "codedisp('\\1')", $message);
}
$msglower = strtolower($message);
$htmlrule = 0;
if($htmlrule) {
$htmlon = $htmlon && $allowhtml ? 1 : 0;
}
if(!$htmlon) {
$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'])) {
if(!$discuzcodes['smiliesreplaced']) {
foreach($GLOBALS['_DCACHE']['smilies']['replacearray'] AS $key => $smiley) {
$GLOBALS['_DCACHE']['smilies']['replacearray'][$key] = '<img src="images/smilies/'.$GLOBALS['_DCACHE']['smileytypes'][$GLOBALS['_DCACHE']['smilies']['typearray'][$key]]['directory'].'/'.$smiley.'" smilieid="'.$key.'" border="0" alt="" />';
}
$discuzcodes['smiliesreplaced'] = 1;
}
$message = preg_replace($GLOBALS['_DCACHE']['smilies']['searcharray'], $GLOBALS['_DCACHE']['smilies']['replacearray'], $message, $maxsmilies);
}
if(!$bbcodeoff && $allowbbcode) {
if(strpos($msglower, '[/url]') !== FALSE) {
$message = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)([^\[\"']+?))?\](.+?)\[\/url\]/ies", "parseurl('\\1', '\\5')", $message);
}
if(strpos($msglower, '[/email]') !== FALSE) {
$message = preg_replace("/\[email(=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+))?\](.+?)\[\/email\]/ies", "parseemail('\\1', '\\4')", $message);
}
$message = str_replace(array(
'[/color]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]',
'[i=s]', '[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
'[list=A]', '[*]', '[/list]', '[indent]', '[/indent]', '[/float]'
), array(
'</font>', '</font>', '</font>', '</p>', '<strong>', '</strong>', '<i class="pstatus">', '<i>',
'</i>', '<u>', '</u>', '<ul>', '<ul type="1" class="litype_1">', '<ul type="a" class="litype_2">',
'<ul type="A" class="litype_3">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
), preg_replace(array(
"/\[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"
), array(
"<font color=\"\\1\">",
"<font size=\"\\1\">",
"<font style=\"font-size: \\1\">",
"<font face=\"\\1 \">",
"<p align=\"\\1\">",
"<span style=\"float: \\1;\">"
), $message));
$nest = 0;
while(strpos($msglower, '[table') !== FALSE && strpos($msglower, '[/table]') !== FALSE){
$message = preg_replace("/\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*(.+?)\s*\[\/table\]/ies", "parsetable('\\1', '\\2', '\\3')", $message);
if(++$nest > 4) break;
}
if($parsetype != 1) {
if(strpos($msglower, '[/quote]') !== FALSE) {
$message = preg_replace("/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is", tpl_quote(), $message);
}
if(strpos($msglower, '[/free]') !== FALSE) {
$message = preg_replace("/\s*\[free\][\n\r]*(.+?)[\n\r]*\[\/free\]\s*/is", tpl_free(), $message);
}
}
if(strpos($msglower, '[/media]') !== FALSE) {
$message = preg_replace("/\[media=([\w,]+)\]\s*([^\[\<\r\n]+?)\s*\[\/media\]/ies", $allowmediacode ?"parsemedia('\\1', '\\2')" : "bbcodeurl('\\2', '<a href=\"%s\" target=\"_blank\">%s</a>')", $message);
}
if($parsetype != 1 && $allowbbcode == 2 && $GLOBALS['_DCACHE']['bbcodes']) {
$message = preg_replace($GLOBALS['_DCACHE']['bbcodes']['searcharray'], $GLOBALS['_DCACHE']['bbcodes']['replacearray'], $message);
}
if($parsetype != 1 && strpos($msglower, '[/hide]') !== FALSE) {
if(strpos($msglower, '[hide]') !== FALSE) {
$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);
$message .= '<script type="text/javascript">replyreload += \',\' + '.$pid.';</script>';
$hideattach[$pid] = 0;
}
}
if(strpos($msglower, '[hide=') !== FALSE) {
$message = preg_replace("/\[hide=(\d+)\]\s*(.+?)\s*\[\/hide\]/ies", "creditshide(\\1,'\\2', $pid)", $message);
}
}
}
if(!$bbcodeoff) {
if($parsetype != 1 && strpos($msglower, '[swf]') !== FALSE) {
$message = preg_replace("/\[swf\]\s*([^\[\<\r\n]+?)\s*\[\/swf\]/ies", "bbcodeurl('\\1', ' <img src=\"images/attachicons/flash.gif\" align=\"absmiddle\" alt=\"\" /> <a href=\"%s\" target=\"_blank\">Flash: %s</a> ')", $message);
}
if(strpos($msglower, '[/img]') !== FALSE) {
$message = preg_replace(array(
"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",
"/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies"
), $allowimgcode ? array(
"bbcodeurl('\\1', '<img src=\"%s\" onload=\"thumbImg(this)\" alt=\"\" />')",
"bbcodeurl('\\3', '<img width=\"\\1\" height=\"\\2\" src=\"%s\" border=\"0\" alt=\"\" />')"
) : array(
"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(array("/(^|>)([^<]+)(?=<|$)/sUe", "/<highlight>(.*)<\/highlight>/siU"), array("highlight('\\2', \$highlightarray, '\\1')", "<strong><font color=\"#FF0000\">\\1</font></strong>"), $message);
}
unset($msglower);
return $htmlon ? $message : nl2br(str_replace(array("\t", ' ', ' '), array(' ', ' ', ' '), $message));
}
function parseurl($url, $text) {
if(!$url && preg_match("/((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)[^\[\"']+/i", trim($text), $matches)) {
$url = $matches[0];
$length = 65;
if(strlen($url) > $length) {
$text = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
}
return '<a href="'.(substr(strtolower($url), 0, 4) == 'www.' ? 'http://'.$url : $url).'" target="_blank">'.$text.'</a>';
} else {
$url = substr($url, 1);
if(substr(strtolower($url), 0, 4) == 'www.') {
$url = 'http://'.$url;
}
return '<a href="'.$url.'" target="_blank">'.$text.'</a>';
}
}
function parseemail($email, $text) {
if(!$email && preg_match("/\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*/i", $text, $matches)) {
$email = trim($matches[0]);
return '<a href="mailto:'.$email.'">'.$email.'</a>';
} else {
return '<a href="mailto:'.substr($email, 1).'">'.$text.'</a>';
}
}
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));
}
if(substr($width, -1) == '%') {
$width = substr($width, 0, -1) <= 98 ? intval($width).'%' : '98%';
} else {
$width = intval($width);
$width = $width ? ($width <= 560 ? $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($params, $url) {
$params = explode(',', $params);
if(in_array(count($params), array(3, 4))) {
$type = $params[0];
$width = intval($params[1]) > 800 ? 800 : intval($params[1]);
$height = intval($params[2]) > 600 ? 600 : intval($params[2]);
$autostart = 0;
$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;
default : return;
}
}
return;
}
function videocode($message, $tid, $pid) {
global $vsiteid, $vsiteurl, $boardurl;
$vsiteurl = urlencode($vsiteurl);
$id = random(5);
$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 = "\n<span id=\"vid_$id\"></span><script type=\"text/javascript\" reload=\"1\">\n$('vid_$id').innerHTML=AC_FL_RunContent('width', '438', 'height', '373', 'src', '$playurl', 'quality', 'high', 'id', 'object_flash_player', 'menu', 'false', 'allowScriptAccess', 'always', 'allowFullScreen', 'true');\n</script>";
return preg_replace("/\[video=(\d)\](\w+)\[\/video\]/", "$flashplayer", $message);
}
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:'.WRAPBG.'">'.$seo.$randomstr.'</font>'."\r\n" :
"\r\n".'<span style="display:none">'.$randomstr.$seo.'</span>';
}
function highlight($text, $words, $prepend) {
$text = str_replace('\"', '"', $text);
foreach($words AS $key => $replaceword) {
$text = str_replace($replaceword, '<highlight>'.$replaceword.'</highlight>', $text);
}
return "$prepend$text";
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/discuzcode.func.php
|
PHP
|
asf20
| 17,397
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: viewthread_video.inc.php 16698 2008-11-14 07:58:56Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
require_once DISCUZ_ROOT.'./api/video.php';
$videolist = array();
$vautoplay = $videosource = '';
$query = $db->query("SELECT vid, vtitle, vautoplay, vtime, vview, vthumb FROM {$tablepre}videos WHERE tid='$tid' ORDER BY displayorder");
while($videoinfo = $db->fetch_array($query)) {
if($videoinfo['vthumb']) {
$videosource = 1;
} else {
$videoinfo['vthumb'] = VideoClient_Util::getThumbUrl($videoinfo['vid'], 'small');
}
$videoinfo['vtime'] = $videoinfo['vtime'] ? sprintf("%02d", intval($videoinfo['vtime'] / 60)).':'.sprintf("%02d", intval($videoinfo['vtime'] % 60)) : '';
$videolist[] = $videoinfo;
}
if(!empty($videolist)) {
$videocount = count($videolist);
if(!empty($vid)) {
foreach($videolist as $video) {
if($video['vid'] == $vid) {
$vid = dhtmlspecialchars($video['vid']);
$vautoplay = $autoplay ? intval($autoplay) :$video['vautoplay'];
break;
}
}
} else {
$vid = $videolist[0]['vid'];
$vautoplay = $autoplay ? intval($autoplay) : $videolist[0]['vautoplay'];
}
if(!$videosource) {
$client = new VideoClient_Util($appid, $siteid, $sitekey);
$videoshow = $client->createPlayer(array(), array('ivid' => $vid, 'site' => $boardurl, 'auto' => $vautoplay));
} else {
$playurl = "http://union.bokecc.com/flash/discuz2/player.swf?siteid=$vsiteid&vid=$vid&tid=$tid&pid=$pid&autoStart=$vautoplay&referer=".urlencode($boardurl."viewthread.php?tid=$tid");
$videoshow = '<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">'.
'<param name="movie" value='.$playurl.'>'.
'<param name="quality" value="high">'.
'<param name="allowScriptAccess" value="always">'.
'<param name="allowFullScreen" value="true">'.
'<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"></object>';
}
} else {
$db->query("UPDATE {$tablepre}threads SET special=0 WHERE tid='$tid'", 'UNBUFFERED');
dheader("Location: {$boardurl}viewthread.php?tid=$tid");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/viewthread_video.inc.php
|
PHP
|
asf20
| 2,504
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cache.func.php 17540 2009-01-21 01:20:42Z cnteacher $
*/
define('DISCUZ_KERNEL_VERSION', '7.0.0');
define('DISCUZ_KERNEL_RELEASE', '20090121');
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'),
'request' => array('request'),
'medals' => array('medals'),
'magics' => array('magics'),
'topicadmin' => array('modreasons'),
'archiver' => array('advs_archiver'),
'register' => array('advs_register'),
'faqs' => array('faqs'),
'secqaa' => array('secqaa'),
'censor' => array('censor'),
'ipbanned' => array('ipbanned'),
'smilies' => array('smilies_js'),
'index' => array('announcements', 'onlinelist', 'forumlinks', 'advs_index'),
'forumdisplay' => array('smilies', 'announcements_forum', 'globalstick', 'floatthreads', 'forums', 'icons', 'onlinelist', 'advs_forumdisplay'),
'viewthread' => array('smilies', 'smileytypes', 'forums', 'usergroups', 'ranks', 'bbcodes', 'smilies', 'advs_viewthread', 'tags_viewthread', 'custominfo', 'groupicon'),
'post' => array('bbcodes_display', 'bbcodes', 'smileycodes', 'smilies', 'smileytypes', 'icons'),
'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 = $styledata = $styleicons = array();
$defaultstyleid = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable = 'styleid'");
list(, $imagemaxwidth) = explode("\t", $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable = 'zoomstatus'"));
$imagemaxwidth = $imagemaxwidth ? $imagemaxwidth : 600;
$imagemaxwidthint = intval($imagemaxwidth);
$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']]);
$datanew = array();
$data['imgdir'] = $data['imgdir'] ? $data['imgdir'] : 'images/default';
$data['styleimgdir'] = $data['styleimgdir'] ? $data['styleimgdir'] : $data['imgdir'];
foreach($data as $k => $v) {
if(substr($k, -7, 7) == 'bgcolor') {
$newkey = substr($k, 0, -7).'bgcode';
$datanew[$newkey] = setcssbackground($data, $k);
}
}
$data = array_merge($data, $datanew);
$styleicons[$data['styleid']] = $data['menuhover'];
if(strstr($data['boardimg'], ',')) {
$flash = explode(",", $data['boardimg']);
$flash[0] = trim($flash[0]);
$flash[0] = preg_match('/^http:\/\//i', $flash[0]) ? $flash[0] : $data['styleimgdir'].'/'.$flash[0];
$data['boardlogo'] = "<embed src=\"".$flash[0]."\" width=\"".trim($flash[1])."\" height=\"".trim($flash[2])."\" type=\"application/x-shockwave-flash\" wmode=\"transparent\"></embed>";
} else {
$data['boardimg'] = preg_match('/^http:\/\//i', $data['boardimg']) ? $data['boardimg'] : $data['styleimgdir'].'/'.$data['boardimg'];
$data['boardlogo'] = "<img src=\"$data[boardimg]\" alt=\"$bbname\" border=\"0\" />";
}
$data['bold'] = $data['nobold'] ? 'normal' : 'bold';
$contentwidthint = intval($data['contentwidth']);
$contentwidthint = $contentwidthint ? $contentwidthint : 600;
if(substr(trim($data['contentwidth']), -1, 1) != '%') {
if(substr(trim($imagemaxwidth), -1, 1) != '%') {
$data['imagemaxwidth'] = $imagemaxwidthint > $contentwidthint ? $contentwidthint : $imagemaxwidthint;
} else {
$data['imagemaxwidth'] = intval($contentwidthint * $imagemaxwidthint / 100);
}
} else {
if(substr(trim($imagemaxwidth), -1, 1) != '%') {
$data['imagemaxwidth'] = '%'.$imagemaxwidthint;
} else {
$data['imagemaxwidth'] = ($imagemaxwidthint > $contentwidthint ? $contentwidthint : $imagemaxwidthint).'%';
}
}
$data['verhash'] = random(3);
$styledata[] = $data;
}
foreach($styledata as $data) {
$data['styleicons'] = $styleicons;
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']);
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 == 'threadsorts') {
$sortlist = $templatedata = array();
$query = $db->query("SELECT t.typeid AS sortid, 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.sortid
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']);
$sortid = $data['sortid'];
$optionid = $data['optionid'];
$sortlist[$sortid][$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);
}
$sortlist[$sortid][$optionid]['choices'] = $choices;
} else {
$typelist[$sortid][$optionid]['choices'] = array();
}
} elseif(in_array($data['type'], array('text', 'textarea'))) {
$sortlist[$sortid][$optionid]['maxlength'] = intval($data['rules']['maxlength']);
} elseif($data['type'] == 'image') {
$sortlist[$sortid][$optionid]['maxwidth'] = intval($data['rules']['maxwidth']);
$sortlist[$sortid][$optionid]['maxheight'] = intval($data['rules']['maxheight']);
} elseif($data['type'] == 'number') {
$sortlist[$sortid][$optionid]['maxnum'] = intval($data['rules']['maxnum']);
$sortlist[$sortid][$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($sortlist as $sortid => $option) {
writetocache($sortid, '', "\$_DTYPE = ".arrayeval($option).";\n\n\$_DTYPETEMPLATE = \"".str_replace('"', '\"', $templatedata[$sortid])."\";\n", 'threadsort_');
}
}
}
function setcssbackground(&$data, $code) {
$codes = explode(' ', $data[$code]);
$css = $codevalue = '';
for($i = 0; $i < count($codes); $i++) {
if($i < 2) {
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['styleimgdir'].'/'.$codes[$i].'") ';
}
}
} else {
$css .= $codes[$i].' ';
}
}
$data[$code] = $codevalue;
$css = trim($css);
return $css ? 'background: '.$css : '';
}
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('_common' => array('css_common', 'css_append', 'css_editor', 'css_editor_append'),
'_editor' => array('css_editor', 'css_editor_append'),
'_seditor' => array('css_seditor', 'css_seditor_append'),
'_viewthread' => array('css_viewthread', 'css_viewthread_append'),
'_calendar' => array('css_calendar', 'css_calendar_append'),
'_float' => array('css_float', 'css_float_append')
) as $extra => $cssfiles) {
$cssdata = '';
foreach($cssfiles as $css) {
$cssfile = DISCUZ_ROOT.'./'.$data['tpldir'].'/'.$css.'.htm';
!file_exists($cssfile) && $cssfile = DISCUZ_ROOT.'./templates/default/'.$css.'.htm';
if(file_exists($cssfile)) {
$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['styleimgdir']) ? str_replace("url(\"$data[styleimgdir]", "url(\"../../$data[styleimgdir]", $cssdata) : $cssdata;
$cssdata = !preg_match('/^http:\/\//i', $data['styleimgdir']) ? str_replace("url($data[styleimgdir]", "url(../../$data[styleimgdir]", $cssdata) : $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;
$cssdata = preg_replace(array('/\s*([,;:\{\}])\s*/', '/[\t\n\r]/', '/\/\*.+?\*\//'), array('\\1', '',''), $cssdata);
if(@$fp = fopen(DISCUZ_ROOT.'./forumdata/cache/style_'.$data['styleid'].$extra.'.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;
$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')";
break;
case 'custominfo':
$table = 'settings';
$conditions = "WHERE variable IN ('extcredits', 'customauthorinfo', 'postno', 'postnocustom')";
break;
case 'request':
$table = 'request';
$conditions = '';
break;
case 'usergroups':
$table = 'usergroups';
$cols = 'groupid, type, grouptitle, creditshigher, creditslower, stars, color, groupavatar, readaccess, allowcusbbcode';
$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 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>'0' WHERE f.status>0 ORDER BY f.type, f.displayorder";
break;
case 'onlinelist':
$table = 'onlinelist';
$conditions = "ORDER BY displayorder";
break;
case 'groupicon':
$table = 'onlinelist';
$conditions = "ORDER BY displayorder";
break;
case 'forumlinks':
$table = 'forumlinks';
$conditions = "ORDER BY displayorder";
break;
case 'bbcodes':
$table = 'bbcodes';
$conditions = "WHERE available>'0' AND type='0'";
break;
case 'bbcodes_display':
$table = 'bbcodes';
$cols = 'type, tag, icon, explanation, params, prompt';
$conditions = "WHERE available='2' AND icon!='' ORDER BY displayorder";
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.available='1' ORDER BY LENGTH(s.code) DESC";
break;
case 'smileycodes':
$table = 'imagetypes';
$cols = 'typeid, directory';
$conditions = "WHERE type='smiley' AND available='1' ORDER BY displayorder";
break;
case 'smileytypes':
$table = 'imagetypes';
$cols = 'typeid, name, directory';
$conditions = "WHERE type='smiley' AND available='1' ORDER BY displayorder";
break;
case 'smilies_js':
$table = 'imagetypes';
$cols = 'typeid, name, directory';
$conditions = "WHERE type='smiley' AND available='1' 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 '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 = 'fpid, id, identifier, keyword';
$conditions = "WHERE identifier!='' AND keyword!=''";
break;
case 'tags_viewthread':
global $viewthreadtags;
$taglimit = intval($viewthreadtags);
$table = 'tags';
$cols = 'tagname, total';
$conditions = "WHERE closed=0 ORDER BY total DESC LIMIT $taglimit";
break;
}
$data = array();
if(!in_array($cachename, array('secqaa')) && 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', 'ec_credit', 'qihoo', 'insenz', 'spacedata', 'infosidestatus', 'uc', 'outextcredits', 'relatedtag', 'sitemessage', 'msn', 'uchome'))) {
$setting['value'] = unserialize($setting['value']);
}
$GLOBALS[$setting['variable']] = $data[$setting['variable']] = $setting['value'];
}
$data['sitemessage']['time'] = !empty($data['sitemessage']['time']) ? $data['sitemessage']['time'] * 1000 : 0;
$data['sitemessage']['register'] = !empty($data['sitemessage']['register']) ? explode("\n", $data['sitemessage']['register']) : '';
$data['sitemessage']['login'] = !empty($data['sitemessage']['login']) ? explode("\n", $data['sitemessage']['login']) : '';
$data['sitemessage']['newthread'] = !empty($data['sitemessage']['newthread']) ? explode("\n", $data['sitemessage']['newthread']) : '';
$data['sitemessage']['reply'] = !empty($data['sitemessage']['reply']) ? explode("\n", $data['sitemessage']['reply']) : '';
$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']);
}
if(is_array($data['relatedtag']['order'])) {
asort($data['relatedtag']['order']);
$relatedtag = array();
foreach($data['relatedtag']['order'] AS $k => $v) {
$relatedtag['status'][$k] = $data['relatedtag']['status'][$k];
$relatedtag['name'][$k] = $data['relatedtag']['name'][$k];
$relatedtag['limit'][$k] = $data['relatedtag']['limit'][$k];
$relatedtag['template'][$k] = $data['relatedtag']['template'][$k];
}
$data['relatedtag'] = $relatedtag;
foreach((array)$data['relatedtag']['status'] AS $appid => $status) {
if(!$status) {
unset($data['relatedtag']['limit'][$appid]);
}
}
unset($data['relatedtag']['status'], $data['relatedtag']['order'], $relatedtag);
}
$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']['animator'] = 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['styles'] = array();
$query = $db->query("SELECT styleid, name FROM {$tablepre}styles WHERE available='1'");
while($style = $db->fetch_array($query)) {
$data['styles'][$style['styleid']] = dhtmlspecialchars($style['name']);
}
$data['stylejumpstatus'] = $data['stylejump'] && count($data['styles']) > 1;
$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['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']['siteid'];
$data['vkey'] = $data['videoinfo']['authkey'];
$data['vsiteurl'] = $data['videoinfo']['url'];
}
unset($data['videoinfo']);
$outextcreditsrcs = $outextcredits = array();
foreach((array)$data['outextcredits'] as $value) {
$outextcreditsrcs[$value['creditsrc']] = $value['creditsrc'];
$key = $value['appiddesc'].'|'.$value['creditdesc'];
if(!isset($outextcredits[$key])) {
$outextcredits[$key] = array('title' => $value['title'], 'unit' => $value['unit']);
}
$outextcredits[$key]['ratiosrc'][$value['creditsrc']] = $value['ratiosrc'];
$outextcredits[$key]['ratiodesc'][$value['creditsrc']] = $value['ratiodesc'];
$outextcredits[$key]['creditsrc'][$value['creditsrc']] = $value['ratio'];
}
$data['outextcredits'] = $outextcredits;
$exchcredits = array();
$allowexchangein = $allowexchangeout = FALSE;
foreach((array)$data['extcredits'] as $id => $credit) {
$data['extcredits'][$id]['img'] = $credit['img'] ? '<img style="vertical-align:middle" src="'.$credit['img'].'" />' : '';
if(!empty($credit['ratio'])) {
$exchcredits[$id] = $credit;
$credit['allowexchangein'] && $allowexchangein = TRUE;
$credit['allowexchangeout'] && $allowexchangeout = TRUE;
}
$data['creditnotice'] && $data['creditnames'][] = str_replace("'", "\'", htmlspecialchars($id.'|'.$credit['title'].'|'.$credit['unit']));
}
$data['creditnames'] = $data['creditnotice'] ? implode(',', $data['creditnames']) : '';
$creditstranssi = explode(',', $data['creditstrans']);
$data['creditstrans'] = $creditstranssi[0];
unset($creditstranssi[0]);
$data['creditstransextra'] = $creditstranssi;
for($i = 1;$i < 5;$i++) {
$data['creditstransextra'][$i] = !$data['creditstransextra'][$i] ? $data['creditstrans'] : $data['creditstransextra'][$i];
}
$data['exchangestatus'] = $allowexchangein && $allowexchangeout;
$data['transferstatus'] = isset($data['extcredits'][$data['creditstrans']]);
list($data['zoomstatus']) = explode("\t", $data['zoomstatus']);
if($data['insenz']['status'] && $data['insenz']['authkey']) {
$insenz = $data['insenz'];
$softadstatus = intval($insenz['softadstatus']);
$hardadstatus = is_array($insenz['hardadstatus']) && $insenz['jsurl'] ? implode(',', $insenz['hardadstatus']) : '';
$relatedadstatus = intval($insenz['relatedadstatus']);
$insenz_cronnextrun = intval($db->result_first("SELECT nextrun FROM {$tablepre}campaigns ORDER BY nextrun LIMIT 1"));
if(!$softadstatus && !$hardadstatus && !$relatedadstatus && !$insenz['virtualforumstatus'] && !$insenz_cronnextrun) {
$data['insenz']['status'] = $data['insenz']['cronnextrun'] = 0;
$db->query("REPLACE INTO {$tablepre}settings (variable, value) VALUES ('insenz', '".addslashes(serialize($insenz))."')");
$data['insenz'] = array();
} else {
$vfstatus = 0;
if($insenz['virtualforumstatus']) {
$vfstatus = $db->result_first("SELECT COUNT(*) FROM {$tablepre}virtualforums WHERE status=1 AND type='forum'");
}
$data['insenz'] = array(
'siteid' => $insenz['siteid'],
'uid' => intval($insenz['uid']),
'username' => addslashes($insenz['username']),
'hardadstatus' => $hardadstatus,
'vfstatus' => $vfstatus,
'vfpos' => in_array($insenz['vfpos'], array('first', 'rand', 'last')) ? $insenz['vfpos'] : 'first',
'topicrelatedad' => $relatedadstatus && $insenz['topicrelatedad'] ? $insenz['topicrelatedad'] : '',
'traderelatedad' => $relatedadstatus && $insenz['traderelatedad'] ? $insenz['traderelatedad'] : '',
'relatedtrades' => $relatedadstatus && $insenz['traderelatedad'] && $insenz['relatedtrades'] ? $insenz['relatedtrades'] : '',
'cronnextrun' => $insenz_cronnextrun,
'statsnextrun' => intval($insenz['statsnextrun']),
'jsurl' => $insenz['jsurl'],
'hash' => $insenz['hash']
);
}
} else {
$data['insenz'] = array();
}
$data['msn']['on'] = $data['msn']['on'] && $data['msn']['domain'] ? 1 : 0;
$data['msn']['domain'] = $data['msn']['on'] ? $data['msn']['domain'] : 'discuz.org';
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;
}
}
}
}
}
$data['tradeopen'] = $db->result_first("SELECT count(*) FROM {$tablepre}usergroups WHERE allowposttrade='1'") ? 1 : 0;
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'];
}
}
$data['navs'] = $data['subnavs'] = $data['navmns'] = array();
list($mnid) = explode('.', basename($data['indexname']));
$data['navmns'][] = $mnid;$mngsid = 1;
$query = $db->query("SELECT * FROM {$tablepre}navs WHERE available='1' AND parentid='0' ORDER BY displayorder");
while($nav = $db->fetch_array($query)) {
if($nav['type'] == '0' && (($nav['url'] == 'member.php?action=list' && !$data['memliststatus']) || ($nav['url'] == 'tag.php' && !$data['tagstatus']))) {
continue;
}
$nav['style'] = parsehighlight($nav['highlight']);
if($db->result_first("SELECT COUNT(*) FROM {$tablepre}navs WHERE parentid='$nav[id]' AND available='1'")) {
$id = random(6);
$subquery = $db->query("SELECT * FROM {$tablepre}navs WHERE available='1' AND parentid='$nav[id]' ORDER BY displayorder");
$subnavs = "<ul class=\"popupmenu_popup headermenu_popup\" id=\"".$id."_menu\" style=\"display: none\">";
while($subnav = $db->fetch_array($subquery)) {
$subnavs .= "<li><a href=\"$subnav[url]\" hidefocus=\"true\" ".($subnav['title'] ? "title=\"$subnav[title]\" " : '').($subnav['target'] == 1 ? "target=\"_blank\" " : '').parsehighlight($subnav['highlight']).">$subnav[name]</a></li>";
}
$subnavs .= '</ul>';
$data['subnavs'][] = $subnavs;
$data['navs'][$nav['id']]['nav'] = "<li class=\"menu_".$nav['id']."\" id=\"$id\" onmouseover=\"showMenu(this.id)\"><a href=\"$nav[url]\" hidefocus=\"true\" ".($nav['title'] ? "title=\"$nav[title]\" " : '').($nav['target'] == 1 ? "target=\"_blank\" " : '')." class=\"dropmenu\"$nav[style]>$nav[name]</a></li>";
} else {
if($nav['id'] == '3') {
$data['navs'][$nav['id']]['nav'] = !empty($data['plugins']['jsmenu']) ? "<li class=\"menu_3\" id=\"plugin\" onmouseover=\"showMenu(this.id)\"><a href=\"javascript:;\" hidefocus=\"true\" ".($nav['title'] ? "title=\"$nav[title]\" " : '').($nav['target'] == 1 ? "target=\"_blank\" " : '')."class=\"dropmenu\"$nav[style]>$nav[name]</a></li>" : '';
} elseif($nav['id'] == '5') {
$data['navs'][$nav['id']]['nav'] = "<li class=\"menu_5\"><a href=\"misc.php?action=nav\" hidefocus=\"true\" ".($nav['title'] ? "title=\"$nav[title]\" " : '')."onclick=\"floatwin('open_nav', this.href, 600, 410);return false;\"$nav[style]>$nav[name]</a></li>";
} else {
if($nav['id'] == '1') {
$nav['url'] = $GLOBALS['indexname'];
}
list($mnid) = explode('.', basename($nav['url']));
$purl = parse_url($nav['url']);
$getvars = array();
if($purl['query']) {
parse_str($purl['query'], $getvars);
$mnidnew = $mnid.'_'.$mngsid;
$data['navmngs'][$mnid][] = array($getvars, $mnidnew);
$mnid = $mnidnew;
$mngsid++;
}
$data['navmns'][] = $mnid;
$data['navs'][$nav['id']]['nav'] = "<li class=\"menu_".$nav['id']."\"><a href=\"$nav[url]\" hidefocus=\"true\" ".($nav['title'] ? "title=\"$nav[title]\" " : '').($nav['target'] == 1 ? "target=\"_blank\" " : '')."id=\"mn_$mnid\"$nav[style]>$nav[name]</a></li>";
}
}
$data['navs'][$nav['id']]['level'] = $nav['level'];
}
require_once DISCUZ_ROOT.'./uc_client/client.php';
$ucapparray = uc_app_ls();
$data['allowsynlogin'] = isset($ucapparray[UC_APPID]['synlogin']) ? $ucapparray[UC_APPID]['synlogin'] : 1;
$appnamearray = array('UCHOME','XSPACE','DISCUZ','SUPESITE','SUPEV','ECSHOP','ECMALL');
$data['ucapp'] = $data['ucappopen'] = array();
$data['uchomeurl'] = '';
$appsynlogins = 0;
foreach($ucapparray as $apparray) {
if($apparray['appid'] != UC_APPID) {
if(!empty($apparray['synlogin'])) {
$appsynlogins = 1;
}
if($data['uc']['navlist'][$apparray['appid']] && $data['uc']['navopen']) {
$data['ucapp'][$apparray['appid']]['name'] = $apparray['name'];
$data['ucapp'][$apparray['appid']]['url'] = $apparray['url'];
}
}
$data['ucapp'][$apparray['appid']]['viewprourl'] = $apparray['url'].$apparray['viewprourl'];
foreach($appnamearray as $name) {
if($apparray['type'] == $name && $apparray['appid'] != UC_APPID) {
$data['ucappopen'][$name] = 1;
if($name == 'UCHOME') {
$data['uchomeurl'] = $apparray['url'];
} elseif($name == 'XSPACE') {
$data['xspaceurl'] = $apparray['url'];
}
}
}
}
$data['allowsynlogin'] = $data['allowsynlogin'] && $appsynlogins ? 1 : 0;
$data['homeshow'] = $data['uchomeurl'] && $data['uchome']['homeshow'] ? $data['uchome']['homeshow'] : '0';
/*
if($data['uchomeurl']) {
$data['homeshow']['avatar'] = $data['uc']['homeshow'] & 1 ? 1 : 0;
$data['homeshow']['viewpro'] = $data['uc']['homeshow'] & 2 ? 1 : 0;
$data['homeshow']['ad'] = $data['uc']['homeshow'] & 4 ? 1 : 0;
$data['homeshow']['side'] = $data['uc']['homeshow'] & 8 ? 1 : 0;
}
*/
$data['medalstatus'] = intval($db->result_first("SELECT count(*) FROM {$tablepre}medals WHERE available='1'"));
include language('runtime');
$dlang['date'] = explode(',', $dlang['date']);
$data['dlang'] = $dlang;
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' => '$post[digestposts]',
'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['title'] = ($value['img'] ? '<img style="vertical-align:middle" src="'.$value['img'].'" /> ' : '').$value['title'];
$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' 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;
}
}
}
}
$data['postminheight'] = 120 + count($customauthorinfo[1]) * 20;
$customauthorinfo[1] = @implode('', $customauthorinfo[1]);
$customauthorinfo[2] = @implode('', $customauthorinfo[2]);
$data['customauthorinfo'] = $customauthorinfo;
$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['postno'] = $postnocustomnew;
break;
case 'request':
while($request = $db->fetch_array($query)) {
$key = $request['variable'];
$data[$key] = unserialize($request['value']);
unset($data[$key]['parameter'], $data[$key]['comment']);
}
$js = dir(DISCUZ_ROOT.'./forumdata/cache');
while($entry = $js->read()) {
if(preg_match("/^(javascript_|request_)/", $entry)) {
@unlink(DISCUZ_ROOT.'./forumdata/cache/'.$entry);
}
}
$js->close();
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 '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';
}
if(!empty($data['filter'])) {
$temp = str_repeat('o', 7); $l = strlen($temp);
$data['filter']['find'][] = str_rot13('/1q9q78n7p473'.'o3q1925oo7p'.'5o6sss2sr/v');
$data['filter']['replace'][] = str_rot13(str_replace($l, ' ', '****7JR7JVYY7JVA7'.
'GUR7SHGHER7****\aCbjrerq7ol7Pebffqnl7Qvfphm!7Obneq7I')).$l;
}
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'];
$data[$fid2]['users'] = $forum2['users'];
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'];
$data[$fid3]['users'] = $forum3['users'];
}
}
}
}
}
}
}
break;
case 'onlinelist':
$data['legend'] = '';
while($list = $db->fetch_array($query)) {
$data[$list['groupid']] = $list['url'];
$data['legend'] .= "<img src=\"images/common/$list[url]\" /> $list[title] ";
if($list['groupid'] == 7) {
$data['guest'] = $list['title'];
}
}
break;
case 'groupicon':
while($list = $db->fetch_array($query)) {
$data[$list['groupid']] = 'images/common/'.$list['url'];
}
break;
case 'forumlinks':
global $forumlinkstatus;
$data = array();
if($forumlinkstatus) {
$tightlink_content = $tightlink_text = $tightlink_logo = $comma = '';
while($flink = $db->fetch_array($query)) {
if($flink['description']) {
if($flink['logo']) {
$tightlink_content .= '<li><div class="forumlogo"><img src="'.$flink['logo'].'" border="0" alt="'.$flink['name'].'" /></div><div class="forumcontent"><h5><a href="'.$flink['url'].'" target="_blank">'.$flink['name'].'</a></h5><p>'.$flink['description'].'</p></div>';
} else {
$tightlink_content .= '<li><div class="forumcontent"><h5><a href="'.$flink['url'].'" target="_blank">'.$flink['name'].'</a></h5><p>'.$flink['description'].'</p></div>';
}
} 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 .= '<li><a href="'.$flink['url'].'" target="_blank" title="'.$flink['name'].'">'.$flink['name'].'</a></li>';
}
}
}
$data = array($tightlink_content, $tightlink_logo, $tightlink_text);
}
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 'smileycodes':
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'])) {
$data[$smiley['id']] = $smiley['code'];
}
}
}
}
break;
case 'smilies_js':
$return_type = 'var smilies_type = new Array();';
$return_array = 'var smilies_array = new Array();';
$spp = $smcols * $smrows;
while($type = $db->fetch_array($query)) {
$return_data = array();
$return_datakey = '';
$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)) {
$i = 0;$j = 1;$pre = '';
$return_type .= 'smilies_type['.$type['typeid'].'] = [\''.str_replace('\'', '\\\'', $type['name']).'\', \''.str_replace('\'', '\\\'', $type['directory']).'\'];';
$return_datakey .= 'smilies_array['.$type['typeid'].'] = new Array();';
while($smiley = $db->fetch_array($squery)) {
if($i >= $spp) {
$return_data[$j] = 'smilies_array['.$type['typeid'].']['.$j.'] = ['.$return_data[$j].'];';
$j++;$i = 0;$pre = '';
}
$i++;
if($size = @getimagesize('./images/smilies/'.$type['directory'].'/'.$smiley['url'])) {
$smiley['code'] = str_replace('\'', '\\\'', $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']);
$return_data[$j] .= $pre.'[\''.$smileyid.'\', \''.$smiley['code'].'\',\''.str_replace('\'', '\\\'', $smiley['url']).'\',\''.$smiley['w'].'\',\''.$smiley['h'].'\',\''.$smiley['lw'].'\']';
$pre = ',';
}
}
$return_data[$j] = 'smilies_array['.$type['typeid'].']['.$j.'] = ['.$return_data[$j].'];';
}
$return_array .= $return_datakey.implode('', $return_data);
}
$cachedir = DISCUZ_ROOT.'./forumdata/cache/';
if(@$fp = fopen($cachedir.'smilies_var.js', 'w')) {
fwrite($fp, 'var smthumb = \''.$GLOBALS['smthumb'].'\';'.$return_type.$return_array);
fclose($fp);
} else {
exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
}
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 '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']]['fpid'] = $faqs['fpid'];
$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");
$i = 1;
while($secqaa = $db->fetch_array($query)) {
$secqaa['answer'] = md5($secqaa['answer']);
$data[$i] = $secqaa;
$i++;
}
while(($secqaas = count($data)) < 9) {
$data[$secqaas + 1] = $data[array_rand($data)];
}
break;
case 'tags_viewthread':
global $tagstatus;
$tagnames = array();
if($tagstatus) {
$data[0] = $data[1] = array();
while($tagrow = $db->fetch_array($query)) {
$data[0][] = $tagrow['tagname'];
$data[1][] = rawurlencode($tagrow['tagname']);
}
$data[0] = '[\''.implode('\',\'', (array)$data[0]).'\']';
$data[1] = '[\''.implode('\',\'', (array)$data[1]).'\']';
$data[2] = $db->result_first("SELECT count(*) FROM {$tablepre}tags", 0);
}
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(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, $insenz;
$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' || $type == 'intercat' ? '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' && $type == 'text')) {
$advs['type'][$type][] = $adv['advid'];
$advs['items'][$adv['advid']] = $adv['code'];
}
}
}
}
if($insenz['hash'] && $insenz['hardadstatus']) {
$typearray = array('insenz' => 0, 'headerbanner' => 1, 'thread3_1' => 2, 'thread2_1' => 3, 'thread1_1' => 4, 'interthread' => 5, 'footerbanner1' => 6, 'footerbanner2' => 7, 'footerbanner3' => 8);
$hardadstatus = is_array($insenz['hardadstatus']) ? $insenz['hardadstatus'] : explode(',', $insenz['hardadstatus']);
$query = $db->query("SELECT * FROM {$tablepre}advcaches");
while($adv = $db->fetch_array($query)) {
$adv['advid'] = 'i'.$adv['advid'];
if($adv['type'] == 'insenz' && $range == 'all') {
$advs['all']['type']['insenz'][] = $adv['advid'];
$advs['all']['items'][$adv['advid']] = $adv['code'];
} elseif(in_array($typearray[$adv['type']], $hardadstatus)) {
if($adv['target'] == 0) {
if(($adv['type'] == 'interthread' || substr($adv['type'], 0, 6) == 'thread') && $range == 'viewthread') {
$advs['type'][$adv['type']]['forum_all'][] = $adv['advid'];
$advs['items'][$adv['advid']] = $adv['code'];
} elseif(($adv['type'] == 'headerbanner' || substr($adv['type'], 0, 12) == 'footerbanner') && $range == 'all') {
$advs['all']['type'][$adv['type']][] = $adv['advid'];
$advs['all']['items'][$adv['advid']] = $adv['code'];
}
} elseif($range == 'viewthread' || ($range == 'forumdisplay' && ($adv['type'] == 'headerbanner' || substr($adv['type'], 0, 12) == 'footerbanner'))) {
$advs['type'][$adv['type']]['forum_'.$adv['target']][] = $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 parsehighlight($highlight) {
if($highlight) {
$colorarray = array('', 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'gray');
$string = sprintf('%02d', $highlight);
$stylestr = sprintf('%03b', $string[0]);
$style = ' style="';
$style .= $stylestr[0] ? 'font-weight: bold;' : '';
$style .= $stylestr[1] ? 'font-style: italic;' : '';
$style .= $stylestr[2] ? 'text-decoration: underline;' : '';
$style .= $string[1] ? 'color: '.$colorarray[$string[1]] : '';
$style .= '"';
} else {
$style = '';
}
return $style;
}
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/51shangcheng.cn/htdocs/include/cache.func.php
|
PHP
|
asf20
| 73,211
|
<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/51shangcheng.cn/htdocs/include/serverbusy.htm
|
HTML
|
asf20
| 728
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magic.func.php 16688 2008-11-14 06:41:07Z 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) {
$post = $db->fetch_first($sql);
if(!$post) {
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 = ', ';
}
}
$member = $db->fetch_first("SELECT $cols FROM {$tablepre}members WHERE username='$username'");
if(!$member) {
showmessage('magics_target_nonexistence');
} else {
return daddslashes($member, 1);
}
}
function givemagic($username, $magicid, $magicnum, $totalnum, $totalprice) {
global $db, $tablepre, $discuz_uid, $discuz_user, $creditstrans, $creditstransextra, $magicarray;
$member = $db->fetch_first("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) {
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', 0);
updatemagiclog($magicid, '3', $magicnum, $magicarray[$magicid]['price'], '0', '0', $member['uid']);
if(empty($totalprice)) {
usemagic($magicid, $totalnum, $magicnum);
showmessage('magics_give_succeed', '', 1);
}
}
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 (isset($GLOBALS['lang'][$setname]) ? $GLOBALS['lang'][$setname] : $setname.' ').''.($comment ? '<br /><span class="smalltxt">'.$comment.'</span>' : NULL);
if($type == 'radio') {
$value ? $check['true'] = 'checked="checked"' : $check['false'] = 'checked="checked"';
echo "<input type=\"radio\" name=\"$varname\" value=\"1\" class=\"radio\" $check[true] /> {$GLOBALS[lang][yes]} \n".
"<input type=\"radio\" name=\"$varname\" value=\"0\" class=\"radio\" $check[false] /> {$GLOBALS[lang][no]}\n";
} elseif($type == 'text') {
echo "<input type=\"$type\" size=\"12\" name=\"$varname\" value=\"".dhtmlspecialchars($value)."\" class=\"txt\"/>\n";
} else {
echo $type;
}
}
function magicshowtips($tips, $title) {
echo '<p>'.$tips.'</p>';
}
function magicshowtype($name, $type = '') {
$name = $GLOBALS['lang'][$name] ? $GLOBALS['lang'][$name] : $name;
if($type != 'bottom') {
if(!$type) {
echo '</p>';
} else {
echo '<p>';
}
} else {
echo '</p>';
}
}
function magicselect($uid, $typeid, $data) {
global $db, $tablepre;
$magiclist = array();
$dataadd = $char = '';
if($uid) {
$typeidadd = $typeid ? "AND m.type='".intval($typeid)."'" : '';
if($data && is_array($data)) {
if($data['magic']) {
foreach($data['magic'] as $item) {
$dataadd .= $char.'m.'.$item;
$char = ' ,';
}
}
if($data['member']) {
foreach($data['member'] as $item) {
$dataadd .= $char.'m.'.$item;
$char = ' ,';
}
}
} else {
$dataadd = 'm.*, mm.*';
}
$query = $db->query("SELECT $dataadd
FROM {$tablepre}membermagics mm
LEFT JOIN {$tablepre}magics m ON mm.magicid=m.magicid
WHERE mm.uid='$uid' $typeidadd");
while($mymagic = $db->fetch_array($query)) {
$magiclist[] = $mymagic;
}
}
return $magiclist;
}
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/51shangcheng.cn/htdocs/include/magic.func.php
|
PHP
|
asf20
| 8,000
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: trade.func.php 16698 2008-11-14 07:58:56Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$apitype = empty($apitype) || !preg_match('/^[a-z0-9]+$/i', $apitype) ? 'alipay' : $apitype;
require_once DISCUZ_ROOT.'./api/trade/'.$apitype.'.api.php';
function trade_offline($tradelog, $returndlang = 1) {
global $discuz_uid, $language, $trade_message;
$tmp = $return = array();
if($discuz_uid == $tradelog['buyerid']) {
$data = array(
0 => array(4,8),
1 => array(4,8),
8 => array(1,4),
5 => array(7,10),
11 => array(10,7),
12 => array(13)
);
$tmp = $data[$tradelog['status']];
} elseif($discuz_uid == $tradelog['sellerid']) {
$data = array(
0 => array(1,8),
8 => array(1),
4 => array(5),
10 => array(12,11),
13 => array(17)
);
$tmp = $data[$tradelog['status']];
}
if($returndlang) {
for($i = 0, $count = count($tmp);$i < $count;$i++) {
$return[$tmp[$i]] = $language['trade_offline_'.$tmp[$i]];
$trade_message .= isset($language['trade_message_'.$tmp[$i]]) ? $language['trade_message_'.$tmp[$i]].'<br />' : '';
}
return $return;
} else {
return $tmp;
}
}
function trade_create($trade) {
global $tablepre, $db, $allowposttrade, $mintradeprice, $maxtradeprice, $timestamp;
extract($trade);
$special = 2;
$expiration = $item_expiration ? strtotime($item_expiration) : 0;
$closed = $expiration > 0 && strtotime($item_expiration) < $timestamp ? 1 : $closed;
$item_price = floatval($item_price);
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;
}
$seller = dhtmlspecialchars($seller);
$item_name = dhtmlspecialchars($item_name);
$item_locus = dhtmlspecialchars($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($postage_express);
$postage_ems = intval($postage_ems);
$item_type = intval($item_type);
$typeid = intval($typeid);
$item_costprice = floatval($item_costprice);
if(empty($pid)) {
$pid = $db->result_first("SELECT pid FROM {$tablepre}posts WHERE tid='$tid' AND first='1' LIMIT 1");
}
$db->query("INSERT INTO {$tablepre}trades (tid, pid, typeid, sellerid, seller, account, subject, price, amount, quality, locus, transport, ordinaryfee, expressfee, emsfee, itemtype, dateline, expiration, lastupdate, totalitems, tradesum, closed, costprice, aid)
VALUES ('$tid', '$pid', '$typeid', '$discuz_uid', '$author', '$seller', '$item_name', '$item_price', '$item_number', '$item_quality', '$item_locus', '$item_transport', '$postage_mail', '$postage_express', '$postage_ems', '$item_type', '$timestamp', '$expiration', '$timestamp', '0', '0', '$closed', '$item_costprice', '$aid')");
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/trade.func.php
|
PHP
|
asf20
| 3,103
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: attachment.func.php 17535 2009-01-20 05:12:20Z monkey $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function attachtype($type, $returnval = 'html') {
static $attachicons = array(
1 => 'unknown.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, $sid, $authkey;
$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)");
$sidauth = rawurlencode(authcode($sid, 'ENCODE', $authkey));
$attachexists = FALSE;
while($attach = $db->fetch_array($query)) {
$attachexists = TRUE;
$exthtml = '';
if($skipaids && in_array($attach['aid'], $skipaids)) {
continue;
}
$attached = 0;
$extension = strtolower(fileext($attach['filename']));
$attach['ext'] = $extension;
$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'] = dgmdate("$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, $sidauth);
$attached = 1;
}
if(!$attached || $attach['unpayed']) {
if($attach['isimage']) {
$postlist[$attach['pid']]['imagelist'] .= attachlist($attach, $sidauth);
} else {
$postlist[$attach['pid']]['attachlist'] .= attachlist($attach, $sidauth);
}
}
}
if($attachexists) {
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');
}
}
function attachwidth($width) {
$imagemaxwidth = intval(IMAGEMAXWIDTH);
if($imagemaxwidth && $width) {
if(substr(IMAGEMAXWIDTH, -1, 1) != '%') {
$s = 'width="'.($width > $imagemaxwidth ? $imagemaxwidth : $width).'" onclick="zoom(this, this.src)"';
} else {
$s = 'thumbImg="1"';
}
} else {
$s = 'thumbImg="1"';
}
return $s;
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/attachment.func.php
|
PHP
|
asf20
| 5,718
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: newreply.inc.php 17198 2008-12-09 09:27:24Z zhaoxiongfei $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$discuz_action = 12;
if($special == 5) {
$debate = array_merge($thread, $db->fetch_first("SELECT * FROM {$tablepre}debates WHERE tid='$tid'"));
$firststand = $db->result_first("SELECT stand FROM {$tablepre}debateposts WHERE tid='$tid' AND uid='$discuz_uid' AND stand<>'0' ORDER BY dateline LIMIT 1");
if($debate['endtime'] && $debate['endtime'] < $timestamp) {
showmessage('debate_end');
}
}
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');
}
} elseif($forum['allowreply'] == -1) {
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(!submitcheck('replysubmit', 0, $seccodecheck, $secqaacheck)) {
if($thread['special'] == 2 && ((!isset($addtrade) || $thread['authorid'] != $discuz_uid) && !$tradenum = $db->result_first("SELECT count(*) FROM {$tablepre}trades WHERE tid='$tid'"))) {
showmessage('trade_newreply_nopermission', NULL, 'HALTED');
}
include_once language('misc');
if(isset($repquote)) {
$thaquote = $db->fetch_first("SELECT tid, fid, author, authorid, first, message, useip, dateline, anonymous, status FROM {$tablepre}posts WHERE pid='$repquote' AND invisible='0'");
if($thaquote['tid'] != $tid) {
showmessage('undefined_action', NULL, 'HALTED');
}
if(!($thread['price'] && !$thread['special'] && $thaquote['first'])) {
$quotefid = $thaquote['fid'];
$message = $thaquote['message'];
if($bannedmessages && $thaquote['authorid']) {
$author = $db->fetch_first("SELECT groupid FROM {$tablepre}members WHERE uid='$thaquote[authorid]'");
if(!$author['groupid'] || $author['groupid'] == 4 || $author['groupid'] == 5) {
$message = $language['post_banned'];
} elseif($thaquote['status'] & 1) {
$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'] = 'Anonymous';
} elseif(!$thaquote['author']) {
$thaquote['author'] = 'Guest from '.$thaquote['useip'];
} else {
$thaquote['author'] = $thaquote['author'];
}
eval("\$language['post_reply_quote'] = \"$language[post_reply_quote]\";");
$message = "[quote]$message\n[size=2][color=#999999]$language[post_reply_quote][/color] [url={$boardurl}redirect.php?goto=findpost&pid=$repquote&ptid=$tid][img]{$boardurl}images/common/back.gif[/img][/url][/size][/quote]\n";
}
} elseif(isset($reppost)) {
$thapost = $db->fetch_first("SELECT tid, author, authorid, useip, dateline, anonymous, status FROM {$tablepre}posts WHERE pid='$reppost' AND invisible='0'");
if($thapost['tid'] != $tid) {
showmessage('undefined_action', NULL, 'HALTED');
}
$thapost['useip'] = substr($thapost['useip'], 0, strrpos($thapost['useip'], '.')).'.x';
if($thapost['author'] && $thapost['anonymous']) {
$thapost['author'] = '[i]Anonymous[/i]';
} elseif(!$thapost['author']) {
$thapost['author'] = '[i]Guest[/i] from '.$thapost['useip'];
} else {
$thapost['author'] = '[i]'.$thapost['author'].'[/i]';
}
$thapost['number'] = $db->result_first("SELECT count(*) FROM {$tablepre}posts WHERE tid='$thapost[tid]' AND dateline<='$thapost[dateline]'");
$message = "[b]$lang[post_reply] [url={$boardurl}redirect.php?goto=findpost&pid=$reppost&ptid=$thapost[tid]]$thapost[number]#[/url] $thapost[author] $lang[post_thread][/b]\n\n\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'] = dgmdate("$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'] & 1) {
$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=threadsorts&tradetype=yes&sortid=\'+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');
} else {
require_once DISCUZ_ROOT.'./include/forum.func.php';
if($subject == '' && $message == '' && $thread['special'] != 2) {
showmessage('post_sm_isnull');
} elseif($thread['closed'] && !$forum['ismoderator']) {
showmessage('post_thread_closed');
} elseif($post_autoclose = checkautoclose()) {
showmessage($post_autoclose);
} elseif($post_invalid = checkpost($special == 2 && $allowposttrade)) {
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');
}
threadsort_checkoption(1, 1);
$optiondata = array();
if($tradetypes && $typeoption && $checkoption) {
$optiondata = threadsort_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 : ($imageexists ? 2 : 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;
$message = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $message);
$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) {
$rewardlog = $db->fetch_first("SELECT * FROM {$tablepre}rewardlog WHERE tid='$tid' AND answererid='$discuz_uid'");
if(!$rewardlog) {
$db->query("INSERT INTO {$tablepre}rewardlog (tid, answererid, dateline) VALUES ('$tid', '$discuz_uid', '$timestamp')");
}
} elseif($special == 5) {
$stand = $firststand ? $firststand : 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, width)
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]', '$attach[width]')");
$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));
}
if($swfupload) {
updateswfattach();
}
$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 (sortid, pid, optionid, value)
VALUES ('$tradetypeid', '$pid', '$optionid', '$value')");
}
}
require_once DISCUZ_ROOT.'./include/trade.func.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');
}
showmessage('post_reply_mod_succeed', "forumdisplay.php?fid=$fid");
} else {
$db->query("UPDATE {$tablepre}threads SET lastposter='$author', lastpost='$timestamp', replies=replies+1 ".($attachment ? ", attachment='$attachment'" : '').", 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');
}
$feed = array();
if($addfeed && $forum['allowfeed'] && $thread['authorid'] != $discuz_uid) {
if($special == 2 && !empty($trade) && !empty($item_name) && !empty($item_price)) {
$feed['icon'] = 'goods';
$feed['title_template'] = 'feed_thread_goods_title';
$feed['body_template'] = 'feed_thread_goods_message';
$feed['body_data'] = array(
'itemname'=> "<a href=\"{$boardurl}viewthread.php?do=tradeinfo&tid=$tid&pid=$pid\">$item_name</a>",
'itemprice'=> $item_price
);
$attachurl = preg_match("/^((https?|ftps?):\/\/|www\.)/i", $attachurl) ? $attachurl : $boardurl.$attachurl;
$imgurl = $boardurl.$attachurl.'/'.$attachments[2]['attachment'].($attachments[2]['thumb'] && $attachments[2]['type'] != 'image/gif' ? '.thumb.jpg' : '');
$feed['images'][] = array('url' => $imgurl, 'link' => "{$boardurl}viewthread.php?do=tradeinfo&tid=$tid&pid=$pid");
} elseif($special == 3) {
$feed['icon'] = 'reward';
$feed['title_template'] = 'feed_reply_reward_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>",
'author' => "<a href=\"space.php?uid=$thread[authorid]\">$thread[author]</a>"
);
} elseif($special == 5) {
$feed['icon'] = 'debate';
$feed['title_template'] = 'feed_thread_debatevote_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>",
'author' => "<a href=\"space.php?uid=$thread[authorid]\">$thread[author]</a>"
);
} else {
$feed['icon'] = 'post';
$feed['title_template'] = 'feed_reply_title';
$feed['title_data'] = array(
'subject' => "<a href=\"{$boardurl}viewthread.php?tid=$tid\">$thread[subject]</a>",
'author' => "<a href=\"space.php?uid=$thread[authorid]\">$thread[author]</a>"
);
}
postfeed($feed);
}
showmessage($replymessage, "viewthread.php?tid=$tid&pid=$pid&page=".(@ceil(($thread['special'] ? $thread['replies'] + 1 : $thread['replies'] + 2) / $ppp))."&extra=$extra#pid$pid");
}
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/newreply.inc.php
|
PHP
|
asf20
| 18,112
|
<?php
/*
[Discuz!] (C)2001-2009 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/51shangcheng.cn/htdocs/include/search_qihoo.inc.php
|
PHP
|
asf20
| 1,226
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: db_mysql_error.inc.php 17439 2008-12-22 04:27:17Z monkey $
*/
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 been dispatched to administrator before.';
}
}
echo '</p>';
echo '<p style="font-family: Verdana, Tahoma; font-size: 12px; background: #FFFFFF;"><a href="http://faq.comsenz.com/?type=mysql&dberrno='.$dberrno.'&dberror='.rawurlencode($dberror).'" target="_blank">到 http://faq.comsenz.com 搜索此错误的解决方案</a></p>';
exit();
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/db_mysql_error.inc.php
|
PHP
|
asf20
| 3,760
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: announcements_daily.inc.php 17476 2008-12-25 02:58:18Z liuqiang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$db->query("UPDATE {$tablepre}tasks SET available='2' WHERE available='1' AND starttime>'0' AND starttime<='$timestamp' AND (endtime IS NULL OR endtime>'$timestamp')", 'UNBUFFERED');
$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(array('announcements', 'announcements_forum', 'pmlist'));
}
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/crons/announcements_daily.inc.php
|
PHP
|
asf20
| 696
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: todayposts_daily.inc.php 16688 2008-11-14 06:41:07Z cnteacher $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$yesterdayposts = intval($db->result_first("SELECT sum(todayposts) FROM {$tablepre}forums"));
$historypost = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable='historyposts'");
$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/51shangcheng.cn/htdocs/include/crons/todayposts_daily.inc.php
|
PHP
|
asf20
| 924
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: cleanup_monthly.inc.php 16688 2008-11-14 06:41:07Z 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");
$db->query("DELETE FROM {$tablepre}mytasks WHERE status='-1' AND dateline<'$timestamp'-2592000", 'UNBUFFERED');
?>
|
zyyhong
|
trunk/jiaju001/51shangcheng.cn/htdocs/include/crons/cleanup_monthly.inc.php
|
PHP
|
asf20
| 793
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: birthdays_daily.inc.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/crons/birthdays_daily.inc.php
|
PHP
|
asf20
| 780
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: promotions_hourly.inc.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/crons/promotions_hourly.inc.php
|
PHP
|
asf20
| 1,209
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: onlinetime_monthly.inc.php 16688 2008-11-14 06:41:07Z 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/51shangcheng.cn/htdocs/include/crons/onlinetime_monthly.inc.php
|
PHP
|
asf20
| 420
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: notify_daily.inc.php 16688 2008-11-14 06:41:07Z 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'];
}
}
global $thread;
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/51shangcheng.cn/htdocs/include/crons/notify_daily.inc.php
|
PHP
|
asf20
| 1,558
|
<?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/51shangcheng.cn/htdocs/include/crons/tags_daily.inc.php
|
PHP
|
asf20
| 276
|
<?php
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: magics_daily.inc.php 16688 2008-11-14 06:41:07Z 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']) {
$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/51shangcheng.cn/htdocs/include/crons/magics_daily.inc.php
|
PHP
|
asf20
| 1,205
|