Esempio n. 1
0
 /**
  * @return FacebookSession
  */
 protected function getSession()
 {
     if (!$this->session) {
         $this->session = FacebookSession::newAppSession();
     }
     return $this->session;
 }
 /**
  * Returns the URL to send the user in order to log out of Facebook.
  * @return string|bool The url to log out
  */
 public function end()
 {
     if (is_null($this->fbsession)) {
         return false;
     }
     return $this->fbsession->getFacebookLoginHelperInstance()->getLogoutUrl(FacebookSession::newAppSession(), "/");
 }
Esempio n. 3
0
 public function register($kernel, $options = array())
 {
     FacebookSession::setDefaultApplication($options['AppId'], $options['AppSecret']);
     $kernel->facebookSession = function () use($options) {
         return FacebookSession::newAppSession();
     };
 }
Esempio n. 4
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     // Same time next week! :D
     $job = (new \App\Jobs\WeeklyMail())->delay(604800);
     $this->dispatch($job);
     // We'll just want to double-check our Facebook events still exist
     // before we email people about them...
     FacebookSession::setDefaultApplication(getenv('FB_ID'), getenv('FB_SECRET'));
     $session = FacebookSession::newAppSession();
     try {
         $session->validate();
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         dd($ex);
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         dd($ex);
     }
     $all_events = Event::where('time', '>', date('Y-m-d H:i:s'))->where('time', '<', date('Y-m-d H:i:s', time() + 604800))->get();
     foreach ($all_events as $event) {
         $request = new FacebookRequest($session, 'GET', "/" . $event->facebook_id);
         try {
             $response = $request->execute();
         } catch (\Exception $ex) {
             // Facebook Exception looking up event; probably deleted, should mirror here.
             $event->delete();
         }
     }
     foreach (User::where('unsubscribed_email', 'no') as $user) {
         $this->dispatch(new SendEmail($user));
     }
 }
Esempio n. 5
0
 public function getAppSession()
 {
     if ($this->appSession) {
         return $this->appSession;
     }
     return $this->appSession = FacebookSession::newAppSession();
 }
Esempio n. 6
0
 public function __construct($config, $logCallback = null)
 {
     if (is_callable($logCallback)) {
         $this->logCallback = $logCallback;
     }
     FacebookSession::setDefaultApplication($config['app_id'], $config['secret']);
     $this->appSession = FacebookSession::newAppSession($config['app_id'], $config['secret']);
     $this->appId = $config['app_id'];
 }
 public function testAppSessionValidates()
 {
     $session = FacebookSession::newAppSession();
     try {
         $session->validate();
     } catch (\Facebook\FacebookSDKException $ex) {
         $this->fail('Exception thrown validating app session.');
     }
 }
Esempio n. 8
0
 /**
  * @param string $appId
  * @param string $appSecret
  *
  * @throws Exception\FacebookSessionException
  */
 public function __construct($appId, $appSecret)
 {
     FacebookSession::setDefaultApplication($appId, $appSecret);
     $session = FacebookSession::newAppSession();
     if (!$session) {
         throw new FacebookSessionException(sprintf('\\C2iS\\SocialWall\\Facebook\\FacebookManager needs a valid facebook session in order to make FB API calls. Check your informations for App ID "%s"', $appId));
     }
     $this->session = $session;
 }
Esempio n. 9
0
 private static function _getChannelV4($channel)
 {
     FacebookSession::setDefaultApplication(self::FACEBOOK_APP_ID, self::FACEBOOK_SECRET_KEY);
     $session = FacebookSession::newAppSession(self::FACEBOOK_APP_ID, self::FACEBOOK_SECRET_KEY);
     $request = new FacebookRequest($session, 'GET', '/' . $channel . '/posts?fields=type,created_time,message,picture,object_id,link');
     $response = $request->execute();
     $graphObject = $response->getGraphObject();
     return $graphObject->getPropertyAsArray('data');
 }
 public function build()
 {
     if ($this->accessToken != null) {
         $session = new FacebookSession($this->accessToken);
     } else {
         $session = FacebookSession::newAppSession();
     }
     return $session;
 }
 public function example()
 {
     $application = FacebookSession::setDefaultApplication($this->config['app_id'], $this->config['app_secret']);
     $session = FacebookSession::newAppSession();
     $request = new FacebookRequest($session, 'GET', '/780788985274738');
     $response = $request->execute();
     $graphObject = $response->getGraphObject();
     $response = $this->app->json($graphObject->asArray(), 200);
     return $response;
 }
