<?php
defined('IN_TS') or die('Access Denied.');  

define( 'OP_API_TOKEN_ERROR' , 10001 );
define( 'OP_API_USER_ERROR' , 10002 );
define( 'OP_API_LEVEL_ERROR' , 10003 );
define( 'OP_API_DB_ERROR' , 10004 );
define( 'OP_API_NOT_IMPLEMENT_YET' , 10005 );
define( 'OP_API_ARGS_ERROR' , 10006 );
define( 'OP_API_DB_EMPTY_RESULT' , 10007 );
define( 'OP_API_UPLOAD_ERROR' , 10008 );
define( 'OP_API_STORAGE_ERROR' , 10009 );

function z( $str )
{
	return strip_tags( $str );
}
function v( $str )
{
	$str = trim($str);
	return isset( $_REQUEST[$str] ) ? $_REQUEST[$str] : false;
}
function s( $str , $db = NULL )
{
	//if( $db == NULL ) $db = db();
	return  mysql_real_escape_string( $str )  ;
	
}

class mobile{

	var $db;
	var $callback;
	
	
	function mobile($dbhandle){
		global $ac,$callback;
		$this->db = $dbhandle;
		$this->callback = $callback;
		echo header("Access-Control-Allow-Origin: *");
		
		if( $ac != 'get_token' && $ac != 'get_zhuti_goods_list'&& $ac != 'get_feed_list' &&$ac != 'admin' && $ac != 'get_cate' && $ac != 'get_hot_list' && $ac != 'get_cate_list' && $ac != 'get_baobei' && $ac != 'get_zhuti_list')
		{
			//$this->check_token();
		}
	}
	
	
	
	public function banner_json()
	{
		$arrSlides = $this->db->fetch_all_assoc("select * from ".dbprefix."mobileslide order by sort asc");
		foreach($arrSlides as $key=>$item){
			$data .= "<li><a class='pic' href='#list' onclick='loadList(\"".$item['desc']."\",this)'><img src='".SITE_URL.$item['img']."' /></a></li>";
			}

		return  $this->send_result( $data );
	}
	
	
	public function cate_json()
	{
		$strsitenav = $this->db->fetch_all_assoc("select * from ".dbprefix."goods_cate where parent_id=0 and appname<>'' order by sort asc");
		$strMobileNav = $this->db->fetch_all_assoc("select * from ".dbprefix."mobile_cate order by sort asc");
		$sitenav = is_array($strMobileNav)?$strMobileNav:$strsitenav;
		foreach($sitenav as $key=>$item){

			$data .= "<div class='col4'><div class='h_b'>
<a class='pic' href='#list' data-nav='dongtai' onclick='loadList(".$item['tbcateid'].",this)'><img src='".SITE_URL.$item['img']."' width='100%'>
<span style='line-height: 24px;background-color: #C55050;color: #fff;'>".$item['cate_name']."</span>
</a></div></div>";
			
			}
		return  $this->send_result( $data );
	}
	
	//获取今日推荐
	public function today_json()
	{
		$today = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where mobile_today=1 order by uptime desc");
		foreach($today as $key=>$item){
			$arruser = aac('user')->getUserForApp($item['uid']);
			if($item['oldimg']){
				$oldimg = explode("|", $item['oldimg']);
				$item['img'] = $oldimg[0].'_400x400.jpg';
			}else{

				$item['img'] = SITE_URL.$item['img'];
			}
			$data .= "<div class='topicBox'>
                    <div class='topicCon pd15'>
                            <p class='personImgDate'>
                                <span class='perImg db'>
                                    <a href='#'>
                                    <img src='".$arruser['face']."' data-original='".$arruser['face']."' class='bImg' width='38' height='38' style='display: block;'>
                                    </a>
                                    
                                    <span class='timeT'>".$arruser['username']."</span>
                            <div class='clearfix'></div>                            
                           </span>
                           
                           <div class='clearfix'></div>
                           </p>
                           
                           
                            <div class='detailCon'>
                            <div style='margin:0 auto; text-align:center' class=''>
                                <a href='#baobei' onclick='loadBaobei(".$item['goods_id'].",this,\"".$item['url']."\")'>
                                    <img src='".$item['img']."' data-original='".$item['img']."' alt='' style='display: inline;'>
                                </a>
                            </div>
                            
                            <div class='title'>".$item['name']."
                            <span>".$item['price']."元</span>
                            </div>
                            
                                                   
                                
                            </div>
                    </div>
            
        </div>";
		}
		return  $this->send_result( $data );
	}
	
