Trying to write a script to get my twitter timeline, cannot get return information - twitter-oauth

I’m trying to write a twitter program to get my tinme line. I’m using Abraham
Williams authentication code. I cannot figure out how to pharse the return value. I think it is return a stdClass, which I’m confused about how it works. I can display the objects values by print_r. I was able to see what the xml and json return values would be at http://dev.twitter.com/doc/get/statuses/home_timeline.
code
// Read in our saved access token/secret
$accessToken = file_get_contents("access_token");
$accessTokenSecret = file_get_contents("access_token_secret");
// Create our twitter API object
require_once("twitteroauth/twitteroauth.php");
$oauth = new TwitterOAuth('mykey', 'secret key', $accessToken, $accessTokenSecret);
// Send an API request to verify credentials
$credentials = $oauth->get("account/verify_credentials");
echo "Connected as #" . $credentials->screen_name;
// Post our new "hello world" status
$home_timeline = $oauth->get('statuses/home_timeline',array('count' => 40));
print_r($home_timeline);
// how do i get the information out of home_timeline

GET statues/home_timeline returns an array of statues. You can either access them directly like $home_timeline[0]->text or write a foreach loop.
foreach ($home_timeline as $status) {
echo "Tweet: $status->text<br />\n";
}

Related

dompdf form not working properly in secure server (ssl)