Esempio n. 12
0
 /**
  * @param $code
  * @return null
  * @throws \Facebook\FacebookRequestException
  * @throws \Facebook\FacebookSDKException
  */
 protected function getAccessToken($code)
 {
     $response = (new FacebookRequest(FacebookSession::newAppSession(), 'GET', '/oauth/access_token', ['client_id' => FacebookSession::_getTargetAppId(), 'client_secret' => FacebookSession::_getTargetAppSecret(), 'redirect_uri' => Config::get('auth.providers.facebook.redirect_uri'), 'code' => $code]))->execute()->getResponse();
     // Graph v2.3 and greater return objects on the /oauth/access_token endpoint
     $accessToken = null;
     if (is_object($response) && isset($response->access_token)) {
         $accessToken = $response->access_token;
     } elseif (is_array($response) && isset($response['access_token'])) {
         $accessToken = $response['access_token'];
     }
     return $accessToken;
 }
Esempio n. 13
0
 private static function getSession()
 {
     FacebookSession::setDefaultApplication('852604174797487', '9e20b12fb740a2f5f58287f4378d23b0');
     $session = FacebookSession::newAppSession();
     try {
         $session->validate();
         return $session;
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         echo $ex->getMessage();
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         echo $ex->getMessage();
     }
 }
Esempio n. 14
0
 /**
  * Let's get started
  */
 protected function init()
 {
     // security - ensure we only run these scripts under CLI
     $this->requireCLI();
     parent::init();
     $this->fb = FacebookSession::newAppSession();
     try {
         $this->fb->validate();
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         error_log($ex->getMessage());
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         error_log($ex->getMessage());
     }
 }
