<?php



/**

 *      [Discuz!] (C)2001-2099 Comsenz Inc.

 *      This is NOT a freeware, use is subject to license terms

 *

 *      $Id: spacecp_friend.php 30797 2012-06-20 03:10:04Z monkey $

 */



if(!defined('IN_DISCUZ')) {

	exit('Access Denied');

}

include_once (DISCUZ_ROOT.'source/discuz_version.php');

require_once libfile('function/friend');



$op = empty($_GET['op'])?'':$_GET['op'];

$uid = empty($_GET['uid'])?0:intval($_GET['uid']);



$space['key'] = space_key($space['uid']);



if($op == 'add') {

        

        //print_r($_GET['debug']);die;

        //推送参数

        //print_r($_GET);die;

        if(empty($_GET['platform'])){

                odz_error('device empty');

        }

        $params      = array();

	if(!checkperm('allowfriend')) {

		odz_error('no_power_addfriend');

	}

        

	if($uid == $_G['uid']) {

		odz_error('friend_self_error');

	}



	if(friend_check($uid)) {

		odz_error('you_have_friends');

	}



	$tospace = getuserbyuid($uid);

	if(empty($tospace)) {

		odz_error('space_does_not_exist');

	}



	if(isblacklist($tospace['uid'])) {

		odz_error('is_blacklist');

	}



	$groups = friend_group_list();



	space_merge($space, 'count');

	space_merge($space, 'field_home');



	$maxfriendnum = checkperm('maxfriendnum');

	if($maxfriendnum && $space['friends'] >= $maxfriendnum + $space['addfriend']) {

		if($_G['magic']['friendnum']) {

			odz_error('enough_of_the_number_of_friends_with_magic');

		} else {

			odz_error('enough_of_the_number_of_friends');

		}

	}



	if(friend_request_check($uid)) {

        //接受好友请求

			$_POST['gid'] = intval($_POST['gid']);

			friend_add($uid, $_POST['gid']);



			if(ckprivacy('friend', 'feed')) {

				require_once libfile('function/feed');

				feed_add('friend', 'feed_friend_title', array('touser'=>"<a href=\"home.php?mod=space&uid=$tospace[uid]\">$tospace[username]</a>"));

			}



			notification_add($uid, 'friend', 'friend_add');

            //接受好友的推送消息

                         

            odz_success('friends_add', 0, array('username'=>$tospace['username']));

                        

                        

                        

                        

                    

	} else {

        //请求添加好友



		if(C::t('home_friend_request')->count_by_uid_fuid($uid, $_G['uid'])) {

                    //重复请求添加好友

		    odz_success('waiting_for_the_other_test');

		}

                

                

		$_POST['gid'] = intval($_POST['gid']);

		$_POST['note'] = censor(htmlspecialchars($_GET['note']));

		friend_add($uid, $_POST['gid'], $_GET['note']);



		$note = array(

			'uid' => $_G['uid'],

			'url' => 'home.php?mod=spacecp&ac=friend&op=add&uid='.$_G['uid'].'&from=notice',

			'from_id' => $_G['uid'],

			'from_idtype' => 'friendrequest',

			'note' => !empty($_GET['note']) ? lang('spacecp', 'friend_request_note', array('note' => $_GET['note'])) : ''

		);

		notification_add($uid, 'friend', 'friend_request', $note);

		require_once libfile('function/mail');

		$values = array(

			'username' => $tospace['username'],

			'url' => getsiteurl().'home.php?mod=spacecp&ac=friend&amp;op=request'

		);

		sendmail_touser($uid, lang('spacecp', 'friend_subject', $values), '', 'friend_add');

                //请求好友的推送消息

                

                $alert = odz_lang('new_message');

                if(CHARSET != 'utf-8') {

                    $alert = iconv(CHARSET, 'utf-8', $alert);

                }

                $params     = array(

                        'uid'=>$_GET['uid'],

                        'channelid'=>$_GET['channelid'],

                        'type'=>'add_friends',

                        'alert'=>$alert,

                        'custom_content'=> json_encode(array('ios'=>array('typename'=>'add_friends','modol'=>1),'android'=>array('extras'=>array('content'=>array('id'=>$_GET['uid']),'typename'=>"app_info")))),

                );

                $res        = curl_push($params);

                if($res){

                        odz_success('request_has_been_sent');

                }else{

                        odz_error('focus_failed');

                }

               

	}



} elseif($op == 'ignore') {



	if($uid) {

		if(friend_check($uid)) {

			friend_delete($uid);

		} else {

			friend_request_delete($uid);

		}

                //删除 相互请求好友的通知消息

                if(DISCUZ_VERSION == 'X2.5'){

                    $res    =  DB::query('DELETE FROM '.DB::table('home_notification')."  WHERE type = 'friend' AND uid = {$_GET['uid']} AND authorid={$_G['uid']}");

                    $res    =  DB::query('DELETE FROM '.DB::table('home_notification')."  WHERE type = 'friend' AND uid = {$_G['uid']} AND authorid={$_GET['uid']}");

                }else{

                    $res    =  DB::query('DELETE FROM '.DB::table('home_notification')."  WHERE type = 'friend' AND uid = {$_GET['uid']} AND authorid={$_G['uid']} AND category=2");

                    $res    =  DB::query('DELETE FROM '.DB::table('home_notification')."  WHERE type = 'friend' AND uid = {$_G['uid']} AND authorid={$_GET['uid']} AND category=2");

                }

		odz_success('operation_done');

	} elseif($_GET['key'] == $space['key']) {

		$count = C::t('home_friend_request')->count_by_uid($_G['uid']);

		if($count) {

			C::t('home_friend_request')->delete_by_uid($_G['uid']);



			dsetcookie('promptstate_'.$_G['uid'], $space['newprompt'], 31536000);

		}

		odz_success('operation_done');

	}



} elseif($op == 'addconfirm') {



	if(!checkperm('allowfriend')) {

		showmessage('no_privilege_addfriend');

	}

	if($_GET['key'] == $space['key']) {



		$maxfriendnum = checkperm('maxfriendnum');

		space_merge($space, 'field_home');

		space_merge($space, 'count');



		if($maxfriendnum && $space['friends'] >= $maxfriendnum + $space['addfriend']) {

			if($_G['magic']['friendnum']) {

				showmessage('enough_of_the_number_of_friends_with_magic');

			} else {

				showmessage('enough_of_the_number_of_friends');

			}

		}



		if($value = C::t('home_friend_request')->fetch_by_uid($space['uid'])) {

			friend_add($value['fuid']);

			odz_success('friend_addconfirm_next');

		}

	}



	odz_success('do_success');



} elseif($op == 'find') {



	$maxnum = 36;



	$recommenduser = $myfuids = $fuids =array();



	$i = 0;

	$query = C::t('home_friend')->fetch_all_by_uid($_G['uid'], 0, 0, true);

	foreach($query as $value) {

		if($i < 100) {

			$fuids[$value['fuid']] = $value['fuid'];

		}

		$myfuids[$value['fuid']] = $value['fuid'];

		$i++;

	}

	$myfuids[$space['uid']] = $space['uid'];



	foreach(C::t('home_specialuser')->range() as $value) {

		$recommenduser[$value['uid']] = $value;

	}



	$i = 0;

	$nearlist = array();

	foreach(C::app()->session->fetch_all_by_ip($_G['clientip'], 200) as $value) {

		if($value['uid'] && empty($myfuids[$value['uid']])) {

			$nearlist[$value['uid']] = $value;

			$i++;

			if($i>=$maxnum) break;

		}

	}



	$i = 0;

	$friendlist = array();

	if($fuids) {

		$query = C::t('home_friend')->fetch_all_by_uid($fuids, 0, 200);

		$fuids[$space['uid']] = $space['uid'];

		foreach($query as $value) {

			$value['fuid'] = $value['uid'];

			$value['fusername'] = $value['username'];

			if(empty($myfuids[$value['uid']])) {

				$friendlist[$value['uid']] = $value;

				$i++;

				if($i>=$maxnum) break;

			}

		}

	}



	$i = 0;

	$onlinelist = array();

	foreach(C::app()->session->fetch_member(1, 2, 200) as $value) {

		if(empty($myfuids[$value['uid']]) && !isset($onlinelist[$value['uid']])) {

			$onlinelist[$value['uid']] = $value;

			$i++;

			if($i>=$maxnum) break;

		}

	}

	$navtitle = lang('core', 'title_people_might_know');



} elseif($op == 'changegroup') {



	if(submitcheck('changegroupsubmit')) {

		C::t('home_friend')->update_by_uid_fuid($_G['uid'], $uid, array('gid'=>intval($_POST['group'])));

		friend_cache($_G['uid']);

		odz_success('do_success');

	}



	$query = C::t('home_friend')->fetch_all_by_uid_fuid($_G['uid'], $uid);

	if(!$friend = $query[0]) {

		showmessage('specified_user_is_not_your_friend');

	}

	$groupselect = array($friend['gid'] => ' checked');



	$groups = friend_group_list();





} elseif($op == 'editnote') {



	if(submitcheck('editnotesubmit')) {

		$note = getstr($_POST['note'], 20);

		C::t('home_friend')->update_by_uid_fuid($_G['uid'], $uid, array('note'=>$note));

		odz_success('do_success');

	}



	$query = C::t('home_friend')->fetch_all_by_uid_fuid($_G['uid'], $uid);

	if(!$friend = $query[0]) {

		showmessage('specified_user_is_not_your_friend');

	}





} elseif($op == 'changenum') {



	if(submitcheck('changenumsubmit')) {

		$num = abs(intval($_POST['num']));

		if($num > 9999) $num = 9999;

		C::t('home_friend')->update_by_uid_fuid($_G['uid'], $uid, array('num'=>$num));

		friend_cache($_G['uid']);

		odz_success('do_success');

	}



	$query = C::t('home_friend')->fetch_all_by_uid_fuid($_G['uid'], $uid);

	if(!$friend = $query[0]) {

		showmessage('specified_user_is_not_your_friend');

	}



} elseif($op == 'group') {



	if(submitcheck('groupsubmin')) {

		if(empty($_POST['fuids'])) {

			showmessage('please_correct_choice_groups_friend', dreferer());

		}

		$ids = $_POST['fuids'];

		$groupid = intval($_POST['group']);

		C::t('home_friend')->update_by_uid_fuid($_G['uid'], $ids, array('gid'=>$groupid));

		friend_cache($_G['uid']);

		odz_success('do_success');

	}



	$perpage = 50;

	$perpage = mob_perpage($perpage);



	$page = empty($_GET['page'])?1:intval($_GET['page']);

	if($page<1) $page = 1;

	$start = ($page-1)*$perpage;



	$list = array();

	$multi = $wheresql = '';



	space_merge($space, 'count');



	if($space['friends']) {



		$groups = friend_group_list();



		$theurl = 'home.php?mod=spacecp&ac=friend&op=group';

		$group = !isset($_GET['group'])?'-1':intval($_GET['group']);

		if($group > -1) {

			$wheresql = "AND main.gid='$group'";

			$theurl .= "&group=$group";

		}



		$count = C::t('home_friend')->fetch_all_search($space['uid'], $group, '', true);

		if($count) {

			$query = C::t('home_friend')->fetch_all_search($space['uid'], $group, '', false, $start, $perpage, true);

			foreach($query as $value) {

				$value['uid'] = $value['fuid'];

				$value['username'] = $value['fusername'];

				$value['group'] = $groups[$value['gid']];

				$list[] = $value;

			}

		}

		$multi = multi($count, $perpage, $page, $theurl);

	}



	$actives = array('group'=>' class="a"');







} elseif($op == 'request') {

    

        $list =array();

	if(submitcheck('requestsubmin')) {

		odz_success('do_success');

	}

	$maxfriendnum = checkperm('maxfriendnum');

	if($maxfriendnum) {

		$maxfriendnum = $maxfriendnum + $space['addfriend'];

	}



	$perpage = 20;

	$perpage = mob_perpage($perpage);



	$page = empty($_GET['page'])?0:intval($_GET['page']);

	if($page<1) $page = 1;

	$start = ($page-1)*$perpage;

	$count = C::t('home_friend_request')->count_by_uid($_GET['uid']);

	if($count) {

		$fuids = array();

		foreach(C::t('home_friend_request')->fetch_all_by_uid($_GET['uid'], $start, $perpage) as $value) {

			$fuids[$value['fuid']] = $value['fuid'];

			$list[$value['fuid']] = $value;

		}

                

	}

        if(!empty($list)){

             sort($list);

             foreach($list as $k=>$v){

                    $list[$k]['avatar'] =avatar($v['fuid'], 'small', true);

                    $list[$k]['username'] = $v['fusername'];

                    $list[$k]['regdate'] =  date('Y-m-d',$v['dateline']);

                    $sightml    = DB::fetch_first('SELECT sightml FROM '.DB::table('common_member_field_forum')." WHERE uid = '$v[fuid]'");

                    $list[$k]['sightml'] = $sightml['sightml']?$sightml['sightml']:odz_lang('no_message_left');

                    if($v['birthyear']){

                        $list[$k]['age']  = (string)age($v["birthyear"].'-'.$v["birthmonth"].'-'.$v["birthday"]);

                    }else{

                        $list[$k]['age'] = '';

                    }

                    $other    = 

                     DB::fetch_first('SELECT gender ,affectivestatus FROM '.DB::table('common_member_profile')." WHERE uid = '$v[fuid]'");

                    $list[$k]['affectivestatus'] = $other['affectivestatus']?$other['affectivestatus']:odz_lang('secrect');

                    $list[$k]['gender'] = $other['gender'];

             }

        }

        odz_result(array('list'=>$list));



} elseif($op == 'groupname') {



	$groups = friend_group_list();

	$group = intval($_GET['group']);

	if(!isset($groups[$group])) {

		odz_error('change_friend_groupname_error');

	}

	space_merge($space, 'field_home');

	if(submitcheck('groupnamesubmit')) {

		$space['privacy']['groupname'][$group] = getstr($_POST['groupname'], 20);

		privacy_update();

		odz_success('do_success');

	}

} elseif($op == 'groupignore') {



	$groups = friend_group_list();

	$group = intval($_GET['group']);

	if(!isset($groups[$group])) {

		odz_error('change_friend_groupname_error');

	}

	space_merge($space, 'field_home');

	if(submitcheck('groupignoresubmit')) {

		if(isset($space['privacy']['filter_gid'][$group])) {

			unset($space['privacy']['filter_gid'][$group]);

			$ignore = false;

		} else {

			$space['privacy']['filter_gid'][$group] = $group;

			$ignore = true;

		}

		privacy_update();

		friend_cache($_G['uid']);



		odz_success('do_success');

	}



} elseif($op == 'blacklist') {



	if($_GET['subop'] == 'delete') {

		$_GET['uid'] = intval($_GET['uid']);

		C::t('home_blacklist')->delete_by_uid_buid($space['uid'], $_GET['uid']);

		odz_success('do_success');

	}



	if(submitcheck('blacklistsubmit')) {

		$_POST['username'] = trim($_POST['username']);

		if(!($tospace = C::t('common_member')->fetch_by_username($_POST['username']))) {

			odz_error('space_does_not_exist');

		}

		if($tospace['uid'] == $space['uid']) {

			odz_error('unable_to_manage_self');

		}



		friend_delete($tospace['uid']);



		C::t('home_blacklist')->insert(array('uid'=>$space['uid'], 'buid'=>$tospace['uid'], 'dateline'=>$_G['timestamp']), false, false, true);

		odz_success('do_success');

	}



} elseif($op == 'rand') {



	$userlist = $randuids = array();

	space_merge($space, 'count');

	if($space['friends']<5) {

		$userlist = C::app()->session->fetch_member(1, 2, 100);

	} else {

		$query = C::t('home_friend')->fetch($_G['uid']);

		foreach($query as $value) {

			$userlist[$value['uid']] = $value['fuid'];

		}

	}

	unset($userlist[$space['uid']]);



	$randuids = sarray_rand($userlist, 1);

	odz_success('do_success');



} elseif ($op == 'getcfriend') {



	$fuid = empty($_GET['fuid']) ? 0 : intval($_GET['fuid']);



	$list = array();

	if($fuid) {

		$friend = $friendlist = array();

		$query = C::t('home_friend')->fetch_all_by_uid_common($space['uid'], $fuid);

		foreach($query as $value) {

			$friendlist[$value['uid']][] = $value['fuid'];

			$friend[$value['fuid']] = $value;

		}

		if($friendlist[$_G['uid']] && $friendlist[$fuid]) {

			$cfriend = array_intersect($friendlist[$_G['uid']], $friendlist[$fuid]);

			$i = 0;

			foreach($cfriend as $key => $uid) {

				if(isset($friend[$uid])) {

					$list[] = array('uid' => $friend[$uid]['fuid'], 'username' => $friend[$uid]['fusername']);

					$i++;

					if($i >= 15) break;

				}

			}

		}



	}

} elseif($op == 'getinviteuser') {

	require_once libfile('function/search');

	$perpage = 20;

	$username = empty($_GET['username'])?'':searchkey($_GET['username'], "f.fusername LIKE '{text}%'");

	$page = empty($_GET['page'])?0:intval($_GET['page']);

	$gid = isset($_GET['gid']) ? intval($_GET['gid']) : -1;

	if($page<1) $page = 1;

	$start = ($page-1) * $perpage;

	$json = array();

	$wheresql = '';

	if($gid > -1) {

		$wheresql .= " AND f.gid='$gid'";

	}

	if(!empty($username)) {

		$wheresql .= $username;

	}



	$count = $count_at = $singlenum = 0;

	if($_GET['at'] == 1 && $gid < 0) {

		$count_at = C::t('home_follow')->count_by_uid_username($_G['uid'], $_GET['username']);

		if($count_at) {

			foreach(C::t('home_follow')->fetch_all_by_uid_username($_G['uid'], $_GET['username'], $start, $perpage) as $value) {

				$value['fusername'] = daddslashes($value['fusername']);

				$value['avatar'] = avatar($value['followuid'], 'small', true);

				$singlenum++;

				$json[$value['followuid']] = "$value[followuid]:{'uid':$value[followuid], 'username':'$value[fusername]', 'avatar':'$value[avatar]'}";

			}

			$perpage = $perpage - $singlenum;

			$start = max($start - $count_at, 0);

		}



	}

	if($perpage && $gid != -2) {

		$count = C::t('home_friend')->fetch_all_search($_G['uid'], $gid, $_GET['username'], true);

		if($count) {

			$homefriend = C::t('home_friend')->fetch_all_search($_G['uid'], $gid, $_GET['username'], false, $start, $perpage, true);



			$usrids = array();

			foreach($homefriend as $key=>$usrs) {

				$usrids[$key] = $usrs['fuid'];

			}



			$usernames = C::t('common_member')->fetch_all_username_by_uid($usrids);

			foreach($homefriend as $value) {

				$value['fusername'] = daddslashes($usernames[$value['fuid']]);

				$value['avatar'] = avatar($value['fuid'], 'small', true);

				$singlenum++;

				$json[$value['fuid']] = "$value[fuid]:{'uid':$value[fuid], 'username':'$value[fusername]', 'avatar':'$value[avatar]'}";

			}

		}

	}

	$jsstr = "{'userdata':{".implode(',', $json)."}, 'maxfriendnum':'".($count+$count_at)."', 'singlenum':'$singlenum'}";



} elseif($op == 'search') {

    

        $result = array();

        $searchkey  = trim($_GET['username']);

        $page       = isset($_GET['page'])?trim($_GET['page']):1;

        $limit      = 20;

        $offset     = ($page-1)*$limit;

        if(empty($searchkey)){

            odz_error('uname_empty',550);

        }

	

	$list = C::t('common_member')->fetch_all_by_like_username($searchkey, $offset, $limit);

        if(!empty($list)){

                

                foreach($list as $k=>$v){

                        $uids[] = $v['uid']; 

                }

                //是否是好友

                $friends = DB::fetch_all('SELECT fuid FROM '.DB::table('home_friend').' WHERE uid = '.$_G['uid']);

                foreach( $friends as $k=>$v){

                        $fuids[] = $v['fuid'];

                }

                

                $query = DB::query('SELECT c.uid,c.gender,c.birthyear,c.birthmonth,c.birthday ,c.affectivestatus,f.sightml  FROM '.DB::table('common_member_profile').' as c inner join '.DB::table('common_member_field_forum').' as f '.

                    " on c.uid=f.uid WHERE c.uid in (".implode(',', $uids).")");

                while($row = DB::fetch($query)){

                        foreach($list as $k => $v ){

                                if( $v['uid'] == $row['uid']){

                                        $result[] = array(

                                                'uid'=>(string)$v['uid'],

                                                'username'=>(string)$v['username'],

                                                'regdate' => date('Y-m-d',$v['regdate']),

                                                'avatar'=>avatar($v['uid'], 'small', true),

                                                'sightml'=>$row['sightml']?(strip_tags($row['sightml'])?strip_tags($row['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left'),

                                                'age'=>$row['birthyear']?age($row["birthyear"].'-'.$row["birthmonth"].'-'.$row["birthday"]):'',

                                                'affectivestatus' => $row['affectivestatus']?$row['affectivestatus']:odz_lang('secrect'),

                                                'isfriends' =>in_array($v['uid'],$fuids)?'1':'0',

                                                'gender'=>empty($row['gender'])?'0':$row['gender'],

                                                'birthyear'=>empty($row['birthyear'])?'0':$row['birthyear'],

                                                'birthmonth'=>empty($row['birthmonth'])?'0':$row['birthmonth'],

                                                'birthday'=>empty($row['birthday'])?'0':$row['birthday'],

                                                

                                        );

                                }

                        }

                }

               

        }

        odz_result(array('list'=>$result));

}elseif($op == 'clear'){

    

        $uid    = $_GET['uid'];

        $fuid  = $_GET['fuid'];

        if( empty($uid) && empty($fuid) ){

                odz_error('param_miss');

        }

        $where = '';

        $where1 = '';

        if(!empty($fuid)){

                $where = " AND fuid = ".$fuid;

                $where1 = " AND authorid = ".$fuid;

        }

        $res    = DB::query('DELETE FROM '.DB::table('home_friend_request')." WHERE uid = {$uid} {$where}");

        

        

        if(DISCUZ_VERSION == 'X2.5'){

            $notification = DB::query('DELETE FROM '.DB::table('home_notification')." WHERE uid = {$uid} AND type='friend' {$where1}");

        }else{

            $notification = DB::query('DELETE FROM '.DB::table('home_notification')." WHERE uid = {$uid} AND category=2 AND type='friend' {$where1}");

        }

        if($notification){

                odz_success();

        }else{

                odz_error();

        }

        

        //print_r($_GET);die;

//        if(!empty($fuid)){

//                //拒绝一条请求

//                $res    = DB::query('DELETE FROM '.DB::table('home_friend_request')." WHERE fuid = {$fuid} AND uid = {$uid}");

//                $notification = DB::query('DELETE FROM '.DB::table('home_notification')." WHERE uid = {$uid} AND authorid = {$fuid} AND type='friend' AND category=2 ");

//                if($res && $notification){

//                        odz_success();

//                }else{

//                        odz_error();

//                }

//        }else{

//                //拒绝所有

//                $res    = DB::query('DELETE FROM '.DB::table('home_friend_request')." WHERE uid = {$uid}");

//                $notification = DB::query('DELETE FROM '.DB::table('home_notification')." WHERE uid = {$uid} AND type='friend' AND category=2 ");

//                if($res && $notification){

//                        odz_success();

//                }else{

//                        odz_error();

//                }

//        }

        

        

}



//include template('home/spacecp_friend');



?>