How to retrieve Twitter search results dynamically using Ajax? - php

I'm building a Twitter application which depends on retrieving Twitter search results. It works fine but I still need to update the page to get the new tweets.
How to let the page refreshes itself dynamically just like Twitter Widgets, to show the new tweets ?
Here is my code, please show me how, because I tired many scripts and it doesn't work with me.
Twitter Class
<?php
class Twitter
{
public function __construct(){ }
public function searchResults( $search = null )
{
$url = "http://search.twitter.com/search.atom?q=" . urlencode( $search ) . "&lang=en&rpp=50";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $curl );
curl_close( $curl );
$return = new SimpleXMLElement( $result );
return $return;
}
}
?>
Test Class
<?php
require_once("twitter.class.php");
$Twitter = new Twitter;
$results = $Twitter->searchResults("usa");
foreach( $results->entry as $result )
{
echo "<h3><a href=\"". $result->author->uri ."\">". $result->author->name ."<a/></h3><img src=\"". $result->link[1]->attributes()->href ."\" style=\"float: left;\"><p>". $result->content."</p><div style=\"clear:both;\"> </div>";
}
?>
.
.
Waiting for your response :)

You could poll for changes through javascript / ajax, by setting up a timer that calls a function in Test Class which returns a list of tweets. Example (using jquery because I am no javascript expert):
$(function() {
function fetchTweets() {
$.ajax({
url: "testclass.php",
success: function(data) {
// Replace contents of one element with data
}
}
setInterval(fetchTweets(), 60000);
}

Related

Woocommerce functions returning 500 when called by Ajax

I have created custom plugin that includes a function that sends a GET call to a third party API to get a list of products. It then loops through the list and sends another GET request(using the sku #) for each products details. Then it checks for an existing product and updates the details, if there is no existing product it adds the product to Woocommerce.
The function I have created works just fine when I just add it to a page but I have put it into a separate file to make calls to it with ajax I get a 500 error.
I have narrowed it down to the breaking point and it's whenever a Woocommerce function is called (wc_get_products(), $NewProd = new WC_Product_Simple(), etc.).
Is this some sort of server timeout thing I can adjust? Or maybe something I can change in the WordPress config file? May be wishful thinking. Hopefully, someone can help.
Custom Loop Function in Separate File:
<?php
const bb_lAPI = 'https://sca1.furnguy.com/sca1web/oecgi3.exe';
const bb_tAPI = 'https://sca1.furnguy.com/sca1play/oecgi3.exe';
if (isset($_GET['sec55135'])):
$bbwdVerify = strval($_GET['sec55135']);
$bb_curl = curl_init();
// OPTIONS:
if( $bbwdVerify == 'Live'):
$bb_url = bb_lAPI;
else:
$bb_url = bb_tAPI;
endif;
curl_setopt($bb_curl, CURLOPT_URL, $bb_url . '/inet_website_product_lookup?searchkey=Aluminum');
curl_setopt($bb_curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer CannotShowThis123',
'Content-Type: application/json'
));
curl_setopt($bb_curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($bb_curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($bb_curl);
if(!$result){die("Connection Failure");}
curl_close($bb_curl);
$bbwd_json = json_decode($result);
if($bbwd_json->errors):
echo '<h1>API Error</h1><p class="bpAPIError">'.$bbwd_json->errors->system.'</p>';
echo '<p>requested url = <strong>' . $bb_url . '/inet_website_product_lookup?priceslist=SCA1</strong></p>';
else:
echo '<h1>No errors!!!</h1>';
echo '<p>requested url = <strong>' . $bb_url . '</strong></p><hr style="margin-bottom: 50px;">';
$bbwdItemArr = $bbwd_json->itemlist;
$bbwdItemArrCount = (int) $bbwd_json->totalresults;
$bbwd_Product = array();
for($bbwdI = 0; $bbwdI <= $bbwdItemArrCount; $bbwdI++):
$bbwdProdSS = $bbwd_json->itemlist[$bbwdI]->skuserial;
if($bbwdProdSS):
echo "Product ".$bbwdI." SKUSerial = ".$bbwdProdSS."<br>";
bbwdItemApiLook($bbwdProdSS, "Live");
endif;
echo "<hr>";
endfor;
endif;//end if errors
endif; // end if isset $_GET['sec55135']
function bbwdItemApiLook($bbwdItemSS, $bbwdTest){
// OPTIONS:
if($bbwdTest == 'Live'):
$bb_url2 = bb_lAPI;
else:
$bb_url2 = bb_tAPI;
endif;
echo $bb_zurl2.'/inet_website_item_detail?item='.$bbwdItemSS."<br>";
//$bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS
$bb_curl2 = curl_init();
curl_setopt($bb_curl2, CURLOPT_URL, $bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS);
curl_setopt($bb_curl2, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer CannotShowThis123',
'Content-Type: application/json'
));
curl_setopt($bb_curl2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($bb_curl2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result2 = curl_exec($bb_curl2);
if(!$result2){die("Connection Failure");}
curl_close($bb_curl2);
$bbwd_json2 = json_decode($result2);
if($bbwd_json2->errors):
echo '<h2>API Error = <u>'.$bbwd_json2->errors->system.'</u></h2>';
else:
$bbwdMapped = bbwdMapProduct($bbwd_json2);
echo "<h3>".$bbwdMapped->ssku."</h3>";
bbwdCheckProd($bbwdMapped);
endif;
}
function bbwdMapProduct($bbwdArr){
$bbwdTitle = $bbwdArr->factsrec->shortdescription[0];
$bbwInStock;
$bbwdSku = $bbwdArr->sku;
$bbwdSSku = $bbwdArr->skuserial;
$bbwdPrice = $bbwdArr->inventoryrec->retail;
$bbwdSalePrice = $bbwdArr->inventoryrec->retail3;
$bbwdDescription = $bbwdArr->inventoryrec->description;
if($bbwdArr->availability == "In Stock"):
$bbwInStock = "instock";
else:
$bbwInStock = "outofstock";
endif;
$bbwdPolishedProd = ["title"=>$bbwdTitle, "instock"=>$bbwInStock, "sku"=>$bbwdSku, "price"=>$bbwdPrice, "sale_price"=>$bbwdSalePrice, "description"=>$bbwdDescription, "ssku"=>$bbwdSSku];
return $bbwdPolishedProd;
}
/*=====================================================================
* Manage Woocommerce Products
* ==================================================================*/
/******** Check if product exists ***********/
function bbwdCheckProd($bbwdTheProd){
$bbwdProdName = $bbwdTheProd["title"];
$bbwdNameAdj = strtolower($bbwdProdName);
$bbwdProdSlug = str_replace(" ", "-", $bbwdNameAdj);
$bbwdProdSku = $bbwdTheProd["ssku"];
$bbwdProdPrice = $bbwdTheProd["price"];
$bbwdProdSPrice = $bbwdTheProd["sale_price"];
$bbwdProdDesc = $bbwdTheProd["description"];
$bbwdProdStock = $bbwdTheProd["instock"];
$bbwdExProds = [];
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
THIS IS WHERE THE CODE IS BREAKING!!!
if you a just leave "bbwdOurProducts2" as an empty var the code breaks at the $bbwdNewProd = new WC_Product_Simple(); function located on the ELSE half of the if statement just below.
/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
$bbwdOurProducts2 = wc_get_products( array('sku' => $bbwdProdSku) );
if(!empty($bbwdOurProducts2)):
foreach($bbwdOurProducts2 as $bbwdSProduct):
if($bbwdSProduct->sku == $bbwdProdSku):
$bbwdProdID = get_the_id($bbwdProdSku);
$bbwdSProduct->set_name( $bbwdProdName );
$bbwdSProduct->set_slug( $bbwdProdSlug );
$bbwdSProduct->set_regular_price( $bbwdProdPrice );
if($bbwdProdSPrice > 0):
$bbwdSProduct->set_sale_price( $bbwdProdSPrice );
else:
$bbwdSProduct->set_sale_price( $bbwdProdPrice );
endif;
$bbwdSProduct->set_stock_status( $bbwdProdStock );
$bbwdSProduct->save();
endif;
endforeach;
else:
$bbwdNewProd = new WC_Product_Simple();
$bbwdNewProd->set_name( $bbwdProdName );
$bbwdNewProd->set_slug( $bbwdProdSlug );
$bbwdNewProd->set_sku( $bbwdProdSku );
$bbwdNewProd->set_regular_price( $bbwdProdPrice );
$bbwdNewProd->set_sale_price( $bbwdProdSPrice );
$bbwdNewProd->set_stock_status( $bbwdProdStock );
$bbwdNewProd->set_short_description( 'short description here...' );
$bbwdNewProd->set_description( 'long description here...' );
$bbwdNewProd->set_image_id( 21 );
$bbwdNewProd->set_category_ids( array( 30 ) );
$bbwdNewProd->save();
endif;
echo "Complete!!!";
}
?>
Ajax request
<script type="text/javascipt">
let bbwdLoader = document.createElement('img');
let resultDiv = jQuery('#bbwdResults');
bbwdLoader.src = "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/assets/img/Rhombus-Loader.gif";
/**************************************************************************************************/
/**************************************************************************************************/
The "syncProds()" function is the "onclick" function attached to a button.
I use jQuery in place of $ because of variable errors when using jQuery with WordPress
/**************************************************************************************************/
/**************************************************************************************************/
function syncProds(){
let resultDiv = jQuery('#bbwdResults');
resultDiv.html(bbwdLoader);
console.log('Script Working!!!');
bbwdTheCall();
}
async function bbwdTheCall(){
let bbwdRes;
await jQuery.ajax({
url: "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php",
type: "GET",
async: true,
timeout: 0,
data: {'sec55135': 'Live'},
success:function(result){
resultDiv.html(result);
bbwdRes = result
},
error:function(error){
resultDiv.html("<h2>There was an error!!!</h2><h4>" + error.status + " " + error.statusText + " </h4>");
console.log(error);
}
});
console.log(bbwdRes);
}
</script>
If I got this correctly, first you added the code in a plugin and it worked but when you moved the code into a separate file,it didn't work. Correct? Did you load the WordPress in your https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php file? Probably not. So you can either load a wordpress in your file with include "path to wp-load.php" or use a proper way of running ajax in WordPress using ajax actions. WordPress has a really good support for ajax. Whatever you do, before you run your custom code, WordPress and plugins must be loaded and ready to use.

View full instagram profile picture php script assistance?

I have a wordpress website with a plugin that when you enter in someone's instagram username, it'll show you it in full size. Recently Instagram changed their ways so it no longer works. I found one way that does work, but I'm not sure how to put it into a PHP code.
Here's the tutorial I found:
Get the userId from https://www.instagram.com/{username}/?_a=1
and get the profile pic url from
https://i.instagram.com/api/v1/users/{user_id}/info/
So basically what you do is you go to the first link with the username in there, eg: https://www.instagram.com/JaredGoff/?__a=1
Then you look for the owner id which should be near the top of the page, eg: "owner":{"id":"35192126"}
You copy that string of numbers then go to that second link with the id pasted in, eg: https://i.instagram.com/api/v1/users/35192126/info/
You go to that link and find the scontent-lax3-1.cdninstagram.com link with the highest resolution. It's this one here: https://scontent-lax3-1.cdninstagram.com/vp/0d671bfd2996c4f750e3022e92c2dffa/5B735E9F/t51.2885-19/s640x640/26073736_1686768224695889_7419777864670642176_n.jpg
Then I want to display that image.
here is my current code that doesn't work:
function instagram(){
$instagram_source = wp_remote_get("https://www.instagram.com/" . $_REQUEST['insta_username'] . "/?__a=1");
$instagram_source = json_decode($instagram_source['body'], true);
$profile_pic = $instagram_source['user']['profile_pic_url_hd'];
$profile_pic = str_replace('/s150x150/', '/', $profile_pic);
if(strlen($profile_pic) > 0){
echo '<img src="' . $profile_pic . '">';
}
else{
echo 'Profile does not exist.';
}
wp_die();
}
function wpb_load_widget() {
register_widget( 'wpb_widget' );
}
class wpb_widget extends WP_Widget {
function __construct() {
parent::__construct('instaimage',
__('Instagram Profile Image', 'Instalab'),
array( 'description' => __( '', 'Instalab'),));
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
echo '<form onsubmit="download_image(); return false;">
<input placeholder="Enter instagram username" type="text" id="insta_username" name="insta_username">
<a class="button is-primary" id="insta_submit">Show</a>
</form><br>
<div id="insta_image" style="width:100%;"></div>
';
echo $args['after_widget'];
}
}
?>
Here is my code (I know not the most efficient, but it works):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.instagram.com/$name/?__a=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$json=json_decode($result);
$insta_id = $json->graphql->user->id;
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL,"https://i.instagram.com/api/v1/users/$insta_id/info/");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch1);
curl_close($ch1);
$json=json_decode($result);
$image_url = $json->user->hd_profile_pic_url_info->url;
if($image_url) {
echo '<img src="'.$image_url.'"/>';
}

Salesforce-to-Wordpress: WP Options Table not populating with json from SF

I am attempting to populate a WordPress site with data from Salesforce. Sort of similar to this question maybe except I'm going in the opposite direction. I am basing my code quite a bit on this example, which worked fine for me when I tried it on it's own but not so much once I tried it with Wordpress.
From the example, I only replaced demo_rest.php with the code below,changed that final line in oauth_callback.php to return to my options page in WordPress, made the proper changed to config.php, and replaced index.html. When I did that I see in Salesforce that I am indeed logging in from my plugin, but nothing is coming back to WordPress from there. It's not displaying in the window I want or updating the the mysql database with the json that should result. What am I doing wrong?
My code.
<?php
/*Assign global variables*/
$plugin_url = WP_PLUGIN_URL . '/my-plugin';
$options = array();
// adds plugin settings page in wordpress admin menu
function salesforce_menu(){
add_options_page( // wordpres helper function to add a settings page
'Salesforce to WordPress Integrator',
'Salesforce Integration',
'manage_options',
'salesforce-integrator',
'salesforce_options_page'
);
}
add_action('admin_menu','salesforce_menu');
function salesforce_options_page(){
if ( !current_user_can('manage_options')){
wp_die ('You do not have sifficient permissions to access this page.');
}
global $plugin_url;
global $options;
if( $access_token != '') {
$response = get_stories($instance_url, $access_token);//This is where I'm probably getting messed up. I'm trying to call the get_stories function (defined later)
$options['response'] = $response;
$options['last_updated'] =time();
update_option ('storybank_approved', $options); //wp helper function to update the options table, hopefully with the results of my call to the API.
}
$options = get_option('storybank_approved');
if ($options !=''){
$response = $options['response'];
}
var_dump ($response); //I want this to show me the json on my settings page just to ensure that I have a response, but it looks like I don't
require('includes/options-page-wrapper.php');
}
//get salesforce records
function get_stories($instance_url, $access_token) {
$query = "SELECT Id, Name from salesforce_Object__c LIMIT 100";
$url = "$instance_url/services/data/v20.0/query?q=" . urlencode($query) ;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Authorization: OAuth $access_token"));
$json_response = curl_exec($curl);
curl_close($curl);
$response =json_decode($json_response,true);
$total_size = $response['totalSize'];
echo "$total_size record(s) returned<br/><br/>";
foreach ((array) $response['records'] as $record) {
echo $record['Id'] . ", " . $record['Name']. "<br/>";
}
echo "<br/>";
}
?>
The getStories function is not returning a value.
$response = get_stories($instance_url, $access_token); // has to return something.
//for example, I deleted the rest of the code for simplicity.
function get_stories($instance_url, $access_token) {
$response =json_decode($json_response,true);
return $response;
}

Twitter Get User Status values using API and is there a limit?

All,
I have the following code to grab a twitter status and display it back to the user:
if( ! $tweet ) {
//$format = 'json';
//$contents = file_get_contents( "http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}", 0, $context );
//$contents = file_get_contents(" https://api.twitter.com/1/statuses/user_timeline.json?screen_name={$username}&count={$how_many}", 0, $context );
$url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name={$username}&count={$how_many}";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$contents = curl_exec( $curl );
curl_close( $curl );
if ( ! empty( $contents ) ) {
// Decode it.
$tweet = json_decode( $contents );
// Cache it for next time.
//set_transient( $id.'-'.$username, $tweet, 60*60*3 ); // 3 hour cache
}
}
// Check to make sure we have a tweet and display it.
if ( is_array($tweet) && isset($tweet[0]->id_str)) {
do_action( 'themeblvd_twitter_slider', $tweet, $options, $username, $slider_id );
} else {
$output = '<span class="tweet-icon '.$options['icon'].'"></span>';
$output .= 'We experienced an error with Twitter! Please check back soon for our reviews!';
}
return $output;
So basically I'm trying to determine if I've already fetched some tweets and if not go fetch them and then pass them back to the loop below to display them to the user.
<?php
foreach($tweet as $t){
?>
<li class="slide tight <?php echo $classes; ?>">
<div class="slide-body">
<div class="grid-protection">
<?php
echo '<span class="tweet-icon '.$options['icon'].'"></span>';
echo '<a href="http://twitter.com/'.$username.'/status/'.$t->id_str.'" target="_blank">';
echo $t->text;
echo '</a>';
?>
</div><!-- .grid-protection (end) -->
</div><!-- .slide-body (end) -->
</li>
<?php
}
?>
For some reason I'm getting the error message saying that they can't be displayed. If I keep the limit to like 10 it displays fairly consistently without an error. If I increase the limit to like 50 or 85 I get the error message saying that twitter is having a problem. Has the API changed recently? Do they have new limits? Any ideas on why I can't display the 85 tweets?
Thanks in advace!
I found out that you can actually determine if you've reached your limit yet or not but calling the following URL:
https://api.twitter.com//1/account/rate_limit_status.json
What I did was check the response in this before actually trying to call the user status API. My code to check the rate limit looks like the following:
$url_check_limit = "https://api.twitter.com//1/account/rate_limit_status.json";
$curl_limit = curl_init();
curl_setopt( $curl_limit, CURLOPT_URL, $url_check_limit );
curl_setopt( $curl_limit, CURLOPT_RETURNTRANSFER, 1 );
$contents_limit = curl_exec( $curl_limit );
curl_close( $curl_limit );
if ( ! empty( $contents_limit ) ) {
// Decode it.
$tweet_limit = json_decode( $contents_limit );
}
if ( $tweet_limit->remaining_hits == "0" ){
$no_tweets = true;
echo "We've reached out rate limit";
}else{
//Execute the Twitter user_status API from my original question
}
This allows me to avoid keep calling the twitter API if I hit my limit already. If I didn't hit my limit I call the code in my original question and display the tweets to the user. Hope this helps someone!

Getting Facebook Like count

I have integrated Facebook Like into my website.Now i need to get/list the count of the Facebook like in the Admin panel of my website. Is there any way to get this done?Need suggestions.Thanks in advance.
$url = 'http://graph.facebook.com/PAGE_OR_APP_ID';
echo '['.$url.']: '.json_decode(file_get_contents($url))->{'likes'};
In order to get the number of likes of any object using Facebook API, use a Facebook API of your choice and commands like this:
https://graph.facebook.com/< your object id>/
You will receive a JSON object and you can extract the number of likes from it:
{
"id": "567454",
"link": "http://www.facebook.com/pages/PHP-Developer/103146756409401",
"likes": 250,
"type": "page"
}
More info on https://developers.facebook.com/docs/reference/api/
The more direct / updated link for this topic on facebook is
https://developers.facebook.com/docs/reference/api/page/
function fbLikeCount($appid,$appsecret){
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$appid.'?access_token='.$appsecret;
$json = file_get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
return $likes = $json_output->likes;
}else{
return 0;
}
}
Facebook - <?php echo fbLikeCount('app/page id here','token here'); ?>
You can achieve that using the Graph API (v3)
function checkFacebookReactions($url){
$access_token = 'YOUR-FACEBOOK-TOKEN'; // Generate a Facebook Token first
$api_url = 'https://graph.facebook.com/v3.0/?id=' . urlencode( $url ) . '&fields=engagement&access_token=' . $access_token;
$fb_connect = curl_init(); // initializing
curl_setopt( $fb_connect, CURLOPT_URL, $api_url );
curl_setopt( $fb_connect, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $fb_connect, CURLOPT_TIMEOUT, 20 );
$json_return = curl_exec( $fb_connect ); // connect and get json data
curl_close( $fb_connect ); // close connection
$body = json_decode( $json_return );
// Print each key values, if needed
foreach($body->engagement as $k=>$v){
echo $k .": " .$v ."<br>";
}
$count = $body->engagement->reaction_count; // Return only reactions (likes + other reactions)
return $count;
}
$url = "REPLACE-WITH-YOUR-URL"; // The url you want to fetch details from
checkFacebookReactions($url);
First, you will need to generate a Facebook token. You can fin plenty of resources that explain how to get a token. This one will do the trick: https://elfsight.com/blog/2017/10/how-to-get-facebook-access-token

Categories