Esempio n. 15
0
 public function __construct()
 {
     $this->ci =& get_instance();
     $this->permissions = $this->ci->config->item('permissions', 'facebook');
     // Initialize the SDK
     FacebookSession::setDefaultApplication($this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook'));
     $this->session = FacebookSession::newAppSession();
     // Create the login helper and replace REDIRECT_URI with your URL
     // Use the same domain you set for the apps 'App Domains'
     // e.g. $helper = new FacebookRedirectLoginHelper( 'http://mydomain.com/redirect' );
     //$this->helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );
     /*
         if ( $this->ci->session->userdata('fb_token') ) {
           $this->session = new FacebookSession( $this->ci->session->userdata('fb_token') );
      
           // Validate the access_token to make sure it's still valid
           try {
             if ( ! $this->session->validate() ) {
               $this->session = null;
             }
           } catch ( Exception $e ) {
             // Catch any exceptions
             $this->session = null;
           }
         } else {
           // No session exists
           try {
             $this->session = $this->helper->getSessionFromRedirect();
           } catch( FacebookRequestException $ex ) {
             // When Facebook returns an error
           } catch( Exception $ex ) {
             // When validation fails or other local issues
           }
         }
      
         if ( $this->session ) {
           $this->ci->session->set_userdata( 'fb_token', $this->session->getToken() );
      
           $this->session = new FacebookSession( $this->session->getToken() );
         }*/
 }
 public function postGif(Gif $gif)
 {
     $appId = $this->container->getParameter('facebook_app_id');
     $appSecret = $this->container->getParameter('facebook_app_secret');
     $accessToken = $this->container->getParameter('facebook_access_token');
     FacebookSession::setDefaultApplication($appId, $appSecret);
     // Open Facebook SDK session
     $session = FacebookSession::newAppSession();
     // To validate the session:
     try {
         $session->validate();
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         //echo $ex->getMessage();
         return false;
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         //echo $ex->getMessage();
         return false;
     }
     $link = $this->router->generate('gif', ['permalink' => $gif->getPermalink()], true);
     $link = Util::fixSymfonyGeneratedURLs($link);
     try {
         $requestParaps = ['access_token' => $accessToken, 'link' => $link, 'message' => $gif->getCaption()];
         // Only provide picture if this is a gif
         if ($gif->getFileType() == 'gif') {
             $requestParaps['picture'] = $gif->getGifUrl();
         }
         $facebookRequest = new FacebookRequest($session, 'POST', '/joiesDeSupinfo/feed', $requestParaps);
         /*$response = */
         $facebookRequest->execute()->getGraphObject();
         //echo "Posted with id: " . $response->getProperty('id');
     } catch (FacebookRequestException $e) {
         //echo "Exception occured, code: " . $e->getCode();
         //echo " with message: " . $e->getMessage();
         return false;
     }
     return true;
 }
Esempio n. 17
0
 public function info()
 {
     FacebookSession::setDefaultApplication($this->appId, $this->appSecret);
     try {
         $session = FacebookSession::newAppSession();
     } catch (FacebookSDKException $e) {
         return ['message' => 'could not start fb session'];
     }
     if ($session) {
         $request = new FacebookRequest($session, 'GET', '/' . $this->pageId . '/feed');
         $result = [];
         try {
             $response = $request->execute();
             $posts = $response->getGraphObject()->asArray()['data'];
             $num = 1;
             foreach ($posts as &$post) {
                 // load only a limited number of posts (maxItems)
                 if ($this->property('maxItems') < $num++) {
                     break;
                 }
                 if (isset($post->object_id)) {
                     $post->image_link = $this->getPictureLink($post->object_id, $session);
                 }
                 if (isset($post->message)) {
                     $post->short = substr($post->message, 0, $this->property('maxDescription')) . '...';
                 } else {
                     $post->short = '';
                 }
                 array_push($result, $post);
             }
             return $result;
         } catch (FacebookRequestException $e) {
             return ['message' => 'could not authorize request. please check your facebook AppID, page id and secret!'];
         }
     }
     return ['message' => 'could not load feed'];
 }
Esempio n. 18
0
 public function api($params, $path, $id = false, $session = false)
 {
     if (!$this->session && ${${"GLOBALS"}["aksbebw"]}) {
         FacebookSession::enableAppSecretProof(false);
         $this->session = FacebookSession::newAppSession();
     }
     if ($this->session) {
         try {
             $tcfjgobu = "params";
             $skkiybshouo = "objects";
             ${"GLOBALS"}["bpcqqafmbh"] = "objects";
             ${"GLOBALS"}["idogdltxft"] = "path";
             ${${"GLOBALS"}["rvfbvujkf"]} = (new FacebookRequest($this->session, ${${"GLOBALS"}["idogdltxft"]}, ${$tcfjgobu}, ${${"GLOBALS"}["bwisnqcgi"]}))->execute();
             ${${"GLOBALS"}["bpcqqafmbh"]} = $request->getGraphObject()->asArray();
             return ${$skkiybshouo};
         } catch (FacebookSDKException $e) {
             return array("error" => $e->getMessage());
         } catch (FacebookRequestException $e) {
             return array("error" => $e->getMessage());
         } catch (FacebookAuthorizationException $e) {
             return array("error" => $e->getMessage());
         }
     }
 }
 /**
  * Get more info about an access token.
  *
  * @param string|null $appId
  * @param string|null $appSecret
  *
  * @return GraphSessionInfo
  */
 public function getInfo($appId = null, $appSecret = null)
 {
     $params = array('input_token' => $this->accessToken);
     $request = new FacebookRequest(FacebookSession::newAppSession($appId, $appSecret), 'GET', '/debug_token', $params);
     $response = $request->execute()->getGraphObject(GraphSessionInfo::className());
     // Update the data on this token
     if ($response->getExpiresAt()) {
         $this->expiresAt = $response->getExpiresAt();
     }
     return $response;
 }
 /**
  * Chiamata a Facebook per avere gli eventi
  *
  * @param stdClass $query openGraph
  * @return stdClass $result
  */
 function facebookCall($query)
 {
     // FACEBOOK SDK
     FacebookSession::setDefaultApplication($this->parameters->appId, $this->parameters->secretKey);
     // If you're making app-level requests:
     if ($this->session == null) {
         try {
             $this->session = FacebookSession::newAppSession();
         } catch (Exception $ex) {
             echo $ex->getMessage();
         }
         // To validate the session:
         try {
             $this->session->validate();
         } catch (FacebookRequestException $ex) {
             // Session not valid, Graph API returned an exception with the reason.
             echo $ex->getMessage();
         } catch (\Exception $ex) {
             // Graph API returned info, but it may mismatch the current app or have expired.
             echo $ex->getMessage();
         }
     }
     $request = new FacebookRequest($this->session, 'GET', "/" . $query->source, $query->params);
     $response = $request->execute();
     // get response
     $fbResult = $response->getResponse();
     return $fbResult;
 }
Esempio n. 21
0
 public function __construct()
 {
     FacebookSession::setDefaultApplication('403558916467083', 'ebe40e4b88e38c0a15dafd38d7f758e0');
     $this->session = FacebookSession::newAppSession();
 }
 public function getAppSession()
 {
     return FacebookSession::newAppSession();
 }
// Include the Config class
// NOTE: This file will not be in GitHub because it contains API keys.
// NEVER COMMIT config.php to a public GitHub repository!!
require_once 'config.php';
// Setup twitter-api-php
require_once 'lib/twitter-api-php/TwitterAPIExchange.php';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$twitterApiPhpSettings = array('oauth_access_token' => Config::Twitter_access_token, 'oauth_access_token_secret' => Config::Twitter_access_secret, 'consumer_key' => Config::Twitter_consumer_key, 'consumer_secret' => Config::Twitter_consumer_secret);
$twitter = new TwitterAPIExchange($twitterApiPhpSettings);
// Setup the FaceBook SDK
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/lib/facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/lib/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication(Config::FaceBook_App_Id, Config::FaceBook_App_Secret);
$facebookSession = FacebookSession::newAppSession();
// To validate the session:
try {
    $facebookSession->validate();
} catch (FacebookRequestException $ex) {
    // Session not valid, Graph API returned an exception with the reason.
    echo $ex->getMessage();
} catch (\Exception $ex) {
    // Graph API returned info, but it may mismatch the current app or have expired.
    echo $ex->getMessage();
}
// Instantiate the Slim app
require 'lib/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');
Esempio n. 24
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     if ($this->isSeeding) {
         $toTake = 200;
         // 200 societies
         $delay = 0;
         // Immediately
     } else {
         $toTake = 20;
         // 20 societies
         $delay = 600;
         // 10 Minutes
     }
     FacebookSession::setDefaultApplication(getenv('FB_ID'), getenv('FB_SECRET'));
     $session = FacebookSession::newAppSession();
     try {
         $session->validate();
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         dd($ex);
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         dd($ex);
     }
     $store = \App\Setting::where('name', 'next_society')->first();
     $lastUpdated = $store->setting;
     // Get last society ID updated;
     $societies = \App\Society::where('id', '>', $lastUpdated)->take($toTake)->orderBy('id')->get();
     // Get Societies to query
     foreach ($societies as $society) {
         $request = new FacebookRequest($session, 'GET', '/' . $society->facebook_ref . '/events' . '?since=' . time() . '&fields=name,start_time,location,description,cover');
         try {
             $response = $request->execute();
         } catch (\Exception $ex) {
             continue;
             // TODO: Report errors back to us :)
         }
         $graphObject = $response->getGraphObject();
         $events = $graphObject->asArray();
         if (array_key_exists('data', $events)) {
             $events = $events['data'];
             foreach ($events as $fbEvent) {
                 $storedEvent = \App\Event::firstOrNew(['facebook_id' => $fbEvent->id]);
                 $storedEvent->society_id = $society->id;
                 $storedEvent->title = $fbEvent->name;
                 $storedEvent->time = $fbEvent->start_time;
                 if (array_key_exists("description", $fbEvent)) {
                     $storedEvent->description = $fbEvent->description;
                 }
                 if (array_key_exists("location", $fbEvent)) {
                     $storedEvent->location = $fbEvent->location;
                 }
                 if (array_key_exists("cover", $fbEvent)) {
                     $storedEvent->image = $fbEvent->cover->source;
                 }
                 $storedEvent->save();
             }
         }
     }
     if (count($societies) < $toTake) {
         $store->setting = 0;
     } else {
         $store->setting += $toTake;
     }
     $store->save();
     $job = (new \App\Jobs\UpdateEvents())->delay($delay);
     if (!$this->isSeeding) {
         $this->dispatch($job);
     }
 }
