Sep 09 2010

How to change twitter status with php and curl without oAuth

Category: PhpGiulio Pons @ 6:43 pm

Twitter api authentication
Since the 31 of august 2010, twitter made its API more secure, stopping basic authentication calls.
So, if you used basic authentication you have to change your code and implement oAuth authentication model (you can read about oAuth on Wikipedia).

The oAuth authentication model
Using oAuth means that you have to register an application on twitter developer site, understand the new model and implement it (here they suggest how to pass to oAuth). In the oAuth model the process of authenticating a user need to take the user on twitter’s site, here he is recognized and he has to grant permission to your application by clicking on an “Allow” button. After this grant step the user is redirected to the application web site with a “token” and a “secret”, and the application that calls the API for posting or reading need to authenticate each call by adding some parameters created with “token” and “secret”. Before this, we needed a few lines of curl to change the status now we need a lot of code, and we really need a user that click on the “allow” button, at least the first time (than we can store “token” and “secret” for each user on database and re-use for each call).
Well, this process is also much more complex, so it’s not possible to think: “I do it by myself!”

Do It Yourself oAuth
I’m really stubborn and I’ve spent quite a day trying to make my own mini-function to post to twitter. But I did only a small part of the process and this part doesn’t fully work and also it wasn’t enough “mini” to include it in my mini php spider class.
So, if you want to use oAuth, I suggest you to use an existing class, especially if you don’t have a week of free time to spend.

Spider, the rough way
twitter php set status with curl
Thus, I did it the rough way: I wrote a bot that calls twitter home, finds the right form to login, fills it with my credentials, and post it. This post returns another page, that’s my homepage, so my bot finds the form to tweet, fills it and sends it. One hour of work, no oAuth. And here is the Php function:

function twitterSetStatus($user,$pwd,$status) {
	if (!function_exists("curl_init")) die("twitterSetStatus needs CURL module, please install CURL on your php.");
	$ch = curl_init();

	// -------------------------------------------------------
	// get login form and parse it
	curl_setopt($ch, CURLOPT_URL, "https://mobile.twitter.com/session/new");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
	curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 ");
	$page = curl_exec($ch);
	$page = stristr($page, "<div class='signup-body'>");
	preg_match("/form action=\"(.*?)\"/", $page, $action);
	preg_match("/input name=\"authenticity_token\" type=\"hidden\" value=\"(.*?)\"/", $page, $authenticity_token);

	// -------------------------------------------------------
	// make login and get home page
	$strpost = "authenticity_token=".urlencode($authenticity_token[1])."&username=".urlencode($user)."&password=".urlencode($pwd);
	curl_setopt($ch, CURLOPT_URL, $action[1]);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost);
	$page = curl_exec($ch);
	// check if login was ok
	preg_match("/\<div class=\"warning\"\>(.*?)\<\/div\>/", $page, $warning);
	if (isset($warning[1])) return $warning[1];
	$page = stristr($page,"<div class='tweetbox'>");
	preg_match("/form action=\"(.*?)\"/", $page, $action);
	preg_match("/input name=\"authenticity_token\" type=\"hidden\" value=\"(.*?)\"/", $page, $authenticity_token);

	// -------------------------------------------------------
	// send status update
	$strpost = "authenticity_token=".urlencode($authenticity_token[1]);
	$tweet['display_coordinates']='';
	$tweet['in_reply_to_status_id']='';
	$tweet['lat']='';
	$tweet['long']='';
	$tweet['place_id']='';
	$tweet['text']=$status;
	$ar = array("authenticity_token" => $authenticity_token[1], "tweet"=>$tweet);
	$data = http_build_query($ar);
	curl_setopt($ch, CURLOPT_URL, $action[1]);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$page = curl_exec($ch);

	return true;
}

Bad things
A you can see from the code there are some things that are not good: we need to make 3 calls because we need to login using a hidden authentication token at the login. This means that this function is slow.
Twitter do not like these methods.
If twitter changes its code, it could happen that this function doesn’t work anymore.

Mini bot class
This class will be included in the Mini bot class, you can try a demo here.

Share

Tags: , , , , , ,


Aug 29 2010

PHP bot to get wikipedia definitions

Category: Php,Spiders & web botsGiulio Pons @ 3:14 pm

