<?php  
if (!defined('IN_WEB')) {
    exit('No direct script access allowed');  
} 
if (!isset($_SESSION)) {
    session_start();
}
/**
* Name: Facebook Login Library
*
* Author: dulu 
*/
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;

class facebooksdk4
{
    //记录重定向登录请求信息
    private $helper;

    //记录session
    private $session;

    //游戏默认授权项
    private $facebook_default_scope = array("user_friends","email","public_profile");

    /**
     * 初始化游戏平台相关信息
     *
     * @author dulu
     *
     * @return object Facebookv4_NewApi
     */  
    public function __construct()
    {
        FacebookSession::setDefaultApplication(oo::$config['facebookAppid'], oo::$config['facebookAppsecret']);
    }
 
    /**
     * [checkAccessToken 检查AccessToken,设置会话信息]
     * @return [type] [description]
     */
    private function checkAccessToken()
    {
        if(isset($_SESSION) && isset($_SESSION['w7poker_fb_token'])) 
        {
            $this->session = new FacebookSession($_SESSION['w7poker_fb_token']);
        }
    }

    /**
     * [setAccessToken 设置token]
     * @param [type] $access_token [token]
     */
    public function setAccessToken($access_token)
    {
        $_SESSION['w7poker_fb_token'] = $access_token;
        $this->session = new FacebookSession($_SESSION['w7poker_fb_token']);
    }

    /**
     * [getAccessToken 获取token]
     * @return [type] [description]
     */
    public function getAccessToken()
    {
       return isset($_SESSION['w7poker_fb_token']) ? $_SESSION['w7poker_fb_token'] : null;
    }

    /**
     * 获取用户ID
     *
     * @author dulu
     *
     * @return [string_type] 平台ID 
     */
    public function getUid()
    { 
        //获取相关FB登录信息
        $signedHelper = new FacebookCanvasLoginHelper();
        $this->session = $signedHelper->getSession();

        //用户会话不存在,重新连接
        if (!isset($this->session) || $this->session === null) 
        {
            $this->resetLogin();
        }
        else
        {
            $sitemid = $this->session->getUserId();
            if(empty($sitemid))
            {
                $this->resetLogin();
            }
            else
            {
                $_SESSION['w7poker_fb_token'] = $this->session->getToken();
                return $sitemid;
            }
        }
    }

    /**
     * [resetLogin 令牌过期,重新登录,生成令牌]
     *
     * @author dulu
     * 
     * @return [void] 获得access_token信息
     */
    private function resetLogin()
    {
        // no session exists
        try {
             $this->helper = new FacebookRedirectLoginHelper(oo::$config['facebookUrl'] . '?' . http_build_query($_REQUEST));
             $this->helper->disableSessionStatusCheck();
             $this->session = $this->helper->getSessionFromRedirect();
             //重定向刷新获取不到信息,说明用户移除了应用
             if(!isset($this->session) || $this->session === null) {
                $this->toAuth($this->facebook_default_scope, 1);
             } else {
                $_SESSION['w7poker_fb_token'] = $this->session->getToken();
             }
        } catch(FacebookRequestException $ex) {
            // When Facebook returns an error
            // handle this better in production code
        } catch(Exception $ex) {
            // When validation fails or other local issues
            // handle this better in production code
        }
    }

    /**
     * [toAuth 显示授权页面授权]
     * 
     * @author dulu
     *
     * @param [array_type]  [授权列表]
     * @param [int_type]    [是否注册游戏授权, 默认不是，默认为游戏内部授权]
     * 
     * @return [array_type] [显示授权页面授权]
     */
    private function toAuth($perms, $type=0)
    {
        //用户游戏中授权
        if(!$type) {
           $this->helper = new FacebookRedirectLoginHelper(oo::$config['facebookUrl'] . '?' . http_build_query($_REQUEST));
        }
        $loginUrl = $this->helper->getLoginUrl($perms);
        echo "<script type=\"text/javascript\">top.location.href=\"{$loginUrl}\"</script>";
    }