Esempio n. 25
0
 /**
  * Publish on fan page by access token text or images jpg
  *
  * Type of post is different 1.Only text  2.Post jpg image 3.Video post
  *
  * @param $data indexs are token, pageID, pageName, message,link, files (should be root path)
  * @return mixed
  *
  */
 public function postOnPage($data)
 {
     $session = new \Facebook\FacebookSession($data['token']);
     $session = \Facebook\FacebookSession::newAppSession();
     try {
         if (!empty($data['files']) & file_exists($data['files'])) {
             $response = (new \Facebook\FacebookRequest($session, 'POST', '/' . $data['pageID'] . '/picture', array('access_token' => $data['token'], 'message' => $data['message'], 'source' => new CURLFile($data['files'], 'image/jpg'), 'place' => $data['place'])))->execute()->getGraphObject()->asArray();
         } else {
             $response = (new \Facebook\FacebookRequest($session, 'POST', '/' . $data['pageID'] . '/feed', array('access_token' => $data['token'], 'message' => $data['message'], 'link' => $data['link'])))->execute()->getGraphObject()->asArray();
         }
         $response['successMessage'] = 'Post has been successfully executed on ' . $data['pageName'];
         $response['status'] = true;
         return $response;
     } catch (\Facebook\FacebookRequestException $e) {
         $response['exceptionCode'] = $e->getCode();
         $response['exceptionMessage'] = $e->getMessage();
         $response['status'] = false;
         return $response;
     }
 }
