<repo_name>mrmoment/heyegg<file_sep>/action/userquit.php
<?php
include_once("lib/head.php");
session_start();
unset($_SESSION['email']);
unset($_SESSION['nickname']);
session_destroy();
print "<code>success</code>";
?>
<file_sep>/codelist.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>黑蛋 | 新用户注册邀请码</title>
<link href="res/style.css" rel="stylesheet" type="text/css" />
<style>
.codeline{
	padding:6px 0;
	font-size:1.1em;
	font-weight:bold;
	margin:auto 10px;
}
.codeline:hover{
	background: #fff;
}
#view h4{
	margin:5px;
}
</style>
</head>

<body>	
<div id="topbar">
	<div id="btm_border"></div>
	<div id="logo" onclick="window.open('index.php');"></div>
</div>
<div id="main">
	<div id="view" style="background:#eaeaea; font-size:14px;">
		<div style="font-family:'Microsoft YaHei'; background:rgba(255,255,255,0.8); padding:10px; margin:10px;">
		<h4>为什么要邀请码</h4>黑蛋"&nbsp;目前处于测试阶段，用户注册需要通过邀请码进行。<br />
		<h4>如何获取邀请码</h4><li>每天我们会定时更新一批邀请码（见下方）。</li><li>活跃用户还将不定期得到发送邀请码的机会，可以分享给您的好友。</li>
		<h4>需要注意什么</h4><li>每天定期更新的邀请码数量有限，如果列表为空请您稍后再试。</li><li>对于已注册用户发送给您的邀请码，请注意保管，不要随意透露给他人。</li><li>当然，您应当及时使用该邀请码进行注册。</li>
		</div>
		<div style="font-family:'Courier New', Courier, monospace; min-height:400px;" align="center" id="codelist">
			<div onclick="document.location=document.location;" style="cursor:pointer; background:#00CCFF; border:1px solid #333; width:60px;">刷新</div>
			<?php
			sleep(1);
			include_once("action/lib/head.php");
			$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
			mysql_select_db('eggsys',$conn);
			$sql="select * from reginvite where used=0 limit 30";
			$query=mysql_query($sql);
			while($myrow=mysql_fetch_array($query)){
				$code=$myrow['code'];
				print "<div class='codeline'>".$code."</div>";
			}
			?>
		</div>
		<script language="javascript">
			if(document.getElementById('codelist').childNodes.length<4){
				var d=document.createElement('div');
				d.className="codeline";
				d.innerHTML="暂无更多邀请码";
				document.getElementById('codelist').appendChild(d);
			}
		</script>
	</div>
</div>
</body>
</html>
<file_sep>/action/lib/head.php
﻿<?php
$URL_PREFIX="../p";
$URL_SUFFIX=".html";
$CMT_SUFFIX=".xml";
$LIST_SIZE=15;//how many lists per page
$mysqlpw="";
$ADMIN_PASSWD="<PASSWORD>";

function seg($tag, $val){
	return "<".$tag.">".$val."</".$tag.">";
}

function mkdirs($dir)  
{  
	if(!is_dir($dir)){  
		if(!mkdirs(dirname($dir))){  
			return false;  
		}  
		if(!mkdir($dir,0777)){
			return false;
		}
	}
	return true;  
}
function randomkeys($length)
{
	$pattern='<KEY>';
	for($i=0;$i<$length;$i++)
	{
 		$key .= $pattern{mt_rand(0,35)};
	}
	return $key;
}

/* @param string $string 原文或者密文
* @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
* @param string $key 密钥
* @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
* @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
* 可以在指定时间内加密还原字符串，超时无法还原 可做单点登录的token加密传输，临时密码等
* @example
*
* $a = authcode('abc', 'ENCODE', 'key');
* $b = authcode($a, 'DECODE', 'key');  // $b(abc)
*
* $a = authcode('abc', 'ENCODE', 'key', 3600);
* $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) { 
	$ckey_length = 4;   
	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥
	
	$key = md5($key ? $key : 'default_key'); //这里可以填写默认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));
	}

}

/*
 * Add score for a user
 */
function addScore($email,$incre){
	$sql="select * from userscores where user_email=\"$email\" limit 1";
	$query=mysql_query($sql);
	if($myrow=mysql_fetch_array($query)){
		$score=$myrow['score'];
		$sql="update userscores set score=($score+$incre) where user_email='$email'";//each post makes 5 scores
		$query=mysql_query($sql);
	}
}
?>
<file_sep>/action/adduser.php
<?php
if( !isset($_POST['p']) || !isset($_POST['m']) || !isset($_POST['n']) || !isset($_POST['c']) ){
	return;
}
include_once("lib/head.php");
$email=$_POST['m'];
$nick=$_POST['n'];
$passwd=$_POST['p'];//encrypted
$code=$_POST['c'];

