How to get the video upload date with YouTube API V3? - api

I know how can I get the video duration and views, like that
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=hqepb5hzuB0&key={YOUR-API-KEY}");
$json_data = json_decode($JSON, true);
echo $json_data['items'][0]['statistics']['viewCount'];
But how can I get the video upload date?

$vidkey = "Gsc7_E5HewM" ; //for example
$apikey = "xxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
//----- duration---
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
// Check if $VidDuration is ISO string so the video is ready
if (is_string($VidDuration)){
//convert duration from ISO to M:S
$date = new DateTime('2000-01-01');
$date->add(new DateInterval($VidDuration));
$vid_durH= $date->format('H') ;
if ($vid_durH=="00") {
$vid_dur= $date->format('i:s') ;
}
else {
$vid_dur= $date->format('H:i:s') ;
}
}
else {
$vid_dur ="error" ;
}
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json_data = json_decode($JSON, true);
$uploadDate = $json_data['items'][0]['snippet']['publishedAt'];
$uploadDate = strtotime($uploadDate);
$uploadDate= date("F j, Y", $uploadDate);
echo $vid_dur ;

Related

How to update youtube annalytics to all previously registered youtube channels

I have a web app in which the users can register and connect their youtube channels. Next in the registration process I collect all the information I can get from youtube data api and youtube analytics and reporting api (with scopes and access tokens) and store it in the database. I show that info on their dashboards. I also display that info in the admin panel for the administrators to see.
The problem is, how can I refresh that info, lets say, once a day? I've tried with the access token but i get error 403 Forbidden message. I want to update the info to all of the registered youtube accounts, this is the function I use to update all but its not working
(In the bellow script, i send $code as a variable and the function is called on the redirect URI)
$youtube_channels = YouTubeChannels::get();
$key = env('NEW_YOUTUBE_API_KEY');
foreach($youtube_channels as $youtube_channel) {
$yt_channel_statistics = Http::get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'statistics,snippet',
'id' => $youtube_channel->youtube_channel_id,
'key' => $key
]);
$yt_channel_statistics_json = $yt_channel_statistics->json();
$update_yt = YouTubeChannels::where('youtube_channel_id', $youtube_channel->youtube_channel_id)->first();
if($update_yt != null) {
$update_yt->channel_name = $yt_channel_statistics_json['items'][0]['snippet']['title'];
$update_yt->channel_subscribers = $yt_channel_statistics_json['items'][0]['statistics']['subscriberCount'];
$update_yt->channel_total_views = $yt_channel_statistics_json['items'][0]['statistics']['viewCount'];
$update_yt->channel_videos_count = $yt_channel_statistics_json['items'][0]['statistics']['videoCount'];
$update_yt->save();
}
//test
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
$apiKey = env('NEW_YOUTUBE_API_KEY');
$channelId = $youtube_channel->youtube_channel_id;
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
$video_ids_string = collect($videos)->implode(',');
//
//endtest
//new test
//
$params = [
'part'=> 'snippet,contentDetails,statistics,status',
'id' => $video_ids_string,
'key'=> $apiKey
];
$url = $baseUrl . 'videos?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos_infos = $json;
//
YouTubeVideos::where('youtube_channel_id', $youtube_channel->id)->delete();
foreach ($videos as $video){
foreach($videos_infos['items'] as $info){
if ($info['id'] == $video) {
if($info['status']['privacyStatus'] == 'public') {
$youtube_video = new YouTubeVideos();
// if (!$live_error) {
// foreach ($live_videos as $live) {
// if ($live->youtube_id == $video) {
// $youtube_video->was_live = true;
// }
// }
// }
// dd($video);
$youtube_video->youtube_channel_id = $youtube_channel->id;
$youtube_video->yt_video_id = $video;
$youtube_video->yt_video_title = $info['snippet']['title'];
$youtube_video->yt_video_description = $info['snippet']['description'];
$youtube_video->yt_video_published_at = Carbon::parse($info['snippet']['publishedAt']);
if(isset($info['snippet']['defaultAudioLanguage'])) {
$youtube_video->yt_video_default_audio_language = $info['snippet']['defaultAudioLanguage'];
} else {
$youtube_video->yt_video_default_audio_language = '';
}
if (strcmp($info['contentDetails']['caption'], 'true') == 0) {
$youtube_video->is_video_captioned = true;
} else {
$youtube_video->is_video_captioned = false;
}
$youtube_video->yt_video_definition = $info['contentDetails']['definition'];
$youtube_video->yt_video_dislike_count = 0;
$youtube_video->yt_video_like_count = $info['statistics']['likeCount'];
$youtube_video->yt_video_views_count = $info['statistics']['viewCount'];
//proba type of views
//
$client = new Google_Client();
try{
$client->setAuthConfig(storage_path('app'.DIRECTORY_SEPARATOR. 'json'. DIRECTORY_SEPARATOR.'client_secret.json'));
}catch (\Google\Exception $e){
dd($e->getMessage());
}
// $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly']);
$client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL,GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, GOOGLE_SERVICE_YOUTUBE::YOUTUBEPARTNER,'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']);
$client->setRedirectUri(env('APP_URL') . '/get_access_token_yt_test');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt("consent");
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true); // incremental auth
if (!isset($code)){
$auth_url = $client->createAuthUrl();
return redirect()->away($auth_url)->send();
}else{
if($code != null) {
$client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($client->getAccessToken());
session()->push('refresh_token_youtube', $client->getRefreshToken());
session()->save();
}
}
$service = new Google_Service_YouTube($client);
$analytics = new Google_Service_YouTubeAnalytics($client);
$typeOfViews = $analytics->reports->query([
'ids' => 'channel==' . $youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'views',
'dimensions' => 'liveOrOnDemand',
'filters' => 'video=='.$video
]);
foreach ($typeOfViews as $viewType) {
if ($viewType[0] == 'ON_DEMAND') {
$youtube_video->yt_video_on_demand_views_count = $viewType[1];
} else if ($viewType[0] == 'LIVE') {
$youtube_video->yt_video_live_views_count = $viewType[1];
}
}
$watch_times = $analytics->reports->query([
'ids' => 'channel=='.$youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'estimatedMinutesWatched',
'dimensions' => 'day',
'filters' => 'video=='.$video
]);
// //update quotas
// // self::update_quotas(1);
$total = 0;
foreach ($watch_times as $watch_time){
$total += $watch_time[1];
}
$youtube_video->estimated_minutes_watch_time = $total;
$youtube_video->save();
//zacuvuva captions
$xmlString = file_get_contents("https://video.google.com/timedtext?type=list&v=" . $video);
$xmlObject = simplexml_load_string($xmlString);
$json = json_encode($xmlObject);
$phpArray = json_decode($json, true);
if (isset($phpArray['track'])) {
foreach ($phpArray['track'] as $array) {
$yt_video_captions = new YouTubeVideosCaptions();
$yt_video_captions->youtube_video_id = $youtube_video->id;
$yt_video_captions->language = $array['lang_code'];
$yt_video_captions->save();
}
}
//zacuvuva tags
if(isset($info['snippet']['tags'])) {
if ($info['snippet']['tags'] != null) {
foreach ($info['snippet']['tags'] as $tag) {
$youtube_video_tags = new YouTubeVideosTags();
$youtube_video_tags->youtube_video_id = $youtube_video->id;
$youtube_video_tags->tag = $tag;
$youtube_video_tags->save();
}
}
}
if ($youtube_video->is_video_captioned) {
$captions = YouTubeVideosCaptions::where('youtube_video_id', $youtube_video->id)->get();
foreach ($captions as $caption) {
$video_id = YouTubeVideos::where('id', $caption->youtube_video_id)->first();
$client->authorize();
$fp = fopen('../storage/app/captions/' . $caption->id . '.xml', 'w');
$xmlString = file_get_contents("http://video.google.com/timedtext?type=track&v=" . $video_id['yt_video_id'] . "&id=0&lang=" . $caption['language']);
fwrite($fp, $xmlString);
fclose($fp);
}
}
echo 'done';
}
}
}
}
// Command::line('Youtube videos updated');
//
//
//end new test
}
}