	public function index()
	{
		$data = array( 'text' => 'welcome to opath api interface' );
		return  $this->send_result( $data );
	}
	
	public function get_cate()
	{
		
		$strsitenav = $this->db->fetch_all_assoc("select * from ".dbprefix."goods_cate where parent_id=0 and appname<>'' order by sort asc");
		$strMobileNav = $this->db->fetch_all_assoc("select * from ".dbprefix."mobile_cate order by sort asc");
		$sitenav = is_array($strMobileNav)?$strMobileNav:$strsitenav;
		foreach($sitenav as $key=>$item){
			$sitenavs[] = $item;
			$sitenavs[$key]['key'] = $key;
			$sitenavs[$key]['img'] = SITE_URL.$item['img'];
			}
		
		$this->send_result( $sitenavs );
	}
	
	
		public function get_baobei()
	{
		$goods_id = z(v('goods_id'));
		if ($goods_id) {
			$good = $this->db->once_fetch_assoc("select * from ".dbprefix."share_goods where goods_id=$goods_id");
		
		//分享者开始
	$shareuserid = $good['uid'];
	
	$strshareUser = $this->db->once_fetch_assoc("select * from ".dbprefix."user_info where userid='$shareuserid'");
	
	//头像
		if($strshareUser['face'] != ''){
			$strshareUser['face'] = SITE_URL.miniimg($strshareUser['face'],'user',180,180,$strshareUser['path'],1);
			
		}else{
			
			$strshareUser['face']	= SITE_URL.'public/images/noavatar.gif';
		}
		$arroldimg = explode('|',$good['oldimg']);
		$good['img'] = SITE_URL.$good['img'];
		$good['oldimg'] = $arroldimg[0];
		$good['strshareUser'] = $strshareUser;
		}
		

		$this->send_result( $good );
	}
	
	public function get_zhuti_list()
	{


		$page = z(v('page'))?z(v('page')):1;
		$lstart = $page*10-10;
		$zhutis = $this->db->fetch_all_assoc("select * from ".dbprefix."theme order by addtime desc limit $lstart,10");
		foreach($zhutis as $key=>$item){
			$zhuti[] = $item;
			$zhuti[$key]['riqi'] = date("m-d",$item['addtime']);
			$item['simg'] = $item['simg']?$item['simg']:'images/nogoods.gif';
			$zhuti[$key]['simg'] = SITE_URL.$item['simg'];
		}
		
		$result['item_num'] = count($zhuti);
		$result['item'] = $zhuti;
		$result['pageCount'] = 10;
		$this->send_result( $result );
	}
	
	
	public function get_zhuti_goods_list()
	{
		$themeid = z(v('themeid'))?z(v('themeid')):0;
		$strTheme = $this ->db->once_fetch_assoc("select * from ".dbprefix."theme where themeid='$themeid'");
		
	if(substr($strTheme['strgoodid'], -1)==','){
		$slen = strlen($strTheme['strgoodid'])-1;
		$strTheme['strgoodid'] = substr($strTheme['strgoodid'],0,$slen);
		$this ->db->query("update ".dbprefix."theme set `strgoodid`='".$strTheme['strgoodid']."' where themeid='$themeid'");
		}
		
	$strTheme['strgoodid'] = str_replace(',,',',',$strTheme['strgoodid']);

	$sqlin = $strTheme['strgoodid']?' where goods_id in ('. $strTheme['strgoodid'] .')':'';
	if($sqlin){
	$strsharesys = $this ->db->fetch_all_assoc("select* from ".dbprefix."share_goods ".$sqlin." limit 100");
	foreach($strsharesys as $key=>$item){
		$strsharey[] = $item;
		$strsharey[$key]['key'] = $key;
		$strsharey[$key]['img'] = SITE_URL.$item['img'];
	}
	}
		
		$result['item_num'] = count($strsharey);
		$result['item'] = $strsharey;
		$this->send_result( $result );
	}
	
