Sending messages with facebook xmpp api - facebook

I have copied and modified some of the facebook's given chat api code, now I want to send a message to my friend. I found that we send a xml <message from="" to=""> to send a message. But that did not happen. maybe it's because i don't know what to put on from and to attribs?
The Code:
<?php
$STREAM_XML = '<stream:stream '.
'xmlns:stream="http://etherx.jabber.org/streams" '.
'version="1.0" xmlns="jabber:client" to="chat.facebook.com" '.
'xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
$AUTH_XML = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" '.
'mechanism="X-FACEBOOK-PLATFORM"></auth>';
$CLOSE_XML = '</stream:stream>';
$RESOURCE_XML = '<iq type="set" id="3">'.
'<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'.
'<resource>fb_xmpp_script</resource></bind></iq>';
$SESSION_XML = '<iq type="set" id="4" to="chat.facebook.com">'.
'<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>';
$START_TLS = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
$MESSAGE = '<message from="-cyberkiller.nishchal#chat.facebook.com" to="-nootan.ghimire#chat.facebook.com">
<body>This is the test message! Sent from App. by, "Nishchal"</body>
</message>';
function open_connection($server) {
$fp = fsockopen($server, 5222, $errno, $errstr);
if (!$fp) {
print "$errstr ($errno)<br>";
} else {
print "connnection open<br>";
}
return $fp;
}
function send_xml($fp, $xml) {
fwrite($fp, $xml);
}
function recv_xml($fp, $size=4096) {
$xml = fread($fp, $size);
if (!preg_match('/^</', $xml)) {
$xml = '<' . $xml;
}
if ($xml === "") {
return null;
}
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml, $val, $index);
xml_parser_free($xml_parser);
return array($val, $index);
}
function find_xmpp($fp, $tag, $value=null, &$ret=null) {
static $val = null, $index = null;
do {
if ($val === null && $index === null) {
list($val, $index) = recv_xml($fp);
if ($val === null || $index === null) {
return false;
}
}
foreach ($index as $tag_key => $tag_array) {
if ($tag_key === $tag) {
if ($value === null) {
if (isset($val[$tag_array[0]]['value'])) {
$ret = $val[$tag_array[0]]['value'];
}
return true;
}
foreach ($tag_array as $i => $pos) {
if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
$val[$pos]['value'] === $value) {
$ret = $val[$pos]['value'];
return true;
}
}
}
}
$val = $index = null;
} while (!feof($fp));
return false;
}
function xmpp_connect($options, $access_token) {
global $STREAM_XML, $AUTH_XML, $RESOURCE_XML, $SESSION_XML, $CLOSE_XML, $START_TLS;
$fp = open_connection($options['server']);
if (!$fp) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $START_TLS);
if (!find_xmpp($fp, 'PROCEED', null, $proceed)) {
return false;
}
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $AUTH_XML);
if (!find_xmpp($fp, 'CHALLENGE', null, $challenge)) {
return false;
}
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_array);
$resp_array = array(
'method' => $challenge_array['method'],
'nonce' => $challenge_array['nonce'],
'access_token' => $access_token,
'api_key' => $options['app_id'],
'call_id' => 0,
'v' => '1.0',
);
$response = http_build_query($resp_array);
$xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">'.
base64_encode($response).'</response>';
send_xml($fp, $xml);
if (!find_xmpp($fp, 'SUCCESS')) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp,'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'STREAM:FEATURES')) {
return false;
}
send_xml($fp, $RESOURCE_XML);
if (!find_xmpp($fp, 'JID')) {
return false;
}
send_xml($fp, $SESSION_XML);
if (!find_xmpp($fp, 'SESSION')) {
return false;
}
send_xml($fp, $MESSAGE);
if (!find_xmpp($fp, 'BODY')) {
return false;
}
send_xml($fp, $CLOSE_XML);
print ("Authentication complete<br>");
fclose($fp);
return true;
}
function get_access_token(){
$token=new Facebook(array("AppId"=>"my app id","AppSecret"=>"my app secret"));
$token=$facebook->getAccessToken();
return $token;
}
function _main() {
require_once("facebook.php");
$app_id='app id';
$app_secret='app secret';
$my_url = "http://localhost/message.php";
$uid = 'cyberkiller.nishchal#chat.facebook.com';
$access_token = get_access_token();
$options = array(
'uid' => $uid,
'app_id' => $app_id,
'server' => 'chat.facebook.com',
);
if (xmpp_connect($options, $access_token)) {
print "Done<br>";
} else {
print "An error ocurred<br>";
}
}
_main();
so what do I need to do to send a message to that user through this, i tried to create a xml with the message but got strucked there, can any one please suggest something, When I run the code, socket enable crypto is being executed after that it is taking some time like 20 secs, then it displays an error occured, do I have to remove the send_xml($fp,$STREAM_XML); for the second time after the stream_socket_enable_crypto($fp, false, STREAM_CRYPTO_METHOD_TLS_CLIENT);
I changed the second parameter of this call to false because I don't have an ssl connection, what should I do next?

