Get users a Twitter user is following - api

I am using the Twitter API to create a web application. However, I would like to be able to get a list of users that a specific user is following. I have looked at the documentation and I have not been able to find how to do this.
For example, I might be trying to get the users that baconman is following. How can I do this using the Twitter API?

<?php
$screen_name = 'baconman';
$url = 'https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name='.$screen_name;
$list = curl($url,'GET');
$followers_ids = json_decode($list);
$user_detail = 'https://api.twitter.com/1/users/lookup.json?user_id='.implode(',',$followers_ids->ids).'&include_entities=true';
$details = curl($user_detail,'GET');
function curl($url, $method = 'get', $header = null, $postdata = null, $includeheader=FALSE, $timeout = 60)
{
$s = curl_init();
curl_setopt($s,CURLOPT_URL, $url);
if ($header)
curl_setopt($s,CURLOPT_HTTPHEADER, $header);
/*if ($this->debug)*/
curl_setopt($s,CURLOPT_VERBOSE, FALSE);
curl_setopt($s,CURLOPT_TIMEOUT, $timeout);
curl_setopt($s,CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($s,CURLOPT_MAXREDIRS, 3);
curl_setopt($s,CURLOPT_RETURNTRANSFER, true);
curl_setopt($s,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($s,CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($s,CURLOPT_COOKIEFILE, 'cookie.txt');
if(strtolower($method) == 'post')
{
curl_setopt($s,CURLOPT_POST, true);
curl_setopt($s,CURLOPT_POSTFIELDS, $postdata);
}
else if(strtolower($method) == 'delete')
{
curl_setopt($s,CURLOPT_CUSTOMREQUEST, 'DELETE');
}
else if(strtolower($method) == 'put')
{
curl_setopt($s,CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($s,CURLOPT_POSTFIELDS, $postdata);
}
curl_setopt($s,CURLOPT_HEADER, $includeheader);
//curl_setopt($s,CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
curl_setopt($s, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec($s);
$status = curl_getinfo($s, CURLINFO_HTTP_CODE);
curl_close($s);
return $html;
}

Related

PHP + curl, HTTP POST to Open cart, add to cart section?

Can anyone show me how to do a PHP curl with an HTTP POST to open cart using API?
I want to send data like this:
product_id = 700, quantity = 1
To www.example.com
I expect the curl to return a response like {"success":"Success: You have modified your shopping cart!"} Are there any examples?
Do it the way as below:
<?php
$output = apirequest();
function apirequest()
{
$params['product_id'] = 700;
$params['quantity'] = 1;
$input = array('data' => json_encode($params));
$options = array(CURLOPT_RETURNTRANSFER=> true, //return web page
CURLOPT_HEADER=> false, //don't return headers
CURLOPT_AUTOREFERER=> true, //set referrer on redirect
CURLOPT_CONNECTTIMEOUT=> 180, //timeout on connect
CURLOPT_TIMEOUT=> 180, //timeout on response
CURLOPT_POST=> 1, //I am sending post data
CURLOPT_POSTFIELDS=> $input
);
$ch = curl_init("www.example.com");
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>

PAYPAL IPN Listner

I have been pulling my hair out trying to get this to work for over a week. I have even purchased an SSL cert for the domain.
I keep getting the error:
[2016-03-14 18:07 Europe/London] Can not connect to PayPal to validate IPN message: SSL connect error
Heres my code.
<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");
error_log(date('[Y-m-d H:i e] '). "Test message: " . PHP_EOL, 3, LOG_FILE);
// Read POST data
// reading posted data directly from $_POST causes serialization
// issues with array data in POST. Reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post IPN data back to PayPal to validate the IPN data is genuine
// Without this step anyone can fake IPN data
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
//$userAgent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2';
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can not connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your PayPal email
// check that payment_amount/payment_currency are correct
// process payment and mark item as paid.
// assign posted variables to local variables
//$item_name = $_POST['item_name'];
//$item_number = $_POST['item_number'];
//$payment_status = $_POST['payment_status'];
//$payment_amount = $_POST['mc_gross'];
//$payment_currency = $_POST['mc_currency'];
//$txn_id = $_POST['txn_id'];
//$receiver_email = $_POST['receiver_email'];
//$payer_email = $_POST['payer_email'];
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
I'm not sure why you bought an SSL certificate to fix connecting to PayPal.
Try changing
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
to
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
My bet is the SSL handshake is failing to the server. Disabling the checks should help clear it up.

WHMCS License Addon not working

I have just authored a WHMCS addon module that works great on my server; however, others that have tried to use it are not having success. There are 2 issues...
1) I use the WHMCS License Addon; however, it does not appear that their remote machines are making a successful connection to my machine to validate the license. I use the WHMCS supplied code to handle the connection and validation. No idea on what else to check... Any ideas?
2) I have a database that my script checks to see if the user has the most current version of the script. Access to the database works great from my local machine and RemoteSQL is enabled with a % wildcard so anyone should be able to connect but yet the remote machines do not seem to be able to connect. Here is my info...
$link = mysql_connect('gjinternetsolutions.com', 'gj_Guest', 'Password1');
mysql_select_db("gj_Software", $link);
$query = "SELECT * FROM `VersionCheck` where `Software`='RedemptionFee'";
... additional code to display the results
Is anyone able to successfully make a remote connection to the above database?
=========== UPDATE ===========
The second issue above has been resolved. We are still having an issue with the licensing code.... Here is what we have....
# Values obtained from our database...
$localkey=$row['LocalKey'];
$licensekey=$vars['License'];
$results = RedemptionFee_check_gj_license($licensekey,$localkey);
function RedemptionFee_check_gj_license($licensekey,$localkey="")
{
$whmcsurl = "http://gjinternetsolutions.com/home/";
$licensing_secret_key = "####-VALUE REMOVED FOR THIS POST-####"; # Unique value, should match what is set in the product configuration for MD5 Hash Verification
$check_token = time().md5(mt_rand(1000000000,9999999999).$licensekey);
$checkdate = date("Ymd"); # Current date
$usersip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];
$localkeydays = 1; # How long the local key is valid for in between remote checks
$allowcheckfaildays = 5; # How many days to allow after local key expiry before blocking access if connection cannot be made
$localkeyvalid = false;
if ($localkey) {
$localkey = str_replace("\n",'',$localkey); # Remove the line breaks
$localdata = substr($localkey,0,strlen($localkey)-32); # Extract License Data
$md5hash = substr($localkey,strlen($localkey)-32); # Extract MD5 Hash
if ($md5hash==md5($localdata.$licensing_secret_key)) {
$localdata = strrev($localdata); # Reverse the string
$md5hash = substr($localdata,0,32); # Extract MD5 Hash
$localdata = substr($localdata,32); # Extract License Data
$localdata = base64_decode($localdata);
$localkeyresults = unserialize($localdata);
$originalcheckdate = $localkeyresults["checkdate"];
if ($md5hash==md5($originalcheckdate.$licensing_secret_key)) {
$localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-$localkeydays,date("Y")));
if ($originalcheckdate>$localexpiry) {
$localkeyvalid = true;
$results = $localkeyresults;
$validdomains = explode(",",$results["validdomain"]);
if (!in_array($_SERVER['SERVER_NAME'], $validdomains)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
$validips = explode(",",$results["validip"]);
if (!in_array($usersip, $validips)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
if ($results["validdirectory"]!=dirname(__FILE__)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
}
}
}
}
if (!$localkeyvalid) {
$postfields["licensekey"] = $licensekey;
$postfields["domain"] = $_SERVER['SERVER_NAME'];
$postfields["ip"] = $usersip;
$postfields["dir"] = dirname(__FILE__);
if ($check_token) $postfields["check_token"] = $check_token;
if (function_exists("curl_exec")) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsurl."modules/servers/licensing/verify.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
} else {
$fp = fsockopen($whmcsurl, 80, $errno, $errstr, 5);
if ($fp) {
$querystring = "";
foreach ($postfields AS $k=>$v) {
$querystring .= "$k=".urlencode($v)."&";
}
$header="POST ".$whmcsurl."modules/servers/licensing/verify.php HTTP/1.0\r\n";
$header.="Host: ".$whmcsurl."\r\n";
$header.="Content-type: application/x-www-form-urlencoded\r\n";
$header.="Content-length: ".#strlen($querystring)."\r\n";
$header.="Connection: close\r\n\r\n";
$header.=$querystring;
$data="";
#stream_set_timeout($fp, 20);
#fputs($fp, $header);
$status = #socket_get_status($fp);
while (!#feof($fp)&&$status) {
$data .= #fgets($fp, 1024);
$status = #socket_get_status($fp);
}
#fclose ($fp);
}
}
if (!$data) {
$localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-($localkeydays+$allowcheckfaildays),date("Y")));
if ($originalcheckdate>$localexpiry) {
$results = $localkeyresults;
} else {
$results["status"] = "Invalid";
$results["description"] = "Remote Check Failed";
return $results;
}
} else {
preg_match_all('/<(.*?)>([^<]+)<\/\\1>/i', $data, $matches);
$results = array();
foreach ($matches[1] AS $k=>$v) {
$results[$v] = $matches[2][$k];
}
}
if ($results["md5hash"]) {
if ($results["md5hash"]!=md5($licensing_secret_key.$check_token)) {
$results["status"] = "Invalid";
$results["description"] = "MD5 Checksum Verification Failed";
return $results;
}
}
if ($results["status"]=="Active") {
$results["checkdate"] = $checkdate;
$data_encoded = serialize($results);
$data_encoded = base64_encode($data_encoded);
$data_encoded = md5($checkdate.$licensing_secret_key).$data_encoded;
$data_encoded = strrev($data_encoded);
$data_encoded = $data_encoded.md5($data_encoded.$licensing_secret_key);
$data_encoded = wordwrap($data_encoded,80,"\n",true);
$results["localkey"] = $data_encoded;
}
$results["remotecheck"] = true;
}
unset($postfields,$data,$matches,$whmcsurl,$licensing_secret_key,$checkdate,$usersip,$localkeydays,$allowcheckfaildays,$md5hash);
return $results;
}
Yes, I can connect using the details above.
Query run:
SELECT * FROM `gj_Software`.`VersionCheck` where `Software`='RedemptionFee'
Result:
# Software, Version, URL
'RedemptionFee', '1.0', 'http://GJinternetSolutions.com/home/upgrade.php?type=package&id=660'
Hope this helps.
Ash

Youtube api upload videos not working "Error : NoLinkedYouTubeAccount "

am using youtube api to upload videos from my website, this is first time am using am got stuck with the google account.I gave youtube account username, password and developer key am getting the error "NoLinkedYouTubeAccount ".
Some one help me to fix this issue.
/**
* developerKey
*/
public $developerKey;
/**
* accessToken - authorization access taken
*/
public $accessToken;
/**
* next_index - used to track short results
*/
public $next_index;
/**
* authType - authentication type GoogleLogin or AuthSub
*/
public $authType;
/**
* initializes the token and API key information for API methods which requires authentication information
* #param developerKey - String
* #param accessToken - array
* #return void
* #access public
* Modified: Sandip
*/
public function __construct($params){
$this->accessToken = $params['accessToken'];
$this->authType = $params['authType'];
$this->developerKey=$params['developerKey'];
}
/**
* client login authentication
* #param username - String
* #param pass - String
* #return array
* #access public
* Modified: Sandip
*/
public function clientLoginAuth($username,$pass){
$this->authType = 'GoogleLogin';
$url = 'https://www.google.com/youtube/accounts/ClientLogin';
$data = 'Email='.urlencode($username).'&Passwd='.urlencode($pass).'&service=youtube&source=Test';
$result = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Content-Type:application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
$result['output'] = curl_exec($ch);
$result['err'] = curl_errno( $ch );
$result['errmsg'] = curl_error( $ch );
$result['header'] = curl_getinfo( $ch );
$temp = explode("YouTubeUser=",$result['output']);
$result['username'] = trim($temp[1]);
$temp2 = explode("=",trim($temp[0]));
$result['token'] = trim($temp2[1]);
$this->accessToken = $result['token'];
curl_close($ch);
return $result;
}
public function uploadVideo($filename,$fullFilePath,$title,$description,$tags)
{
$fdata = file_get_contents($fullFilePath);
$tmpdata = '<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">'.$title.'</media:title>
<media:description type="plain">'.$description.'</media:description>
<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category> <media:keywords>'.$tags.'</media:keywords>
</media:group>
</entry>
';
$url = 'http://gdata.youtube.com/feeds/api/users/default/uploads';
$data = '--f93dcbA3
Content-Type: application/atom+xml; charset=UTF-8
'.$tmpdata.'
--f93dcbA3
Content-Type: video/quicktime
Content-Transfer-Encoding: binary
'.$fdata.'
--f93dcbA3--';
$token = $this->accessToken;
$developerKey = $this->developerKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Host: uploads.gdata.youtube.com";
if($this->authType == 'GoogleLogin')
$curlheader[1] = "Authorization: ".$this->authType." auth=\"$token\"";
else
$curlheader[1] = "Authorization: ".$this->authType." token=\"$token\"";
$curlheader[2] = "GData-Version: 2";
$curlheader[3] = "X-GData-Key: key=\"$developerKey\"";
$curlheader[4] = "Slug: ".$filename;
$curlheader[5] = "Content-Type: multipart/related; boundary=\"f93dcbA3\"";
$curlheader[6] = "Content-Length: ".strlen($data);
$curlheader[7] = "Connection: close";
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
//print_r($info);
curl_close($ch);
unset($fdata);
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$webSite = 'http://www.youtube.com/';
$criteria = 'uploads';
$mediaInfo = array();
$gdMedia = $xml->children('http://schemas.google.com/g/2005');
$media = $xml->children('http://search.yahoo.com/mrss/');
$ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
$georssMedia = $xml->children('http://www.georss.org/georss');
if($media->group->title){
$mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
}else{
$mediaInfo['title'] = '';
}
if($media->group->description){
$mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
}else{
$mediaInfo['description'] = '';
}
if($media->group->player){
$video = $media->group->player[0]->attributes()->url;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}else{
if($entry->link[0]->attributes()->href){
$video = $entry->link[0]->attributes()->href;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}else{
return "video not found.";
}
}
$mediaInfo['path_url'] = $mediaInfo['contentUrl'];
$mediaInfo['webSite'] = $webSite;
$mediaInfo['genre'] = sprintf("%s",#$media->group->category[0]);
$mediaInfo['criteria'] = $criteria;
unset($xml);
unset($gdMedia);
unset($media);
unset($ytMedia);
unset($georssMedia);
return $mediaInfo;
}
else
{
$result = array();
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
unset($validresult);
return $result;
}
}
public function getUploadedVideos($username='default',$startIndex=1,$limit=10,$location='',$location_radius='',$safeSearch='strict',$strict='true'){
$url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
if($location !='')
{
$url .= '&location='.$location;
$url .= '&location-radius='.$location_radius;
}
//echo "<br>".$url;
$criteria = 'uploads';
if($username == 'default')
$output = $this->make_api_call($url);
else
{
$response = $this->make_get_call($url);
$output = $response['output'];
}
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
//$tmp = $xml->xpath("openSearch:itemsPerPage");
//$result['itemsPerPage'] = (string)$tmp[0];
$res = $this->getFormatedVideoresult($xml,$criteria);
//Pagination logic
$shortCnt = $this->getShortCount();
//
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
if($location !='')
{
$url .= '&location='.$location;
$url .= '&location-radius='.$location_radius;
}
$shortResult = $this->getShortResult($url,$criteria);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']))
{
////echo "<br>INSIDE";
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//while
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
//pagination logic
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
unset($validresult);
return $result;
}
public function checkErrors($response){
$result = array();
$result['is_error'] = 'No';
$reg_ex = '/<H1>Bad Request<\/H1>/';
$res = preg_match_all($reg_ex,$response,$matches);
if(!empty($matches[0])) {
$result['is_error'] = 'Yes';
$result['error'] = "Bad Request";
}
else {
$xml = #simplexml_load_string($response);
if($xml === FALSE && $response !=''){
$result['error'] = $response;
$result['is_error'] = 'Yes';
}
else{
if(#$xml->error){
$msg = #(string)$xml->error->code.':'.#(string)$xml->error->internalReason;
unset($xml);
$result['error'] = $msg;
$result['is_error'] = 'Yes';
}
else{
$result['xml'] = $xml;
}
}
}
unset($xml);
unset($response);
return $result;
}
public function getContentURL($url){
$output = $this->make_api_call($url);
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
$result['term'] = $xml->category[1]->attributes()->term;
$result['title'] = (string)$xml->title;
$result['username'] = (string)$ytMedia->username;
$result['contentURL'] = (string)$xml->content->attributes()->src;
if(stristr($result['title'],'Activity of'))
{
$result['contentURL'] = 'http://gdata.youtube.com/feeds/api/users/'.$result['username'].'/uploads?v=2';
}
}
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
unset($validresult);
return $result;
}
public function getRecentUploadedVideos($xml){
$i = 0;
$res = array();
foreach($xml->entry as $fentry){
$i++;
$term = $fentry->category[1]->attributes()->term;
if($term == 'video_uploaded')
{
$mediaInfo = array();
$entry = $fentry->link[1]->entry;
$gdMedia = $entry->children('http://schemas.google.com/g/2005');
$media = $entry->children('http://search.yahoo.com/mrss/');
$ytMedia = $entry->children('http://gdata.youtube.com/schemas/2007');
$georssMedia = $entry->children('http://www.georss.org/georss');
if($gdMedia->rating){
$rating = (string)$gdMedia->rating->attributes();
$mediaInfo['rating'] = $rating['average'];
}else{
$mediaInfo['rating'] = 0;
}
if($media->group->thumbnail){
$mediaInfo['iconImage'] = sprintf("%s",$media->group->thumbnail[0]->attributes()->url);
}else{
$mediaInfo['iconImage'] = '';
}
if($media->group->title){
$mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
}else{
$mediaInfo['title'] = '';
}
if($media->group->description){
$mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
}else{
$mediaInfo['description'] = '';
}
if($media->group->player){
$video = $media->group->player[0]->attributes()->url;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', #$test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}
else{
$tmp = #$entry->xpath("app:control");
$tmp2 = #$tmp[0]->xpath("yt:state");
if(#$tmp2[0]->attributes()->name == 'restricted')
{
//echo "<br>INSIDE ".$mediaInfo['title'];
$this->next_index[$i] = 'n';
continue;
}
if(isset($entry->link) && $entry->link[0]->attributes()->href !=''){
$video = $entry->link[0]->attributes()->href;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
if(!$mediaInfo['videoId'])
{
$this->next_index[$i] = 'n';
//echo "video Skipped.";
continue;
}
}
else{
$this->next_index[$i] = 'n';
continue;
}
}
$this->next_index[$i] = 'y';
$res[] = $mediaInfo;
}
else
{
$this->next_index[$i] = 'n';
}
} // foreach
return $res;
}
public function getRecentShortResult($url){
$token = $this->accessToken;
$developerKey = $this->developerKey;
if($token !='' && $developerKey !='')
$output = $this->make_api_call($url);
else
{
$response = $this->make_get_call($url);
$output = $response['output'];
}
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:itemsPerPage");
$result['itemsPerPage'] = (string)$tmp[0];
//$result['itemsPerPage'] = $maxresults;
if($tmp_totalresults > $result['startindex']){
$res = $this->getRecentUploadedVideos($xml);
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
else
$result['nextPageIndex'] = 0;
$result['result'] = #$res;
}
else
{
$result['error'] = $validresult['error'];
}
$result['is_error'] = $validresult['is_error'];
unset($validresult);
unset($output);
unset($response);
return $result;
}
public function getVideosBysubscriptionID($subscriptionID,$startIndex=1,$limit=10,$safeSearch='strict',$strict='true'){
$url = 'http://gdata.youtube.com/feeds/api/users/default/subscriptions/'.$subscriptionID.'?v=2';
$feedResponse = $this->getContentURL($url);
$contentURL = #$feedResponse['contentURL'];
$tempcontentURL = $contentURL;
$contentURL .= '&start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
$result = array();
if($contentURL !=''){
$output = $this->make_api_call($contentURL);
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No'){
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
if(#$feedResponse['recentUpload'] == 1){
$res = $this->getRecentUploadedVideos($validresult['xml']);
$shortCnt = $this->getShortCount();
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
$shortResult = $this->getRecentShortResult($url);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']) && count($res) <= $limit)
{
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//WHILE
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = #$result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
else
{
$criteria = $feedResponse['title'];
$xml = $validresult['xml'];
$res = $this->getFormatedVideoresult($xml,$criteria);
//Pagination logic
$shortCnt = $this->getShortCount();
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
$shortResult = $this->getShortResult($url,$criteria);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']))
{
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//while
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
//pagination logic
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
}// NO
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
}
else
{
$result['is_error'] = $feedResponse['is_error'];
$result['error'] = $feedResponse['error'];
}
unset($validresult);
unset($feedResponse);
return $result;
}
}
/* End of file Someclass.php */
Thanks.
For anyone that comes across this, I had this error and fixed it by logging into YouTube as the main user, going to the top right and clicking 'Youtube Settings'. Then I clicked 'create channel'. Error gone!
This doesn't have anything to do with your code or program. It simply means you have not linked your Google account with Youtube, or vice versa.
I encountered the same problem too. But for me, I initially created a Google account, and even though when I went to Youtube.com I could see that I was logged it, but that did not mean that my Google account was actually linked to YouTube yet. So in my case, when I was on youtube.com, I actually clicked on my username in the upper right corner and did something...but basically it just prompted me to link YouTube to my Google account. When that was all done, it finally took me to my YouTube profile page. And then when I ran my program again, the "NoLinkedYoutubeAccount" error message was gone.
Give that a try. For you, it might be the opposite. Hope this helps!

Problem with confirming subscription pubsubhubbub

The first code:
if(isset($_GET["hub_challenge"])) {
echo $_GET["hub_challenge"];
}
else {
}
$feeded = $_POST['feed'];
$ch = curl_init("http://pubsubhubbub.appspot.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,"hub.mode=subscribe&hub.verify=async&hub.callback=http://rssreaderbg.net/pubsubbub/example/index.php?url=$feeded&hub.topic=$feeded");
curl_exec($ch);
The callback code:
file_put_contents("logmeme.txt",$HTTP_RAW_POST_DATA,FILE_APPEND);
https://pubsubhubbub.appspot.com/topic-details?hub.url=http%3A%2F%2Frssreaderbg.net%2Fblog%2F%3Ffeed%3Drss2
https://pubsubhubbub.appspot.com/subscription-details?hub.callback=http%3A%2F%2Frssreaderbg.net%2Fpubsubbub%2Fexample%2Findex.php&hub.topic=http%3A%2F%2Frssreaderbg.net%2Fblog%2F%3Ffeed%3Drss2&hub.secret=
It can't reach the callback url or ?
Try explicitly setting the header to 2xx before echoing the challenge.
header('HTTP/1.1 204 "No Content"', true, 204);