	public function get_feed_list()
	{

		$page = z(v('page'))?z(v('page')):1;
		$lstart = $page*10-10;
		$arrfollowfeeds = $this->db->fetch_all_assoc("select feedid,feedtype,data,userid,addtime from ".dbprefix."feed  where feedtype='goods' order by addtime desc limit $lstart,10");

		foreach($arrfollowfeeds as $key=>$item){
		$arrfollowfeed[] = $item;
		
	$strshareUser = $this->db->once_fetch_assoc("select * from ".dbprefix."user_info where userid='".$item['userid']."'");
	
	//头像
		if($strshareUser['face'] != ''){
			$strshareUser['face'] = SITE_URL.miniimg($strshareUser['face'],'user',180,180,$strshareUser['path'],1);
			
		}else{
			
			$strshareUser['face']	= SITE_URL.'public/images/noavatar.gif';
		}
		$arrdata = unserialize($item['data']);
		$arrfollowfeed[$key]['username'] = $strshareUser['username'];
		$arrfollowfeed[$key]['face'] = $strshareUser['face'];
		$arrfollowfeed[$key]['data'] = $arrdata;
		$arrfollowfeed[$key]['data']['img'] = SITE_URL.$arrdata['img'];
		}
		$result['item'] =  $arrfollowfeed;
		$result['item_num'] = count($arrfollowfeed);
		$this->send_result($result);

	}
	
	
	public function get_cate_list()
	{
		$page = z(v('page'))?z(v('page')):1;
		$cate_id= z(v('catid'))? z(v('catid')):999999;
		if (intval($cate_id)) {
			$where = 'cate_id = '.$cate_id.'';
		}else{

			$where = 'name like \'%'.$cate_id.'%\'';
		}
		$lstart = $page*10-10;
		$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where ".$where." order by uptime desc limit $lstart,10");
		foreach($Goods as $key=>$item){
					$Good[] = $item;
					$Good[$key]['key'] = $key;
					if($item['oldimg']){
						$oldimg = explode("|", $item['oldimg']);
						$Good[$key]['img'] = $oldimg[0].'_400x400.jpg';
					}else{
						$Good[$key]['img'] = SITE_URL.$item['img'];
					}
				}
		
		$result['item_num'] = count($Good);
		$result['item'] = $Good;
		$result['pageCount'] = 10;
		$this->send_result( $result );
	}
	
	public function get_hot_list()
	{
		$spage = z(v('p'))?z(v('p')):1;
		$pull = z(v('pull'));
		$type = z(v('type'));
		$lastid = z(v('lastid'));
		
		switch ($type)
			{
			case 'new_tab':
				if($pull=='down'){
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where goods_id>".$lastid." order by uptime desc limit 10");
					$result['lastid'] = $Goods[0]['goods_id'];
					$result['p'] = count($Goods)?$spage+10:0;
				}else{
					
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods order by uptime desc limit $spage,10");
					$result['p'] = count($Goods)?$spage+10:0;
				}
			 
			  break;  
			case 'hot_tab':
					
				if($pull=='down'){
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where goods_id>".$lastid." order by count_view+count_comment+count_like+count_worth desc limit 10");
					$result['last_id'] = $Goods[0]['goods_id'];
				}else{
					
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods order by count_view+count_comment+count_like+count_worth desc limit $spage,10");
					
				}
			
			  break;
			case 'follow_tab':
					
				if($pull=='down'){
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where goods_id>".$lastid." order by count_view+count_comment+count_like+count_worth desc limit 10");
					$result['last_id'] = $Goods[0]['goods_id'];
					$result['p'] = count($Goods)?$spage+10:0;
				}else{
					
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods order by count_view+count_comment+count_like+count_worth desc limit $spage,10");
					$result['p'] = count($Goods)?$spage+10:0;
				}
			
			  break;
			  
			  case 'shop_tab':
					
				if($pull=='down'){
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where goods_id>".$lastid." and is_loc=1 order by uptime desc limit 10");
					$result['last_id'] = $Goods[0]['goods_id'];
					$result['p'] = count($Goods)?$spage+10:0;
				}else{
					
					$Goods = $this->db->fetch_all_assoc("select * from ".dbprefix."share_goods where and is_loc=1  orderby uptime desc limit $spage,10");
					$result['p'] = count($Goods)?$spage+10:0;
				}
			
			  break;
			  
			  
			 
			}
	
		foreach($Goods as $key=>$item){
					$Good[] = $item;
					$Good[$key]['key'] = $key;
					$Good[$key]['img'] = SITE_URL.$item['img'];
				}
		
		$result['item_num'] = count($Good);
				
		$result['item'] = $Good;
		$this->send_result( $result );
	}
	