Image upload type for Graphql magento2

Is there any way to upload image using graphql without using base64 format in magento2
public function uploadFile($fileData)
{
// convert base64 string to image and save as file on server.
$uploadedFileName = "";
$fileName = '';
if (isset($fileData['name'])) {
$fileName = $fileData['name'];
} else {
$fileName = rand() . time();
}
if (isset($fileData['filecontent'])) {
$mediaPath = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
$originalPath = 'ModuleName/Attachments/';
$mediaFullPath = $mediaPath . $originalPath;
if (!file_exists($mediaFullPath)) {
mkdir($mediaFullPath, 0775, true);
}
/* Check File is exist or not */
$fullFilepath = $mediaFullPath . $fileName;
if ($this->fileDriver->isExists($fullFilepath)) {
$fileName = rand() . time() . $fileName;
}
$fileContent = base64_decode($fileData['filecontent']);
$savedFile = fopen($mediaFullPath . $fileName, "wb");
fwrite($savedFile, $fileContent);
fclose($savedFile);
$uploadedFileName = "/" . $fileName ;
}
return $uploadedFileName;
}
See more: https://magento.stackexchange.com/a/351629/101754

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>";
}
?>

How to resize a image while uploading in ZF2

I'm new to Zend Frame work and I need to implement image resize while uploading in zend framework 2. I try to use the method in image resize zf2 but it didnot work for me.
please help?
public function addAction(){
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$width = $this->params('width', 30); // #todo: apply validation!
$height = $this->params('height', 30); // #todo: apply validation!
$imagine = $this->getServiceLocator()->get('my_image_service');
$image = $imagine->open($File['tmp_name']);
$transformation = new \Imagine\Filter\Transformation();
$transformation->thumbnail(new \Imagine\Image\Box($width, $height));
$transformation->apply($image);
$response = $this->getResponse();
$response->setContent($image->get('png'));
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('./data/tmpuploads/');
if ($adapter->receive($File['name'])) { //identify the uploaded errors
$profile->exchangeArray($form->getData());
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
}
}
}
}
return array('form' => $form);
}
Related to :-image resize zf2
I get answer for this question by adding external library to zend module.It is a easy way for me. i used http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ class as external library.this is my controller class.
class ProfileController extends AbstractActionController{
public function addAction()
{
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
//set data post and file ...
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('//destination for upload the file');
if ($adapter->receive($File['name'])) {
$profile->exchangeArray($form->getData());
//print_r($profile);
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
$image = new SimpleImage();
$image->load('//destination of the uploaded file');
$image->resizeToHeight(500);
$image->save('//destination for where the resized file to be uploaded');
}
}
}
}
return array('form' => $form);
}
}
Related:-Zend Framework 2 - How to use an external library
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

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