Esempio n. 26
0
 public function fbAuthAction()
 {
     $this->view->disable();
     $params = array('client_id' => FacebookSession::_getTargetAppId($this->config->facebook->appId), 'redirect_uri' => $this->config->facebook->redirect, 'client_secret' => FacebookSession::_getTargetAppSecret($this->config->facebook->secret), 'code' => isset($_GET['code']) ? $_GET['code'] : null);
     $response = (new FacebookRequest(FacebookSession::newAppSession($this->config->facebook->appId, $this->config->facebook->secret), 'GET', '/oauth/access_token', $params))->execute()->getResponse();
     if (isset($response['access_token'])) {
         $session = new FacebookSession($response['access_token']);
     }
     if (isset($session)) {
         $userSession['access_token'] = $response['access_token'];
         $request = new FacebookRequest($session, 'GET', '/me');
         $response = $request->execute();
         // get response
         $graphObject = $response->getGraphObject();
         $email = $graphObject->getProperty('email');
         $fbId = $graphObject->getProperty('id');
         $verified = $graphObject->getProperty('verified');
         $firstName = $graphObject->getProperty('first_name');
         $lastName = $graphObject->getProperty('last_name');
         $fullName = $graphObject->getProperty('name');
         $gender = $graphObject->getProperty('gender');
         $profileLink = $graphObject->getProperty('link');
         $bday = $graphObject->getProperty('birthday');
         $email = $graphObject->getProperty('email');
         $city = $graphObject->getProperty('location')->getProperty('name');
         if (!isset($email)) {
             $email = $fbId . '@facebook.com';
         }
         if (isset($bday)) {
             $bday = date('Y-m-d', strtotime($bday));
         }
         $socialData = array('social_network' => 'Facebook', 'social_id' => $fbId, 'first_name' => $firstName, 'last_name' => $lastName, 'full_name' => $fullName, 'gender' => $gender, 'profile_link' => $profileLink, 'birthday' => $bday, 'email' => $email, 'city' => $city, 'access_token' => $userSession['access_token']);
         if ($member = Members::findFirstByEmail($email)) {
             $userSession = get_object_vars($member);
             if (!($socialProfile = SocialProfiles::findFirstByEmail($email))) {
                 $socialData['member_id'] = $member->id;
                 $this->newSocialProfile($socialData);
             }
         } else {
             $memberId = $this->newMember($socialData);
             $socialData['id'] = $memberId;
             $userSession = $socialData;
             $socialData['member_id'] = $memberId;
             $this->newSocialProfile($socialData);
         }
         //print_r($graphObject);
         $this->session->set('userSession', $userSession);
     }
     return $this->response->redirect();
 }
 public function loginAsApp()
 {
     $this->session = FacebookSession::newAppSession();
     return $this;
 }