	public function get_token()
	{
		$email = z(v('email'));
		$password = z(v('password'));
		
		$sql = "SELECT * FROM `".dbprefix."user` WHERE `email` = '" . s( $email ) . "' AND `pwd` = '" . md5( $password ) . "'";

		
		if( $user = $this->db->once_fetch_assoc($sql))
		{
			
			session_start();
			$token = session_id();
			$sql = "SELECT * FROM `".dbprefix."user_info` WHERE `userid` = '" .$user['userid'] . "'";
			$userinfo = $this->db->once_fetch_assoc($sql);
			$_SESSION['token'] = $token;
			$_SESSION['uid'] = $user['userid'];
			$_SESSION['name'] = $userinfo['username'];
			$_SESSION['email'] = $user['email'];
			
			return $this->send_result( array( 'token' => $token , 'uid' => $user['userid'] ) );
			
		}
		else
		{
			return $this->send_error( OP_API_TOKEN_ERROR , 'BAD EMAIL OR PASSWORD' );
		}
		
	}
	
	public function user_verify()
	{	
	
		$uid = z(v('uid'));
		$sql = "SELECT * FROM `".dbprefix."user_info` WHERE `userid` = '"  . intval( $uid ) . "'";
		
		if( $user = $this->db->once_fetch_assoc($sql))
		{
			$user['refresh_time'] = date("m月d日 H:i");
			$user['face'] = $user['face']?SITE_URL.miniimg($user['face'],'user',180,180,$user['path'],1):SITE_URL.'public/images/noavatar.gif';
			$this->send_result( $user );
		}
		else
		{
			return $this->send_error( OP_API_USER_ERROR , 'NO SUCH UID' );
		}
	}
	
	public function user_remove()
	{
		$uid = intval(v('uid'));
		if( $uid < 1 || !$user = get_line( "SELECT `id` as `uid` , `name` FROM `user` WHERE `id` = '" . intval( $uid ) . "' AND `id` != '" . intval( ss('uid') ) . "' LIMIT 1" ) )
		{
			return $this->send_error( OP_API_USER_ERROR , 'NO SUCH UID OR UID IS SELF' );
		}
		else
		{
			if( ss('level') != 'SUPERADMIN' ) return $this->send_error( OP_API_LEVEL_ERROR , 'ONLY SUPER ADMIN CAN DELETE MEMBER' );
			
			$sql = "UPDATE `user` SET `status` = 'FORBIDDEN' WHERE `id` = '" . intval( $uid ) . "' LIMIT 1";
			
			run_sql( $sql );
			
			if( mysql_errno() != 0 )
			{
				return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
			}
			else return $this->send_result( array( 'msg' => 'OK' ) );
		}
	}
        