Use Facebook ID instead of the url username.Get it by requesting http://graph.facebook.com/{username}
Then replace it on "from" and "to" attributes.Also remove the hyphen on "from" attribute, or just remove all of it (from my experience its still going to work).Hyphen on "to" attribute is mandatory.

Related

a function is giving me an error about a comma

function emptyInputSignup($fname, $lname, $email, $username, $pwd, $pwdrepeat) {
$result = null;
if (empty($fname) || empty($lname) || empty($email) || empty($username) || empty($pwd) || empty($pwdrepeat)) {
$result = true;
} else {
$result = false;
}
return $result;
};
function invalidUid($username) {
$result = null;
if (!preg_match('/^[a-zA-Z0-9]*$/'), $username) {
$result = true;
} else {
$result = false;
}
return $result;
}
What have I donr wrong, what does it want, i literally copied the emptyInputSignup function and then wrote some regex in and vscode is confused
I've stared at it for an hour, when I google for regex not working properly, I couldn't find anyone having similar problems.
You need to put , $username inside the preg_match function parenthesis, after the regex pattern. It is in the wrong place.
It should be:
if (!preg_match('/^[a-zA-Z0-9]*$/', $username)) {
$result = true;
} else {
$result = false;
}

Webmaster Tool Api Crawl Optimize