$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error());
mysql_select_db('eggsys',$conn);
//check invite code first
$sql="select * from reginvite where code='$code' and used=0 limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	$sql="select * from uauth where email='$email' limit 1";
	$query=mysql_query($sql);
	if($myrow=mysql_fetch_array($query))
	{
		print "<code>existing_email</code>";
		return;
	}else{
		$sql="select * from uauth where nickname='$nick' limit 1";
		$query=mysql_query($sql);
		if($myrow=mysql_fetch_array($query)){
			print "<code>existing_nick</code>";
			return;
		}else{
			//forbid sensitive nicknames
			$postFile=$dir."/".$timestr.$URL_SUFFIX;		
			$kwFile="../cfg/nickkeywords.txt";
			if(file_exists($kwFile)){
				$handler= fopen($kwFile, "r");
				$fileContent=fread($handler,fileSize($kwFile));
				$words=explode(",",$fileContent);
				for($i=0; $i<count($words); $i++){
					if(strpos($nick,$words[$i])!==false){
						print "<code>bad_nick</code>";
						return;
					}
				}
			}
			date_default_timezone_set("PRC");
			$createtime=date("YmdHis");
			$sql="insert into uauth (email, nickname, passwd, create_time) values ('$email','$nick','$passwd','$createtime')";
			$query=mysql_query($sql);
			$sql="update reginvite set used=1 where code='$code'";
			$query=mysql_query($sql);
		}
	}
}else{
	print "<code>invite_code_error</code>";
	return;
}
$sql="insert into userscores (user_email, score, items) values ('$email',200,',0001,')";
$query=mysql_query($sql);
print "<code>register_ok</code>";
?><file_sep>/action/loadnearbypost.php
<?php
include_once("lib/head.php");
////TODO: update post view stat
if(!isset($_GET['id']) || !isset($_GET['tp']) || !isset($_GET['m']) || !isset($_GET['o']) ){
	return;
}
$id=$_GET['id'];
$type=$_GET['tp'];
$mode=$_GET['m'];
$orient=$_GET['o'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);
if($orient<0){
	$sql="select * from posts where id<$id and type='$type' and public='$mode' order by id desc limit 1";
}else{
	$sql="select * from posts where id>$id and type='$type' and public='$mode' order by id limit 1";
}
$query=mysql_query($sql);
////TODO: this is same segment to loadpost.php, change it to function
if($myrow=mysql_fetch_array($query)){
	print $myrow['id'].'<>'.$myrow['title']."<>".$myrow['create_time']."<>";
	$dir=$URL_PREFIX."/".$myrow['author_email'];
	$timestr=str_replace(":","",$myrow['create_time']);
	$timestr=str_replace("-","",$timestr);
	$timestr=str_replace(" ","",$timestr);
	$postFile=$dir."/".$timestr.$URL_SUFFIX;
	if(file_exists($postFile)){
		$handler= fopen($postFile, "r");
		$fileContent=fread($handler,fileSize($postFile));
	}else{
		$fileContent="原文已丢失";///TODO: add a link for user to report this
	}
	print $fileContent."<>";
	$email=$myrow['author_email'];
}else{
	print "<code>no_post</code>";
	return;
}
//get current user nickname
$sql="select * from uauth where email='$email'";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	print $myrow['nickname'];
}else{
	print "未知";
}
?><file_sep>/index.php
﻿<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>黑蛋 | 品质新闻阅读</title>
<link rel="stylesheet" type="text/css" href="jsMessage/codebase/themes/message_growl_dark.css">
<link href="res/style.css" rel="stylesheet" type="text/css" />
<link href="res/effect.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="res/jquery-1.6.2.min.js"></script>
<script language="javascript" src="res/extool.js?v=0.1"></script>
<script language="javascript" src="res/md5-min.js"></script>
<script language="javascript" src="res/hey.js"></script>
<script type="text/javascript" src='jsMessage/codebase/message.js'></script>
<script language="javascript">
$(document).ready(function(){
	scrHgt=screen.availHeight;
	$('#post_text').css('min-height',(scrHgt-370)+"px");
	$('#comment_view').css('min-height',(scrHgt-216)+"px");
	setToolTop();
	initUser();
	var pid="<?php
		if( isset($_GET['pid']) ){
			print $_GET['pid'];
		}else{
			print "";
		}
	?>";
	if(pid==""){
		quickEgg();	
	}else{
		loadEggById(pid);
	}
});
function initUser(){	
	tmpemail="<?php 
		if(isset($_SESSION['email'])) {
			print $_SESSION['email'];
		}else{
			print "";
		}
	?>";
	tmpnickname="<?php
		if(isset($_SESSION['nickname'])) {
			print $_SESSION['nickname'];
		}else{
			print "";
		}
	?>";
	if(tmpemail==""){
		tmpemail=getCookie("email");
		if(tmpemail!=null){	
			tmppassword=getCookie("password");
			$.post("./action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);});
			//todo: show a loading circle nearby "login" span			
		}
	}else{
		email=tmpemail;
		nickname=tmpnickname;
		showTopbar(nickname);
	}
}
</script>
</head>

<body>
<div id="topbar">
	<div id="btm_border"></div>
	<div id="left_panel"></div>
	<div id="right_panel">
		<div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div>
		<div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout()">退出</span></div>
	</div>
	<div id="logo"></div>
</div>
<div id="main">
	<div id="view">
		<div id="post_view" onmouseup="doSelect()">
			<div id="post_title">加载中...</div>
			<div id="post_avatar"><!--img src="img/default_avatar_64.gif" width="32" height="32"/--></div>
			<div id="post_author">作者:&nbsp;<a id="post_author_name" target="_blank">加载中...</a></div>
			<div id="post_time">时间:&nbsp;加载中...</div>
			<div id="post_text">正在载入...</div>
		</div>
		<div id="comment_view">
			<div id="new_cmt">
				<h3 id="comment_to"></h3>
				<textarea id="cmt_content" wrap="soft"></textarea>
				<button id="submit" onclick="doComment()" style="top:10px;margin-bottom:20px;">发表</button>
			</div>
			<div id="cmt_list">	</div>
		</div>
	</div>
	<div id="footer">
		 <div style="width:330px; margin:auto; font-size:12px; font-family:sans-serif">All rights reserved&copy;2012&nbsp;黑蛋网&nbsp;京ICP备11034032号</div>
	</div>
</div>
<div id="tool">
	<div id="tool_main">
		<div id="left_tool" class="toolpanel">
			<div class="leftbtn">
				<div class="ltoolname" onclick="browseType(0);">
					<div style="float:left">科技</div>
					<div class="type_icon"></div>
				</div>				
			</div>
			<div class="leftbtn">
				<div class="ltoolname" onclick="browseType(1);">
					<div style="float:left">社会</div>
					<div class="type_icon"></div>
				</div>				
			</div>
			<div class="leftbtn">
				<div class="ltoolname" onclick="browseType(2);">
					<div style="float:left">奇趣</div>
					<div class="type_icon"></div>
				</div>				
			</div>
			<div class="leftbtn">
				<div class="ltoolname" onclick="browseType(3);">
					<div style="float:left">娱乐</div>
					<div class="type_icon"></div>
				</div>				
			</div>
		</div><!--eof left_tool-->
		<div id="right_tool" class="toolpanel">
			<div id="tl_list" class="rightbtn tran-9" onclick="openList()">
				<div class="rtoolname">
					<div style="float:left">列表</div>
					<div class="tl_icon" style="float:right"></div>
				</div>
			</div>
			<div id="tl_review" class="rightbtn tran-9" onclick="window.open('review.php')">
				<div class="rtoolname">
					<div style="float:left">审稿</div>
					<div class="tl_icon" style="float:right"></div>
				</div>				
			</div>
			<div id="tl_submit" class="rightbtn tran-9" onclick="window.open('ueditor/_examples/post.php');"  style="margin-bottom:10px;">
				<div class="rtoolname">
					<div style="float:left">投递</div>
					<div class="tl_icon" style="float:right"></div>
				</div>				
			</div>
			<div id="tl_cmt" class="rightbtn tran-9" onclick="triggerComment()">
				<div class="rtoolname">
					<div id="cmt_btn" style="float:left">评论</div>
					<div id="cmt_icon" style="float:right"></div>
				</div>
			</div>
			<div id="tl_score" class="rightbtn tran-9">				
				<div class="rtoolname">
					<div style="float:left">打分</div>
					<div id="rate_box" style="float:right">
						<div class="star active" onmousemove="lightStars(1)" onmouseover="lightStars(1)" onclick="votePost(1)"></div>
						<div class="star active" onmousemove="lightStars(2)" onmouseover="lightStars(2)" onclick="votePost(2)"></div>
						<div class="star active" onmousemove="lightStars(3)" onmouseover="lightStars(3)" onclick="votePost(3)"></div>
						<div class="star" onmousemove="lightStars(4)" onmouseover="lightStars(4)" onclick="votePost(4)"></div>
						<div class="star" onmousemove="lightStars(5)" onmouseover="lightStars(5)" onclick="votePost(5)"></div>
					</div>
				</div>
			</div>
			<div id="tl_fav" class="rightbtn tran-9" onclick="checkFav()">
				<div class="rtoolname">
					<div style="float:left">收藏</div>
					<div style="float:right">
						<div id="check_fav" class="unchecked" style="float:right"></div>
					</div>
				</div>
			</div>
		</div><!--eof right_tool-->
		<div id="page_tool">
			<div class="pager" id="prev_post" onclick="nearbyEgg(-1)" title="较早的文章"></div>
			<div class="pager" id="next_post" onclick="nearbyEgg(1)" title="较新的文章"></div>
		</div>
	</div>
</div>
<div id="list">
	<div id="close_list" onclick="closeList()"><div></div></div>
	<div id="list_rows">	</div>
	<div id="list_pager">
		<div id="prev_list" onclick="prevList();"></div>
		<div id="list_now" align="center">1&nbsp;/&nbsp;14&nbsp;页</div>
		<div id="list_goto"><input id="jumpNum" /><a onclick="gotoList()">跳至</a></div>
		<div id="next_list" onclick="nextList();"></div>
	</div>
</div>
<div id="login_wrapper" style="display:none">
	<div id="login">
		<div id="close_login" onclick="$('#login_wrapper').hide();"></div>
		<input type="text" value="Email" id="email" onfocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onblur="this.className='';if(this.value.trim()=='') this.value='Email';" />
		<input type="text" value="密码" id="password" onfocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onblur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/>
		<button id="submit" onclick="doLogin()" style="top:80px;left:-37px;float:right;">登录</button>
	</div>
</div>
</body>
</html>
<file_sep>/user.php
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="jsMessage/codebase/themes/message_growl_dark.css">
<link href="res/style.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="res/jquery-1.6.2.min.js"></script>
<script language="javascript" src="res/extool.js?v=0.1"></script>
<script language="javascript" src="res/md5-min.js"></script>
<script language="javascript" src="res/hey.js"></script>
<script type="text/javascript" src='jsMessage/codebase/message.js'></script>
<title>黑蛋 | 查看用户</title>
<script language="javascript">
$(document).ready(function(){
	scrHgt=screen.availHeight;	
	$('#user_view').css('min-height',(scrHgt-216)+"px");
	initUser();
	loadUserInfo();	
});
function initUser(){	
	tmpemail="<?php 
		if(isset($_SESSION['email'])) {
			print $_SESSION['email'];
		}else{
			print "";
		}
	?>";
	tmpnickname="<?php
		if(isset($_SESSION['nickname'])) {
			print $_SESSION['nickname'];
		}else{
			print "";
		}
	?>";
	if(tmpemail==""){
		tmpemail=getCookie("email");
		if(tmpemail!=null){	
			tmppassword=getCookie("password");
			$.post("./action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);});
			//todo: show a loading circle nearby "login" span			
		}
	}else{
		email=tmpemail;
		nickname=tmpnickname;
		showTopbar(nickname);
	}
}
function loadUserInfo(){
	var tmpid="<?php 
		if(isset($_GET['uid'])) {
			print $_GET['uid'];
		}else{
			print "";
		}
	?>";
	if(tmpid==""){
		dhtmlx.alert({
			text:"错误的调用,将跳转到主页", 
			callback: function(){
	       		document.location="index.php";
	    	}
		});
	}else{
		$.get(phpDir+"loaduserinfo.php",{uid: tmpid}, function(resp){handleUserInfo(resp)});
	}
}

function handleUserInfo(resp){
	var code=getRespCode(resp);
	if(code=="user_id_error"){
		dhtmlx.alert({
			text:"被查询的用户信息错误,将跳转到主页", 
			callback: function(){
	       		document.location="index.php";
	    	}
		});
		
		return;
	}else if(code=="user_info_ok"){
		var data=getRespData(resp);
		var userinfo=my_substr(data, "user");
		var nick=my_substr(userinfo, "nick");
		var score=my_substr(userinfo, "score");
		var group=my_substr(userinfo, "group");
		$('#nick').html(nick);
		$('#point').html(score);
		$('#group').html(group);
		
		var posts=my_substr(data, "post");
		var pcs=posts.split("<|>");
		var list=document.getElementById('user_post_list');
		if(pcs.length==1){
			list.childNodes[0].innerHTML="暂无投递";
		}else{
			list.innerHTML="";
			for(i=0; i<pcs.length-1; i++){
				var post=pcs[i];
				var items=post.split("<>");
				var public=items[3];
				var a=document.createElement('a');
				if(public==0){
					a.innerHTML=unescape(decodeURI(items[1]))+"<a class='inreview'>(审核中)</a>";
					a.href="review.php?pid="+items[0];
				}else if(public==-1){
					a.innerHTML=unescape(decodeURI(items[1]))+"<a class='reject'>(未通过)</a>";
				}else{
					a.innerHTML=unescape(decodeURI(items[1]));
					a.href="index.php?pid="+items[0];
				}
				a.title=items[2];			
				a.target="_blank";
				a.className="list_item";
				list.appendChild(a);
			}
		}
		
		var favs=my_substr(data, "fav");
		pcs2=favs.split("<|>");		
		var list2=document.getElementById('user_fav_list');
		if(pcs2.length==1){		
			list2.childNodes[0].innerHTML="暂无收藏";
		}else{
			list2.innerHTML="";
			for(j=0; j<pcs2.length-1; j++){
				var fav=pcs2[j];
				var items2=fav.split("<>");
				var a2=document.createElement('a');
				a2.innerHTML=unescape(decodeURI(items2[1]));
				a2.href="index.php?pid="+items2[0];
				a2.title=items2[2];			
				a2.target="_blank";
				a2.className="list_item";
				list2.appendChild(a2);
			}
		}		
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
}
</script>
<style>
#user_view{
	margin-top:40px;
	border:0px dashed #ccc;
	padding:0 60px;
	font-size:14px;
}
#user_view i{
	color:#999;
}
#avatar{
	width:64px;
	height:64px;
	float:left;
	background:#fff url(img/default_avatar_64.gif) no-repeat;
	border-radius:4px;
	box-shadow:0 0 4px #ccc;
}
#name{
	width:440px;
	height:64px;
	float:right;
}
#info{
	margin-top:20px;
	margin-bottom:10px;
	border-top: 6px solid #39c;
}
.record{
	width:240px;
	border:1px solid #eee;
	min-height:400px;
	background:#fbfbfb;
	padding:5px;
	word-break:break-all;
}
#post_rec{
	float:left;
}
#fav_rec{	
	float:right;
}
.record span:first-child{
	display:block;
	font-weight:bold;
	margin-bottom:8px;
}
.list_item{
	display:block;
	margin:5px 0;
	cursor:pointer;
}
.list_item:hover{
	background:#fdfdfd;
}
#main a, #main a:visited, #main a:active{
	text-decoration:underlined;
	color:#000;
}
a.inreview{
	color:green !important;
	font-style:italic;
}
a.reject{
	color:blue !important;
	font-style:italic;
}
</style>
</head>