I created a form using dompdf and when I uploaded it to the regular server the website belongs to, it worked fine. However, when I moved it to a secure server (ssl) it didn't work and didn't send the form. The server runs Linux. The webserver is Nginx with FastCGI. Any ideas about what could be going on? I just get an error message from the form saying that not all the mandatory fields have been filled, but there's only two and I filled them.
2015/09/10 22:07:35 [error] 14522#0: *1509 FastCGI sent in stderr: "PHP
message: PHP Warning: strip_tags() expects parameter 1 to be string,
array given in
/var/www/nuweights.net/html/patient_registration_form/form.php on line 13
PHP message: PHP Warning: strip_tags() expects parameter 1 to be
string, array given in
/var/www/nuweights.net/html/patient_registration_form/form.php on line 13
PHP message: PHP Notice: Undefined property: stdClass::$prim_phone in
/var/www/nuweights.net/html/patient_registration_form/pdf.php on line
180" while reading response header from upstream, client: 72.83.230.123,
server: nuweights.net, request: "POST
/patient_registration_form/form.php HTTP/1.1", upstream:
"fastcgi://unix:/var/run/php5-fpm.sock:", host: "ssl.nuweights.net",
referrer: "https://ssl.nuweights.net/patient_registration_form/form.php"
This is the code for the php file. If I need more validation, how can I add it? what would be the code for that?
<?php
if (!empty($_POST)) {
// Used for later to determine result
$success = $error = false;
// Object syntax looks better and is easier to use than arrays to me
$post = new stdClass;
// Usually there would be much more validation and filtering, but this
// will work for now.
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
// Check for blank fields
if (empty($post->first_name) OR empty($post->last_name))
$error = true;
else {
// Get this directory, to include other files from
$dir = dirname(__FILE__);
// Get the contents of the pdf into a variable for later
ob_start();
require_once($dir.'/pdf.php');
$pdf_html = ob_get_contents();
ob_end_clean();
// Load the dompdf files
require_once($dir.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF(); // Create new instance of dompdf
$dompdf->load_html($pdf_html); // Load the html
$dompdf->render(); // Parse the html, convert to PDF
$pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
// Get the contents of the HTML email into a variable for later
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('Patient Registration Form') // Message subject
->setTo(array('info#hotmail.com' => 'Sam')) // Array of people to send to
->setFrom(array('no-reply#net.tutsplus.com' => 'PRF')) // From:
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::newInstance($pdf_content, 'reg_form.pdf', 'application/pdf')); // Attach the generated PDF from earlier
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
}
?>
Your secure server is separate from your non-secure one, correct? It looks like maybe display_errors (in the PHP configuration) is set to "on" for the secure server. Because of this you're seeing messages from PHP related to code notices and errors. Unless you're on a dev server you should pretty much always disable that setting to avoid information disclosure.
Before you worry about what dompdf is doing you should address the configuration issues and add some exception handling and/or validation to your code.
Some thoughts on what you've posted.
You're generally validating without regard to the data type in your foreach loop. You should at least check whether the variable is parseable by strip_slashes(), e.g.:
foreach ($_POST as $key => $val) {
if (is_array($_POST[$key])) {
// assuming this is an array of values
$post->$key = array_map('trim', array_map('strip_slashes', $_POST[$key]));
}
else
{
$post->$key = trim(strip_tags($_POST[$key]));
}
}
2 - You're trying to validate properties that may or may not exist on your object. Since you're not making any definite assignments you need to check that these properties even exist before you validate against them:
if (!property_exists($post, 'first_name') || !property_exists($post, 'last_name') || empty($post->first_name) || empty($post->last_name))
{
$error = true;
}
3 - Why are you assigning properties to a generic object in the first place? If you want to use an object you should probably go ahead and define the class so that you can populate and validate the values during instantiation. If you don't want to do that assign them to variables so you know, really know, what data you have. If you want to short-cut it you could do something like this (or write your own):
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
To simplify this for a large number of you could even set up an array of expected params and parse that array to set your values:
$post = array();
foreach (array('first_name','last_name') as $key)
{
$post[$key] = filter_var($_POST[$key], FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
}
4 - Use curly braces for clarity ... always
You might want to take this over to https://codereview.stackexchange.com/ to get a more thorough critique.

Instagram Real-time API duplicate requests

I have an issue where when I create a real-time subscription I get duplicate notifications from different Instagram IP addresses. I have it set up so that when I get a notification, I send a request for latest updates using the min_tag_id setting. I store that in my db to use it for the next request. I don't always get duplicates, but when I do, everything about the notification is the same (time, object,changed_aspect), except I can tell they are different from my debugging output which lists two almost identical requests... the only differing info being a different IP address and the REQUEST_TIME_FLOAT is different by about 1/10th of a second. They even have the same HTTP_X_HUB_SIGNATURE value.
My general algorithm is:
process_subscription_update($data){
# get old min_id
$min_tag_id = mysqli_fetch_object(mysqli_query($dbconnecti,sprintf("SELECT instagram_min_id+0 as instaid FROM xxxx WHERE xxxx=%d",$_GET['xxxx'])));
$min_id = $min_tag_id->instaid;
# make api call
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.instagram.com/v1/tags/'.$_GET['tag'].'/media/recent?client_id=xxxx&min_tag_id='.$min_id.($min_id==0?'&count=1':''));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$i = json_decode($result);
if ($min_id == $i->pagination->min_tag_id) { exit; }
# write new min_id to db
record_min_id($i->pagination->min_tag_id);
$data2 = $i->data;
foreach($data2 as $d) {
process_instagram($d);
}
// debugging output: ****************
$file = file_get_contents($_SERVER['DOCUMENT_ROOT'].'instagram/updates.txt');
$foo = "\n";
foreach($_SERVER as $key_name => $key_value) {
$foo .= $key_name . " = " . $key_value . "\n";
}
$fulldata = $file . "\n\n\n" . $result . "\n min_id = " . $min_id . $foo;
$fulldata .= "\nTIME:".$data[0]->time;
$fulldata .= "\nOBJECT:".$data[0]->object;
$fulldata .= "\nCHANGED_ASPECT:".$data[0]->changed_aspect;
file_put_contents($_SERVER['DOCUMENT_ROOT'].'instagram/updates.txt', $fulldata);
// end debugging output *************
}
I'd like to avoid checking if the instagram message id already exists in my db within the process_instagram function, and with the duplicates only coming 1/10th of a second apart, I don't know if that would work anyway.
Anybody else experience this and/or have a solution?
I solved this. I don't think there is anything I can do about receiving the duplicate notifications. So, when writing the Instagram to my db, I have a field for the Instagram id and put a unique constraint on the field. After doing the mysqli INSERT, I check to see if the errno = 1062, and if it does, I exit.
mysqli_query($dbconnecti,"INSERT INTO xxx (foo, etc, instagram_id ...")
if ($dbconnecti->errno==1062) { exit; }
...
// more script runs here if we don't have a duplicate.

How to match a result to a request when sending multiple requests?

A. Summary
As its title, Guzzle allows to send multiple requests at once to save time, as in documentation.
$responses = $client->send(array(
$requestObj1,
$requestObj2,
...
));
(given that each request object is an instance of
Guzzle\Http\Message\EntityEnclosingRequestInterface)
When responses come back, to identify which response is for which request, we can loop through each request and get the response (only available after executing the above command):
$response1 = $requestObj1->getResponse();
$response2 = $requestObj2->getResponse();
...
B. Problem
If the request object contains the same data. It's impossible to identify the original request.
Assume we have the following scenario where we need to create 2 articles: A and B on a distance server: something.com/articles/create.json
Each request has same POST data:
subject: This is a test article
After created, the Guzzle responses with 2 location come back:
something.com/articles/223.json
something.com/articles/245.json
Using the above method to link response-to-its-request, we still don't know which response is for which article, because the request object is exactly the same.
Hence in my database I cannot write down the result:
article A -> Location: 245.json
article B -> Location: 223.json
because it can be the other way arround:
article A -> Location: 223.json
article B -> Location: 245.json
A solution is to put some extra parameter in the POST request, e.g.
subject: This is a test article
record: A
However, the distance server will return error and does not create article because it does not understand the key "record". The distance server is a third party server and I cannot change the way it works.
Another proper solution for this is to set some specific id/tag on the request object, so we can identify it afterwards. However, I've looked through the documentation but there is no method to uniquely identity the request like
$request->setID("id1")
or
$request->setTag("id1")
This has been bugging me for months and still cannot resolve this issue.
If you have solution, please let me know.
Many many thanks and you've saved me!!!!
Thanks for reading this long post.
I've found a proper way to do it, Guzzle allow to add callback once a request is completed. So we can achieve this by setting it on each request in the batch
Each request by default can be created like this
$request = $client->createRequest('GET', 'http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar']
]);
So, to achieve what we want:
$allRequests = [];
$allResults = [];
for($k=0; $k<=10; $k++){
$allRequests['key_'.$k] = $client->createRequest('GET', 'http://httpbin.org?id='.$k, [
'headers' => ['X-Foo' => 'Bar'],
'events' => [
'complete' => function ($e) use (&$allResults, $k){
$response = $e->getResponse();
$allResults['key_'.$k] = $response->getBody().'';
}
]
]);
}
$client->sendAll(array_values($allRequests));
print_r($allResults);
So now the $allResults has result for each corresponding request.
e.g. $allResults['key_1'] is the result of $allRequests['key_1']
I was having the same problem with this.
I solved it by adding a custom query parameter with a unique id generated for each request and add it to the request url (you will need to remember this ids for each one of them to address it after).
After $responses = $client->send($requests) you could iterate through the responses and retrieve the effective url $response->getEffectiveUrl() and parse it (see parse_url and parse_str) to get the custom parameter (with the unique id) and search in your array of requests which one has it.
I found a much better answer.
I was sending batches of 20 requests at a time, 4 concurrently, and used the pooling technique where I got fulfilled, and rejected back, as in the documentation.
I found that I could add this code to the end of my requestAsync() function calls, when yielding / building the array (I do both in different places).
$request = $request->then(function (\GuzzleHttp\Psr7\Response $response) use ($source_db_object) {
$response->_source_object = $source_db_object;
return $response;
});
And then in the clousures on the pool, I can just access the _source_object on the response normally, and it works great.
I find it a little hacky, but if you are just sure to use a name that NEVER clashes with anything in Guzzle, this should be fine.
Here is a full example:
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response as GuzzleResponse;
$client = new Client();
$requests = [];
// Simple set-up here, generate some random async requests
for ($i = 0; $i < 10; $i++) {
$request = $client->requestAsync('GET', 'https://jsonplaceholder.typicode.com/todos/1');
// Here we can attach any identifiable data
$request->_source_object = $i;
array_push($requests, $request);
}
$generator = function () use($requests) {
while ($request = array_pop($requests)) {
yield function() use ($request) {
return $request->then(function (GuzzleResponse $response) use ($request) {
// Attach _source_object from request to the response
$response->_source_object = $request->_source_object ?? [];
return $response;
});
};
}
};
$requestPool = new Pool($client, $generator(), [
'concurrency' => 5,
'fulfilled' => function ($response) {
// Then we can properly access the _source_object data once response has arrived here!
echo $response->_source_object . "\n";
}
]);
$requestPool->promise()->wait();
I do it this way :
// create your requests
$requests[] = $client->createRequest('GET', '/endpoint', ['config' => ['order_id' => 123]]);
...
// in your success callback get
$id = $event->getRequest()->getConfig()['order_id']
An update related to the new GuzzleHttp guzzlehttp/guzzle
Concurrent/parallel calls are now run through a few different methods including Promises.. Concurrent Requests
The old way of passing a array of RequestInterfaces will not work anymore.
See example here
$newClient = new \GuzzleHttp\Client(['base_uri' => $base]);
foreach($documents->documents as $doc){
$params = [
'language' =>'eng',
'text' => $doc->summary,
'apikey' => $key
];
$requestArr[$doc->reference] = $newClient->getAsync( '/1/api/sync/analyze/v1?' . http_build_query( $params) );
}
$time_start = microtime(true);
$responses = \GuzzleHttp\Promise\unwrap($requestArr); //$newClient->send( $requestArr );
$time_end = microtime(true);
$this->get('logger')->error(' NewsPerf Dev: took ' . ($time_end - $time_start) );
In this example you will be able to refer to each of the Responses using $requestArr[$doc->reference] . In short give an index to your array and run the Promise::unwrap call.
I also had come across this issue. This was the first thread coming up. I know this is a resolved thread, but I have eventually come up with a better solution. This is for all those who might encounter the issue.
One of the options is to use Guzzle Pool::batch.
What batch does is, it pushed the results of pooled requests into an array and returns the array. This ensures that the response and requests are in the same order.
$client = new Client();
// Create the requests
$requests = function ($total) use($client) {
for ($i = 1; $i <= $total; $i++) {
yield new Request('GET', 'http://www.example.com/foo' . $i);
}
};
// Use the Pool::batch()
$pool_batch = Pool::batch($client, $requests(5));
foreach ($pool_batch as $pool => $res) {
if ($res instanceof RequestException) {
// Do sth
continue;
}
// Do sth
}