By using webmaster tool API to parse data from google. The speed of downloading is very slow, Is there any way to optimize, Or use another method. It can take more than hour depending on the data.
Regards.
const HOST = "https://www.google.com";
const SERVICEURI = "/webmasters/tools/";
public function __construct()
{
$this->_auth = $this->_loggedIn = $this->_domain = false;
$this->_data = array();
}
public function getArray($domain)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
return $this->_data;
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getCsv($domain, $localPath = false)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
if (!$localPath) {
$this->_HttpHeaderCSV();
$this->_outputCSV();
} else {
$this->_outputCSV($localPath);
}
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getSites()
{
if ($this->_loggedIn) {
$feed = $this->_getData('feeds/sites/');
if ($feed) {
$doc = new DOMDocument();
$doc->loadXML($feed);
$sites = array();
foreach ($doc->getElementsByTagName('entry') as $node) {
array_push($sites, $node->getElementsByTagName('title')->item(0)->nodeValue);
}
return (0 < sizeof($sites)) ? $sites : false;
} else {
return false;
}
} else {
return false;
}
}
public function login($mail, $pass)
{
$postRequest = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => $mail,
'Passwd' => $pass,
'service' => "sitemaps",
'source' => "Google-WMTdownloadscript-0.11-php"
);
// Before PHP version 5.2.0 and when the first char of $pass is an # symbol,
// send data in CURLOPT_POSTFIELDS as urlencoded string.
if ('#' === (string) $pass[0] || version_compare(PHP_VERSION, '5.2.0') < 0) {
$postRequest = http_build_query($postRequest);
}
$ch = curl_init(self::HOST . '/accounts/ClientLogin');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postRequest,
));
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if (200 != $info['http_code']) {
throw new Exception('Login failed!');
exit;
} else {
#preg_match('/Auth=(.*)/', $output, $match);
if (isset($match[1])) {
$this->_auth = $match[1];
$this->_loggedIn = true;
return true;
} else {
throw new Exception('Login failed!');
exit;
}
}
}
private function _prepareData()
{
if ($this->_loggedIn) {
$currentIndex = 1;
$maxResults = 100;
$encUri = urlencode($this->_domain);
/*
* Get the total result count / result page count
*/
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index=1&max-results=1");
if (!$feed) {
return false;
}
$doc = new DOMDocument();
$doc->loadXML($feed);
$totalResults = (int) $doc->getElementsByTagNameNS('http://a9.com/-/spec/opensearch/1.1/', 'totalResults')->item(0)->nodeValue;
$resultPages = (0 != $totalResults) ? ceil($totalResults / $maxResults) : false;
unset($feed, $doc);
if (!$resultPages) {
return false;
}
/*
* Paginate over issue feeds
*/
else {
// Csv data headline
$this->_data = Array(
Array(
'Issue Id',
'Crawl type',
'Issue type',
'Detail',
'URL',
'Date detected',
'Last detected'
)
);
while ($currentIndex <= $resultPages) {
$startIndex = ($maxResults * ($currentIndex - 1)) + 1;
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index={$startIndex}&max-results={$maxResults}");
$doc = new DOMDocument();
$doc->loadXML($feed);
foreach ($doc->getElementsByTagName('entry') as $node) {
$issueId = str_replace(self::HOST . self::SERVICEURI . "feeds/{$encUri}/crawlissues/", '', $node->getElementsByTagName('id')->item(0)->nodeValue);
$crawlType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'crawl-type')->item(0)->nodeValue;
$issueType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'issue-type')->item(0)->nodeValue;
$detail = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'detail')->item(0)->nodeValue;
$url = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'url')->item(0)->nodeValue;
$dateDetected = date('d/m/Y', strtotime($node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'date-detected')->item(0)->nodeValue));
$updated = date('d/m/Y', strtotime($node->getElementsByTagName('updated')->item(0)->nodeValue));
// add issue data to results array
array_push($this->_data, Array(
$issueId,
$crawlType,
$issueType,
$detail,
$url,
$dateDetected,
$updated
));
}
unset($feed, $doc);
$currentIndex++;
}
return true;
}
} else {
return false;
}
}
private function _getData($url)
{
if ($this->_loggedIn) {
$header = array(
'Authorization: GoogleLogin auth=' . $this->_auth,
'GData-Version: 2'
);
$ch = curl_init(self::HOST . self::SERVICEURI . $url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_ENCODING => 1,
CURLOPT_HTTPHEADER => $header
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (200 != $info['http_code']) ? false : $result;
} else {
return false;
}
}
private function _HttpHeaderCSV()
{
header('Content-type: text/csv; charset=utf-8');
header('Content-disposition: attachment; filename=gwt-crawlerrors-' . $this->_getFilename());
header('Pragma: no-cache');
header('Expires: 0');
}
private function _outputCSV($localPath = false)
{
$outstream = !$localPath ? 'php://output' : $localPath . DIRECTORY_SEPARATOR . $this->_getFilename();
$outstream = fopen($outstream, "w");
if (!function_exists('__outputCSV')) {
function __outputCSV(&$vals, $key, $filehandler)
{
fputcsv($filehandler, $vals); // add parameters if you want
}
}
array_walk($this->_data, "__outputCSV", $outstream);
fclose($outstream);
}
private function _getFilename()
{
return 'gwt-crawlerrors-' . parse_url($this->_domain, PHP_URL_HOST) . '-' . date('Ymd-His') . '.csv';
}
private function _validateDomain($domain)
{
if (!filter_var($domain, FILTER_VALIDATE_URL)) {
return false;
}
$sites = $this->getSites();
if (!$sites) {
return false;
}
foreach ($sites as $url) {
if (parse_url($domain, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) {
$this->_domain = $domain;
return true;
}
}
return false;
}
The url from Google is in error Google has added a false extension look carefully and you will see it.
Google Crap!
Your site is probably fine.

access_token facebook sign up says "Trying to get property of non-object"

I am having some "Trying to get property of non-object" issue with facebook sign up. The server returns errors related to access_token.
i have error form line 490 and 451. on line 451 i succeed to solve it but i ve still 2 errors from line 490.
the line was fixed by changing if ( $token->access_token ) by if ( $token['access_token'] )
I think the problem is due to codeigniter.
the line 490 is the following one:
private function _token_string()
{
return 'access_token='.$this->_get('token')->access_token;
}
Here is the entire code:
class Facebook_Lib extends CI_Config
{
private $_api_url;
private $_api_key;
private $_api_secret;
private $_errors = array();
private $_enable_debug = FALSE;
function __construct()
{
$this->_obj =$CI =& get_instance();
$this->_obj->load->library('session');
$this->_obj->load->helper('url');
$this->_obj->load->helper('facebook');
$fb_api_id = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_ID'))->row()->string_value;
$fb_api_secret = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_SECRET'))->row()->string_value;
$this->_api_url = $this->_obj->config->item('facebook_api_url');
$this->_api_key = $fb_api_id;
$this->_api_secret = $fb_api_secret;
$this->session = new facebookSession();
$this->connection = new facebookConnection();
}
public function logged_in()
{
return $this->session->logged_in();
}
public function login($scope = NULL)
{
return $this->session->login($scope);
}
public function login_url($scope = NULL)
{
return $this->session->login_url($scope);
}
public function logout()
{
return $this->session->logout();
}
public function user()
{
return $this->session->get();
}
public function call($method, $uri, $data = array())
{
$response = FALSE;
try
{
switch ( $method )
{
case 'get':
$response = $this->connection->get($this->append_token($this->_api_url.$uri));
break;
case 'post':
$response = $this->connection->post($this->append_token($this->_api_url.$uri), $data);
break;
}
}
catch (facebookException $e)
{
$this->_errors[] = $e;
if ( $this->_enable_debug )
{
echo $e;
}
}
return $response;
}
public function errors()
{
return $this->_errors;
}
public function last_error()
{
if ( count($this->_errors) == 0 ) return NULL;
return $this->_errors[count($this->_errors) - 1];
}
public function append_token($url)
{
return $this->session->append_token($url);
}
public function set_callback($url)
{
return $this->session->set_callback($url);
}
public function enable_debug($debug = TRUE)
{
$this->_enable_debug = (bool) $debug;
}
}
class facebookConnection {
// Allow multi-threading.
private $_mch = NULL;
private $_properties = array();
function __construct()
{
$this->_mch = curl_multi_init();
$this->_properties = array(
'code' => CURLINFO_HTTP_CODE,
'time' => CURLINFO_TOTAL_TIME,
'length' => CURLINFO_CONTENT_LENGTH_DOWNLOAD,
'type' => CURLINFO_CONTENT_TYPE
);
}
private function _initConnection($url)
{
$this->_ch = curl_init($url);
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, TRUE);
}
public function get($url, $params = array())
{
if ( count($params) > 0 )
{
$url .= '?';
foreach( $params as $k => $v )
{
$url .= "{$k}={$v}&";
}
$url = substr($url, 0, -1);
}
$this->_initConnection($url);
$response = $this->_addCurl($url, $params);
return $response;
}
public function post($url, $params = array())
{
// Todo
$post = '';
foreach ( $params as $k => $v )
{
$post .= "{$k}={$v}&";
}
$post = substr($post, 0, -1);
$this->_initConnection($url, $params);
curl_setopt($this->_ch, CURLOPT_POST, 1);
curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $post);
$response = $this->_addCurl($url, $params);
return $response;
}
private function _addCurl($url, $params = array())
{
$ch = $this->_ch;
$key = (string) $ch;
$this->_requests[$key] = $ch;
$response = curl_multi_add_handle($this->_mch, $ch);
if ( $response === CURLM_OK || $response === CURLM_CALL_MULTI_PERFORM )
{
do {
$mch = curl_multi_exec($this->_mch, $active);
} while ( $mch === CURLM_CALL_MULTI_PERFORM );
return $this->_getResponse($key);
}
else
{
return $response;
}
}
private function _getResponse($key = NULL)
{
if ( $key == NULL ) return FALSE;
if ( isset($this->_responses[$key]) )
{
return $this->_responses[$key];
}
$running = NULL;
do
{
$response = curl_multi_exec($this->_mch, $running_curl);
if ( $running !== NULL && $running_curl != $running )
{
$this->_setResponse($key);
if ( isset($this->_responses[$key]) )
{
$response = new facebookResponse( (object) $this->_responses[$key] );
if ( $response->__resp->code !== 200 )
{
$error = $response->__resp->code.' | Request Failed';
if ( isset($response->__resp->data->error->type) )
{
$error .= ' - '.$response->__resp->data->error->type.' - '.$response->__resp->data->error->message;
}
throw new facebookException($error);
}
return $response;
}
}
$running = $running_curl;
} while ( $running_curl > 0);
}
private function _setResponse($key)
{
while( $done = curl_multi_info_read($this->_mch) )
{
$key = (string) $done['handle'];
$this->_responses[$key]['data'] = curl_multi_getcontent($done['handle']);
foreach ( $this->_properties as $curl_key => $value )
{
$this->_responses[$key][$curl_key] = curl_getinfo($done['handle'], $value);
curl_multi_remove_handle($this->_mch, $done['handle']);
}
}
}
}
class facebookResponse {
private $__construct;
public function __construct($resp)
{
$this->__resp = $resp;
$data = json_decode($this->__resp->data);
if ( $data !== NULL )
{
$this->__resp->data = $data;
}
}
public function __get($name)
{
if ($this->__resp->code < 200 || $this->__resp->code > 299) return FALSE;
$result = array();
if ( is_string($this->__resp->data ) )
{
parse_str($this->__resp->data, $result);
$this->__resp->data = (object) $result;
}
if ( $name === '_result')
{
return $this->__resp->data;
}
return $this->__resp->data->$name;
}
}
class facebookException extends Exception {
function __construct($string)
{
parent::__construct($string);
}
public function __toString() {
return "exception '".__CLASS__ ."' with message '".$this->getMessage()."' in ".$this->getFile().":".$this->getLine()."\nStack trace:\n".$this->getTraceAsString();
}
}
class facebookSession {
private $_api_key;
private $_api_secret;
private $_token_url = 'oauth/access_token';
private $_user_url = 'me';
private $_data = array();
function __construct()
{
$this->_obj =$CI =& get_instance();
$fb_api_id = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_ID'))->row()->string_value;
$fb_api_secret = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_SECRET'))->row()->string_value;
$this->_api_key = $fb_api_id;
$this->_api_secret = $fb_api_secret;
$this->_token_url = $this->_obj->config->item('facebook_api_url').$this->_token_url;
$this->_user_url = $this->_obj->config->item('facebook_api_url').$this->_user_url;
$this->_set('scope', $this->_obj->config->item('facebook_default_scope'));
$this->connection = new facebookConnection();
if ( !$this->logged_in() )
{
// Initializes the callback to this page URL.
$this->set_callback();
}
}
public function logged_in()
{
return ( $this->get() === NULL ) ? FALSE : TRUE;
}
public function logout()
{
$this->_unset('token');
$this->_unset('user');
}
public function login_url($scope = NULL)
{
$url = "http://www.facebook.com/dialog/oauth?client_id=".$this->_api_key.'&redirect_uri='.urlencode($this->_get('callback'));
if ( empty($scope) )
{
$scope = $this->_get('scope');
}
else
{
$this->_set('scope', $scope);
}
if ( !empty($scope) )
{
$url .= '&scope='.$scope;
}
return $url;
}
public function login($scope = NULL)
{
$this->logout();
if ( !$this->_get('callback') ) $this->_set('callback', current_url());
$url = $this->login_url($scope);
return redirect($url);
}
public function get()
{
$token = $this->_find_token();
if ( empty($token) ) return NULL;
// $user = $this->_get('user');
// if ( !empty($user) ) return $user;
try
{
$user = $this->connection->get($this->_user_url.'?'.$this->_token_string());
}
catch ( facebookException $e )
{
$this->logout();
return NULL;
}
// $this->_set('user', $user);
return $user;
}
private function _find_token()
{
$token = $this->_get('token');
if ( !empty($token) )
{
if ( !empty($token->expires) && intval($token->expires) >= time() )
{
// Problem, token is expired!
return $this->logout();
}
$this->_set('token', $token);
return $this->_token_string();
}
if ( !isset($_GET['code']) )
{
return $this->logout();
}
if ( !$this->_get('callback') ) $this->_set('callback', current_url());
$token_url = $this->_token_url.'?client_id='.$this->_api_key."&client_secret=".$this->_api_secret."&code=".$_GET['code'].'&redirect_uri='.urlencode($this->_get('callback'));
try
{
$token = $this->connection->get($token_url);
}
catch ( facebookException $e )
{
$this->logout();
redirect($this->_strip_query());
return NULL;
}
$this->_unset('callback');
if ( $token['access_token'] )
{
if ( !empty($token->expires) )
{
$token->expires = strval(time() + intval($token->expires));
}
$this->_set('token', $token);
redirect($this->_strip_query());
}
return $this->_token_string();
}
private function _get($key)
{
$key = '_facebook_'.$key;
return $this->_obj->session->userdata($key);
}
private function _set($key, $data)
{
$key = '_facebook_'.$key;
$this->_obj->session->set_userdata($key, $data);
}
private function _unset($key)
{
$key = '_facebook_'.$key;
$this->_obj->session->unset_userdata($key);
}
public function set_callback($url = NULL)
{
$this->_set('callback', $this->_strip_query($url));
}
private function _token_string()
{
return 'access_token='.$this->_get('token')->access_token;
}
public function append_token($url)
{
if ( $this->_get('token') ) $url .= '?'.$this->_token_string();
return $url;
}
private function _strip_query($url = NULL)
{
if ( $url === NULL )
{
$url = ( empty($_SERVER['HTTPS']) ) ? 'http' : 'https';
$url .= '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$parts = explode('?', $url);
return $parts[0];
}
}
I am not sure what is going on with this library. On line 451 you are looking in the $token array for the values that got returned and then it goes through a very convoluted way of setting that in the CI session and then instantly call it back from the CI session.
Line 458 sets the token into the session and then on 462 they return it but by calling a method that calls a method that returns session->userdata('token').
That seems to be why its failing on 490 because it gets the value in the session data but then tries finding the data for ->access_token on top of the returned value and that does not exist.
dump out $token before line 462 and see if it is an object or an array. If it's ann array then that would explain why ->access_token on 490 does not work. If it is an object then I would change line 462 to
return 'access_token='.$token->access_token;
or whatever the dump of $token says the value of the object is (I am assuming it is access_token) and see if that works. if it does then you have to figure out why they wrote all these extra steps and what it will be used for. If not, call it good.
Facebook has a library written that is available on github that you can just drop in the library dir in codeigniter and it will work fine. I would suggest dropping this class you are using and just use the one Facebook provides. This way you can learn how to integrate with Facebook right from their developer site and if they ever change their API calls, you do not have to rewrite code; you just replace the two files in the library dir.
https://github.com/facebook/facebook-php-sdk/tree/master/src
Hope this helps.

How to get my zend script picture filename into a hidden field

OK, I am stumped here. I'm using a Zend script that helps me to upload pictures. It works great, but I am trying to capture the pictures name into a hidden field for a form. I'd like to note that the name changes, so I'd need to get whichever it ends up being put into the hidden field. Here is the Zend script:
<?php
if (isset($_POST['upload'])) {
require_once('scripts/library.php');
try {
$destination = 'xxxxxxxx';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '90kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
if (!$uploader->isValid()) {
$messages = $uploader->getMessages();
} else {
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$uploaded .= " and renamed $no_spaces";
}
$messages[] = "$uploaded";
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Here I am trying to make the $pic variable not to throw an error for now (on the form page)
if (isset($_POST['upload'])) { } else { $pic = "unknown";}
The $pic variable is what I was trying to have the filename from the zend script copied into. Any feedback is greaaaatly appreciated :)

Acces token from facebook is not retrived for sign up? access_token (trying to get propert of non object )

private $_api_key;
private $_api_secret;
private $_token_url = 'oauth/access_token';
private $_user_url = 'me';
private $_data = array();
function __construct()
{
$this->_obj =$CI =& get_instance();
$fb_api_id = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_ID'))->row()->string_value;
$fb_api_secret = $CI->db->get_where('settings', array('code' => 'SITE_FB_API_SECRET'))->row()->string_value;
$this->_api_key = $fb_api_id;
$this->_api_secret = $fb_api_secret;
$this->_token_url = $this->_obj->config->item('facebook_api_url').$this->_token_url;
$this->_user_url = $this->_obj->config->item('facebook_api_url').$this->_user_url;
$this->_set('scope', $this->_obj->config->item('facebook_default_scope'));
$this->connection = new facebookConnection();
if ( !$this->logged_in() )
{
// Initializes the callback to this page URL.
$this->set_callback();
}
}
public function logged_in()
{
return ( $this->get() === NULL ) ? FALSE : TRUE;
}
public function logout()
{
$this->_unset('token');
$this->_unset('user');
}
public function login_url($scope = NULL)
{
$url = "http://www.facebook.com/dialog/oauth?client_id=".$this->_api_key.'&redirect_uri='.urlencode($this->_get('callback'));
if ( empty($scope) )
{
$scope = $this->_get('scope');
}
else
{
$this->_set('scope', $scope);
}
if ( !empty($scope) )
{
$url .= '&scope='.$scope;
}
return $url;
}
public function login($scope = NULL)
{
$this->logout();
if ( !$this->_get('callback') ) $this->_set('callback', current_url());
$url = $this->login_url($scope);
return redirect($url);
}
public function get()
{
$token = $this->_find_token();
if ( empty($token) ) return NULL;
// $user = $this->_get('user');
// if ( !empty($user) ) return $user;
try
{
$user = $this->connection->get($this->_user_url.'?'.$this->_token_string());
}
catch ( facebookException $e )
{
$this->logout();
return NULL;
}
// $this->_set('user', $user);
return $user;
}
private function _find_token()
{
$token = $this->_get('token');
if ( !empty($token) )
{
if ( !empty($token->expires) && intval($token->expires) >= time() )
{
// Problem, token is expired!
return $this->logout();
}
$this->_set('token', $token);
return $this->_token_string();
}
if ( !isset($_GET['code']) )
{
return $this->logout();
}
if ( !$this->_get('callback') ) $this->_set('callback', current_url());
$token_url = $this->_token_url.'?client_id='.$this->_api_key."&client_secret=".$this->_api_secret."&code=".$_GET['code'].'&redirect_uri='.urlencode($this->_get('callback'));
try
{
$token = $this->connection->get($token_url);
}
catch ( facebookException $e )
{
$this->logout();
redirect($this->_strip_query());
return NULL;
}
$this->_unset('callback');
if ( $token->access_token )
{
if ( !empty($token->expires) )
{
$token->expires = strval(time() + intval($token->expires));
}
$this->_set('token', $token);
redirect($this->_strip_query());
}
return $this->_token_string();
}
private function _get($key)
{
$key = '_facebook_'.$key;
return $this->_obj->session->userdata($key);
}
private function _set($key, $data)
{
$key = '_facebook_'.$key;
$this->_obj->session->set_userdata($key, $data);
}
private function _unset($key)
{
$key = '_facebook_'.$key;
$this->_obj->session->unset_userdata($key);
}
public function set_callback($url = NULL)
{
$this->_set('callback', $this->_strip_query($url));
}
private function _token_string()
{
return 'access_token='.$this->_get('token')->access_token;
}
public function append_token($url)
{
if ( $this->_get('token') ) $url .= '?'.$this->_token_string();
return $url;
}
private function _strip_query($url = NULL)
{
if ( $url === NULL )
{
$url = ( empty($_SERVER['HTTPS']) ) ? 'http' : 'https';
$url .= '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$parts = explode('?', $url);
return $parts[0];
}
please tell me what and all retrieved from facebook as token when user tries to sign in using fb account in a site.
I get the followin errors in this code :
Message: Trying to get property of non-object
Filename: libraries/Facebook_Lib.php
Line Number: 454
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: libraries/Facebook_Lib.php
Line Number: 493
Severity: Notice
Message: Trying to get property of non-object
Filename: libraries/Facebook_Lib.ph
Line Number: 493
all errors regarding access_token
Its was an database error due to session have not created due to facebook app not live.