<body>
<div id="topbar">
	<div id="btm_border"></div>
	<div id="left_panel"></div>
	<div id="right_panel">
		<div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div>
		<div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout()">退出</span></div>
	</div>
	<div id="logo" onclick="window.open('index.php')"></div>
</div>
<div id="main">
	<div id="view">
		<div id="user_view">
			<div id="avatar">
			</div>
			<div id="name">
				<div id="nick" style="margin-bottom:10px; font-size:18px; font-weight:bold;"><i>用户页面正在载入...</i></div>
				<div>身份:&nbsp;<a id="group"><i>加载中...</i></a></div>
				<div>
					<span>积分:&nbsp;<a id="point"><i>加载中...</i></a></span>&nbsp;<!--span>邮箱:&nbsp;<a id="mail"><i>加载中...</i></a></span-->
				</div>
			</div>
			<br style="clear:both" />
			<div id="info">				
			</div>
			<div id="post_rec" class="record">
				<span>投稿列表</span>
				<div id="user_post_list"><i>加载中...</i></div>
			</div>
			<div id="fav_rec" class="record">
				<span>收藏列表</span>
				<div id="user_fav_list"><i>加载中...</i></div>
			</div>
		</div>
	</div>
</div>
<div id="login_wrapper" style="display:none">
	<div id="login">
		<div id="close_login" onClick="$('#login_wrapper').hide();"></div>
		<input type="text" value="Email" id="email" onFocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onBlur="this.className='';if(this.value.trim()=='') this.value='Email';" />
		<input type="text" value="密码" id="password" onFocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onBlur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/>
		<button id="submit" onclick="doLogin()" style="top:80px;left:-37px;float:right;">登录</button>
	</div>
</div>
</body>
</html>
<file_sep>/action/loadcomment.php
<?php
if( !isset($_GET['id']) ){
	return;
}
$COMMENTS_READ_AT_ONCE=10;
$id=$_GET['id'];
if( isset($_GET['all']) ){
	$readall=$_GET['all'];
}
include_once("lib/head.php");
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);

$sql="select * from posts where id=$id limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	$dir=$URL_PREFIX."/".$myrow['author_email'];
	$timestr=str_replace(":","",$myrow['create_time']);
	$timestr=str_replace("-","",$timestr);
	$timestr=str_replace(" ","",$timestr);
	$cmtDir=$dir."/".$timestr."-cmt";
	if(!file_exists($cmtDir)){
		print "<code>no_comment</code>";
		return;
	}
	$files=glob($cmtDir."/*".$CMT_SUFFIX);
	if(isset($readall) && $readall=1){
		$count=count($files);
	}else{
		$count=min(count($files),$COMMENTS_READ_AT_ONCE);		
	}
	print $count;
	if($count!=0){
		print "<data>";
	}
	for($idx=count($files)-1; $idx>=(count($files)-$count); $idx--){
		$handle=fopen($files[$idx],"r");
		$cmt=fread($handle, fileSize($files[$idx]));
		$start=strpos($cmt,"<u>")+3;
		$end=strpos($cmt,"</u>");
		$email=substr($cmt,$start,($end-$start));
		$tmpsql="select * from uauth where email='$email' limit 1";
		$tmpquery=mysql_query($tmpsql);
		if($tmprow=mysql_fetch_array($tmpquery)){
			$nick=$tmprow['nickname'];
		}else{
			$nick="未知用户";
		}
		$cmt=str_replace($email,$nick,$cmt);		
		print $cmt."<>";
	}
	if($count!=0){
		print "</data>";
	}
}else{
	print "<code>no_such_post</code>";
	return;
}
print "<code>load_comment_ok</code>";
///TODO: load comment num for users to reference
?><file_sep>/action/addpost.php
<?php
session_start();