    /**
     * [getMe 获取用户信息]
     * 
     * @author dulu
     * 
     * @return [array] [用户平台信息]
     */
    public function getMe($isMobile=0)
    {
        $this->checkAccessToken();
        // if($isMobile == 0)
        // {
        //     $perms = $this->getUserPerms();
        //     if(!in_array("public_profile", $perms))
        //     {
        //         //授权
        //         $this->toAuth(array("public_profile"));
        //     }
        // }
		
        $graphObject = array();
        if(isset($this->session))
        {
            try {
                $path = '/me?fields=id,name,email,first_name,gender,locale,location,birthday,hometown,token_for_business,picture.height(200).width(200)';
//                if ( in_array(SGSID,array(1,2)) ){
                  $path = str_replace(',token_for_business', '', $path);
//                }
                $request = new FacebookRequest($this->session, 'GET', $path);
                $response = $request->execute();
                // get response
                $graphObject = $response->getGraphObject()->asArray();
            } catch(FacebookRequestException $e) { 
                oo::logs()->debug3(array($e->getMessage(), 'line' => __LINE__), 'fblogin.log');
                return array();
            } catch(Exception $e) {
                oo::logs()->debug3(array($e->getMessage(), 'line' => __LINE__), 'fblogin.log');
                return array();
            }
        }
        else
        {
            $this->resetLogin();
        }
        if(!empty($graphObject) && isset($graphObject['id']))
        {
        	return $graphObject;
        }
        return array(); 
    }


	/**
     * [获取该用户所有平台FBid]
     * 
     * @author dulu
     * 
     * @return [array] [用户各个平台应用信息]
     */
    public function getIdsForBusiness($type=0)
    {
        $this->checkAccessToken();
        
        $userInfo = array();
        $graphObject = array();
        if(isset($this->session))
        {
            try{
                $request = new FacebookRequest($this->session, 'GET', '/me/ids_for_business');
                $response = $request->execute();
                // get response
                $graphObject = $response->getGraphObject()->asArray();
            }catch(FacebookRequestException $e){
                //oo::logs()->logsUdp("debug",$e->getMessage(), 'fblog');
                return array();
            }catch(Exception $e){
               // oo::logs()->logsUdp("debug",$e->getMessage(), 'fblog');
                return array();
            }
        }
        else
        {
            $this->resetLogin();
        }
        if(!empty($graphObject) && isset($graphObject['data']))
        {
        	$i = 0;
        	if ( $type == 1) {
        		return (array)$graphObject['data'];
        	} else {
        		foreach ((array)$graphObject['data'] as $key => $value)
        		{
        			if ( $value->app->id == '1468603136785474') {
        				return $value->id;
        			}
        		}
        	}
        }
        return '';        
    }

    /**
     * 获取非游戏好友列表
     *
     * @author dulu
     *
     * @return array
     */
    public function getNoAppFriendList() 
    {
        $this->checkAccessToken();
        $perms = $this->getUserPerms();
        if(!in_array("user_friends", $perms))
        {
            //授权
            $this->toAuth(array("user_friends"));
        }
        $friends = array();
        $friendInfo = array();
        $i = 0;
        if(isset($this->session))
        {
            //$request = new FacebookRequest($this->session, 'GET', "/me/invitable_friends");
            $request = new FacebookRequest($this->session, 'GET', "/me/invitable_friends?field=name,picture");
            $response = $request->execute();

            // get response
            $friends = $response->getGraphObject()->asArray();
        }
        else
        {
            $this->resetLogin();
        }
        if(!empty($friends) && isset($friends['data']) && is_array($friends['data']))
        {
            foreach ((array)$friends['data'] as $key => $value) 
            {
                $friendInfo[$i] = array($value->id, $value->name, $value->picture);
                // $friendInfo[$i]['id'] = $value->id;
                // $friendInfo[$i]['name'] = $value->name;
                // $friendInfo[$i]['url'] = $value->picture->data->url;
                $i++;
            }
        }
        else
        {
            $friendInfo = array();
        }
       
        return $friendInfo;
    }

    /**
     * 获取游戏好友列表
     *
     * @author dulu
     *
     * @return array
     */
    public function getAppFriendList() 
    {
        $this->checkAccessToken();
        $perms = $this->getUserPerms();
        if(!in_array("user_friends", $perms))
        {
            //授权
            $this->toAuth(array("user_friends"));
        }

        $friends = array();
        $friendInfo = array();
        $i = 0;
        if(isset($this->session))
        {
            $request = new FacebookRequest($this->session, 'GET', "/me/friends");
            $response = $request->execute();

            // get response
            $friends = $response->getGraphObject()->asArray();
            //var_dump($friends);
        }
        else
        {
            $this->resetLogin();
        }

        if(!empty($friends) && isset($friends['data']) && is_array($friends['data']))
        {
            foreach ((array)$friends['data'] as $key => $value) 
            {
                $friendInfo[$i] = $value->id;
                /*$friendInfo[$i]['id'] = $value->id;
                $friendInfo[$i]['name'] = $value->name;*/
                $i++;
            }
        }
        else
        {
            $friendInfo = array();
        }
        return $friendInfo;
    }

