hooking a wp function into the cron - php

I've created the following functions to access the twitter api and retrieve the latest tweet. It works just fine and I can display the latest tweet in the footer of my site but rather than happening on every page load I'd like to set up a cron job to fetch the latest tweet every hour.
I've not used the wp cron before so wondered if anyone could advise me on how best to do this?
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function hs_tweets_fetch($screen_name = 'XXXXXXXXXXX', $count = 1) {
$config = array(
'oauth_access_token' => 'XXXXXXXXXXXXXX',
'oauth_access_token_secret' => 'XXXXXXXXXXXXXXX',
'consumer_key' => 'XXXXXXXXXXXXXXXXXXXXXX',
'consumer_secret' => 'XXXXXXXXXXXXXXXX',
'base_url' => 'https://api.twitter.com/1.1/'
);
$url = 'statuses/user_timeline.json?screen_name=' . $screen_name . '&count=' . $count;
$url_parts = parse_url($url);
parse_str($url_parts['query'], $url_arguments);
$full_url = $config['base_url'].$url; // Url with the query on it.
$base_url = $config['base_url'].$url_parts['path']; // Url without the query.
$oauth = array(
'oauth_consumer_key' => $config['consumer_key'],
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $config['oauth_access_token'],
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$base_info = buildBaseString($base_url, 'GET', array_merge($oauth, $url_arguments));
$composite_key = rawurlencode($config['consumer_secret']) . '&' . rawurlencode($config['oauth_access_token_secret']);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(
buildAuthorizationHeader($oauth),
'Expect:'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $full_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$result = curl_exec($feed);
$info = curl_getinfo($feed);
curl_close($feed);
if ($info['http_code'] == 200) {
$result = json_decode($result);
} else {
$result = false;
}
return $result;
}

You have to schedule hourly cron and than have to save tweets in your db. Cron to get tweets could be something like this.
if (!wp_next_scheduled('hs_tweets_fetch_cron'))
{
wp_schedule_event(time(), 'hourly', 'hs_tweets_fetch_cron');
}
add_action('hs_tweets_fetch_cron', 'hs_tweets_fetch');
function hs_tweets_fetch_cron()
{
1- // fetch the tweets
2- // Save/update the tweets in Wordpress options meta or custom table
}
And than display the tweets from database table in footer.

Instead of a cron for this type of work, I'll use the WordPress transient api.
Transient will make the same than à cron but differently. You can set an expiration and datas are store in the options table, If the transient name doesn't exists or if the expiration is over, then the function will create the transient with the data you need.

Related

Twitter API Not Getting Mentions Only Posts

I've set up the twitter API for getting tweets from a username being matthutchings95 and on this account I have posted 10 times with test tweets. Now the page is reading these fine but I then made a second twitter account dannybots111 and wrote a tweet mentioning the first account. But this isn't showing on the page have I got to change the screen_name to something else? I thought this did both mentions and tweets from that account.
<?
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "1140776708-Z03sg5mVXqc4il9ff1EfBcbE5aycwlfslDni2Lt";
$oauth_access_token_secret = "gr6RbsvIq9kUoREjVkwlOgHSwJJU7do91NpCz87PKNMOz";
$consumer_key = "Ub3R51niGzjJIFQtCDrb7tvjJ";
$consumer_secret = "T74d8SJYDET9n8T4PDI7aobNwo9M6fkmQI0hHhWd9ntzY9y5hL";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'screen_name' => 'matthutchings95',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
$tweet = returnTweet();
echo "Tweet No.1: " .$tweet[0]["text"];
echo '<br><br>';
echo "Tweet No.2: " .$tweet[1]["text"];
echo '<br><br>';
echo "Tweet No.3: " .$tweet[2]["text"];
echo '<br><br>';
echo '<br><br>';
print_r(returnTweet());
?>
The user_timeline will only return Tweets posted by the user specified in the screen_name value. You would need to read the mentions_timeline, and you would need to be authenticated as the mentioned user, to see the mentions.

Can't get Twitter trends using PHP

So I'm trying to make a fairly simple php script that fetches the latest worldwide trends from Twitter. Most of the code comes from another StackOverflow post, with some minor modifications. Unfortunately, regardless what I try, all I get is:
{"errors":[{"message":"Could not authenticate you","code":32}]}
Yet this same code works just fine to get timelines, get tweets, post tweets, etc... But when I try trends, for some reason it fails.
$twitterurl = "https://api.twitter.com/1.1/trends/place.json?id=1";
$oauth_access_token = "XXXXXXXXXXXXXXXXXXX";
$oauth_access_token_secret = "XXXXXXXXXXXXXXXXXX";
$consumer_key = "XXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXX";
$oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0');
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value)
{
$r[] = "$key=" . rawurlencode($value);
}
return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
{
$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);
return $r;
}
$base_info = buildBaseString($twitterurl, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $twitterurl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$trends = json_decode($json);
print_r($json);
You can try to modify your php script in these lines:
$twitterurl = "https://api.twitter.com/1.1/trends/place.json"; // DELETE ?id=1
and
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'id' => '1', // ADD THIS ROW
'oauth_nonce' => time(),
and
CURLOPT_URL => $twitterurl . '?id=1', // ADD . '?id=1'
I hope this helps.

Twitter API not authorized when running from crontab

I have set up OAuth and I am using CURL to get the latest tweet, this works perfectly when I run it from my browser
http://mydomain.com/getstatus.php
The script write statuses into a file:
$xTIME = time();
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => $xTIME,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => $xTIME,
'oauth_version' => '1.0'
);
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array(
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
if(isset($twitter_data[0]->text))
{
$fp = fopen('/var/www/mydomain.com/feeds/twitter.feed', 'w');
fwrite($fp, $twitter_data[0]->text);
fclose($fp);
}
This writes to the file nicely, the idea is to have this run every hour.
So I set up a cronjob
0 * * * * lynx -accept_all_cookies http://mydomain.com/getstatus.php
But I get this returned:
[request] => /1/statuses/user_timeline.json?count=1&screen_name=twitter
[error] => Rate limit exceeded. Clients may not make more than 150 requests per hour.
Which suggests it is not authorizing and so treating the request as an unauth'd request.
My question is, why would it not be authorizing?
I have tried running it as a crontab and running it through lynx and I get the same outcome both times.
Edit:
Here are the full functions,
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function loadTW($twID)
{
$url = "https://api.twitter.com/1/statuses/user_timeline.json&count=1&screen_name=" .$twID;
$oauth_access_token = "68161130-X4HRZje9wB3lpyeOPYDJPsqG1JfJxxxxxxxx";
$oauth_access_token_secret = "zN98CUldHN4eiVeGahZIvpNeUGljRTxxxxxxxx";
$consumer_key = "PeVEz2Z0QSKtxxxxxxx";
$consumer_secret = "An9Xh3qHHTEiTQzW5wKLFMHOrbzwFtwxxxxxxxx";
$xTIME = time();
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => $xTIME,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => $xTIME,
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
if(isset($twitter_data[0]->text))
{
$fp = fopen('/var/www/carlandalexfishing.co.uk/feeds/twitter.feed', 'w');
fwrite($fp, $twitter_data[0]->text);
fclose($fp);
}
}
It's pretty hard to know what's going on in your code, as it's not the full code. Anyway :
Your OAuth code only signs the oauth_* headers, not any query arguments.
Your $url variable seems to contain query parameters as well, judging by the error message.
To solve this, just move the query parameters into a separate array and sign the OAuth request with them.
Illustration of what's going wrong (intentionally left out url encoding and added spaces):
GET & https://api.twitter.com/1/endpoint.json?count=1&screen_name=twitter & oauth_abc=def&oauth_ghi=jkl
The query part of the URL shouldn't go in the second part of the OAuth base string. Better :
GET & https://api.twitter.com/1/endpoint.json & count=1&oauth_abc=def&oauth_ghi=jkl&screen_name=twitter

Twitter API PHP Get latest tweets not authenticating

I'm using this peice of code to try and get all my latest tweets for printing on my site but it's returning an error about being not authenticated. I've created an app in the Dev section and get my consumer and OAuth keys, and added them in the right place in the code.
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
$oauth_access_token = "SECURITY";
$oauth_access_token_secret = "SECURITY";
$consumer_key = "SECURITY";
$consumer_secret = "SECURITY";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
foreach ($twitter_data as $elem)
{
print_r($elem);
echo '<br>';
}
Error returned on page
Array ( [0] => Array ( [message] => Could not authenticate you [code] => 32 ) )
Answer seemed to be that the line
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
should not have the ?screen_name=jameskrawczyk at the end.
You have to use an library to get data from twitter
"themattharris" is a good and famous library download it from here

Show facebook, twitter status updates in PHP

in my webpage, I want to show facebook and twitter status updates of my account, as one. Means show statuses from twitter and fb date wise. As shown below:
T: twitter status update 1
T: twitter status update 2
F: Facebook status update 3
T: twitter status update 4
F: Facebook status update 5
I am using wordpress for my website, is there any such plugin in wordpress? or any code using which I can do it manually in php?
Please check and advise.
Thanks!
Here is php code for twitter update/status.
$body = array(
'status'=>'YOURMESSAGE'
);
$url = "https://api.twitter.com/1.1/statuses/update.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$result_data = json_decode($json);
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
`

Categories