if( !isset($_SESSION['email']) || !isset($_POST['tp']) || !isset($_POST['tl']) || !isset($_POST['ct']) ){
	return;
}

include_once('lib/head.php');
$email=$_SESSION['email'];
$type=$_POST['tp'];
$title=$_POST['tl'];
$content=$_POST['ct'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);

date_default_timezone_set("PRC");
$createtime=date("YmdHis");
$title=urlencode($title);
$sql="insert into posts (type, title, author_email, create_time) values ('$type', '$title', '$email', '$createtime')";
$query=mysql_query($sql) or die ("<code>insert_error</code>".mysql_error());
$dir=$URL_PREFIX."/".$email;
$postFile=$dir."/".$createtime.$URL_SUFFIX;
mkdirs($dir);
$handle=fopen($postFile,"w");
fwrite($handle, $content);
/////TODO: write a single html file (for seo?)
fclose($handle);
$cmtDir=$dir."/".$createtime."-cmt";
mkdirs($cmtDir);
/*$commentFile=$cmtDir."/".$createtime."-cmt".$CMT_SUFFIX;
$handle=fopen($commentFile,"w");
fclose($handle);*/
addScore($email, 5);

print "<code>post_ok</code>";
?><file_sep>/action/votepost.php
<?php
session_start();
if( !isset($_GET['id']) || !isset($_GET['s']) || !isset($_SESSION['email']) ){
	return;
}

include_once("lib/head.php");
$MIN_VOTE_USERS=5;
$MIN_VOTE_SCORE=3;
$MIN_REJECT_SCORE=2;
$id=$_GET['id'];
$score=$_GET['s'];
$email=$_SESSION['email'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);

$sql="select count(*) from postvote where post_id=$id limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){//TODO: this count process can be rewritten, see loadpostbyid.php; also change favpost.php
	if($myrow[0]==0){
		//add a new record
		$sql="insert into postvote (post_id, voted, score, vote_users) values ($id, 1, $score, ',$email,')";
		$query=mysql_query($sql);
		print '<code>vote_ok</code>';
	}else{
		$sql="select * from postvote where post_id=$id limit 1";
		$query=mysql_query($sql);
		$myrow=mysql_fetch_array($query);
		$users=$myrow['vote_users'];
		if(strpos($users,','.$email.',')!==false){
			print "<code>already_voted</code>";
			return;
		}else{
			$curScore=$myrow['score'];
			$curPeople=$myrow['voted'];
			$newScore=($curScore*$curPeople+$score)/($curPeople+1);
			$newUsers=$users.$email.',';
			$sql="update postvote set voted=($curPeople+1), score=$newScore, vote_users='$newUsers' where post_id=$id";
			$query=mysql_query($sql);
			print '<code>vote_ok</code>';
		}		
		//check if publicize this post		
		if( ($curPeople+1)>=$MIN_VOTE_USERS && $newScore>=$MIN_VOTE_SCORE ){
			$sql="update posts set public=1 where id=$id";	
			$query=mysql_query($sql);		
		}else if( ($curPeople+1)>=$MIN_VOTE_USERS && $newScore<=$MIN_REFJECT_SCORE ){//check if reject this post
			$sql="update posts set public=-1 where id=$id";	
			$query=mysql_query($sql);
		}
	}
	//check if publicize this post by admin
	if( isset($_SESSION['admin']) && $_SESSION['admin']==true ){
		if( $score>=$MIN_VOTE_SCORE ){
			$sql="update posts set public=1 where id=$id";
			$query=mysql_query($sql);
		}else if($score<=$MIN_REJECT_SCORE){
			$sql="update posts set public=-1 where id=$id";
			$query=mysql_query($sql);
		}
	}
}
?>
<file_sep>/action/loadpost.php
<?php
session_start();
include_once("lib/head.php");
////TODO: update post view stat
if( !isset($_GET['id']) || !isset($_GET['tp']) || !isset($_GET['m']) ){
	return;
}

$idx=$_GET['id'];
$type=$_GET['tp'];
$mode=$_GET['m'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);

$pid=0;
$sql="select * from posts where type='$type' and public='$mode' order by id desc limit $idx, 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	$pid=$myrow['id'];
	print $pid.'<>'.$myrow['title']."<>".$myrow['create_time']."<>";
	$dir=$URL_PREFIX."/".$myrow['author_email'];
	$timestr=str_replace(":","",$myrow['create_time']);
	$timestr=str_replace("-","",$timestr);
	$timestr=str_replace(" ","",$timestr);
	$postFile=$dir."/".$timestr.$URL_SUFFIX;
	if(file_exists($postFile)){
		$handler= fopen($postFile, "r");
		$fileContent=fread($handler,fileSize($postFile));
	}else{
		$fileContent="原文已丢失";///TODO: add a link for user to report this
	}
	print $fileContent."<>";
	$email=$myrow['author_email'];
}else{
	print "<code>no_post</code>";
	return;
}
//get current user nickname
$sql="select * from uauth where email='$email'";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	print $myrow['nickname']."<>".$myrow['id'];
}
//get fav status
if($mode==1){//1:view mode
	if( isset($_SESSION['email']) ){
		$myemail=$_SESSION['email'];
		$sql="select * from userlike where user_email='$myemail' limit 1";
		$query=mysql_query($sql);
		if($myrow=mysql_fetch_array($query)){
			$likes=$myrow['liked_posts'];
			if(strpos($likes,",".$pid.",")!==false){
				print "<>1";
			}else{
				print "<>0";
			}
		}
	}else{
		print "<>0";
	}
}else{
	print "<>0";
}
?><file_sep>/action/loadlist.php
<?php
include_once("lib/head.php");
if(!isset($_GET['n']) || !isset($_GET['tp']) || !isset($_GET['m']) ){	
	return;
}
$idx=$_GET['n'];
$type=$_GET['tp'];
$mode=$_GET['m'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);
$offset=$idx*$LIST_SIZE;
$sql="select * from posts where type='$type' and public=$mode order by id desc limit $offset, $LIST_SIZE";
$query=mysql_query($sql);
while($myrow=mysql_fetch_array($query)){
	$id=$myrow['id'];
	$title=$myrow['title'];
	$time=$myrow['create_time'];
	//print_r($myrow);
	$author=$myrow['author_email'];
	print $id."<>".$title."<>".$time."<>".$author;
	print "<|>";
}
$sql="select count(*) from posts where type='$type' and public=$mode";
$query=mysql_query($sql);
$myrow=mysql_fetch_array($query);
print $myrow[0];//total posts in this type
?><file_sep>/action/verifyuser.php
<?php
session_start();
include_once("lib/head.php");
if( !isset($_POST['p']) || !isset($_POST['u']) ){
	return;
}
$email=$_POST['u'];
$enpasswd=$_POST['p'];//encrypted

$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error());
mysql_select_db('eggsys',$conn);
$sql="select * from uauth where email='$email' limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query))
{
	if(strcasecmp($myrow['passwd'], $enpasswd)==0){
		print '<code>verify_ok</code><data>'.$myrow['nickname'].'</data>';
		$_SESSION['email']=$email;
		$_SESSION['nickname']=$myrow['nickname'];
		if($myrow['group']==0){//0 admin; 1 user			
			$_SESSION['admin']=true;
		}
		return;
	}	
}
print '<code>verify_error</code>';
?><file_sep>/action/postcomment.php
<?php
session_start();
if( !isset($_POST['id']) || !isset($_POST['c']) || !isset($_SESSION['email']) ){
	return;
}