    /**
     * 获取所有好友列表
     *
     * @author dulu
     *
     * @return array
     */
    public function getAllFriendList() 
    {
        $this->checkAccessToken();
        $perms = $this->getUserPerms();
        if(!in_array("user_friends", $perms))
        {
            //授权
            $this->toAuth(array("user_friends"));
        }

        $friends = array();
        $friendInfo = array();
        $i = 0;
        if(isset($this->session))
        {
            $request = new FacebookRequest($this->session, 'GET', "/me/taggable_friends");
            $response = $request->execute();

            // get response
            $friends = $response->getGraphObject()->asArray();
        }
        else
        {
            $this->resetLogin();
        }

        if(!empty($friends) && isset($friends['data']) && is_array($friends['data']))
        {
            foreach ((array)$friends['data'] as $key => $value) 
            {
                $friendInfo[$i] = $value->id;
                // $friendInfo[$i]['name'] = $value->name;
                // $friendInfo[$i]['url'] = $value->picture->data->url;
                $i++;
            }
        }
        else
        {
            $friendInfo = array();
        }
        return $friendInfo;
    }

    /**
     * [getUserPerms 获取用户授权信息]
     *
     * @author dulu
     *
     * @return [type]      [description]
     */
    public function getUserPerms()
    {
        $this->checkAccessToken();
        $permissions = array();
        $perms = array();
        if(isset($this->session))
        {
            try {
                $request = new FacebookRequest($this->session, 'GET', "/me/permissions");
                $response = $request->execute();

                // get response
                $permissions = $response->getGraphObject()->asArray();
            } catch(FacebookRequestException $e) {
                oo::logs()->logsUdp("debug",$e->getMessage(), 'fblog');
                return array();
            } catch(Exception $e) {
                oo::logs()->logsUdp("debug",$e->getMessage(), 'fblog');
                return array();
            }
        }
        else
        {
            $this->resetLogin();
        }

        if(!empty($permissions) && is_array($permissions))
        {
            foreach ($permissions as $key => $value) 
            {
                if($value->status == "granted")
                {
                    array_push($perms, $value->permission);
                }
            }
        }
        return $perms;
    }

    /**
     * 发送通知小地球（用这个）
     * @from  https://developers.facebook.com/docs/games/notifications/ 官方文档
     * https://developers.facebook.com/docs/graph-api/reference/v2.2/user/notifications?locale=zh_CN
     *
     * @author dulu
     * 
     * @param array $uid FB用户ID集合
     * @param string $content 内容
     * @param string $href 链接地址 &用%26来代替
     * @return array
     */
    public function sendNotifications($uid, $content, $href='?faction=notifx')
    {
        if(empty($uid)) 
        {
            return array();
        }
        if(!is_array($uid))
        {
           $uid = array($uid);
        }

        $appid =  oo::$config['facebookAppid'];
        $secret = oo::$config['facebookAppsecret'];
        $access_token = $appid."|".$secret;
        $batchs = array();
        $sitemid = $uid[0];
        foreach ($uid as $u)
        {
          $msg = str_replace('{sitemid}', "@[{$u}]", $content);
          $batch = array();
          $batch['method'] = 'POST';
          $batch['relative_url'] = "{$u}/notifications";
          $batch['body'] = 'template='.urlencode($msg).'&href='.$href.'%26sent='.date('Ymd');
          $batchs[] = $batch;
          $sitemid = $u;
        }
        if(empty($batchs))
        {
            return array('error'=>'param error.');
        }
        else
        {
            $batchs = json_encode($batchs);
        }
       
        $ret = array('error'=>'send query exception.');
        
        try
        {
            $session = new FacebookSession($access_token);
            $request = new FacebookRequest($session, 'POST', "/{$sitemid}/notifications", array(
                'access_token' => $access_token,
                'batch' => $batchs,
            ));
            $response = $request->execute();
            // get response
            $ret = $response->getGraphObject()->asArray();
        }
        catch(Exception $e)
        {
            $ret = array('error'=>$e);
        }

        if(isset($ret['error']))
        {
            return $ret;
        }
        else
        {
            //统计成功发送的个数
            $successNum = 0;
            $loseNum = 0;
            foreach ($ret as $key => $value) 
            {
                //获取返回值
                $info = json_decode($value->body, true);
                if(isset($info['success']) && $info['success'] == 'true')
                {
                    //成功发送
                    $successNum++;
                }
                else
                {
                    //发送失败
                    $loseNum = 0;
                }
            }
            return array("success"=>"true", "successNum" => $successNum);
        }
    }