Twitter RSS feed, [domdocument.load]: failed to open stream:

i'm using the following:
<?php
$doc = new DOMDocument();
$doc->load('http://twitter.com/statuses/user_timeline/XXXXXX.rss');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
);
array_push($arrFeeds, $itemRSS);
}
for($i=0;$i<=3;$i++) {
$tweet=substr($arrFeeds[$i]['title'],17);
$tweetDate=strtotime($arrFeeds[$i]['date']);
$newDate=date('G:ia l F Y ',$tweetDate);
if($i==0) { $b='style="border:none;"'; }
$tweetsBox.='<div class="tweetbox" ' . $b . '>
<div class="tweet"><p>' . $tweet . '</p>
<div class="tweetdate">#' . $newDate .'</div>
</div>
</div>';
}
return $tweetsBox;
?>
to return the 4 most recent tweets from a given timeline (XXXXX is the relevant feed)
It seems to work fine but i've recently been getting the following error sporadically:
PHP error debug
Error: DOMDocument::load(http://twitter.com/statuses/user_timeline/XXXXXX.rss) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.1 502 Bad Gateway
I've read that the above code is dependant on Twitter beign available and I know it gets rather busy sometimes. Is there either a better way of receiving twits, or is there any kind of error trapping i could do to just to display "tweets are currently unavailable..." ind of message rather than causing an error. I'm usnig ModX CMS so any parse error kills the site rather than just ouputs a warning.
thanks.
I know this is old, but I was just searching for the same solution for a nearly identical script for grabbing a twitter timeline. I ended up doing this, though I haven't been able to thoroughly test it.
I defined the twitter url as a variable ($feedURL), which I also used in $doc_load. Then, I wrapped everything except for the $feedURL into this conditional statement:
$feedURL = "http://twitter.com/statuses/user_timeline/XXXXXXXX.rss"
$headers = #get_headers($feedURL);
if (preg_match("/200/", $headers[0])){
//the rest of you original code in here
}
else echo "Can't connect user-friendly message (or a fake tweet)";
So, it's just checking the headers of the the feed's page, and if its status is 200 (OK), then the rest of the script will execute. Otherwise, it'll echo a message of your choice.
(reference: http://www.phptalk.com/forum/topic/3940-how-to-check-if-an-external-url-is-valid-andor-get-file-size/ )
ETA: Or even better, save a cached version of the feed (which will also ensure you don't go over your API limit of loads):
<?php
$cache_file = dirname(__FILE__).'/cache/twitter_cache.rss';
// Start with the cache
if(file_exists($cache_file)){
$mtime = (strtotime("now") - filemtime($cache_file));
if($mtime > 600) {
$cache_rss = file_get_contents('http://twitter.com/statuses/user_timeline/75168146.rss');
$cache_static = fopen($cache_file, 'wb');
fwrite($cache_static, $cache_rss);
fclose($cache_static);
}
echo "<!-- twitter cache generated ".date('Y-m-d h:i:s', filemtime($cache_file))." -->";
}
else {
$cache_rss = file_get_contents('http://twitter.com/statuses/user_timeline/75168146.rss');
$cache_static = fopen($cache_file, 'wb');
fwrite($cache_static, $cache_rss);
fclose($cache_static);
}
//End of caching
?>
Then use $cache_file in your $doc->load($cache_file) statement instead of the actual feed url.
(Adapted from here: http://snipplr.com/view/8156/twitter-cache/).

Triggering conversion tracking code on form submit

I have a PHP form that mail()s the form data on submit and then if successful returns them to the referring page (in other words keeping them on the same page as the form) and appends ?success=TRUE to the URL.
The question is, how would I implement the AdWords and Yahoo Search Marketing conversion code snippets to trigger only when the form is submitted? For functionality purposes, it is unfortunately not feasible to send them to another page on submit which would have been the easiest way to do it.
The relevant code from the form submit action that mails the results and sends them back to the homepage is below. I have a hunch it might be as simple as outputting the conversion tracking code snippets in the if statement at the end there but I'm not sure if that is correct or the syntax to properly do that.
if ( isset($_POST['sendContactEmail']) )
{
$fname = $_POST['posFName'];
$lname = $_POST['posLName'];
$phone = $_POST['posPhone'];
$email = $_POST['posEmail'];
$note = $_POST['posText'];
$to = $yourEmail;
$subject = $yourSubject;
$message = "From: $fname $lname\n\n Phone: $phone\n\n Email: $email\n\n Note: $note";
$headers = "From: ".cleanPosUrl($_POST['posFName']. " " .$_POST['posLName'])." \r\n";
$headers .= 'To: '.$yourName.' '."\r\n";
$mailit = mail($to,$subject,$message,$headers);
if ( #$mailit ) {
header('Location: '.$referringPage.'?success=true');
}
else {
header('Location: '.$referringPage.'?error=true');
}
}
Outputting it in the if-Statement would be a possibility, but the script you posted adds another way to do it as it redirects to the $referringPage - if the mail was successfully sent. And that's the only event you want to track a conversion.
So edit the code of $referringPage (the page that holds the form fields) and add:
<?php
if($_GET['success'] == 'true') {
echo "...";
}
?>
"..." ofcourse has to be replaced by the Adwords conversion Code Google gave you.
If you add it to your question, I could even add it to my answer.