include_once("lib/head.php");
$id=$_POST['id'];
$comment=$_POST['c'];
$email=$_SESSION['email'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);

$sql="select * from posts where id=$id limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	$dir=$URL_PREFIX."/".$myrow['author_email'];
	$timestr=str_replace(":","",$myrow['create_time']);
	$timestr=str_replace("-","",$timestr);
	$timestr=str_replace(" ","",$timestr);
	$cmtDir=$dir."/".$timestr."-cmt";
	if(!file_exists($cmtDir)){//comment dir is deleted (in development case)
		mkdirs($cmtDir);
	}
	$files=glob($cmtDir."/*".$CMT_SUFFIX);
	//$cmtIdx=count($files)+1;
	$createtime=date("YmdHis");
	$cmtFile=$cmtDir."/".$createtime.$CMT_SUFFIX;
	$handle=fopen($cmtFile,"w");
	date_default_timezone_set("PRC");
	$createtime=date("Y-m-d H:i:s");
	$content="<u>".$email."</u><t>".$createtime."</t><c>".$comment."</c>";
	fwrite($handle, $content);
	fclose($handle);
	
	$newComments=$myrow['comments']+1;
	$sql="update posts set comments=$newComments where id=$id";
	$query=mysql_query($sql);
}else{
	print "<code>no_such_post</code>";
	return;
}
addScore($email, 2);
print "<code>comment_ok</code>";
?><file_sep>/action/addcodes.php
<?php
session_start();
include_once("lib/head.php");
if( !isset($_SESSION['admin']) || !isset($_POST['u']) || !isset($_POST['p']) || !isset($_POST['n']) ){
	return;
}