  /**
   * 判断用户是否某个页面的like
   *
   * @author dulu
   *
   * @param string_type $pageId  页面ID
   * @param string_type $uid     平台ID
   */
  public function isFans($pageId, $uid)
  { 
      $this->checkAccessToken();
      $graphObject = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest(
            $this->session,
            'GET',
            "/{$uid}/likes/{$pageId}"
          );
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      //不存在就是用户还没有对此页点缀
      if(empty($graphObject))
      {
          return 0;
      }
      else
      {
          return 1;
      }
  }

  /**
   * 获得用户本地化货币设置币种
   * 
   * @author dulu
   *
   * @return string_type $local 本地币种
  **/
  public function getUserLocalCurrency()
  {
      $this->checkAccessToken();

      $local = "USD"; //默认值为USD取不到的时候
      $graphObject = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest(
            $this->session,
            'GET',
            "/me?fields=currency"
          );
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      if(!empty($graphObject))
      {
          $local = $graphObject['currency']->user_currency;
      }
      return $local;
  }

  /**
   * 上传一张图片(URL)
   *
   * @author dulu
   * 
   * @param string $file          图片在服务器的文件绝对地址
   * @param string $picMessage    图片的说明
   */
  public function uploadPictureByUrl($file, $picMessage='good')
  {
      $this->checkAccessToken();
      //创建相簿
      $graphObject = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest($this->session, 'POST', '/me/photos', array(
                'url' => $file,
                'message' => $picMessage,
                'value' => 'EVERYONE'
          ));
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      return $graphObject;
  }

  /**
   * 上传一张图片(Source)
   *
   * @author dulu
   * 
   * @param string $file 获取通过文件上传照片multipart/form-data数据然后使用源参数
   * @param string $message 照片的说明
   */
  public function uploadPictureBySource($file, $picMessage='good')
  {
      $this->checkAccessToken();

      //创建相簿
      $graphObject = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest($this->session, 'POST', '/me/photos', array(
                'url' => $file,
                'message' => $picMessage,
                'value' => 'EVERYONE'
          ));
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      return $graphObject;
  }
  
  /**
   * 创建一个指定名称的相册, 如果存在就直接返回相簿ID
   *
   * @author dulu
   * 
   * @param string $name 相册名称
   * @param string $message 相册说明
   *
   * @return string 相簿ID
   */
  public function createAlbum($name, $message='')
  {
      $this->checkAccessToken();

      //检查是否已经存在此相簿,避免重复创建同名称相簿
      $albumInfo = $this->getAlbum();
      foreach ($albumInfo as $key => $value) 
      {
          if($name == $value['name'])
          {
              return $value['id'];
          }
      }

      //创建相簿
      $graphObject = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest($this->session, 'POST', '/me/albums', array(
                'name' => $name,
                'message' => $message,
                'value' => 'EVERYONE'
          ));
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      //是否创建成功,成功返回相簿ID
      if(!empty($graphObject) && is_array($graphObject) && isset($graphObject['id']))
      {
          return $graphObject['id'];
      }
      else
      {
          return 0;
      }
  }

  /**
   * [getAlbum 获得用户所有相簿信息]
   *
   * @author dulu
   * 
   * @return [array] [相簿信息(名称，ID)]
   */
  public function getAlbum()
  {
      $this->checkAccessToken();

      $graphObject = array();
      $photosInfo = array();
      if(isset($this->session))
      {
          $request = new FacebookRequest($this->session, 'GET', '/me/albums');
          $response = $request->execute();
          $graphObject = $response->getGraphObject()->asArray();
      }
      else
      {
          $this->resetLogin();
      }

      if(!empty($graphObject) && is_array($graphObject['data']) && isset($graphObject['data']))
      {
          foreach ($graphObject['data'] as $key => $value) 
          {
              $photosInfo[$key]['name'] = $value->name;
              $photosInfo[$key]['id'] = $value->id;
          }
      }
      
      return $photosInfo;
  }
}