        public function avatar_upload()
	{
		if( $_FILES['file']['error'] != 0 ) 
			return $this->send_error( OP_API_UPLOAD_ERROR , 'UPLOAD ERROR ' . $_FILES['file']['error'] ); 
                        
                        
                 $tmp_image_name =  SAE_TMP_PATH . md5(time().rand(1,99999)) . '.tmp.jpg';
                 jpeg_up( $_FILES['file']['tmp_name'], $tmp_image_name)   ;    
		
		include_once( CROOT . 'function/thumbnail.class.php' );
		
		$s = new SaeStorage();
		
		
		$file_thumb_name = md5(time().rand(1,99999)) . '.snap.jpg';
                
                $tmp_file = SAE_TMP_PATH.$file_thumb_name;
		
                
          	include_once( CROOT . 'function/icon.class.php' );
                
                $icon = new Icon();
                
                $icon->path = $tmp_image_name;
                $icon->size = 80;
                $icon->dest = $tmp_file;
                $icon->createIcon();
                
          	/*
                
		$myThumb = new Thumbnail; // Start using a class
		$myThumb->setMaxSize( 80 , 80 ); // Specify maximum size (width, height)
		$myThumb->setImgSource(	$tmp_image_name ); // Specify original image filename
		
		$myThumb->Create( $tmp_file );
		 
		*/
                
                
                
                
                if(!$thumb_url = $s->write( 'upload' , $file_thumb_name , file_get_contents($tmp_file) ))
		{
			return $this->send_error( OP_API_STORAGE_ERROR , 'SAVE ERROR ' . $s->errmsg() );
		}
		
		
		$sql = "UPDATE `user` SET `picture` = '" . s( $thumb_url ) . "' WHERE `id` = '" . intval(ss( 'uid' )) . "' LIMIT 1";
				 
				 
		 run_sql( $sql );
				 
		 if( mysql_errno() != 0 )
		 {
		 	return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
		 }
		 else
		 {
		 	$sql = "SELECT `id` as `uid` , `name` , `timeline` , `level`, `cover` , `picture` FROM `user` WHERE `id` = '" . intval( $_SESSION['uid'] ) . "' LIMIT 1";
		
			if( $user = get_line( $sql ) )
			{
				$user['refresh_time'] = date("m月d日 H:i");
				$this->send_result( $user );	
		 	}
		 	else
		 		return $this->send_error( OP_API_DB_ERROR , 'NO SUCH UID ' );
		 
                 }		 
         
	}
	
	
	public function image_upload()
	{
		if( $_FILES['file']['error'] != 0 ) 
			return $this->send_error( OP_API_UPLOAD_ERROR , 'UPLOAD ERROR ' . $_FILES['file']['error'] ); 
                        
                        
                 $tmp_image_name =  SAE_TMP_PATH . md5(time().rand(1,99999)) . '.tmp.jpg';
                 jpeg_up( $_FILES['file']['tmp_name'], $tmp_image_name)   ;    
		
		include_once( CROOT . 'function/thumbnail.class.php' );
		
		$s = new SaeStorage();
		
		$file_name = md5(time().rand(1,99999)) . '.jpg';
		
		if( !$url = $s->write( 'upload' , $file_name , file_get_contents( $tmp_image_name ) ))
		{
			return $this->send_error( OP_API_STORAGE_ERROR , 'SAVE ERROR ' . $s->errmsg() );
		}
		
		
		$file_thumb_name = md5(time().rand(1,99999)) . '.snap.jpg';
		
		$myThumb = new Thumbnail; // Start using a class
		$myThumb->setMaxSize( 430 , 600 ); // Specify maximum size (width, height)
		$myThumb->setImgSource(	$tmp_image_name ); // Specify original image filename
		
		$tmp_file = SAE_TMP_PATH.$file_thumb_name;
		$myThumb->Create( $tmp_file );
		 
		if(!$thumb_url = $s->write( 'upload' , $file_thumb_name , file_get_contents($tmp_file) ))
		{
			return $this->send_error( OP_API_STORAGE_ERROR , 'SAVE ERROR ' . $s->errmsg() );
		}
		
		
		$sql = "INSERT INTO `path` ( `uid` , `name` , `type` ,  `timeline` , `image` , `image_thumb`  ) VALUES " 
				 . " ( '" . intval( ss('uid') ) . "' , '" . s( ss('name') ) . "' , 'MBLOG' , NOW() , '" . s( $url ) . "' , '" . s( $thumb_url ) . "' )";
				 
				 
		 run_sql( $sql );
				 
		 if( mysql_errno() != 0 )
		 {
		 	return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
		 }
		 else
		 {
		 	// todo
		 	// this will cause some problem when using mysql relocation
		 	
		 	$pid = last_id();
		 	if( intval( $pid ) < 1 ) return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
		 	
		 	
		 	if($path = get_line( "SELECT * FROM `path` WHERE `id` = '" . intval( $pid ) . "' LIMIT 1" ))
		 		return $this->send_result( $path );
		 	else
		 		return $this->send_error( OP_API_DB_ERROR , 'NO SUCH PID ' );	
		 }
		 
				 
		
		
	}
	