Wikipedia, the collaborative and multilingual encyclopedia project, has a lot of usefull terms defined in its database, you can find informations on artists, cities, medical terms, cars, brands… quite everything.
If you need to add some content to your pages without having that content in your database you can use Wikipedia API or Google define query (probably there’s also a Google API). You can, for example, need to add automatically a simple description to a city name, or to a band name. Or you could need to add the definition of some technological terms. You can do all of this things using Wikipedia, since Wikipedia has an API that easily lets you do it.

The php job is simple: we use CURL to call the API that returns an XML response, we parse it and the get the defnition.
Here is the code that make it for italian wikipedia, you can modify the url to match your wikipedia country site:

function wikidefinition($s) {
	$url = "http://it.wikipedia.org/w/api.php?action=opensearch&search=".urlencode($s)."&format=xml&limit=1";
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
	curl_setopt($ch, CURLOPT_POST, FALSE);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_NOBODY, FALSE);
	curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
	curl_setopt($ch, CURLOPT_REFERER, "");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
	$page = curl_exec($ch);
	$xml = simplexml_load_string($page);
	if((string)$xml->Section->Item->Description) {
		return array((string)$xml->Section->Item->Text, (string)$xml->Section->Item->Description, (string)$xml->Section->Item->Url);
	} else {
		return "";
	}
}

This code will be added to the MINI BOTS CLASS.

Share

Tags: , , , , , ,


Aug 09 2010

Send push notification to iPhone with PHP and pushme.to

Category: Php,Spiders & web botsGiulio Pons @ 4:48 pm

Push service is a technology that allows you to send alerts/notifications to a mobile device. Blackberry has its own push service, iPhone has its own, and also Android devices have their own push services (you can learn more on Wikipedia page).
Push notifications are like “sms” but they are free if you have a flat service contract on your mobile.
I want to send push to my iPhone, but I’m not able to develop an iPhone application that receive push alerts, and I don’t want to send only email alerts.
Ok, let’s recap: I have an iPhone and I need to send notifications to my mobile from my PHP scripts.
So I’ve looked deeply in the appStore and I’ve found pushme.to application. This application is made to talk with friends trought web sites and iPhones.
Pushme.to is good because after you’ve registered you can go on their widget page and create a widget for your account to put on your web site. Well, in this post, I will not use this widget for my web site (I don’t want users to write me), but I will use their widget with a mini web bot to send alerts directly to my device through a PHP function.
It happens this way: the cron job calls my php script, my script uses a small bot to call pushme.to widget, pushmeTo sends alerts to my iPhone.

So, if you want to send push to your iPhone thorught a PHP script, download the pushme.to app (it’s free) on your iPhone, register an account and get your pushme.to widget. From the widget code extract the url called in the iframe, it’s something like this:


http://pushme.to/q/widget/export/?hash=51ff0b6e3c1ce3a7a7e473198e1b6d9a

Then, use this php bot function in your scripts:

function pushMeTo($widgeturl,$text,$signature) {
	$agent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12";
	if (!function_exists("curl_init")) die("pushMeTo needs CURL module, please install CURL on your php.");
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $widgeturl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, $agent);
	$page = curl_exec($ch);
	preg_match("/form action=\"(.*?)\"/", $page, $form_action);
	preg_match("/textarea name=\"(.*?)\"/", $page, $message_field);
	preg_match("/input type=\"text\" name=\"(.*?)\"/", $page, $signature_field);
	$ch = curl_init();
	$strpost = $message_field[1].'=' . urlencode($text) . '&'.$signature_field[1].'=' . urlencode($signature);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $strpost );
	curl_setopt($ch, CURLOPT_URL, $form_action[1]);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, $agent);
	$page = curl_exec($ch);
}

Call the function when you want, for example after a database check:

<?
// ... send an alert if database is down...
$url = "http://pushme.to/q/widget/export/?hash=51ff0b6e3c1ce3a7a7e473198e1b6d9a";
if (!mysql_connect( "domain", "user", "password" )) {
	pushmeTo ($url,"Mysql server 'domain' is down!","Your Bot");
}
?>

This small PHP bot “pushmeto” is included in the Mini Bots Class!

Share

Tags: , , , , , , , , ,


« Previous PageNext Page »