How to use SHA256 With salt? - sha256

I have a hash function on sa-mp
new MyHash[256];
SHA256_PassHash(inputtext, "78sdjs86d2h", MyHash, sizeof(MyHash));
if(!strcmp(MyHash, PlayerInfo[playerid][pKey]))
I assume 78sdjs86d2h is the salt, but how do I set the salt in PHP?
I am using this code, and it hashes but not with my salt.
if(isset($_POST['username']) && isset($_POST['password'])){
mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
$username = mysql_real_escape_string($_POST['username']);
$parola = mysql_real_escape_string($_POST['password']);
$hash = hash('sha256', $parola);
$check = get_row("SELECT ID FROM players WHERE Name='$username' && password='$hash' LIMIT 1");
if(isset($check['ID']))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$id = $check['ID'];
header("location: index.php");
}
else
{
printf("%s", $hash);
$err = 'Username sau parola incorecte';
}
}
How do I make it hash with my own salt?

UPDATE: Tried this way
$username = mysqli_real_escape_string($DB_H, addslashes($_POST['username']));
$password1 = $_POST['password'];
$salt = '78sdjs86d2h';
$parola = hash('sha256', $password1 . $salt);
The result: 33ca067dc70ef75fc1a1107f4345f3a819ecca657d3d9646d26822fd691cd10c
The original: BFD2832240F5FC1FD12004634EBE9FDE97BD0D4690695DFAC1350D0AE037398F

Related

AES 256 GCM with php 5.6

I have taken reference of code from this post :
Trying to decrypt with aes-256-gcm with php
Code :
< ?php
$textToEncrypt = "demo text";
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$tag_length = 16;
$iv = openssl_random_pseudo_bytes($iv_len);
$ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv.$ciphertext);
$textToDecrypt = $encrypted;
$encrypted = base64_decode($textToDecrypt);
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted, 0, $iv_len);
$ciphertext = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
var_dump (openssl_error_string());
var_dump($decrypted);
echo $decrypted;
?>
Running this code on PHP 5.6
Now the issue is I am always getting false as decrypted text.
What is wrong?

Missing file in my email when doing resumable upload with gmail api

I'd like to have some help because I'm a bit lost right now.
I'm trying to send attachment with my email through resumable upload. But when I check my email in my inbox, I don't see any file. So I've probably forgot something.
Here's my code. So if someone see something ^^
$send_data = 'From: <FROM_EMAIL>' . "\n";
$send_data = 'To: <TO_EMAIL>' . "\n";
$send_data = 'Subject: <SUBJECT>' . "\n";
$send_data = '' . "\n";
$send_data = '<MY MESSAGE>' . "\n";
$send_data= rtrim(strtr(base64_encode($send_data), '+/', '-_'), '=');
$msg = new \Google_Service_Gmail_Mesage();
$msg->setRaw($send_data);
$this->client->setDefer(true);
$request = $this->service->users_messages->send('me', $msg, array('uploadType' => 'resumable'));
$chunkSizeBytes = 1 * 1024 * 1024;
$media = new \Google_Http_MediaFileUpload(
$this->client,
$request,
'message/rfc822',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize(TEST_FILE));
$status = false;
$handle = fopen(TEST_FILE, "rb");
$i = 0;
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
$this->client->setDefer(false);
Thanks
I don't know much about gmail api, but I feel like setRaw() will need you to compose the full email (include the attachment) instead just of "body".

How to grab contacts from gmail using google API's and contact grabber in PHP?

In my project i want to grab the contacts from gmail using google API's. I provide three keys such as client id, client secret and signature key. When i trying to get contacts the pop-up window is showing error message "Signature key must be formatted". What i have done wrong? Thanks in advance.
Here is my code
keyConfig.php
<?php
$apiRequestUrl = "https://stescodes.com/api/contactsapi.aspx"; // StesCodes contact grabber API request url
$originalsignaturekey = "lxFWDA5ng36sdvlFGukof75vyi";//replace with your signature key
$gmailConsumerKey = "1009516162377-n5s7lo5b4dvlt8e7s3rt12f8i02lpk1f.apps.googleusercontent.com";
$gmailConsumerSecret = "raCUba1smsZCzrVNjqFIqiqC";
$YahooConsumerKey = "your yahoo api key";
$YahooConsumerSecret = "your yahoo api key";
$LiveConsumerKey = "your live api key";
$LiveConsumerSecret = "your live api key";
$fbConsumerKey = "your facebook api key";
$fbConsumerSecret = "your facebook api key";
$callbackurl = "http://localhost/grab/oauth.php";// eg: return url after user authentication http://yourdomain/oauth.php
$currentdirpath = "http://dev.stescodes.com/";//your current web directory path eg:http://yourdomain/
?>
oauth.php
<?php
session_start();
?>
<?php include 'keyConfig.php'; ?>
<html>
<head><title></title>
<script>
function redirectrequest(a)
{
window.location = a;
}
function closepopup(a,b,c,d) {
window.opener.startGrabbingContactsOauth(a,b,c,d);
window.self.close();
}
</script>
</head>
<body>
<?php
$servicename = "gmail";
$token = "";
$ConsumerKey = "";
$ConsumerSecret="";
$tokensecret="";
$tokenverifier="";
$flag=0;
$parameters="";
if($_GET['currpage']!=null)
$_SESSION['currpage']=$_GET['currpage'];
if($_SESSION['currpage']=="gmail")
{
$servicename = "gmail";
$ConsumerKey = $gmailConsumerKey;
$ConsumerSecret = $gmailConsumerSecret;
if ($_GET['code'] != null)
{
$token = $_GET['code'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="yahoo")
{
$servicename = "yahoo";
$ConsumerKey = $YahooConsumerKey;
$ConsumerSecret = $YahooConsumerSecret;
if (($_GET['oauth_token'] != null) && ($_GET['oauth_verifier'] != null))
{
$token = $_GET['oauth_token'];
$tokenverifier = $_GET['oauth_verifier'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="facebook")
{
$servicename = "facebook";
$ConsumerKey = $fbConsumerKey;
$ConsumerSecret = $fbConsumerSecret;
if (($_GET['code'] != null))
{
$token = $_GET['code'];
$tokenverifier = "";
$tokensecret = "";
$flag = 1;
}
}
else if(($_SESSION['currpage']=="msn") || ($_SESSION['currpage']=="hotmail") || ($_SESSION['currpage']=="msnmessenger"))
{
$servicename = $_SESSION['currpage'];
$ConsumerKey = $LiveConsumerKey;
$ConsumerSecret = $LiveConsumerSecret;
//Live settings
if ($_GET["code"] != null)
{
$token = $_GET["code"];
$flag = 1;
}
}
if ($flag == 1)
{
$parameters = "type=accesstoken&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) . "&Token=" . urlencode($token) . "&TokenSecret=" . urlencode($tokensecret) . "&TokenVerifier=" . urlencode($tokenverifier);
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $_SESSION['tokenverifier'];
$_SESSION["consumerkey"] = $ConsumerKey;
$_SESSION["consumersecret"] = $ConsumerSecret;
echo "<SCRIPT LANGUAGE=\"javascript\"> closepopup('".$servicename."',". $result .",'".$ConsumerKey."','".$ConsumerSecret."');</SCRIPT>";
}
else
{
$parameters = "type=authenticationurl&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) ;
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $tokenverifier;
echo "<SCRIPT LANGUAGE=\"javascript\"> redirectrequest('".$authdetails[details][authUrl]."'); </SCRIPT>";
}
?>

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!