$uname=strtolower($_POST['u']);
$passwd=$_POST['p'];
if( strcmp($uname,"maxadmin")!=0 || strcmp($passwd,"<PASSWORD>")!=0 ){
	sleep(10);
	return;
}
print "<p>Start...</p>";
$num=$_POST['n'];
$CODE_LEN=12;
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error());
mysql_select_db('eggsys',$conn);
for($i=0; $i<$num; $i++){
	$code=randomkeys($CODE_LEN);
	$sql="select * from reginvite where code='$code' limit 1";
	$query=mysql_query($sql);
	if($myrow=mysql_fetch_array($query)){
		$i--;//duplicate code doesn't count
	}else{
		print "New Code:&nbsp;";
		$nsql="insert into reginvite (code, used) values ('$code', 0)" or die(mysql_error());
		$query=mysql_query($nsql);
		print $code."<br />";
	}
}
odbc_close($conn);
print "<p>Done...</p>";
?>
<file_sep>/action/loaduserinfo.php
<?php
if( !isset($_GET['uid']) ){
	return;
}
include_once("lib/head.php");
$userid=$_GET['uid'];
print $userid;
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error());
mysql_select_db('eggsys',$conn);
$sql="select * from uauth where id='$userid' limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	print "<data>";
	$email=$myrow['email'];//TODO: now no email info to display
	$group=$myrow['group'];
	if($group==0){
		$group='管理员';
	}else{
		$group='用户';
	}
	$nick=$myrow['nickname'];
	$score=0;//TODO: add score table in db...
	$sql="select * from userscores where user_email='$email' limit 1";
	$query=mysql_query($sql);
	if($scorerow=mysql_fetch_array($query)){
		$score=$scorerow['score'];
	}
	print "<user><nick>".$nick."</nick><score>".$score."</score><group>".$group."</group></user>";
	
	$sql="select * from posts where author_email='$email' order by id desc limit 30";//30 posts at most to display at once
	if( isset($_SESSION['email']) && strncmp($_SESSION['email'], $email)==0 ){
		$sql="select * from posts where author_email='$email' order by id desc";//fetch all for himself
	}
	
	$query=mysql_query($sql);
	print "<post>";
	while($newrow=mysql_fetch_array($query)){
		$id=$newrow['id'];
		$title=$newrow['title'];
		$time=$newrow['create_time'];
		$public=$newrow['public'];
		print $id."<>".$title."<>".$time."<>".$public;
		print "<|>";
	}
	print "</post>";
	
	$sql="select * from userlike where user_email='$email' limit 1";
	$query=mysql_query($sql);
	print "<fav>";
	if($newrow=mysql_fetch_array($query)){
		$str=$newrow['like_posts'];
		$pcs=explode(",",$str);
		for($idx=1; $idx<count($pcs)-1; $idx++){
			$id=$pcs[$idx];
			$sql="select * from posts where id=$id limit 1";
			$query=mysql_query($sql);
			if($xrow=mysql_fetch_array($query)){
				print $id."<>".$xrow['title']."<>".$xrow['create_time'];
			}
			print "<|>";
		}		
	}
	print "</fav>";
	
	print "</data>";
}else{
	print "<code>user_id_error</code>";
}
print "<code>user_info_ok</code>";
?>
<file_sep>/res/hey.js
﻿var scrHgt;
var nickname, email, password, tmpemail, tmppassword, tmpnickname;
var phpDir="./action/";
var postId=0;
var commentToId=0;//which post now commenting to
var viewMode=1;//1 for view, 0 for review
var TYPES=new Array('tech', 'news', 'fun', 'ent');
var heyType=TYPES[0];
var listIdx=0, totalLists=0;
var LIST_SIZE=15;
var MSG_NO_MORE_POST="<b>没有更多文章...</b><br /><li>过会儿更新试试</li><li>点击\"审稿\"审批新文章</li><li>点击\"投递\"发表一篇</li><button style=\"border:none; font-size:11px; margin-left:120px;\" onclick=\"closeHint('no_more_post')\">关闭建议</button>";
function setToolTop(){
	$('#page_tool').css('top',Math.max((scrHgt*0.5-$('#tool')[0].offsetHeight), 240)+"px");
}
function lightStars(idx){
	var box=document.getElementById('rate_box').children;
	for(i=0; i<idx; i++){
		box[i].className="star active";
	}
	for(i=idx;i<5; i++){
		box[i].className="star";
	}
}
function checkFav(){
	if(email){
		if(postId==0){
			dhtmlx.message({type:"error", text:"当前没有可收藏的文章" });
			return;
		}
		$('#tl_fav')[0].onclick=null;
		var check=$('#check_fav')[0];
		var like;
		if(check.className=="unchecked"){
			check.className="checked";
			like=1;
		}else{
			check.className="unchecked";
			like=-1;
		}
		$.get(phpDir+"favpost.php", { id: postId, f: like }, function(resp){handleFavPost(resp);} );
	}else{
		dhtmlx.message({type:"error", text:"请先登录" });
	}
}
function handleFavPost(resp){
	var code=getRespCode(resp);
	if(code=="fav_ok"){
		dhtmlx.message("收藏成功!");
	}else if(code=="unfav_ok"){
		dhtmlx.message("取消收藏!");
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
	$('#tl_fav')[0].onclick=checkFav;
}
function triggerComment(force){//force=force_to_close
	if(!$('#comment_view')[0]){//this is null in review.php
		return;
	}
	if(postId==0){
		return;
	}
	var postHgt=$('#post_view')[0].offsetHeight;
	var commentHgt=$('#comment_view')[0].offsetHeight;
	if(commentHgt==0){
		if(!force){
			$('#post_view').hide();
			$('#comment_view').fadeIn();
			$('#comment_to').html("关于&nbsp;\""+$('#post_title').html()+"\"&nbsp;的评论");
			if(commentToId!=postId && postId!=0){
				$.get(phpDir+"loadcomment.php", { id: postId }, function(resp){handleLoadComment(resp);});
				commentToId=postId;
			}
		}
	}else{
		$('#comment_view').hide();
		$('#post_view').fadeIn();
	}	
}
function handleLoadComment(resp){
	var code=getRespCode(resp);
	var list=$('#cmt_list')[0];
	list.innerHTML="";
	if(code=="no_comment"){
		dhtmlx.message("本文暂无评论,赶紧抢沙发啦~");
	}else if(code=="load_comment_ok"){
		var data=getRespData(resp);
		var pcs=data.split("<>");		
		for(i=0; i<pcs.length-1; i++){			
			var user=my_substr(pcs[i],"u");//later use it to load avartar
			var time=my_substr(pcs[i],"t");
			var comment=my_substr(pcs[i],"c");
			addAComment(list, user, time, comment);
		}
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
}
function addAComment(list, user, time, comment, head){
	var avtDiv=document.createElement('div');
	avtDiv.className="cmt_avatar";
	var cmtDiv=document.createElement('div');
	cmtDiv.className="cmt_text";
	cmtDiv.innerHTML="<i><b>"+user+"</b></i>&nbsp;("+time+")&nbsp;说:<br />"+comment;
	var pDiv=document.createElement('div');
	pDiv.className="cmtbox";
	pDiv.appendChild(avtDiv);
	pDiv.appendChild(cmtDiv);
	var hr=document.createElement('hr');
	hr.className="clear";
	if(head==1){//insert to head
		list.insertBefore(hr,list.childNodes[0]);
		list.insertBefore(pDiv,list.childNodes[0]);
	}else{
		list.appendChild(pDiv);
		list.appendChild(hr);
	}
}
function doComment(){
	if(!email){
		dhtmlx.alert("您尚未登录,无法评论。请先登录或注册后再试!");
		return;
	}
	var text=$('#cmt_content')[0].value;
	if(text==null || text==""){
		dhtmlx.message({ type:"error", text:"请输入评论内容!" });
		return;
	}
	$.post(phpDir+"postcomment.php", { id: commentToId, c:text }, function(resp){handleComment(resp);});
	//immediately add new comment locally
	addAComment($('#cmt_list')[0],nickname,"",text,1);
	$('#cmt_content')[0].value="";
}
function handleComment(resp){
	var code=getRespCode(resp);
	if(code=="no_such_post"){
		dhtmlx.message({ type:"error", text:"原帖已删除,无法评论,请更新网页" });
	}else if(code=="comment_ok"){
		dhtmlx.message("成功添加评论!");
	}else{
		dhtmlx.message({ type:"error", text:"抱歉,出现未知错误!" });
	}
}
function login(){
	$('#login_wrapper').show();	
}
function showTopbar(nick){
	if(nick){		
		$('#anony').hide()
		$('#identity').fadeIn();		
		$('#nickname')[0].innerHTML=nick;
	}else{
		$('#identity').hide()
		$('#anony').fadeIn();
		$('#nickname')[0].innerHTML="";
	}
}
function handleUAuth(resp){
	if(getRespCode(resp)=="verify_ok"){
		email=tmpemail;
		password=<PASSWORD>;
		$('#login_wrapper').hide();
		showTopbar(getRespData(resp));		
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
}
function getRespCode(resp){
	return resp.substring(resp.indexOf("<code>")+6, resp.indexOf("</code>"));
}
function getRespData(resp){
	return resp.substring(resp.indexOf("<data>")+6, resp.indexOf("</data>"));
}
function logout(path){
	delCookie("email");
	delCookie("password");
	if(path==undefined){
		path="";
	}
	$.post(path+phpDir+"userquit.php", {}, function(resp){handleUserQuit(resp);});	
}
function handleUserQuit(resp){
	email=null;
	password=null;
	showTopbar();
}
function doLogin(path){
	tmpemail=$('#email')[0].value;
	tmppassword=$('#password')[0].value;
	if(tmpemail!="test"||tmppassword!="<PASSWORD>"){
		tmppassword=hex_md5(tmppassword);
	}
	if(path==undefined){
		path="";
	}
	$.post(path+phpDir+"verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);});
	//todo: hint circle
}
function quickEgg(id,type){
	if(!id){
		id=0;
	}
	if(!type){
		type=heyType;
	}
	$.get(phpDir+"loadpost.php", { tp: type, id: id, m: viewMode }, function(resp){handleLoadEgg(resp);});
}
function handleLoadEgg(resp){
	var code=getRespCode(resp);
	if(code=="no_post"){		
		dhtmlx.message(MSG_NO_MORE_POST);
		var title=$('#post_title')[0];
		if(title.innerHTML=="加载中..." && postId==0){
			title.innerHTML="暂无文章";
			$('#post_author_name').html("-");
			$('#post_time').html("时间:&nbsp;-");
			$('#post_text').html("");
		}
	}else if(code=="no_such_post"){
		dhtmlx.alert("文章找不到了,看看别的吧" );
	}else{
		resp=decodeURIComponent(resp);
		var pcs=resp.split("<>");
		postId=Number(pcs[0]);
		$('#post_title').html(pcs[1]);
		$('#post_time').html("时间:&nbsp;"+pcs[2]);
		$('#post_text').html(pcs[3]);
		$('#post_author_name').html(pcs[4]);
		$('#post_author_name')[0].href="user.php?uid="+pcs[5];
		//check other components
		if($('#tl_fav')[0]){//in review.php, it's null
			$('#tl_fav')[0].onclick=checkFav;
			if(pcs[6]==0){
				$('#check_fav')[0].className="unchecked";
			}else{
				$('#check_fav')[0].className="checked";
			}
		}
		closeList();
		triggerComment(true);
	}
}
function nearbyEgg(orient,id){
	if(!id){
		id=postId;
	}
	$.get(phpDir+"loadnearbypost.php", { tp: heyType, id: id, m: viewMode, o: orient }, function(resp){handleLoadEgg(resp);});
	triggerComment(true);
}
function openList(){
	$('#list').show();
	$('#list').animate({
		width:"420px"
	},300,function(){
		if(!$('#list_rows')[0].childNodes[0] || $('#list_rows')[0].childNodes[0].className!="rows"){
			loadList();
		}		
	}
	);
}
function closeList(){
	$('#list').animate({
		width:"0"
	},300,function(){
		$('#list').hide();
	}
	);
}
function prevList(){
	if(listIdx==0){
		dhtmlx.message(MSG_NO_MORE_POST);
		return;
	}
	listIdx--;
	loadList();
}
function nextList(){
	if(listIdx==totalLists-1 || totalLists==0){		
		dhtmlx.message(MSG_NO_MORE_POST);
		return;
	}
	listIdx++;
	loadList();
}
function loadList(){
	$.get(phpDir+'loadlist.php', { n: listIdx, tp: heyType, m: viewMode }, function(resp){handleLoadList(resp);});
}
function handleLoadList(resp){
	$('#list_rows').html('');//reset
	resp=decodeURIComponent(resp.trim());
	var mbrs=resp.split("<|>");
	var list=$('#list_rows')[0];
	for(i=0; i<mbrs.length-1; i++){
		var blks=mbrs[i].split("<>");
		var pDiv=document.createElement('div');
		pDiv.className="row";
		pDiv.innerHTML=blks[1];//title
		pDiv.title=blks[1];
		pDiv.onclick=function(v){return function(){loadEggById(v);}}(blks[0])//blks[0]=id, note the grammar
		list.appendChild(pDiv);
	}
	postsInType=Number(mbrs[mbrs.length-1]);//last piece is total lists
	totalLists=Math.ceil(postsInType/LIST_SIZE);
	if(isNaN(totalLists)){
		totalLists=0;
	}
	showListNow();
}
function showListNow(){
	$('#list_now').html((listIdx+1)+"&nbsp;/&nbsp;"+totalLists+"页");
}
function gotoList(){
	var target=$('#jumpNum')[0].value;
	if(target!=null && !isNaN(target) && target.indexOf(".")<0){
		target=Number(target);
		if(target>0 && target<=totalLists){
			listIdx=target-1;
			loadList();
		}else{
			dhtmlx.message( {type:"error", text:"页码超过范围"} );
		}
	}else{		
		dhtmlx.message( {type:"error", text:"请输入要跳转的页码数字"} );
	}
}
function votePost(score){
	if(postId==0){
		dhtmlx.message({type:"error", text:"当前没有可打分的文章"});
		return;
	}
	if(email){
		$.get(phpDir+"votepost.php", { id: postId, s: score }, function(resp){handleVotePost(resp);} );
	}
}
function handleVotePost(resp){
	//alert(resp);
	var code=getRespCode(resp);
	if(code=="vote_ok"){
		dhtmlx.message("打分成功!");
	}else if(code=="already_voted"){
		dhtmlx.message("已经打过分了!");
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
}
function loadEggById(id){
	if(!id){
		id=postId;
	}
	$.get(phpDir+"loadpostbyid.php", { id: id }, function(resp){handleLoadEgg(resp);});	
}
function checkEmail(){
	var r_email=document.getElementById('mail').value;
	if(r_email==""){
		dhtmlx.alert("邮箱地址必须填写!");
		return false;
	}else{
		var at=r_email.indexOf("@");
		var dot=r_email.lastIndexOf(".");
		if(at<1 || dot<3 || dot<at || at!=r_email.lastIndexOf('@') || dot==r_email.length-1){
			dhtmlx.alert("邮箱格式不正确,请检查!");
			return false;
		}
	}
	return true;
}
function checkNick(){
	var nick=document.getElementById('nick').value;
	if(nick.length<2){
		dhtmlx.alert("昵称不能少于2个字符");
		return false;
	}
	return true;
}
function checkPass(){
	var pw=document.getElementById('passwd').value;
	if(pw.length<6 || pw.length>18){
		dhtmlx.alert("密码由6至18个字符组成");
		return false;
	}
	var pw2=document.getElementById('passwd2').value;
	if(pw!=pw2){
		dhtmlx.alert("确认密码不一致,请检查");
		return false;
	}
	return true;
}
function checkCode(){
	var code=document.getElementById('regcode').value;
	if(code.length!=12){
		dhtmlx.alert("邀请码不正确");
		return false;
	}
	return true;
}
function doReg(){
	var email=document.getElementById('mail').value;
	var pw=document.getElementById('passwd').value;
	var nick=document.getElementById('nick').value;
	var code=document.getElementById('regcode').value;
	if( checkEmail() &&	checkPass() && checkNick() && checkCode() ){
		dhtmlx.message("注册中,请稍候...");
		//document.getElementById('submit').onclick="";
		$.post(phpDir+"adduser.php", { m: email, p: hex_md5(pw), n: nick, c: code}, function(resp){handleReg(resp);});
	}
}
function handleReg(resp){
	var code=getRespCode(resp);
	if(code=="register_ok"){
		dhtmlx.message("恭喜,注册成功!");
	}else if(code=="existing_email"){
		dhtmlx.alert("该邮箱已被注册!请直接登录或用其它邮箱注册");
	}else if(code=="existing_nick"){
		dhtmlx.alert("该昵称已经存在了,请尝试其它名字吧");
	}else if(code=="invite_code_error"){
		dhtmlx.alert("邀请码不OK哦");
	}else if(code=="bad_nick"){
		dhtmlx.alert("不适当的昵称,保护黑蛋,人人有责");
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
	$('#submit')[0].onclick=doReg;
}
function browseType(idx){
	if(heyType!=TYPES[idx]){
		heyType=TYPES[idx];
		postId=0;
		commentToId=0;
		listIdx=0; 
		totalLists=0;
		closeList();
		triggerComment(true);
		quickEgg();
	}
}
function closeHint(cmd){
	if(cmd=="no_more_post"){
		MSG_NO_MORE_POST="<b>暂时没有更多文章.</b>";
	}
}
function doSelect(){
	//TODO
}<file_sep>/todo.txt
* post/post-under-review db
	-need to evaluate design tradeoff (two table or one?)
		-done. ONE db for both posts.
* postnew function
	-done without the writing seperate post.html file.
	-need disable local upload for image in editor page
* load default function
	-"no-type-parameter" loading is done for view mode.
	-need do with type parameter
		-done.
	-review mode
		-done.
* page function
	-done.
* list view design
	-container and closer done.
	-need to paginate
		-done.
	-need to list rows
		-done.
	-consider loading abstract together with title, and reduce list_size to 5
* list function
	-loadEggsById not done
		-done.
	-handle empty list case
		-done. don't handle.
	-others done.
* list page function
	-done.
%	-list pager overflow case
		-done.
* review function
	-consider add reviewers to give feedbacks to poster
	-others done.
%	-review page tool button rotate
		-done.
* user favourate function
%	-need to init like/unlike status on the icon when load a post
		//-need to rebuild the mechanism (show two buttons, not one) to make it simpler
		-done.
	-others done.
* comment view
	-rough layout done.
* comment function
	-post new comment done.
	-need to consider comment id (so for future deletion)
		-partly done with timestamp.
	-comment load mechanism (not all at a time, or firstly all, refine later)
		-need to do small files - one comment one file in a dir
			-done.
* register page
	-design / ui done.
	-need to do registration process
		-need to check invitation mechanism first
			-done.
		-others done.
* user info view and link updates in other related pages
	-view and load function done.
	-need to handle parameter input for index.php and review.php
		-done.
	-no information yet
%	-links should be added at all proper places (topbar, post author, comment author)
* user info edit 
	-no yet
* messaging
	-integrated jsMessage.
%	-check out all alert places, and unify the style
		-error: red, info: black
%	-define alert strings as constant

-------------------

-> Masking (especially in post.php)


-------------------

* selection pop-up view
* selection comment function
* selection user-focus function*
* user credit function*
* add post view counts (design the method & rule first)

-------------------
* score mechanism

-------------------

* allow anonymous post submission?
* all masking effect for loading (load post/list/paging, login, logout, like, comment, score, submit, review)

----------------------------------
* Check all similar pages are with same frame ui and functions
* TEST logics that i can think... (remember the test script written down)
* TEST on the deployed environment...

----------------------------------
* check SQL injection (add keyword judgement for input parameters)
* data & code backup mechanism<file_sep>/action/favpost.php
<?php 
session_start();
if( !isset($_SESSION['email']) || !isset($_GET['id']) || !isset($_GET['f']) ){
	return;
}
include_once("lib/head.php");
$email=$_SESSION['email'];
$id=$_GET['id'];
$like=$_GET['f'];
$conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error());
mysql_select_db('eggsys',$conn);
$sql="select count(*) from postlike where post_id=$id limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	if($myrow[0]==0){
		if($like==1){
			$sql="insert into postlike values ($id, 1, ',$email,')";
			$query=mysql_query($sql);
		}
	}else{
		$sql="select * from postlike where post_id=$id limit 1";
		$query=mysql_query($sql);
		$myrow=mysql_fetch_array($query);
		$users=$myrow['like_users'];
		if(strpos($users,','.$email.',')!==false){
			if($like==-1){//cancel favourate
				$users=str_replace(",".$email.",",",",$users);
				$liked=$myrow['liked']-1;
				$sql="update postlike set like_users='$users', liked=$liked where post_id=$id";
				$query=mysql_query($sql);				
			}
		}else{
			if($like==1){
				$users=$users.$email.",";
				$liked=$myrow['liked']+1;
				$sql="update postlike set like_users='$users', liked=$liked where post_id=$id";
				$query=mysql_query($sql);
			}			
		}
	}
}
//update user's like list
$sql="select count(*) from userlike where user_email='$email' limit 1";
$query=mysql_query($sql);
if($myrow=mysql_fetch_array($query)){
	if($myrow[0]==0){//first time for this user to like a post
		if($like==1){
			$sql="insert into userlike values ('$email', 1, ',$id,')";
			$query=mysql_query($sql);
			print "<code>fav_ok</code>";
		}
	}else{
		$sql="select * from userlike where user_email='$email' limit 1";
		$query=mysql_query($sql);
		$myrow=mysql_fetch_array($query);
		$posts=$myrow['like_posts'];
		if(strpos($posts,','.$id.',')!==false){
			if($like==-1){//cancel favourate
				$posts=str_replace(",".$id.",", ",", $posts);
				$liked=$myrow['liked']-1;
				$sql="update userlike set like_posts='$posts', liked=$liked where user_email='$email'";
				$query=mysql_query($sql);	
				print "<code>unfav_ok</code>";			
			}
		}else{
			if($like==1){
				$posts=$posts.$id.",";
				$liked=$myrow['liked']+1;
				$sql="update userlike set like_posts='$posts', liked=$liked where user_email='$email'";
				$query=mysql_query($sql);
				print "<code>fav_ok</code>";
			}			
		}
	}
}
?>
<file_sep>/README.md
heyegg
======

Heyegg is a Digg-like yet reading friendly news service. It allows users to submit and evaluate news posts. Posts with recommendations will be public accessible. Heyegg is built upon jQuery, PHP, and MySQL.
A sample site is available at http://www.heyegg.com (closed now).
<file_sep>/res/extool.js
/*firefox's event*/
function __firefox(){
    HTMLElement.prototype.__defineGetter__("runtimeStyle", __element_style);
    window.constructor.prototype.__defineGetter__("event", __window_event);
    Event.prototype.__defineGetter__("srcElement", __event_srcElement);
}
function __element_style(){
    return this.style;
}
function __window_event(){
    return __window_event_constructor();
}
function __event_srcElement(){
    return this.target;
}
function __window_event_constructor(){
    if(document.all){
        return window.event;
    }
    var _caller = __window_event_constructor.caller;
    while(_caller!=null){
        var _argument = _caller.arguments[0];
        if(_argument){
            var _temp = _argument.constructor;
            if(_temp.toString().indexOf("Event")!=-1){
                return _argument;
            }
        }
        _caller = _caller.caller;
    }
    return null;
}
if(window.addEventListener){
    __firefox();
}

/*Browser detection*/
var Browser = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},{
			prop: window.opera,
			identity: "Opera"
		},{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "IE",
			versionSearch: "MSIE"
		},{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

/*Cookie management*/
function setCookie(name,value){
    var days = 30;
    var exp  = new Date();
    exp.setTime(exp.getTime() + days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

/*String prototype*/
String.prototype.trim= function(){   
    return this.replace(/(^\s*)|(\s*$)/g, "");  
}

/*Misc*/
function my_substr(origin, tag){//parse xml like strings
	var fromstr="<"+tag+">";
	var tostr="</"+tag+">";
	if(origin.indexOf(fromstr)>=0 && origin.indexOf(tostr)>=0){
		return origin.substring(origin.indexOf(fromstr)+fromstr.length, origin.indexOf(tostr));
	}else{
		return null;
	}
}

function getSelectedText() 
{ 
	if (window.getSelection) 
		{ // This technique is the most likely to be standardized. 
		// getSelection() returns a Selection object, which we do not document. 
		return window.getSelection().toString(); 
	} 
	else if (document.getSelection) 
	{ 
		// This is an older, simpler technique that returns a string 
		return document.getSelection(); 
	} 
	else if (document.selection) 
	{ 
		// This is the IE-specific technique. 
		// We do not document the IE selection property or TextRange objects. 
		return document.selection.createRange().text; 
	} 
}
<file_sep>/ueditor/_examples/post.php
﻿<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>黑蛋 | 投递新稿件</title>
<link rel="stylesheet" type="text/css" href="../../jsMessage/codebase/themes/message_growl_dark.css">
<link href="../../res/style.css" rel="stylesheet" type="text/css" />
<link href="../../res/effect.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../themes/default/ueditor.css"/>
<script language="javascript" src="../../res/jquery-1.6.2.min.js"></script>
<script language="javascript" src="../../res/extool.js"></script>
<script language="javascript" src="../../res/md5-min.js"></script>
<script language="javascript" src="../../res/hey.js?v=0.2"></script>
<script type="text/javascript" src='../../jsMessage/codebase/message.js?v=0.2'></script>
<script type="text/javascript" charset="utf-8" src="../editor_config.js"></script>    
<script type="text/javascript" charset="utf-8" src="../editor_all_min.js"></script>
<style>
#view{
	font-size:14px;
	font-family:'Microsoft YaHei';
	padding:40px 10px;
}
#ptitle{
	width:100%;
}
label{
	display:block;
	margin:25px 0px 2px 0;
}
</style>
<script language="javascript">
$(document).ready(function(){
	initUser();
});

function initUser(){	
	tmpemail="<?php 
		if(isset($_SESSION['email'])) {
			print $_SESSION['email'];
		}else{
			print "";
		}
	?>";
	tmpnickname="<?php
		if(isset($_SESSION['nickname'])) {
			print $_SESSION['nickname'];
		}else{
			print "";
		}
	?>";
	if(tmpemail==""){
		tmpemail=getCookie("email");
		if(tmpemail!=null){	
			tmppassword=getCookie("password");
			$.post("../../action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);});
			//todo: show a loading circle nearby "login" span			
		}
	}else{
		email=tmpemail;
		nickname=tmpnickname;
		showTopbar(nickname);
	}
}
function doPost(){
	var type=$('#type')[0].value;
	var title=$('#ptitle')[0].value;
	var content=editor_a.getContent();	
	if(email){
		if(title==""){
			dhtmlx.alert("请输入文章标题!");
		}else if(!editor_a.hasContents()){
			dhtmlx.alert("请输入文章内容!");
		}else{
			editor_a.sync();
			$.post("../../action/addpost.php", { tp: type, tl: title, ct: content}, function(resp){handlePost(resp);});
		}
	}else{		
		dhtmlx.alert("请先登录!");
	}
}
function handlePost(resp){
	var code=getRespCode(resp);
	if(code=="post_ok"){
		dhtmlx.message("投递成功!");
		$('#ptitle')[0].value="";
	}else if(code=="identity_error"){
		dhtmlx.alert("登录信息错误,请重新登录!");
	}else{
		dhtmlx.alert("抱歉,出现未知错误!");
	}
}
</script>
</head>

<body>
<div id="topbar">
	<div id="btm_border"></div>
	<div id="left_panel"></div>
	<div id="right_panel">
		<div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div>
		<div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout('../../')">退出</span></div>
	</div>
	<div id="logo" onclick="window.open('../../index.php');"></div>
</div>
<div id="main">
	<div id="view">
		<div>
			<label>文章标题</label>
			<input type="text" id="ptitle" maxlength="50" />
		</div>
		<div>
			<label>类别:</label>
			<select id="type">
				<option value="tech">科技</option>
				<option value="news">社会</option>
				<option value="fun">奇趣</option>
				<option value="ent">娱乐</option>
			</select>
		</div>
		<div>
			<label>正文内容</label>
			<script type="text/plain" id="myEditor" class="myEditor"></script>
			<script type="text/javascript">
				var editor_a = new baidu.editor.ui.Editor();
				editor_a.render('myEditor');
				//remove unused tools
				var unused=Array(3,6,7,8,15,16,18,19,20,21,50,57,88,89,90,122,133,138,143,144,149,166,167,168,169,170,171,172,173,174,175,176,177,184,186);
				//alert(unused+";"+unused.length);
				var i=0;
				for(; i<unused.length; i++){
					hideTool('edui'+unused[i]);
				}
				
				function hideTool(tid){
					var tobj=document.getElementById(tid);
					if(tobj){
						/*var tparent=tobj.parentNode;
						tparent.removeChild(tobj);
						*///we don't remove it as warnings in console, so just hide it
						tobj.style.display="none !important";    		
					}
				}
			</script>
		</div>
		<div>
			<button id="submit" style="top:10px" onclick="doPost()" style="top:90px; right:-270px;">投递</button>
		</div>
	</div>
</div>
<div id="login_wrapper" style="display:none">
	<div id="login">
		<div id="close_login" onClick="$('#login_wrapper').hide();"></div>
		<input type="text" value="Email" id="email" onFocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onBlur="this.className='';if(this.value.trim()=='') this.value='Email';" />
		<input type="text" value="密码" id="password" onFocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onBlur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/>
		<button id="submit" onclick="doLogin('../../');" style="top:80px;left:-37px;float:right;">登录</button>
	</div>
</div>
</body>
</html>