Esempio n. 28
0
function fbe_facebook_sdk($facebook_page,$appID,$appSecret){


		FacebookSession::setDefaultApplication($appID,$appSecret);

		$session = FacebookSession::newAppSession();

		try {
			  $session->validate();
		} 
			
		catch (FacebookRequestException $ex) {
			echo $ex->getMessage();
		} 
			
		catch (\Exception $ex) {
			echo $ex->getMessage();
		}


		$i=0;
		$u=0;


		try{

			$eventResponse = (new FacebookRequest($session, 'GET', '/'.$facebook_page.'/events?fields=place,cover,attending_count,description,end_time,id,name,owner,start_time,ticket_uri,timezone&limit=99'))->execute()->getResponse();
			$events = $eventResponse->data;

			foreach ($events as $e) {	
				$session = FacebookSession::newAppSession();
				$venue = (new FacebookRequest($session, 'GET', '/'.$facebook_page.'?fields=phone,photos,username,about,category,cover,emails,general_info,general_manager,location,website&limit=99'))->execute()->getResponse();

				$startDate = $e->start_time;
				$endDate = $e->end_time;
				$timezone = $e->timezone;

				// Convert time for myEventON
				$c_evcal_srow = date("U",strtotime($startDate));
				$c_evcal_erow = date("U",strtotime($endDate));
				$custom_year = date("U",strtotime($StartDate));
				$c_event_year = gmdate("Y", $custom_year);
				//
				
				$category = $e->owner->category;


				$event_id = $e->id;
				$eId = wp_strip_all_tags($e->id);	
				$city = $e->place->location->city;
				$state = $e->place->location->state;
				$zip = $e->place->location->zip;
				$street = $e->place->location->street;
				$region = $e->place->location->region;
				$country = $e->place->location->country;
				$ticket_uri = $e->ticket_uri;
				$eventImage = $e->cover->source;
				$name = $e->place->name;
				$fb_event_uri = 'https://www.facebook.com/events/'.$event_id;
				$lat = $e->place->location->latitude;
				$long = $e->place->location->longitude;

				$venue_name = $e->place->name;
				$venue_phone = $venue->phone;
				$venue_desc = $venue->about;
				$emails = $venue->emails;
				$username = $venue->username; 
				$emailAddress = $emails[0];
				$venue_website = $venue->website;	
				$event_tag = $venue->category;	

				////PRINT
				////$posts_array = get_posts('post_type=post_title');
				////print_r($posts_array);
				//print_r($e->place->name);
				////PRINT
	
				if($state){
					$state = $state.'&nbsp;';
				}
				if($street){
					$street = $street.',&nbsp;';
				}
				if($city){
					$city = $city.',&nbsp;';
				}
				if($country){
					$country = $country.'&nbsp;';
				}
				if($region){
					$region = $region.'&nbsp;';
				}
				 if($zip){
					$zip = $zip.'&nbsp;';
				}

				$location = $street.$city.$state.$zip.$country.$region ;
				$location = str_replace('<<not-applicable>>', '', $location);
				if($location == '&nbsp;' || $location == '' ){
				$location = getaddress(get_fbe_field($lat),get_fbe_field($long));
				}


				$args = array (
				'post_type' => 'facebook_events',
				'posts_per_page' => -1,
				'meta_key' => 'facebook_event_id',
				'meta_query' => array(
						'key'		=> 'facebook_event_id',
						'value'		=> $event_id,
					),
				);
				
				$loop = new WP_Query( $args );
			    if( $loop->have_posts() ){ 
					$u++;	
					while ( $loop->have_posts() ) : $loop->the_post();
						
					  $post_id = get_the_ID();
					  $curEventImage = get_post_meta( $post_id, 'image_url', true );
					  $post_information = array(
							'post_type' => 'facebook_events',
							'ID' => $post_id,
							'post_title' => wp_strip_all_tags($e->name),
							'post_content' => wp_strip_all_tags($e->description),
							'tags_input' => $event_tag,
						);
						 
						if($eventImage != $curEventImage ){insert_image($eventImage,$post_id); }
						 
						wp_update_post( $post_information );
						
					endwhile;
				}
				else
				{ 
				$post_information = array(
					'post_type' => 'facebook_events',
					'post_title' => wp_strip_all_tags($e->name),
					'post_content' => wp_strip_all_tags($e->description),
					'post_status' => 'publish',
					'tags_input' => $event_tag,
				);		
	        
			 $post_id = wp_insert_post( $post_information ); 
			 insert_image($eventImage,$post_id); 
	           

			}
			/*	$i++;

				update_post_meta($post_id,'event_timezone',$timezone);
				update_post_meta($post_id,'start_time',$startDate);
				update_post_meta($post_id,'event_starts',$startDate);
				update_post_meta($post_id,'event_starts_sort_field',$startDate);
				update_post_meta($post_id,'event_ends',$endDate);
				update_post_meta($post_id,'end_time', $endDate);
				update_post_meta($post_id,'facebook_event_id', $eId);
				update_post_meta($post_id,'location',$location);
				update_post_meta($post_id,'ticket_uri',$ticket_uri);
				update_post_meta($post_id,'fb_event_uri',$fb_event_uri);
				update_post_meta($post_id,'geo_latitude',$lat);
				update_post_meta($post_id,'geo_longitude',$long);			
				update_post_meta($post_id,'venue_email',$emailAddress);	
				update_post_meta($post_id,'venue_phone',$phone);	
				update_post_meta($post_id,'venue_website',$website);
				update_post_meta($post_id,'facebook','https://facebook.com/'.$username);
				update_post_meta($post_id,'venue_desc',$venue_desc);
				update_post_meta($post_id,'venue_name',$venue_name);
				*/
			
				/////////////////////////////////////
				// Get the Old Post
				$old_post = get_post( $post_id );

				//$my_post_meta = get_post_meta($post_id, 'image_url', true);
				
				
				$args = array(
					'numberposts' => 1,
					'order'=> 'DESC',
					'post_mime_type' => 'image',
					'post_parent' => $post->ID,
					'post_type' => 'attachment'
					);

				$get_children_array = get_children($args,ARRAY_A);  //returns Array ( [$image_ID]... 
				$rekeyed_array = array_values($get_children_array);
				$child_image = $rekeyed_array[0];  

				// Show Facebook Events ID & Title
				echo "FB_Id		-$post_id<br>";
				echo "FB_Title	-$old_post->post_title <br>";


				//print_r($child_image);  	//Show the contents of the $child_image array.
				//echo "Show the $child_image ID";
				echo "Image_Id   -";
				echo $child_image['ID'];   	//Show the $child_image ID.
				echo "<br>";
				
				$post_image_media = get_post_meta($child_image['ID'], '_wp_attached_file', true);
				echo "Media_file - $post_image_media <br>"; //image location 2015/08/11800415_396471520542665_8991308386259432158_n142.jpg
				
				
				
				
				
				
				$new_post = array(
					'post_status'    => 'publish',
					'menu_order'     => $old_post->menu_order,
					'post_type'      => 'ajde_events',
					'comment_status' => $old_post->comment_status,
					'ping_status'    => $old_post->ping_status,
					'pinged'         => $old_post->pinged,
					'post_author'    => $old_post->post_author,
					'post_category'  => $old_post->post_category,
					'post_content'   => $old_post->post_content,
					'post_excerpt'   => $old_post->post_excerpt,
					'post_name'      => $old_post->post_name,
					'post_parent'    => $old_post->post_parent,
					'post_password'  => $old_post->post_password,
					'post_title'     => $old_post->post_title,
					'tags_input'     => $old_post->tags_input,
					'to_ping'        => $old_post->to_ping,
					'tax_input'      => $old_post->tax_input,
				);
				
				$new_post_id = wp_insert_post( $new_post ); 
				/////////////////////////////////////////
				update_post_meta($new_post_id,'_thumbnail_id', $child_image['ID']);
				
				echo "New_Post_Id- $new_post_id<br>";
				echo "$new_post_id - _thumbnail_id - ";
				echo $child_image['ID'];
				echo "<br>";
				echo "______________________ <br><br>";
				
				$i++;
				/*
				update_post_meta($new_post_id,'evcal_event_color', 206177);
				update_post_meta($new_post_id,'evcal_location', $location);
				update_post_meta($new_post_id,'evcal_location_name', $venue_name);
				update_post_meta($new_post_id,'evcal_name_over_img', no);
				//	update_post_meta($new_post_id,'evcal_organizer', HHHEventOrganizerNameHHH);
				//	update_post_meta($new_post_id,'evcal_org_contact', $emailAddress);
				//	update_post_meta($new_post_id,'evcal_lmlink', JJJEventLinkJJJ);
				update_post_meta($new_post_id,'evcal_subtitle', $venue_desc);
				update_post_meta($new_post_id,'evcal_gmap_gen', yes);
				update_post_meta($new_post_id,'evcal_repeat', no);
				update_post_meta($new_post_id,'evcal_rep_freq', daily);
				update_post_meta($new_post_id,'evcal_rep_gap', 1);
				update_post_meta($new_post_id,'evcal_rep_num', 1);
				update_post_meta($new_post_id,'evp_repeat_rb', dom);
				update_post_meta($new_post_id,'evo_repeat_wom', none);
				update_post_meta($new_post_id,'_evcal_exlink_option', 1);
				update_post_meta($new_post_id,'evo_hide_endtime', no);
				update_post_meta($new_post_id,'evo_span_hidden_end', no);
				update_post_meta($new_post_id,'evo_year_long', no);
				update_post_meta($new_post_id,'event_year', $c_event_year);
				update_post_meta($new_post_id,'evo_evcrd_field_org', no);
				update_post_meta($new_post_id,'evo_exclude_ev', no);
				update_post_meta($new_post_id,'_cancel', no);
				update_post_meta($new_post_id,'evcal_lat', $lat);
				update_post_meta($new_post_id,'evcal_lon', $long);
				update_post_meta($new_post_id,'evcal_srow', $c_evcal_srow);
				update_post_meta($new_post_id,'evcal_erow', $c_evcal_erow);
				update_post_meta($new_post_id,'_evcal_ec_f1a1_cus', Link);
				update_post_meta($new_post_id,'_evcal_ec_f1a1_cusL', $fb_event_uri);
				update_post_meta($new_post_id,' _evcal_ec_f1_onw', yes);
				update_post_meta($new_post_id,'_evcal_ec_f2a1_cus', Buy);
				update_post_meta($new_post_id,'_evcal_ec_f2a1_cusL', $ticket_uri);
				update_post_meta($new_post_id,'_evcal_ec_f2_onw', yes);
				*/
				
				// Image
			
				
				


			
				
			}  


			$a ='';
			$c ='';
			$n ='';

			$error ='';
			if($u > 1){
				$c = $u;
				$a = $i-$u;
				$n = 'updated';
			}
			
			else
			
			{
			$c = $i;
			$n = 'imported';
			}

		} 
	
		catch(Exception $ex){

			$error  = $ex->getCode();
			$errorMsg  = $ex->getMessage();

			if($error == 100 ){
				echo '<div class="error" style="color:#222222; font-weight:700; font-size:1em; padding:10px">Error '.$error.': <a href="https://www.facebook.com/'.$facebook_page.'/events" target="_blank">'.$facebook_page.'</a>. <i> Country or age restricted material. Check your app settings.</i> </div>';
			}
			
			else if ($error == 102){	
				echo '<div class="error" style="color:#222222; font-weight:700; font-size:1em; padding:10px">Error '.$error.': Session key invalid or no longer valid.</div>';
			}
			
			else
				
			{
				echo '<div class="error" style="color:#222222; font-weight:700; font-size:1em; padding:10px">Error '.$error.'&nbsp;'.$errorMsg .'&nbsp;: Troubleshooting tip <a href="https://developers.facebook.com/docs/marketing-api/error-reference" target="_blank">View API Error Codes</a></div>';
			}

		}
		
		if($a >= 1){
			echo '<div class="updated" style="color:#222222; font-weight:700; font-size:1em; padding:10px">'.$a. ' events added</div>';
		}
		
		if($i > 1){
			echo '<div class="updated" style="color:#222222; font-weight:700; font-size:1em; padding:10px">'.$c . ' events '.$n.'</div>';
		}
		
		else if($i == 0){
			 if($error != 100){
			 echo '<div class="updated" style="color:#222222; font-weight:700; font-size:1em; padding:10px">There are <b>no upcoming</b> events to import at <a href="https://www.facebook.com/'.$facebook_page.'/events" target="_blank">'.$facebook_page.'</a></div>';
				}
		}
		
		else
		
		{
			echo '<div class="updated" style="color:#222222; font-weight:700; font-size:1em; padding:10px">'.$c . ' event '.$n.'</div>';
		}

	}