	public function path_add()
	{
		// check the type first
		$type = t(z(v('type')));
		
		switch( $type )
		{
			case 'MUSIC':
				return $this->send_error( OP_API_NOT_IMPLEMENT_YET , 'coming soon' );
				break;
				
			case 'SLEEP':
				return $this->send_error( OP_API_NOT_IMPLEMENT_YET , 'coming soon' );
				break;
				
			case 'MBLOG':
			default:
					
				// pic - text - with - local can't be empty at the same time
				$text = z(t(v('text')));
				
				$picture = z(t(v('picture')));
				$with_uids = z(t(v('with_uids')));
				$location = z(t(v('location')));
				
				if( (strlen( $text ) < 1) && (strlen( $picture ) < 1) && (strlen( $with_uids ) < 1) && (strlen( $location ) < 1)  )
				{
					return $this->send_error( OP_API_ARGS_ERROR , 'text/pic/with/local can\'t be empty at same time' );
				}
				
				// TODO 
				// generate text when is empty
				
				if( strlen($text) < 1  )
				{
					return $this->send_error( OP_API_ARGS_ERROR , 'text can\'t be empty' );
				}
				
				$sql = "INSERT INTO `path` ( `uid` , `name` , `type` , `text` , `timeline` , `image` , `image_thumb` , `with_uids` 
				 , `music_info` , `sleep_info` , location_info ) VALUES " 
				 . " ( '" . intval( ss('uid') ) . "' , '" . s( ss('name') ) . "' , 'MBLOG' , '" . s( $text ) . "' , NOW() ";
				 
				 $image = z(t(v('image')));
				 if( strlen($image) > 1 )
				 {
				 	// todo 
				 	// make thumb for image
				 	$image_thumb = $image;
				 }
				 else
				 {
				 	$image_thumb = '';
				 }
				 

				 $sql .= " , '" . s( $image ) . "' , '" . s( $image_thumb ) . "' ";
				 
				 $with_uids = z(t(v('with_uids')));
				 $sql .= " , '" . s( $with_uids ) . "' , '' , '' "; // music info , sleep info
				 
				 $location = z(t(v('location')));
				 $sql .= " , '" . s( $location ) . "' ";
				 
				 
				 
				 $sql .= " )";
				 
				 //echo $sql;
				 
				 run_sql( $sql );
				 
				 if( mysql_errno() != 0 )
				 {
				 	return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
				 }
				 else
				 {
				 	// todo
				 	// this will cause some problem when using mysql relocation
				 	
				 	$pid = last_id();
				 	if( intval( $pid ) < 1 ) return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
				 	
				 	
				 	if($path = get_line( "SELECT * FROM `path` WHERE `id` = '" . intval( $pid ) . "' LIMIT 1" ))
				 		return $this->send_result( $path );
				 	else
				 		return $this->send_error( OP_API_DB_ERROR , 'NO SUCH PID ' );	
				 }
				 
				 
				
		}
		
				
	}
	
	
	public function path_remove()
	{
		$pid = intval( v('pid') );
		
		if(!$path = get_line( "SELECT * FROM `path` WHERE `id` = '" . intval( $pid ) . "' LIMIT 1" ))
		{
			return $this->send_error( OP_API_DB_ERROR , 'NO SUCH PID ' );
		}
		
		// you can only remove the path you add , or you are admin
		if( $path['uid'] == ss('uid') || is_admin() )
		{
			$sql = "DELETE FROM `path` WHERE `id` = '" . intval( $pid ) . "' LIMIT 1";
			run_sql( $sql );
			
			if( mysql_errno() != 0 )
			{
				return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
			}
			else return $this->send_result( array( 'msg' => 'OK' ) );
			
			
		}
		else return $this->send_error( OP_API_LEVEL_ERROR , 'U CAN DELETE YOUR PATH ONLY' );
	}
	
	public function path_list()
	{
		
		$since_id = intval( v('since_id') );
		if( $since_id > 0 ) $since_sql = " AND `id` < '" . intval( $since_id ) . "' ";
		else
		{
			$since_sql = "";
			
			$max_id = intval( v('max_id') );
			if( $max_id > 0 ) $max_sql = " AND `id` < '" . intval( $max_id ) . "' ";
			else $max_sql = "";

		} 
		
		
				
		$count = intval( v('count') );
		
		if( $count < 1 ) $count = 10;
		
		$sql = "SELECT * FROM `path` WHERE 1 " . $since_sql . " " . $max_sql . " ORDER BY `id` DESC LIMIT " . $count ;
		
		if( !$fdata = get_data( $sql ) )
		{
			if( mysql_errno() != 0 )
				return $this->send_error( OP_API_DB_ERROR , 'DATABASE ERROR ' . mysql_error() );
			else
				return $this->send_error( OP_API_DB_EMPTY_RESULT , 'NO DATA RETURN '  );	
		}
		
		$fitem = reset( $fdata );
		$max = $min = $fitem['id'];
		
		foreach( $fdata as $item )
		{
			$uids[] = $item['uid'];
			$umap[$item['uid']][] = $item['id'];
			$rdata[$item['id']] = $item;
			
			if( $item['id'] > $max ) $max = $item['id'];
			if( $item['id'] < $min ) $min = $item['id'];	
		}
		
		//echo "umap: ";
		//print_r( $umap );
		
		if( isset( $uids ) )
		{
			$sql = "SELECT `id` , `name` , `timeline` , `level`, `cover` , `picture` FROM `user` WHERE `id` IN ( " . join( ' , ' , $uids ) . " )";
			
			if( $udata = get_data( $sql ) )
			{
				
				//echo "udata: ";
				//print_r( $udata );
				
				foreach( $udata as $uitem )
				{
					
					if( isset( $umap[$uitem['id']] ) && is_array( $umap[$uitem['id']] ) )
					{
						foreach( $umap[$uitem['id']] as $itemid )
						{
							//echo "itemid  =  " . $itemid . "  ";
							
							$rdata[$itemid]['user'] = $uitem;
												
						}
					}
				}
			}
		}
		
		//print_r( $rdata );
		
		// jquery-tmpl can't render the data array with numeric index
		// so i have to do this make it happy
		$result['items'] = array_values($rdata);
		$result['max'] = $max;
		$result['min'] = $min;
		$result['refresh_time'] = date("m月d日 H:i");
		
		
		
		return $this->send_result( $result ); 
		
		
	}
	
	
	private function check_token()
	{
		$token = z(v('token'));
		
		if( strlen( $token ) < 2 ) return $this->send_error( OP_API_TOKEN_ERROR , 'no token' );
		
		//Session问题后期完善,这里无法正常调取id为$token的值
		
		//session_id($token );
		//session_start();

		//if( $_SESSION['token'] != $token ) return $this->send_error( OP_API_TOKEN_ERROR , 'bad token' );
	}
	
	public function send_error( $number , $msg )
	{	
		$obj = array();
		$obj['err_code'] = intval( $number );
		$obj['err_msg'] = $msg;
		
		die( json_encode( $obj ) );
	}
	
	public function send_result( $data )
	{
		$obj = array();
		$obj['err_code'] = '0';
		$obj['err_msg'] = 'success';
		$obj['data'] = $data;
		
		die($this->callback.'('.json_encode( $obj ).')' );
	}
	
}
	
