Commit 0560ed18 by Jithin

first review

parent d79460db
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Facebook API Configuration
| -------------------------------------------------------------------
|
| To get an facebook app details you have to create a Facebook app
| at Facebook developers panel (https://developers.facebook.com)
|
| facebook_app_id string Your Facebook App ID.
| facebook_app_secret string Your Facebook App Secret.
| facebook_login_type string Set login type. (web, js, canvas)
| facebook_login_redirect_url string URL to redirect back to after login. (do not include base URL)
| facebook_logout_redirect_url string URL to redirect back to after logout. (do not include base URL)
| facebook_permissions array Your required permissions.
| facebook_graph_version string Specify Facebook Graph version. Eg v2.6
| facebook_auth_on_load boolean Set to TRUE to check for valid access token on every page load.
*/
$config['facebook_app_id'] = '1986687558274486';
$config['facebook_app_secret'] = 'd848d17b4c5427ca8d55c99fdae378a5';
$config['facebook_login_type'] = 'web';
$config['facebook_login_redirect_url'] = 'Home/facebook_login';
$config['facebook_logout_redirect_url'] = 'user_authentication/logout';
$config['facebook_permissions'] = array('email');
$config['facebook_graph_version'] = 'v2.6';
$config['facebook_auth_on_load'] = TRUE;
\ No newline at end of file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Doctor extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct()
{
parent::__construct();
$this->load->model('Doctor_model');
$this->load->model('Home_model');
date_default_timezone_set("Asia/Kolkata");
global $default_date ;
$this->default_date = '01/01/2017';
}
public function index()
{
if($this->session->userdata('UserData'))
{
$userdata = $this->session->userdata('UserData');
if($userdata['type']=="DOCTOR")
{
$template['page'] = "doctor_dash";
$template['page_title'] = "Dashboard";
$template['data'] = "Doctor page";
$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
$clinic_list = $this->Doctor_model->get_doctor_clinic_list($userdata['id']);
$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],'null');
foreach ($day_appointment as $key => $value)
{
$times = explode('-', $value['booking_time']);
$day_appointment[$key]['time_start'] = $times[0];
$day_appointment[$key]['time_end'] = $times[1];
}
/*print_r($day_appointment);
die();*/
//print_r($day_appointment);die();
$template['doctor_data'] = $doctor_data;
$template['clinic_list'] = $clinic_list;
$template['day_appointment'] = $day_appointment;
$this->load->view('template/template', $template);
}
else
{
header('Location: '.base_url());
}
//print_r($userdata);
}
else
{
header('Location: '.base_url());
}
}
public function doctor_appointments_month()
{
$userdata = $this->session->userdata('UserData');
$month_appointment = $this->Doctor_model->get_doctor_appointments_month($userdata['id']);
$template['month_appointment'] = $month_appointment;
$this->load->view('doctor_dash_appointments_month',$template);
//print json_encode($day_appointments);
}
public function doctor_appointments_week()
{
$day_appointments = array();
$userdata = $this->session->userdata('UserData');
for ($i=0; $i < 7; $i++)
{
$day = date('D',strtotime('+'.$i.'day'));
$dayno = date('d',strtotime('+'.$i.'day'));
$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($userdata['id'],date('y-m-d',strtotime('+'.$i.'day')));
}
$template['week_appointments'] = $week_appointments;
$this->load->view('doctor_dash_appointments_week',$template);
//print json_encode($day_appointments);
}
public function getScheduleforClinic()
{
//print_r($_POST);
if($this->session->userdata('UserData'))
{
$userdata = $this->session->userdata('UserData');
if($userdata['type']=="DOCTOR")
{
$result = $this->Doctor_model->Schedulelist($_POST['clinic_id'],$userdata['id']);
if(!empty($result))
{
$res = array('status' => 'success', 'data'=>$result['date']);
}
else
{
$res = array('status' => 'fail', 'data'=>$result['date']);
}
print json_encode($res);
}
}
}
public function addSchedule()
{
if($this->session->userdata('UserData'))
{
if($this->session->userdata('UserData')['type']=="DOCTOR")
{
// print_r($this->default_date);
//print_r($_POST);
//die();
$insert_array = array();
$not_available_day = array();
$flag = 0;
$request = $_POST;
$flag_day_equal = 0;
//print_r($request);
$result = $this->Doctor_model->checkDoctorExist($this->session->userdata('UserData')['id']);
if(!empty($result))
{
//print_r($result);die();
foreach ($request['dct_sch_day'] as $req_day_key => $req_day_value)
{
foreach ($result as $db_key => $db_value)
{
$decode_date = json_decode($db_value['date'],true);
if(!empty($decode_date))
{
foreach ($decode_date as $time_key => $time_value)
{
if($req_day_value == $time_value['day'] && $db_value['clinic_id'] != $request['dct_sch_clinic'])
{
$startTime = 'dct_sch_'.$req_day_value.'_start';
$endTime = 'dct_sch_'.$req_day_value.'_end';
$interval = 'dct_sch_'.$req_day_value.'_int';
if((strtotime($this->default_date.$time_value['time']['start']) < strtotime($this->default_date.$request[$startTime ]) && strtotime($this->default_date.$request[$startTime ]) < strtotime($this->default_date.$time_value['time']['end'])) || (strtotime($this->default_date.$time_value['time']['start']) < strtotime($this->default_date.$request[$endTime]) && strtotime($this->default_date.$request[$endTime ]) < strtotime($this->default_date.$time_value['time']['end'])) || (strtotime($this->default_date.$request[$startTime ]) < strtotime($this->default_date.$time_value['time']['start']) && strtotime($this->default_date.$time_value['time']['start']) <strtotime($this->default_date.$request[$endTime])) || (strtotime($this->default_date.$request[$startTime ]) < strtotime($this->default_date.$time_value['time']['end']) && strtotime($this->default_date.$time_value['time']['end']) < strtotime($this->default_date.$request[$endTime])))
{
$flag_day_equal = 1;
}
}
}
}
}
}
if($flag_day_equal == 0)
{
foreach ($request['dct_sch_day'] as $key_elseDay => $value_elseDay)
{
$start = 'dct_sch_'.$value_elseDay.'_start';
$end = 'dct_sch_'.$value_elseDay.'_end';
$interval = 'dct_sch_'.$value_elseDay.'_int';
$res = array('day'=>$value_elseDay,
'time'=>array('start'=>$request[$start],
'end'=>$request[$end],
'interval'=>$request[$interval]));
array_push($insert_array, $res);
}
//print_r($insert_array);exit;
$this->Doctor_model->set_new_consultation($insert_array,$request['dct_sch_clinic'],array($this->session->userdata('UserData')['id']));
//print_r("success");
$res = array('status' => 'success','msg' => 'Successfully assigned' );
}
else{
//print_r("already");
$res = array('status' => 'fail','msg' => 'Schedule Assiging Failed' );
}
}
print json_encode($res);
}
}
}
public function addVacation()
{
if($this->session->userdata('UserData'))
{
$userdata = $this->session->userdata('UserData');
if($userdata['type']=="DOCTOR")
{
$request = array('doctor_id' => $userdata['id'],'clinic_id' => $_POST['doc-leave-clinic'],'start_date' => strtotime($_POST['dctr-leave-start']),'end_date' => strtotime($_POST['dctr-leave-end']));
//print_r($request);
$result = $this->Doctor_model->insertVacation($request);
if($result)
{
$res = array('status' => 'success');
}
else
{
$res = array('status' => 'fail' );
}
print json_encode($res);
}
}
}
public function get_myappointments_day()
{
//print_r($_POST['appointment_day']);
$userdata = $this->session->userdata('UserData');
$day_appointment = $this->Doctor_model->get_doctor_appointments_day($userdata['id'],$_POST['appointment_day']);
foreach ($day_appointment as $key => $value)
{
$times = explode('-', $value['booking_time']);
$day_appointment[$key]['time_start'] = $times[0];
$day_appointment[$key]['time_end'] = $times[1];
}
//print_r($day_appointment);
$template['day_appointment'] = $day_appointment;
$this->load->view('doctor_dash_appointments_day',$template);
}
public function medicalrecords()
{
$template['page'] = "doctor_medical_records";
$template['page_title'] = "Records";
$userdata = $this->session->userdata('UserData');
$doctor_data = $this->Doctor_model->get_single_doctor($userdata['id']);
$patient_attended = $this->Doctor_model->get_single_doc_pat_attended($userdata['id']);
//$template['doctor_data'] = $doctor_data;
//$template['clinic_list'] = $clinic_list;
//$template['day_appointment'] = $day_appointment;
$this->load->view('template/template', $template);
}
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Patient extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct()
{
parent::__construct();
$this->load->model('Patient_model');
$this->load->model('Home_model');
$this->load->model('Search_doctor_model');
date_default_timezone_set("Asia/Kolkata");
}
public function index()
{
if($this->session->userdata('UserData'))
{
$userdata = $this->session->userdata('UserData');
if($userdata['type']=="PATIENT")
{
$template['page'] = "patient_dash";
$template['page_title'] = "Dashboard";
$template['data'] = "Patient page";
$patient_data = $this->Patient_model->get_single_patient($userdata['id']);
$completed_consultation = $this->Patient_model->get_patient_completed_consultation($userdata['id']);
$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
//print_r($completed_consultation);
//$clinic_list = $this->Doctor_model->get_doctor_clinic_list($userdata['id']);
//$template['clinic_list'] = $clinic_list;
//print_r($patient_data);
$template['patient_data'] = $patient_data;
$template['completed_consultation'] = $completed_consultation;
$template['confirmed_consultation'] = $confirmed_consultation;
$this->load->view('template/template', $template);
}
else
{
header('Location: '.base_url());
}
//print_r($userdata);
}
else
{
header('Location: '.base_url());
}
}
public function getBooking()
{
$result = $this->Patient_model->get_Booking($_POST['booking_id']);
$result['book_date'] = date('d F Y',$result['book_date']);
$result['doc_pic'] = ''. base_url().$result['doc_pic'].'';
//print_r($result['doc_pic']);die();
print json_encode($result);
}
public function cancelBooking()
{
//print_r($_POST);die();
$userdata = $this->session->userdata('UserData');
$result = $this->Patient_model->cancel_Booking($_POST['booking_id']);
$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
$template['confirmed_consultation'] = $confirmed_consultation;
$this->load->view('patient_dash_scheduled_booking',$template);
}
public function reScheduleConsultation()
{
$result = $this->Patient_model->get_Booking($_POST['booking_id']);
$result['book_date'] = date('d F Y',$result['book_date']);
$result['doc_pic'] = ''. base_url().$result['doc_pic'].'';
print json_encode($result);
}
public function updateBooking()
{
$userdata = $this->session->userdata('UserData');
//print_r($_POST);
$this->Patient_model->update_Booking($_POST);
$confirmed_consultation = $this->Patient_model->get_patient_confirmed_consultation($userdata['id']);
$template['confirmed_consultation'] = $confirmed_consultation;
$this->load->view('patient_dash_scheduled_booking',$template);
}
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Searchdoctor extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct()
{
parent::__construct();
$this->load->model('Search_doctor_model');
$this->load->model('Home_model');
$this->load->model('Doctor_model');
date_default_timezone_set("Asia/Kolkata");
}
public function index()
{
if(isset($_POST)&&(!empty($_POST)))
{
$request = $_POST;
//print_r($request);die();
$this->session->set_userdata('DoctorSearchData',$request);
}
header('Location: '.base_url().'Searchdoctor/search');
}
public function search()
{
$speciality_list = $this->Home_model->get_speciality();
$template['speciality_list'] = $speciality_list;
if($this->session->userdata('DoctorSearchData'))
{
$request = $this->session->userdata('DoctorSearchData');
//print_r($request);
//die();
if((isset($request['doctor-search-date']))&&(!empty($request['doctor-search-date'])))
{
$request['doctor-search-date'] = strtotime($request['doctor-search-date']);
}
$all_doctors = $this->Search_doctor_model->filter_search($request);
//print_r($all_doctors);die();
if(!empty($all_doctors))
{
$template['doctors_list'] = $all_doctors;
}
$template['page'] = "search_doctor";
$template['page_title'] = "Search Doctor";
$template['searchdata'] = $request;
$this->load->view('template/template', $template);
}
else
{
$template['page'] = "search_doctor";
$template['page_title'] = "Search Doctor";
$this->load->view('template/template', $template);
}
}
public function filter_search()
{
if(isset($_POST)&&(!empty($_POST)))
{
$request = $_POST;
//print_r($request);die();
$this->session->set_userdata('DoctorSearchData',$request);
//print_r($request);die();
if((isset($request['doctor-search-date']))&&(!empty($request['doctor-search-date'])))
{
$request['doctor-search-date'] = strtotime($request['doctor-search-date']);
}
$template['searchdata'] = $request;
$all_doctors = $this->Search_doctor_model->filter_search($request);
$template['doctors_list'] = $all_doctors;
//print_r($all_doctors);die();
$this->load->view('search_doctor_result',$template);
// print_r($html);die();
/*if(!empty($all_doctors))
{
$res = array(
"status"=> "success",
"html"=> $html);
}
else
{
$res = array(
"status"=> "error",
"message"=> "cant find result"
);
}
print_r($res);*/
//die();
}
}
public function doctorprofile()
{
$doctor_id = $this->uri->segment(3);
$clinic_id = $this->uri->segment(4);
$doctor_data = $this->Search_doctor_model->get_single_doctor_clinic($doctor_id,$clinic_id);
$day_appointments = array();
$userdata = $this->session->userdata('UserData');
for ($i=0; $i < 7; $i++)
{
$day = date('D',strtotime('+'.$i.'day'));
$dayno = date('d',strtotime('+'.$i.'day'));
$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($doctor_id,date('y-m-d',strtotime('+'.$i.'day')));
}
$template['week_appointments'] = $week_appointments;
//$this->load->view('doctor_dash_appointments_week',$template);
//print_r($doctor_data);die();
$template['page'] = "search_doctor_complete_profile";
$template['page_title'] = "Doctor Profile";
$template['doctor_data'] = $doctor_data;
$this->load->view('template/template', $template);
}
public function confirmbooking()
{
$doctor_id = $this->uri->segment(3);
$clinic_id = $this->uri->segment(4);
$doctor_data = $this->Search_doctor_model->get_single_doctor_clinic($doctor_id,$clinic_id);
//$template['time_slot'] = $res_new;
$template['page'] = "search_doctor_confirm_booking";
$template['page_title'] = "Booking";
$template['doctor_data'] = $doctor_data;
$this->load->view('template/template', $template);
}
public function getDoctorClinic_timeslot()
{
//print_r($_POST);
$result_availability = $this->Search_doctor_model->doctor_availability($_POST['doctor_id'],$_POST['clinic_id']);
if($result_availability['status'] == 'success')
{
$day = date('D',strtotime($_POST['book_date']));
$res = array();
$result_availability['data']['date'] = json_decode($result_availability['data']['date'],true);
foreach ($result_availability['data']['date'] as $key => $value) {
if($value['day'] == strtolower($day))
{
$interval_time = $value['time']['interval']*60;
$start_time = strtotime($value['time']['start']);
$end_time = strtotime($value['time']['end']);
for ($i=$start_time; $i <= $end_time; $i=$i+$interval_time) {
$initial = $i;
$end = $i+$interval_time;
array_push($res, array('time'=>date('h:i:sa',$initial).' - '.date('h:i:sa',$end)));
}
}
}
$res_new = array_values(array_unique($res,SORT_REGULAR));
//print_r($res_new);die();
}
print json_encode($res_new);
}
public function checkDoctorAvailability()
{
//print_r($_POST);
$check_leave = $this->Search_doctor_model->checkDoctorLeave($_POST);
//print_r($check_leave);
if($check_leave['count']==0)
{
$check_booking = $this->Search_doctor_model->checkDoctorBooking($_POST);
if($check_booking['count']==0)
{
if($this->session->userdata('UserData'))
{
$res = array('status' => 'success', 'msg' => 'booking success','isLogin' =>'true');
}
else
{
$res = array('status' => 'success', 'msg' => 'booking success','isLogin' =>'false');
}
}
else
{
$res = array('status' => 'fail', 'type' => 'booking slot','msg' => 'Booking Slot Unavailable, Choose Another' );
}
}
else
{
$res = array('status' => 'fail','type' => 'doctor leave', 'msg' => 'Doctor Unavailable, Choose Another Date' );
}
//print_r($res);die();
print json_encode($res);
}
public function markbooking()
{
if($this->session->userdata('UserData'))
{
$userdata = $this->session->userdata('UserData');
if($userdata['type']=="PATIENT")
{
$now = new DateTime();
$times = explode('-', $_POST['confirm-book-time']);
//print_r($_POST['confirm-book-date']);die();
$date = date('y-m-d');
$book_start_time = strtotime($_POST['confirm-book-date'].' '.$times[0]);
$book_end_time = strtotime($_POST['confirm-book-date'].' '.$times[1]);
//print_r($book_end_time);die();
$doctor_price = $this->Search_doctor_model->getDoctorPrice($_POST['confirm-book-doctor']);
$data = array('doctor_id' =>$_POST['confirm-book-doctor'] ,'clinic_id' =>$_POST['confirm-book-clinic'] ,'clinic_id' =>$_POST['confirm-book-clinic'],'patient_id' =>$userdata['id'] ,'date' =>strtotime($_POST['confirm-book-date']),'time' =>$_POST['confirm-book-time'],'amount'=>$doctor_price['price'],'requested_date'=>$now->getTimestamp(),'time_start'=>$book_start_time,'time_end'=>$book_end_time);
$res = $this->Search_doctor_model->insertBooking($data);
}
}
}
public function booking_payment()
{
$check_markbooking = $this->Search_doctor_model->checkBooking($_POST);
//print_r($check_markbooking);
if($check_markbooking['count']==1)
{
$result = $this->Search_doctor_model->set_payment_status($_POST);
$res = array('status' => 'success', 'payment_status'=>'1','message'=>'payment success','booking_date'=>date('d/m/Y',$check_markbooking['booking_date']),'booking_slot'=>$check_markbooking['booking_slot']);
}
else
{
$res = array('status' => 'fail', 'payment_status'=>'0','message'=>'nobooking/alreadypaid');
}
//print_r($res);die();
print json_encode($res);
}
public function doctor_complete_profile_appointments_week_next()
{
$day_appointments = array();
for ($i=0; $i < 7; $i++)
{
$day = date('D',strtotime('+'.$i.'day', strtotime($_POST['enddate'])));
$dayno = date('d',strtotime('+'.$i.'day', strtotime($_POST['enddate'])));
$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($_POST['doctor_id'],date('y-m-d',strtotime('+'.$i.'day', strtotime($_POST['enddate']))));
}
//print_r($week_appointments);
$template['week_appointments'] = $week_appointments;
$template['start_day'] = $_POST['enddate'];
$template['doctorid'] = $_POST['doctor_id'];
$this->load->view('search_doctor_complete_profile_appointments_week',$template);
}
public function doctor_complete_profile_appointments_week_prev()
{
$day_appointments = array();
for ($i=6; $i >=0; $i--)
{ /*date('y-m-d', strtotime('-7 days'))*/
$day = date('D',strtotime('+'.$i.'day', strtotime($_POST['startdate'])));
$dayno = date('d',strtotime('+'.$i.'day', strtotime($_POST['startdate'])));
$week_appointments[$i] = $this->Doctor_model->get_doctor_appointments_week($_POST['doctor_id'],date('y-m-d',strtotime('-'.$i.'day', strtotime($_POST['startdate'],strtotime('-7 days')))));
/*print_r(date('y-m-d',strtotime('-'.$i.'day', strtotime($_POST['startdate'])))); */
}
//print_r($week_appointments);die();
$template['week_appointments'] = $week_appointments;
$template['start_day'] = date('y-m-d',strtotime('-6day', strtotime($_POST['startdate'])));
//print_r($template);die();
$template['doctorid'] = $_POST['doctor_id'];
$this->load->view('search_doctor_complete_profile_appointments_week',$template);
}
}
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Facebook PHP SDK v5 for CodeIgniter 3.x
*
* Library for Facebook PHP SDK v5. It helps the user to login with their Facebook account
* in CodeIgniter application.
*
* This library requires the Facebook PHP SDK v5 and it should be placed in libraries folder.
*
* It also requires facebook configuration file and it should be placed in the config directory.
*
* @package CodeIgniter
* @category Libraries
* @author CodexWorld
* @license http://www.codexworld.com/license/
* @link http://www.codexworld.com
* @version 2.0
*/
// Include the autoloader provided in the SDK
require_once 'facebook-php-sdk/autoload.php';
use Facebook\Facebook as FB;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Helpers\FacebookJavaScriptHelper;
use Facebook\Helpers\FacebookRedirectLoginHelper;
Class Facebook
{
/**
* @var FB
*/
private $fb;
/**
* @var FacebookRedirectLoginHelper|FacebookJavaScriptHelper
*/
private $helper;
/**
* Facebook constructor.
*/
public function __construct(){
// Load fb config
$this->load->config('facebook');
// Load required libraries and helpers
$this->load->library('session');
$this->load->helper('url');
if (!isset($this->fb)){
$this->fb = new FB([
'app_id' => $this->config->item('facebook_app_id'),
'app_secret' => $this->config->item('facebook_app_secret'),
'default_graph_version' => $this->config->item('facebook_graph_version')
]);
}
// Load correct helper depending on login type
// set in the config file
switch ($this->config->item('facebook_login_type')){
case 'js':
$this->helper = $this->fb->getJavaScriptHelper();
break;
case 'canvas':
$this->helper = $this->fb->getCanvasHelper();
break;
case 'page_tab':
$this->helper = $this->fb->getPageTabHelper();
break;
case 'web':
$this->helper = $this->fb->getRedirectLoginHelper();
break;
}
if ($this->config->item('facebook_auth_on_load') === TRUE){
// Try and authenticate the user right away (get valid access token)
$this->authenticate();
}
}
/**
* @return FB
*/
public function object(){
return $this->fb;
}
/**
* Check whether the user is logged in.
* by access token
*
* @return mixed|boolean
*/
public function is_authenticated(){
$access_token = $this->authenticate();
if(isset($access_token)){
return $access_token;
}
return false;
}
/**
* Do Graph request
*
* @param $method
* @param $endpoint
* @param array $params
* @param null $access_token
*
* @return array
*/
public function request($method, $endpoint, $params = [], $access_token = null){
try{
$response = $this->fb->{strtolower($method)}($endpoint, $params, $access_token);
return $response->getDecodedBody();
}catch(FacebookResponseException $e){
return $this->logError($e->getCode(), $e->getMessage());
}catch (FacebookSDKException $e){
return $this->logError($e->getCode(), $e->getMessage());
}
}
/**
* Generate Facebook login url for web
*
* @return string
*/
public function login_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get login url
return $this->helper->getLoginUrl(
base_url() . $this->config->item('facebook_login_redirect_url'),
$this->config->item('facebook_permissions')
);
}
/**
* Generate Facebook logout url for web
*
* @return string
*/
public function logout_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get logout url
return $this->helper->getLogoutUrl(
$this->get_access_token(),
base_url() . $this->config->item('facebook_logout_redirect_url')
);
}
/**
* Destroy local Facebook session
*/
public function destroy_session(){
$this->session->unset_userdata('fb_access_token');
}
/**
* Get a new access token from Facebook
*
* @return array|AccessToken|null|object|void
*/
private function authenticate(){
$access_token = $this->get_access_token();
if($access_token && $this->get_expire_time() > (time() + 30) || $access_token && !$this->get_expire_time()){
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
// If we did not have a stored access token or if it has expired, try get a new access token
if(!$access_token){
try{
$access_token = $this->helper->getAccessToken();
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
// If we got a session we need to exchange it for a long lived session.
if(isset($access_token)){
$access_token = $this->long_lived_token($access_token);
$this->set_expire_time($access_token->getExpiresAt());
$this->set_access_token($access_token);
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
}
// Collect errors if any when using web redirect based login
if($this->config->item('facebook_login_type') === 'web'){
if($this->helper->getError()){
// Collect error data
$error = array(
'error' => $this->helper->getError(),
'error_code' => $this->helper->getErrorCode(),
'error_reason' => $this->helper->getErrorReason(),
'error_description' => $this->helper->getErrorDescription()
);
return $error;
}
}
return $access_token;
}
/**
* Exchange short lived token for a long lived token
*
* @param AccessToken $access_token
*
* @return AccessToken|null
*/
private function long_lived_token(AccessToken $access_token){
if(!$access_token->isLongLived()){
$oauth2_client = $this->fb->getOAuth2Client();
try{
return $oauth2_client->getLongLivedAccessToken($access_token);
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
}
return $access_token;
}
/**
* Get stored access token
*
* @return mixed
*/
private function get_access_token(){
return $this->session->userdata('fb_access_token');
}
/**
* Store access token
*
* @param AccessToken $access_token
*/
private function set_access_token(AccessToken $access_token){
$this->session->set_userdata('fb_access_token', $access_token->getValue());
}
/**
* @return mixed
*/
private function get_expire_time(){
return $this->session->userdata('fb_expire');
}
/**
* @param DateTime $time
*/
private function set_expire_time(DateTime $time = null){
if ($time) {
$this->session->set_userdata('fb_expire', $time->getTimestamp());
}
}
/**
* @param $code
* @param $message
*
* @return array
*/
private function logError($code, $message){
log_message('error', '[FACEBOOK PHP SDK] code: ' . $code.' | message: '.$message);
return ['error' => $code, 'message' => $message];
}
/**
* Enables the use of CI super-global without having to define an extra variable.
*
* @param $var
*
* @return mixed
*/
public function __get($var){
return get_instance()->$var;
}
}
\ No newline at end of file
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Authentication;
/**
* Class AccessToken
*
* @package Facebook
*/
class AccessToken
{
/**
* The access token value.
*
* @var string
*/
protected $value = '';
/**
* Date when token expires.
*
* @var \DateTime|null
*/
protected $expiresAt;
/**
* Create a new access token entity.
*
* @param string $accessToken
* @param int $expiresAt
*/
public function __construct($accessToken, $expiresAt = 0)
{
$this->value = $accessToken;
if ($expiresAt) {
$this->setExpiresAtFromTimeStamp($expiresAt);
}
}
/**
* Generate an app secret proof to sign a request to Graph.
*
* @param string $appSecret The app secret.
*
* @return string
*/
public function getAppSecretProof($appSecret)
{
return hash_hmac('sha256', $this->value, $appSecret);
}
/**
* Getter for expiresAt.
*
* @return \DateTime|null
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Determines whether or not this is an app access token.
*
* @return bool
*/
public function isAppAccessToken()
{
return strpos($this->value, '|') !== false;
}
/**
* Determines whether or not this is a long-lived token.
*
* @return bool
*/
public function isLongLived()
{
if ($this->expiresAt) {
return $this->expiresAt->getTimestamp() > time() + (60 * 60 * 2);
}
if ($this->isAppAccessToken()) {
return true;
}
return false;
}
/**
* Checks the expiration of the access token.
*
* @return boolean|null
*/
public function isExpired()
{
if ($this->getExpiresAt() instanceof \DateTime) {
return $this->getExpiresAt()->getTimestamp() < time();
}
if ($this->isAppAccessToken()) {
return false;
}
return null;
}
/**
* Returns the access token as a string.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Returns the access token as a string.
*
* @return string
*/
public function __toString()
{
return $this->getValue();
}
/**
* Setter for expires_at.
*
* @param int $timeStamp
*/
protected function setExpiresAtFromTimeStamp($timeStamp)
{
$dt = new \DateTime();
$dt->setTimestamp($timeStamp);
$this->expiresAt = $dt;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Authentication;
use Facebook\Facebook;
use Facebook\FacebookApp;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookClient;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
/**
* Class OAuth2Client
*
* @package Facebook
*/
class OAuth2Client
{
/**
* @const string The base authorization URL.
*/
const BASE_AUTHORIZATION_URL = 'https://www.facebook.com';
/**
* The FacebookApp entity.
*
* @var FacebookApp
*/
protected $app;
/**
* The Facebook client.
*
* @var FacebookClient
*/
protected $client;
/**
* The version of the Graph API to use.
*
* @var string
*/
protected $graphVersion;
/**
* The last request sent to Graph.
*
* @var FacebookRequest|null
*/
protected $lastRequest;
/**
* @param FacebookApp $app
* @param FacebookClient $client
* @param string|null $graphVersion The version of the Graph API to use.
*/
public function __construct(FacebookApp $app, FacebookClient $client, $graphVersion = null)
{
$this->app = $app;
$this->client = $client;
$this->graphVersion = $graphVersion ?: Facebook::DEFAULT_GRAPH_VERSION;
}
/**
* Returns the last FacebookRequest that was sent.
* Useful for debugging and testing.
*
* @return FacebookRequest|null
*/
public function getLastRequest()
{
return $this->lastRequest;
}
/**
* Get the metadata associated with the access token.
*
* @param AccessToken|string $accessToken The access token to debug.
*
* @return AccessTokenMetadata
*/
public function debugToken($accessToken)
{
$accessToken = $accessToken instanceof AccessToken ? $accessToken->getValue() : $accessToken;
$params = ['input_token' => $accessToken];
$this->lastRequest = new FacebookRequest(
$this->app,
$this->app->getAccessToken(),
'GET',
'/debug_token',
$params,
null,
$this->graphVersion
);
$response = $this->client->sendRequest($this->lastRequest);
$metadata = $response->getDecodedBody();
return new AccessTokenMetadata($metadata);
}
/**
* Generates an authorization URL to begin the process of authenticating a user.
*
* @param string $redirectUrl The callback URL to redirect to.
* @param string $state The CSPRNG-generated CSRF value.
* @param array $scope An array of permissions to request.
* @param array $params An array of parameters to generate URL.
* @param string $separator The separator to use in http_build_query().
*
* @return string
*/
public function getAuthorizationUrl($redirectUrl, $state, array $scope = [], array $params = [], $separator = '&')
{
$params += [
'client_id' => $this->app->getId(),
'state' => $state,
'response_type' => 'code',
'sdk' => 'php-sdk-' . Facebook::VERSION,
'redirect_uri' => $redirectUrl,
'scope' => implode(',', $scope)
];
return static::BASE_AUTHORIZATION_URL . '/' . $this->graphVersion . '/dialog/oauth?' . http_build_query($params, null, $separator);
}
/**
* Get a valid access token from a code.
*
* @param string $code
* @param string $redirectUri
*
* @return AccessToken
*
* @throws FacebookSDKException
*/
public function getAccessTokenFromCode($code, $redirectUri = '')
{
$params = [
'code' => $code,
'redirect_uri' => $redirectUri,
];
return $this->requestAnAccessToken($params);
}
/**
* Exchanges a short-lived access token with a long-lived access token.
*
* @param AccessToken|string $accessToken
*
* @return AccessToken
*
* @throws FacebookSDKException
*/
public function getLongLivedAccessToken($accessToken)
{
$accessToken = $accessToken instanceof AccessToken ? $accessToken->getValue() : $accessToken;
$params = [
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $accessToken,
];
return $this->requestAnAccessToken($params);
}
/**
* Get a valid code from an access token.
*
* @param AccessToken|string $accessToken
* @param string $redirectUri
*
* @return AccessToken
*
* @throws FacebookSDKException
*/
public function getCodeFromLongLivedAccessToken($accessToken, $redirectUri = '')
{
$params = [
'redirect_uri' => $redirectUri,
];
$response = $this->sendRequestWithClientParams('/oauth/client_code', $params, $accessToken);
$data = $response->getDecodedBody();
if (!isset($data['code'])) {
throw new FacebookSDKException('Code was not returned from Graph.', 401);
}
return $data['code'];
}
/**
* Send a request to the OAuth endpoint.
*
* @param array $params
*
* @return AccessToken
*
* @throws FacebookSDKException
*/
protected function requestAnAccessToken(array $params)
{
$response = $this->sendRequestWithClientParams('/oauth/access_token', $params);
$data = $response->getDecodedBody();
if (!isset($data['access_token'])) {
throw new FacebookSDKException('Access token was not returned from Graph.', 401);
}
// Graph returns two different key names for expiration time
// on the same endpoint. Doh! :/
$expiresAt = 0;
if (isset($data['expires'])) {
// For exchanging a short lived token with a long lived token.
// The expiration time in seconds will be returned as "expires".
$expiresAt = time() + $data['expires'];
} elseif (isset($data['expires_in'])) {
// For exchanging a code for a short lived access token.
// The expiration time in seconds will be returned as "expires_in".
// See: https://developers.facebook.com/docs/facebook-login/access-tokens#long-via-code
$expiresAt = time() + $data['expires_in'];
}
return new AccessToken($data['access_token'], $expiresAt);
}
/**
* Send a request to Graph with an app access token.
*
* @param string $endpoint
* @param array $params
* @param AccessToken|string|null $accessToken
*
* @return FacebookResponse
*
* @throws FacebookResponseException
*/
protected function sendRequestWithClientParams($endpoint, array $params, $accessToken = null)
{
$params += $this->getClientParams();
$accessToken = $accessToken ?: $this->app->getAccessToken();
$this->lastRequest = new FacebookRequest(
$this->app,
$accessToken,
'GET',
$endpoint,
$params,
null,
$this->graphVersion
);
return $this->client->sendRequest($this->lastRequest);
}
/**
* Returns the client_* params for OAuth requests.
*
* @return array
*/
protected function getClientParams()
{
return [
'client_id' => $this->app->getId(),
'client_secret' => $this->app->getSecret(),
];
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookAuthenticationException
*
* @package Facebook
*/
class FacebookAuthenticationException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookAuthorizationException
*
* @package Facebook
*/
class FacebookAuthorizationException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookClientException
*
* @package Facebook
*/
class FacebookClientException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookOtherException
*
* @package Facebook
*/
class FacebookOtherException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
use Facebook\FacebookResponse;
/**
* Class FacebookResponseException
*
* @package Facebook
*/
class FacebookResponseException extends FacebookSDKException
{
/**
* @var FacebookResponse The response that threw the exception.
*/
protected $response;
/**
* @var array Decoded response.
*/
protected $responseData;
/**
* Creates a FacebookResponseException.
*
* @param FacebookResponse $response The response that threw the exception.
* @param FacebookSDKException $previousException The more detailed exception.
*/
public function __construct(FacebookResponse $response, FacebookSDKException $previousException = null)
{
$this->response = $response;
$this->responseData = $response->getDecodedBody();
$errorMessage = $this->get('message', 'Unknown error from Graph.');
$errorCode = $this->get('code', -1);
parent::__construct($errorMessage, $errorCode, $previousException);
}
/**
* A factory for creating the appropriate exception based on the response from Graph.
*
* @param FacebookResponse $response The response that threw the exception.
*
* @return FacebookResponseException
*/
public static function create(FacebookResponse $response)
{
$data = $response->getDecodedBody();
if (!isset($data['error']['code']) && isset($data['code'])) {
$data = ['error' => $data];
}
$code = isset($data['error']['code']) ? $data['error']['code'] : null;
$message = isset($data['error']['message']) ? $data['error']['message'] : 'Unknown error from Graph.';
if (isset($data['error']['error_subcode'])) {
switch ($data['error']['error_subcode']) {
// Other authentication issues
case 458:
case 459:
case 460:
case 463:
case 464:
case 467:
return new static($response, new FacebookAuthenticationException($message, $code));
// Video upload resumable error
case 1363030:
case 1363019:
case 1363037:
case 1363033:
case 1363021:
case 1363041:
return new static($response, new FacebookResumableUploadException($message, $code));
}
}
switch ($code) {
// Login status or token expired, revoked, or invalid
case 100:
case 102:
case 190:
return new static($response, new FacebookAuthenticationException($message, $code));
// Server issue, possible downtime
case 1:
case 2:
return new static($response, new FacebookServerException($message, $code));
// API Throttling
case 4:
case 17:
case 341:
return new static($response, new FacebookThrottleException($message, $code));
// Duplicate Post
case 506:
return new static($response, new FacebookClientException($message, $code));
}
// Missing Permissions
if ($code == 10 || ($code >= 200 && $code <= 299)) {
return new static($response, new FacebookAuthorizationException($message, $code));
}
// OAuth authentication error
if (isset($data['error']['type']) && $data['error']['type'] === 'OAuthException') {
return new static($response, new FacebookAuthenticationException($message, $code));
}
// All others
return new static($response, new FacebookOtherException($message, $code));
}
/**
* Checks isset and returns that or a default value.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
private function get($key, $default = null)
{
if (isset($this->responseData['error'][$key])) {
return $this->responseData['error'][$key];
}
return $default;
}
/**
* Returns the HTTP status code
*
* @return int
*/
public function getHttpStatusCode()
{
return $this->response->getHttpStatusCode();
}
/**
* Returns the sub-error code
*
* @return int
*/
public function getSubErrorCode()
{
return $this->get('error_subcode', -1);
}
/**
* Returns the error type
*
* @return string
*/
public function getErrorType()
{
return $this->get('type', '');
}
/**
* Returns the raw response used to create the exception.
*
* @return string
*/
public function getRawResponse()
{
return $this->response->getBody();
}
/**
* Returns the decoded response used to create the exception.
*
* @return array
*/
public function getResponseData()
{
return $this->responseData;
}
/**
* Returns the response entity used to create the exception.
*
* @return FacebookResponse
*/
public function getResponse()
{
return $this->response;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookResumableUploadException
*
* @package Facebook
*/
class FacebookResumableUploadException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookSDKException
*
* @package Facebook
*/
class FacebookSDKException extends \Exception
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookServerException
*
* @package Facebook
*/
class FacebookServerException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Exceptions;
/**
* Class FacebookThrottleException
*
* @package Facebook
*/
class FacebookThrottleException extends FacebookSDKException
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookSDKException;
class FacebookApp implements \Serializable
{
/**
* @var string The app ID.
*/
protected $id;
/**
* @var string The app secret.
*/
protected $secret;
/**
* @param string $id
* @param string $secret
*
* @throws FacebookSDKException
*/
public function __construct($id, $secret)
{
if (!is_string($id)
// Keeping this for BC. Integers greater than PHP_INT_MAX will make is_int() return false
&& !is_int($id)) {
throw new FacebookSDKException('The "app_id" must be formatted as a string since many app ID\'s are greater than PHP_INT_MAX on some systems.');
}
// We cast as a string in case a valid int was set on a 64-bit system and this is unserialised on a 32-bit system
$this->id = (string) $id;
$this->secret = $secret;
}
/**
* Returns the app ID.
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Returns the app secret.
*
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* Returns an app access token.
*
* @return AccessToken
*/
public function getAccessToken()
{
return new AccessToken($this->id . '|' . $this->secret);
}
/**
* Serializes the FacebookApp entity as a string.
*
* @return string
*/
public function serialize()
{
return implode('|', [$this->id, $this->secret]);
}
/**
* Unserializes a string as a FacebookApp entity.
*
* @param string $serialized
*/
public function unserialize($serialized)
{
list($id, $secret) = explode('|', $serialized);
$this->__construct($id, $secret);
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook;
use ArrayIterator;
use IteratorAggregate;
use ArrayAccess;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookSDKException;
/**
* Class BatchRequest
*
* @package Facebook
*/
class FacebookBatchRequest extends FacebookRequest implements IteratorAggregate, ArrayAccess
{
/**
* @var array An array of FacebookRequest entities to send.
*/
protected $requests;
/**
* @var array An array of files to upload.
*/
protected $attachedFiles;
/**
* Creates a new Request entity.
*
* @param FacebookApp|null $app
* @param array $requests
* @param AccessToken|string|null $accessToken
* @param string|null $graphVersion
*/
public function __construct(FacebookApp $app = null, array $requests = [], $accessToken = null, $graphVersion = null)
{
parent::__construct($app, $accessToken, 'POST', '', [], null, $graphVersion);
$this->add($requests);
}
/**
* Adds a new request to the array.
*
* @param FacebookRequest|array $request
* @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'.
* If a string is given, it is the value of the 'name' option.
*
* @return FacebookBatchRequest
*
* @throws \InvalidArgumentException
*/
public function add($request, $options = null)
{
if (is_array($request)) {
foreach ($request as $key => $req) {
$this->add($req, $key);
}
return $this;
}
if (!$request instanceof FacebookRequest) {
throw new \InvalidArgumentException('Argument for add() must be of type array or FacebookRequest.');
}
if (null === $options) {
$options = [];
} elseif (!is_array($options)) {
$options = ['name' => $options];
}
$this->addFallbackDefaults($request);
// File uploads
$attachedFiles = $this->extractFileAttachments($request);
$name = isset($options['name']) ? $options['name'] : null;
unset($options['name']);
$requestToAdd = [
'name' => $name,
'request' => $request,
'options' => $options,
'attached_files' => $attachedFiles,
];
$this->requests[] = $requestToAdd;
return $this;
}
/**
* Ensures that the FacebookApp and access token fall back when missing.
*
* @param FacebookRequest $request
*
* @throws FacebookSDKException
*/
public function addFallbackDefaults(FacebookRequest $request)
{
if (!$request->getApp()) {
$app = $this->getApp();
if (!$app) {
throw new FacebookSDKException('Missing FacebookApp on FacebookRequest and no fallback detected on FacebookBatchRequest.');
}
$request->setApp($app);
}
if (!$request->getAccessToken()) {
$accessToken = $this->getAccessToken();
if (!$accessToken) {
throw new FacebookSDKException('Missing access token on FacebookRequest and no fallback detected on FacebookBatchRequest.');
}
$request->setAccessToken($accessToken);
}
}
/**
* Extracts the files from a request.
*
* @param FacebookRequest $request
*
* @return string|null
*
* @throws FacebookSDKException
*/
public function extractFileAttachments(FacebookRequest $request)
{
if (!$request->containsFileUploads()) {
return null;
}
$files = $request->getFiles();
$fileNames = [];
foreach ($files as $file) {
$fileName = uniqid();
$this->addFile($fileName, $file);
$fileNames[] = $fileName;
}
$request->resetFiles();
// @TODO Does Graph support multiple uploads on one endpoint?
return implode(',', $fileNames);
}
/**
* Return the FacebookRequest entities.
*
* @return array
*/
public function getRequests()
{
return $this->requests;
}
/**
* Prepares the requests to be sent as a batch request.
*/
public function prepareRequestsForBatch()
{
$this->validateBatchRequestCount();
$params = [
'batch' => $this->convertRequestsToJson(),
'include_headers' => true,
];
$this->setParams($params);
}
/**
* Converts the requests into a JSON(P) string.
*
* @return string
*/
public function convertRequestsToJson()
{
$requests = [];
foreach ($this->requests as $request) {
$options = [];
if (null !== $request['name']) {
$options['name'] = $request['name'];
}
$options += $request['options'];
$requests[] = $this->requestEntityToBatchArray($request['request'], $options, $request['attached_files']);
}
return json_encode($requests);
}
/**
* Validate the request count before sending them as a batch.
*
* @throws FacebookSDKException
*/
public function validateBatchRequestCount()
{
$batchCount = count($this->requests);
if ($batchCount === 0) {
throw new FacebookSDKException('There are no batch requests to send.');
} elseif ($batchCount > 50) {
// Per: https://developers.facebook.com/docs/graph-api/making-multiple-requests#limits
throw new FacebookSDKException('You cannot send more than 50 batch requests at a time.');
}
}
/**
* Converts a Request entity into an array that is batch-friendly.
*
* @param FacebookRequest $request The request entity to convert.
* @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'.
* If a string is given, it is the value of the 'name' option.
* @param string|null $attachedFiles Names of files associated with the request.
*
* @return array
*/
public function requestEntityToBatchArray(FacebookRequest $request, $options = null, $attachedFiles = null)
{
if (null === $options) {
$options = [];
} elseif (!is_array($options)) {
$options = ['name' => $options];
}
$compiledHeaders = [];
$headers = $request->getHeaders();
foreach ($headers as $name => $value) {
$compiledHeaders[] = $name . ': ' . $value;
}
$batch = [
'headers' => $compiledHeaders,
'method' => $request->getMethod(),
'relative_url' => $request->getUrl(),
];
// Since file uploads are moved to the root request of a batch request,
// the child requests will always be URL-encoded.
$body = $request->getUrlEncodedBody()->getBody();
if ($body) {
$batch['body'] = $body;
}
$batch += $options;
if (null !== $attachedFiles) {
$batch['attached_files'] = $attachedFiles;
}
return $batch;
}
/**
* Get an iterator for the items.
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->requests);
}
/**
* @inheritdoc
*/
public function offsetSet($offset, $value)
{
$this->add($value, $offset);
}
/**
* @inheritdoc
*/
public function offsetExists($offset)
{
return isset($this->requests[$offset]);
}
/**
* @inheritdoc
*/
public function offsetUnset($offset)
{
unset($this->requests[$offset]);
}
/**
* @inheritdoc
*/
public function offsetGet($offset)
{
return isset($this->requests[$offset]) ? $this->requests[$offset] : null;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook;
use ArrayIterator;
use IteratorAggregate;
use ArrayAccess;
/**
* Class FacebookBatchResponse
*
* @package Facebook
*/
class FacebookBatchResponse extends FacebookResponse implements IteratorAggregate, ArrayAccess
{
/**
* @var FacebookBatchRequest The original entity that made the batch request.
*/
protected $batchRequest;
/**
* @var array An array of FacebookResponse entities.
*/
protected $responses = [];
/**
* Creates a new Response entity.
*
* @param FacebookBatchRequest $batchRequest
* @param FacebookResponse $response
*/
public function __construct(FacebookBatchRequest $batchRequest, FacebookResponse $response)
{
$this->batchRequest = $batchRequest;
$request = $response->getRequest();
$body = $response->getBody();
$httpStatusCode = $response->getHttpStatusCode();
$headers = $response->getHeaders();
parent::__construct($request, $body, $httpStatusCode, $headers);
$responses = $response->getDecodedBody();
$this->setResponses($responses);
}
/**
* Returns an array of FacebookResponse entities.
*
* @return array
*/
public function getResponses()
{
return $this->responses;
}
/**
* The main batch response will be an array of requests so
* we need to iterate over all the responses.
*
* @param array $responses
*/
public function setResponses(array $responses)
{
$this->responses = [];
foreach ($responses as $key => $graphResponse) {
$this->addResponse($key, $graphResponse);
}
}
/**
* Add a response to the list.
*
* @param int $key
* @param array|null $response
*/
public function addResponse($key, $response)
{
$originalRequestName = isset($this->batchRequest[$key]['name']) ? $this->batchRequest[$key]['name'] : $key;
$originalRequest = isset($this->batchRequest[$key]['request']) ? $this->batchRequest[$key]['request'] : null;
$httpResponseBody = isset($response['body']) ? $response['body'] : null;
$httpResponseCode = isset($response['code']) ? $response['code'] : null;
// @TODO With PHP 5.5 support, this becomes array_column($response['headers'], 'value', 'name')
$httpResponseHeaders = isset($response['headers']) ? $this->normalizeBatchHeaders($response['headers']) : [];
$this->responses[$originalRequestName] = new FacebookResponse(
$originalRequest,
$httpResponseBody,
$httpResponseCode,
$httpResponseHeaders
);
}
/**
* @inheritdoc
*/
public function getIterator()
{
return new ArrayIterator($this->responses);
}
/**
* @inheritdoc
*/
public function offsetSet($offset, $value)
{
$this->addResponse($offset, $value);
}
/**
* @inheritdoc
*/
public function offsetExists($offset)
{
return isset($this->responses[$offset]);
}
/**
* @inheritdoc
*/
public function offsetUnset($offset)
{
unset($this->responses[$offset]);
}
/**
* @inheritdoc
*/
public function offsetGet($offset)
{
return isset($this->responses[$offset]) ? $this->responses[$offset] : null;
}
/**
* Converts the batch header array into a standard format.
* @TODO replace with array_column() when PHP 5.5 is supported.
*
* @param array $batchHeaders
*
* @return array
*/
private function normalizeBatchHeaders(array $batchHeaders)
{
$headers = [];
foreach ($batchHeaders as $header) {
$headers[$header['name']] = $header['value'];
}
return $headers;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook;
use Facebook\HttpClients\FacebookHttpClientInterface;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookStreamHttpClient;
use Facebook\Exceptions\FacebookSDKException;
/**
* Class FacebookClient
*
* @package Facebook
*/
class FacebookClient
{
/**
* @const string Production Graph API URL.
*/
const BASE_GRAPH_URL = 'https://graph.facebook.com';
/**
* @const string Graph API URL for video uploads.
*/
const BASE_GRAPH_VIDEO_URL = 'https://graph-video.facebook.com';
/**
* @const string Beta Graph API URL.
*/
const BASE_GRAPH_URL_BETA = 'https://graph.beta.facebook.com';
/**
* @const string Beta Graph API URL for video uploads.
*/
const BASE_GRAPH_VIDEO_URL_BETA = 'https://graph-video.beta.facebook.com';
/**
* @const int The timeout in seconds for a normal request.
*/
const DEFAULT_REQUEST_TIMEOUT = 60;
/**
* @const int The timeout in seconds for a request that contains file uploads.
*/
const DEFAULT_FILE_UPLOAD_REQUEST_TIMEOUT = 3600;
/**
* @const int The timeout in seconds for a request that contains video uploads.
*/
const DEFAULT_VIDEO_UPLOAD_REQUEST_TIMEOUT = 7200;
/**
* @var bool Toggle to use Graph beta url.
*/
protected $enableBetaMode = false;
/**
* @var FacebookHttpClientInterface HTTP client handler.
*/
protected $httpClientHandler;
/**
* @var int The number of calls that have been made to Graph.
*/
public static $requestCount = 0;
/**
* Instantiates a new FacebookClient object.
*
* @param FacebookHttpClientInterface|null $httpClientHandler
* @param boolean $enableBeta
*/
public function __construct(FacebookHttpClientInterface $httpClientHandler = null, $enableBeta = false)
{
$this->httpClientHandler = $httpClientHandler ?: $this->detectHttpClientHandler();
$this->enableBetaMode = $enableBeta;
}
/**
* Sets the HTTP client handler.
*
* @param FacebookHttpClientInterface $httpClientHandler
*/
public function setHttpClientHandler(FacebookHttpClientInterface $httpClientHandler)
{
$this->httpClientHandler = $httpClientHandler;
}
/**
* Returns the HTTP client handler.
*
* @return FacebookHttpClientInterface
*/
public function getHttpClientHandler()
{
return $this->httpClientHandler;
}
/**
* Detects which HTTP client handler to use.
*
* @return FacebookHttpClientInterface
*/
public function detectHttpClientHandler()
{
return extension_loaded('curl') ? new FacebookCurlHttpClient() : new FacebookStreamHttpClient();
}
/**
* Toggle beta mode.
*
* @param boolean $betaMode
*/
public function enableBetaMode($betaMode = true)
{
$this->enableBetaMode = $betaMode;
}
/**
* Returns the base Graph URL.
*
* @param boolean $postToVideoUrl Post to the video API if videos are being uploaded.
*
* @return string
*/
public function getBaseGraphUrl($postToVideoUrl = false)
{
if ($postToVideoUrl) {
return $this->enableBetaMode ? static::BASE_GRAPH_VIDEO_URL_BETA : static::BASE_GRAPH_VIDEO_URL;
}
return $this->enableBetaMode ? static::BASE_GRAPH_URL_BETA : static::BASE_GRAPH_URL;
}
/**
* Prepares the request for sending to the client handler.
*
* @param FacebookRequest $request
*
* @return array
*/
public function prepareRequestMessage(FacebookRequest $request)
{
$postToVideoUrl = $request->containsVideoUploads();
$url = $this->getBaseGraphUrl($postToVideoUrl) . $request->getUrl();
// If we're sending files they should be sent as multipart/form-data
if ($request->containsFileUploads()) {
$requestBody = $request->getMultipartBody();
$request->setHeaders([
'Content-Type' => 'multipart/form-data; boundary=' . $requestBody->getBoundary(),
]);
} else {
$requestBody = $request->getUrlEncodedBody();
$request->setHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
]);
}
return [
$url,
$request->getMethod(),
$request->getHeaders(),
$requestBody->getBody(),
];
}
/**
* Makes the request to Graph and returns the result.
*
* @param FacebookRequest $request
*
* @return FacebookResponse
*
* @throws FacebookSDKException
*/
public function sendRequest(FacebookRequest $request)
{
if (get_class($request) === 'Facebook\FacebookRequest') {
$request->validateAccessToken();
}
list($url, $method, $headers, $body) = $this->prepareRequestMessage($request);
// Since file uploads can take a while, we need to give more time for uploads
$timeOut = static::DEFAULT_REQUEST_TIMEOUT;
if ($request->containsFileUploads()) {
$timeOut = static::DEFAULT_FILE_UPLOAD_REQUEST_TIMEOUT;
} elseif ($request->containsVideoUploads()) {
$timeOut = static::DEFAULT_VIDEO_UPLOAD_REQUEST_TIMEOUT;
}
// Should throw `FacebookSDKException` exception on HTTP client error.
// Don't catch to allow it to bubble up.
$rawResponse = $this->httpClientHandler->send($url, $method, $body, $headers, $timeOut);
static::$requestCount++;
$returnResponse = new FacebookResponse(
$request,
$rawResponse->getBody(),
$rawResponse->getHttpResponseCode(),
$rawResponse->getHeaders()
);
if ($returnResponse->isError()) {
throw $returnResponse->getThrownException();
}
return $returnResponse;
}
/**
* Makes a batched request to Graph and returns the result.
*
* @param FacebookBatchRequest $request
*
* @return FacebookBatchResponse
*
* @throws FacebookSDKException
*/
public function sendBatchRequest(FacebookBatchRequest $request)
{
$request->prepareRequestsForBatch();
$facebookResponse = $this->sendRequest($request);
return new FacebookBatchResponse($request, $facebookResponse);
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\FileUpload;
use Facebook\Exceptions\FacebookSDKException;
/**
* Class FacebookFile
*
* @package Facebook
*/
class FacebookFile
{
/**
* @var string The path to the file on the system.
*/
protected $path;
/**
* @var int The maximum bytes to read. Defaults to -1 (read all the remaining buffer).
*/
private $maxLength;
/**
* @var int Seek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position.
*/
private $offset;
/**
* @var resource The stream pointing to the file.
*/
protected $stream;
/**
* Creates a new FacebookFile entity.
*
* @param string $filePath
* @param int $maxLength
* @param int $offset
*
* @throws FacebookSDKException
*/
public function __construct($filePath, $maxLength = -1, $offset = -1)
{
$this->path = $filePath;
$this->maxLength = $maxLength;
$this->offset = $offset;
$this->open();
}
/**
* Closes the stream when destructed.
*/
public function __destruct()
{
$this->close();
}
/**
* Opens a stream for the file.
*
* @throws FacebookSDKException
*/
public function open()
{
if (!$this->isRemoteFile($this->path) && !is_readable($this->path)) {
throw new FacebookSDKException('Failed to create FacebookFile entity. Unable to read resource: ' . $this->path . '.');
}
$this->stream = fopen($this->path, 'r');
if (!$this->stream) {
throw new FacebookSDKException('Failed to create FacebookFile entity. Unable to open resource: ' . $this->path . '.');
}
}
/**
* Stops the file stream.
*/
public function close()
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
}
/**
* Return the contents of the file.
*
* @return string
*/
public function getContents()
{
return stream_get_contents($this->stream, $this->maxLength, $this->offset);
}
/**
* Return the name of the file.
*
* @return string
*/
public function getFileName()
{
return basename($this->path);
}
/**
* Return the path of the file.
*
* @return string
*/
public function getFilePath()
{
return $this->path;
}
/**
* Return the size of the file.
*
* @return int
*/
public function getSize()
{
return filesize($this->path);
}
/**
* Return the mimetype of the file.
*
* @return string
*/
public function getMimetype()
{
return Mimetypes::getInstance()->fromFilename($this->path) ?: 'text/plain';
}
/**
* Returns true if the path to the file is remote.
*
* @param string $pathToFile
*
* @return boolean
*/
protected function isRemoteFile($pathToFile)
{
return preg_match('/^(https?|ftp):\/\/.*/', $pathToFile) === 1;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\FileUpload;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookResumableUploadException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\FacebookApp;
use Facebook\FacebookClient;
use Facebook\FacebookRequest;
/**
* Class FacebookResumableUploader
*
* @package Facebook
*/
class FacebookResumableUploader
{
/**
* @var FacebookApp
*/
protected $app;
/**
* @var string
*/
protected $accessToken;
/**
* @var FacebookClient The Facebook client service.
*/
protected $client;
/**
* @var string Graph version to use for this request.
*/
protected $graphVersion;
/**
* @param FacebookApp $app
* @param FacebookClient $client
* @param AccessToken|string|null $accessToken
* @param string $graphVersion
*/
public function __construct(FacebookApp $app, FacebookClient $client, $accessToken, $graphVersion)
{
$this->app = $app;
$this->client = $client;
$this->accessToken = $accessToken;
$this->graphVersion = $graphVersion;
}
/**
* Upload by chunks - start phase
*
* @param string $endpoint
* @param FacebookFile $file
*
* @return FacebookTransferChunk
*
* @throws FacebookSDKException
*/
public function start($endpoint, FacebookFile $file)
{
$params = [
'upload_phase' => 'start',
'file_size' => $file->getSize(),
];
$response = $this->sendUploadRequest($endpoint, $params);
return new FacebookTransferChunk($file, $response['upload_session_id'], $response['video_id'], $response['start_offset'], $response['end_offset']);
}
/**
* Upload by chunks - transfer phase
*
* @param string $endpoint
* @param FacebookTransferChunk $chunk
* @param boolean $allowToThrow
*
* @return FacebookTransferChunk
*
* @throws FacebookResponseException
*/
public function transfer($endpoint, FacebookTransferChunk $chunk, $allowToThrow = false)
{
$params = [
'upload_phase' => 'transfer',
'upload_session_id' => $chunk->getUploadSessionId(),
'start_offset' => $chunk->getStartOffset(),
'video_file_chunk' => $chunk->getPartialFile(),
];
try {
$response = $this->sendUploadRequest($endpoint, $params);
} catch (FacebookResponseException $e) {
$preException = $e->getPrevious();
if ($allowToThrow || !$preException instanceof FacebookResumableUploadException) {
throw $e;
}
// Return the same chunk entity so it can be retried.
return $chunk;
}
return new FacebookTransferChunk($chunk->getFile(), $chunk->getUploadSessionId(), $chunk->getVideoId(), $response['start_offset'], $response['end_offset']);
}
/**
* Upload by chunks - finish phase
*
* @param string $endpoint
* @param string $uploadSessionId
* @param array $metadata The metadata associated with the file.
*
* @return boolean
*
* @throws FacebookSDKException
*/
public function finish($endpoint, $uploadSessionId, $metadata = [])
{
$params = array_merge($metadata, [
'upload_phase' => 'finish',
'upload_session_id' => $uploadSessionId,
]);
$response = $this->sendUploadRequest($endpoint, $params);
return $response['success'];
}
/**
* Helper to make a FacebookRequest and send it.
*
* @param string $endpoint The endpoint to POST to.
* @param array $params The params to send with the request.
*
* @return array
*/
private function sendUploadRequest($endpoint, $params = [])
{
$request = new FacebookRequest($this->app, $this->accessToken, 'POST', $endpoint, $params, null, $this->graphVersion);
return $this->client->sendRequest($request)->getDecodedBody();
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\FileUpload;
/**
* Class FacebookTransferChunk
*
* @package Facebook
*/
class FacebookTransferChunk
{
/**
* @var FacebookFile The file to chunk during upload.
*/
private $file;
/**
* @var int The ID of the upload session.
*/
private $uploadSessionId;
/**
* @var int Start byte position of the next file chunk.
*/
private $startOffset;
/**
* @var int End byte position of the next file chunk.
*/
private $endOffset;
/**
* @var int The ID of the video.
*/
private $videoId;
/**
* @param FacebookFile $file
* @param int $uploadSessionId
* @param int $videoId
* @param int $startOffset
* @param int $endOffset
*/
public function __construct(FacebookFile $file, $uploadSessionId, $videoId, $startOffset, $endOffset)
{
$this->file = $file;
$this->uploadSessionId = $uploadSessionId;
$this->videoId = $videoId;
$this->startOffset = $startOffset;
$this->endOffset = $endOffset;
}
/**
* Return the file entity.
*
* @return FacebookFile
*/
public function getFile()
{
return $this->file;
}
/**
* Return a FacebookFile entity with partial content.
*
* @return FacebookFile
*/
public function getPartialFile()
{
$maxLength = $this->endOffset - $this->startOffset;
return new FacebookFile($this->file->getFilePath(), $maxLength, $this->startOffset);
}
/**
* Return upload session Id
*
* @return int
*/
public function getUploadSessionId()
{
return $this->uploadSessionId;
}
/**
* Check whether is the last chunk
*
* @return bool
*/
public function isLastChunk()
{
return $this->startOffset === $this->endOffset;
}
/**
* @return int
*/
public function getStartOffset()
{
return $this->startOffset;
}
/**
* Get uploaded video Id
*
* @return int
*/
public function getVideoId()
{
return $this->videoId;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\FileUpload;
/**
* Class FacebookVideo
*
* @package Facebook
*/
class FacebookVideo extends FacebookFile
{
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
use DateTime;
/**
* Birthday object to handle various Graph return formats
*
* @package Facebook
*/
class Birthday extends DateTime
{
/**
* @var bool
*/
private $hasDate = false;
/**
* @var bool
*/
private $hasYear = false;
/**
* Parses Graph birthday format to set indication flags, possible values:
*
* MM/DD/YYYY
* MM/DD
* YYYY
*
* @link https://developers.facebook.com/docs/graph-api/reference/user
*
* @param string $date
*/
public function __construct($date)
{
$parts = explode('/', $date);
$this->hasYear = count($parts) === 3 || count($parts) === 1;
$this->hasDate = count($parts) === 3 || count($parts) === 2;
parent::__construct($date);
}
/**
* Returns whether date object contains birth day and month
*
* @return bool
*/
public function hasDate()
{
return $this->hasDate;
}
/**
* Returns whether date object contains birth year
*
* @return bool
*/
public function hasYear()
{
return $this->hasYear;
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class Collection
*
* Modified version of Collection in "illuminate/support" by Taylor Otwell
*
* @package Facebook
*/
use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
class Collection implements ArrayAccess, Countable, IteratorAggregate
{
/**
* The items contained in the collection.
*
* @var array
*/
protected $items = [];
/**
* Create a new collection.
*
* @param array $items
*/
public function __construct(array $items = [])
{
$this->items = $items;
}
/**
* Gets the value of a field from the Graph node.
*
* @param string $name The field to retrieve.
* @param mixed $default The default to return if the field doesn't exist.
*
* @return mixed
*/
public function getField($name, $default = null)
{
if (isset($this->items[$name])) {
return $this->items[$name];
}
return $default;
}
/**
* Gets the value of the named property for this graph object.
*
* @param string $name The property to retrieve.
* @param mixed $default The default to return if the property doesn't exist.
*
* @return mixed
*
* @deprecated 5.0.0 getProperty() has been renamed to getField()
* @todo v6: Remove this method
*/
public function getProperty($name, $default = null)
{
return $this->getField($name, $default);
}
/**
* Returns a list of all fields set on the object.
*
* @return array
*/
public function getFieldNames()
{
return array_keys($this->items);
}
/**
* Returns a list of all properties set on the object.
*
* @return array
*
* @deprecated 5.0.0 getPropertyNames() has been renamed to getFieldNames()
* @todo v6: Remove this method
*/
public function getPropertyNames()
{
return $this->getFieldNames();
}
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
/**
* Get the collection of items as a plain array.
*
* @return array
*/
public function asArray()
{
return array_map(function ($value) {
return $value instanceof Collection ? $value->asArray() : $value;
}, $this->items);
}
/**
* Run a map over each of the items.
*
* @param \Closure $callback
*
* @return static
*/
public function map(\Closure $callback)
{
return new static(array_map($callback, $this->items, array_keys($this->items)));
}
/**
* Get the collection of items as JSON.
*
* @param int $options
*
* @return string
*/
public function asJson($options = 0)
{
return json_encode($this->asArray(), $options);
}
/**
* Count the number of items in the collection.
*
* @return int
*/
public function count()
{
return count($this->items);
}
/**
* Get an iterator for the items.
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->items);
}
/**
* Determine if an item exists at an offset.
*
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key)
{
return array_key_exists($key, $this->items);
}
/**
* Get an item at a given offset.
*
* @param mixed $key
*
* @return mixed
*/
public function offsetGet($key)
{
return $this->items[$key];
}
/**
* Set the item at a given offset.
*
* @param mixed $key
* @param mixed $value
*
* @return void
*/
public function offsetSet($key, $value)
{
if (is_null($key)) {
$this->items[] = $value;
} else {
$this->items[$key] = $value;
}
}
/**
* Unset the item at a given offset.
*
* @param string $key
*
* @return void
*/
public function offsetUnset($key)
{
unset($this->items[$key]);
}
/**
* Convert the collection to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->asJson();
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphAchievement
*
* @package Facebook
*/
class GraphAchievement extends GraphNode
{
/**
* @var array Maps object key names to Graph object types.
*/
protected static $graphObjectMap = [
'from' => '\Facebook\GraphNodes\GraphUser',
'application' => '\Facebook\GraphNodes\GraphApplication',
];
/**
* Returns the ID for the achievement.
*
* @return string|null
*/
public function getId()
{
return $this->getField('id');
}
/**
* Returns the user who achieved this.
*
* @return GraphUser|null
*/
public function getFrom()
{
return $this->getField('from');
}
/**
* Returns the time at which this was achieved.
*
* @return \DateTime|null
*/
public function getPublishTime()
{
return $this->getField('publish_time');
}
/**
* Returns the app in which the user achieved this.
*
* @return GraphApplication|null
*/
public function getApplication()
{
return $this->getField('application');
}
/**
* Returns information about the achievement type this instance is connected with.
*
* @return array|null
*/
public function getData()
{
return $this->getField('data');
}
/**
* Returns the type of achievement.
*
* @see https://developers.facebook.com/docs/graph-api/reference/achievement
*
* @return string
*/
public function getType()
{
return 'game.achievement';
}
/**
* Indicates whether gaining the achievement published a feed story for the user.
*
* @return boolean|null
*/
public function isNoFeedStory()
{
return $this->getField('no_feed_story');
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphAlbum
*
* @package Facebook
*/
class GraphAlbum extends GraphNode
{
/**
* @var array Maps object key names to Graph object types.
*/
protected static $graphObjectMap = [
'from' => '\Facebook\GraphNodes\GraphUser',
'place' => '\Facebook\GraphNodes\GraphPage',
];
/**
* Returns the ID for the album.
*
* @return string|null
*/
public function getId()
{
return $this->getField('id');
}
/**
* Returns whether the viewer can upload photos to this album.
*
* @return boolean|null
*/
public function getCanUpload()
{
return $this->getField('can_upload');
}
/**
* Returns the number of photos in this album.
*
* @return int|null
*/
public function getCount()
{
return $this->getField('count');
}
/**
* Returns the ID of the album's cover photo.
*
* @return string|null
*/
public function getCoverPhoto()
{
return $this->getField('cover_photo');
}
/**
* Returns the time the album was initially created.
*
* @return \DateTime|null
*/
public function getCreatedTime()
{
return $this->getField('created_time');
}
/**
* Returns the time the album was updated.
*
* @return \DateTime|null
*/
public function getUpdatedTime()
{
return $this->getField('updated_time');
}
/**
* Returns the description of the album.
*
* @return string|null
*/
public function getDescription()
{
return $this->getField('description');
}
/**
* Returns profile that created the album.
*
* @return GraphUser|null
*/
public function getFrom()
{
return $this->getField('from');
}
/**
* Returns profile that created the album.
*
* @return GraphPage|null
*/
public function getPlace()
{
return $this->getField('place');
}
/**
* Returns a link to this album on Facebook.
*
* @return string|null
*/
public function getLink()
{
return $this->getField('link');
}
/**
* Returns the textual location of the album.
*
* @return string|null
*/
public function getLocation()
{
return $this->getField('location');
}
/**
* Returns the title of the album.
*
* @return string|null
*/
public function getName()
{
return $this->getField('name');
}
/**
* Returns the privacy settings for the album.
*
* @return string|null
*/
public function getPrivacy()
{
return $this->getField('privacy');
}
/**
* Returns the type of the album.
*
* enum{ profile, mobile, wall, normal, album }
*
* @return string|null
*/
public function getType()
{
return $this->getField('type');
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphApplication
*
* @package Facebook
*/
class GraphApplication extends GraphNode
{
/**
* Returns the ID for the application.
*
* @return string|null
*/
public function getId()
{
return $this->getField('id');
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphCoverPhoto
*
* @package Facebook
*/
class GraphCoverPhoto extends GraphNode
{
/**
* Returns the id of cover if it exists
*
* @return int|null
*/
public function getId()
{
return $this->getField('id');
}
/**
* Returns the source of cover if it exists
*
* @return string|null
*/
public function getSource()
{
return $this->getField('source');
}
/**
* Returns the offset_x of cover if it exists
*
* @return int|null
*/
public function getOffsetX()
{
return $this->getField('offset_x');
}
/**
* Returns the offset_y of cover if it exists
*
* @return int|null
*/
public function getOffsetY()
{
return $this->getField('offset_y');
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
use Facebook\FacebookRequest;
use Facebook\Url\FacebookUrlManipulator;
use Facebook\Exceptions\FacebookSDKException;
/**
* Class GraphEdge
*
* @package Facebook
*/
class GraphEdge extends Collection
{
/**
* @var FacebookRequest The original request that generated this data.
*/
protected $request;
/**
* @var array An array of Graph meta data like pagination, etc.
*/
protected $metaData = [];
/**
* @var string|null The parent Graph edge endpoint that generated the list.
*/
protected $parentEdgeEndpoint;
/**
* @var string|null The subclass of the child GraphNode's.
*/
protected $subclassName;
/**
* Init this collection of GraphNode's.
*
* @param FacebookRequest $request The original request that generated this data.
* @param array $data An array of GraphNode's.
* @param array $metaData An array of Graph meta data like pagination, etc.
* @param string|null $parentEdgeEndpoint The parent Graph edge endpoint that generated the list.
* @param string|null $subclassName The subclass of the child GraphNode's.
*/
public function __construct(FacebookRequest $request, array $data = [], array $metaData = [], $parentEdgeEndpoint = null, $subclassName = null)
{
$this->request = $request;
$this->metaData = $metaData;
$this->parentEdgeEndpoint = $parentEdgeEndpoint;
$this->subclassName = $subclassName;
parent::__construct($data);
}
/**
* Gets the parent Graph edge endpoint that generated the list.
*
* @return string|null
*/
public function getParentGraphEdge()
{
return $this->parentEdgeEndpoint;
}
/**
* Gets the subclass name that the child GraphNode's are cast as.
*
* @return string|null
*/
public function getSubClassName()
{
return $this->subclassName;
}
/**
* Returns the raw meta data associated with this GraphEdge.
*
* @return array
*/
public function getMetaData()
{
return $this->metaData;
}
/**
* Returns the next cursor if it exists.
*
* @return string|null
*/
public function getNextCursor()
{
return $this->getCursor('after');
}
/**
* Returns the previous cursor if it exists.
*
* @return string|null
*/
public function getPreviousCursor()
{
return $this->getCursor('before');
}
/**
* Returns the cursor for a specific direction if it exists.
*
* @param string $direction The direction of the page: after|before
*
* @return string|null
*/
public function getCursor($direction)
{
if (isset($this->metaData['paging']['cursors'][$direction])) {
return $this->metaData['paging']['cursors'][$direction];
}
return null;
}
/**
* Generates a pagination URL based on a cursor.
*
* @param string $direction The direction of the page: next|previous
*
* @return string|null
*
* @throws FacebookSDKException
*/
public function getPaginationUrl($direction)
{
$this->validateForPagination();
// Do we have a paging URL?
if (!isset($this->metaData['paging'][$direction])) {
return null;
}
$pageUrl = $this->metaData['paging'][$direction];
return FacebookUrlManipulator::baseGraphUrlEndpoint($pageUrl);
}
/**
* Validates whether or not we can paginate on this request.
*
* @throws FacebookSDKException
*/
public function validateForPagination()
{
if ($this->request->getMethod() !== 'GET') {
throw new FacebookSDKException('You can only paginate on a GET request.', 720);
}
}
/**
* Gets the request object needed to make a next|previous page request.
*
* @param string $direction The direction of the page: next|previous
*
* @return FacebookRequest|null
*
* @throws FacebookSDKException
*/
public function getPaginationRequest($direction)
{
$pageUrl = $this->getPaginationUrl($direction);
if (!$pageUrl) {
return null;
}
$newRequest = clone $this->request;
$newRequest->setEndpoint($pageUrl);
return $newRequest;
}
/**
* Gets the request object needed to make a "next" page request.
*
* @return FacebookRequest|null
*
* @throws FacebookSDKException
*/
public function getNextPageRequest()
{
return $this->getPaginationRequest('next');
}
/**
* Gets the request object needed to make a "previous" page request.
*
* @return FacebookRequest|null
*
* @throws FacebookSDKException
*/
public function getPreviousPageRequest()
{
return $this->getPaginationRequest('previous');
}
/**
* The total number of results according to Graph if it exists.
*
* This will be returned if the summary=true modifier is present in the request.
*
* @return int|null
*/
public function getTotalCount()
{
if (isset($this->metaData['summary']['total_count'])) {
return $this->metaData['summary']['total_count'];
}
return null;
}
/**
* @inheritDoc
*/
public function map(\Closure $callback)
{
return new static(
$this->request,
array_map($callback, $this->items, array_keys($this->items)),
$this->metaData,
$this->parentEdgeEndpoint,
$this->subclassName
);
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphEvent
*
* @package Facebook
*/
class GraphEvent extends GraphNode
{
/**
* @var array Maps object key names to GraphNode types.
*/
protected static $graphObjectMap = [
'cover' => '\Facebook\GraphNodes\GraphCoverPhoto',
'place' => '\Facebook\GraphNodes\GraphPage',
'picture' => '\Facebook\GraphNodes\GraphPicture',
'parent_group' => '\Facebook\GraphNodes\GraphGroup',
];
/**
* Returns the `id` (The event ID) as string if present.
*
* @return string|null
*/
public function getId()
{
return $this->getField('id');
}
/**
* Returns the `cover` (Cover picture) as GraphCoverPhoto if present.
*
* @return GraphCoverPhoto|null
*/
public function getCover()
{
return $this->getField('cover');
}
/**
* Returns the `description` (Long-form description) as string if present.
*
* @return string|null
*/
public function getDescription()
{
return $this->getField('description');
}
/**
* Returns the `end_time` (End time, if one has been set) as DateTime if present.
*
* @return \DateTime|null
*/
public function getEndTime()
{
return $this->getField('end_time');
}
/**
* Returns the `is_date_only` (Whether the event only has a date specified, but no time) as bool if present.
*
* @return bool|null
*/
public function getIsDateOnly()
{
return $this->getField('is_date_only');
}
/**
* Returns the `name` (Event name) as string if present.
*
* @return string|null
*/
public function getName()
{
return $this->getField('name');
}
/**
* Returns the `owner` (The profile that created the event) as GraphNode if present.
*
* @return GraphNode|null
*/
public function getOwner()
{
return $this->getField('owner');
}
/**
* Returns the `parent_group` (The group the event belongs to) as GraphGroup if present.
*
* @return GraphGroup|null
*/
public function getParentGroup()
{
return $this->getField('parent_group');
}
/**
* Returns the `place` (Event Place information) as GraphPage if present.
*
* @return GraphPage|null
*/
public function getPlace()
{
return $this->getField('place');
}
/**
* Returns the `privacy` (Who can see the event) as string if present.
*
* @return string|null
*/
public function getPrivacy()
{
return $this->getField('privacy');
}
/**
* Returns the `start_time` (Start time) as DateTime if present.
*
* @return \DateTime|null
*/
public function getStartTime()
{
return $this->getField('start_time');
}
/**
* Returns the `ticket_uri` (The link users can visit to buy a ticket to this event) as string if present.
*
* @return string|null
*/
public function getTicketUri()
{
return $this->getField('ticket_uri');
}
/**
* Returns the `timezone` (Timezone) as string if present.
*
* @return string|null
*/
public function getTimezone()
{
return $this->getField('timezone');
}
/**
* Returns the `updated_time` (Last update time) as DateTime if present.
*
* @return \DateTime|null
*/
public function getUpdatedTime()
{
return $this->getField('updated_time');
}
/**
* Returns the `picture` (Event picture) as GraphPicture if present.
*
* @return GraphPicture|null
*/
public function getPicture()
{
return $this->getField('picture');
}
/**
* Returns the `attending_count` (Number of people attending the event) as int if present.
*
* @return int|null
*/
public function getAttendingCount()
{
return $this->getField('attending_count');
}
/**
* Returns the `declined_count` (Number of people who declined the event) as int if present.
*
* @return int|null
*/
public function getDeclinedCount()
{
return $this->getField('declined_count');
}
/**
* Returns the `maybe_count` (Number of people who maybe going to the event) as int if present.
*
* @return int|null
*/
public function getMaybeCount()
{
return $this->getField('maybe_count');
}
/**
* Returns the `noreply_count` (Number of people who did not reply to the event) as int if present.
*
* @return int|null
*/
public function getNoreplyCount()
{
return $this->getField('noreply_count');
}
/**
* Returns the `invited_count` (Number of people invited to the event) as int if present.
*
* @return int|null
*/
public function getInvitedCount()
{
return $this->getField('invited_count');
}
}
<?php
/**
* Copyright 2017 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\GraphNodes;
/**
* Class GraphGroup
*
* @package Facebook
*/
class GraphGroup extends GraphNode
{
/**
* @var array Maps object key names to GraphNode types.
*/
protected static $graphObjectMap = [
'cover' => '\Facebook\GraphNodes\GraphCoverPhoto',
'venue' => '\Facebook\GraphNodes\GraphLocation',
];
/**
* Returns the `id` (The Group ID) as string if present.
*
* @return string|null
*/
public function getId()
{
return $this->getField('id');
}
/**
* Returns the `cover` (The cover photo of the Group) as GraphCoverPhoto if present.
*
* @return GraphCoverPhoto|null
*/
public function getCover()
{
return $this->getField('cover');
}
/**
* Returns the `description` (A brief description of the Group) as string if present.
*
* @return string|null
*/
public function getDescription()
{
return $this->getField('description');
}
/**
* Returns the `email` (The email address to upload content to the Group. Only current members of the Group can use this) as string if present.
*
* @return string|null
*/
public function getEmail()
{
return $this->getField('email');
}
/**
* Returns the `icon` (The URL for the Group's icon) as string if present.
*
* @return string|null
*/
public function getIcon()
{
return $this->getField('icon');
}
/**
* Returns the `link` (The Group's website) as string if present.
*
* @return string|null
*/
public function getLink()
{
return $this->getField('link');
}
/**
* Returns the `name` (The name of the Group) as string if present.
*
* @return string|null
*/
public function getName()
{
return $this->getField('name');
}
/**
* Returns the `member_request_count` (Number of people asking to join the group.) as int if present.
*
* @return int|null
*/
public function getMemberRequestCount()
{
return $this->getField('member_request_count');
}
/**
* Returns the `owner` (The profile that created this Group) as GraphNode if present.
*
* @return GraphNode|null
*/
public function getOwner()
{
return $this->getField('owner');
}
/**
* Returns the `parent` (The parent Group of this Group, if it exists) as GraphNode if present.
*
* @return GraphNode|null
*/
public function getParent()
{
return $this->getField('parent');
}
/**
* Returns the `privacy` (The privacy setting of the Group) as string if present.
*
* @return string|null
*/
public function getPrivacy()
{
return $this->getField('privacy');
}
/**
* Returns the `updated_time` (The last time the Group was updated (this includes changes in the Group's properties and changes in posts and comments if user can see them)) as \DateTime if present.
*
* @return \DateTime|null
*/
public function getUpdatedTime()
{
return $this->getField('updated_time');
}
/**
* Returns the `venue` (The location for the Group) as GraphLocation if present.
*
* @return GraphLocation|null
*/
public function getVenue()
{
return $this->getField('venue');
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment