Automated MySQL Database Backup System

I just finished writing a tool to automate mysql database backup. It dumps the configured mysql database, zips the SQL file into a TGZ archive and emails the attachment to a predefined email address.

Download: http://masnun.googlecode.com/files/sqlbackup.zip

What you need to do to use this tool is to download it, extract the folder named “sqlbackup”, edit the index.php file to configure the database and email settings, upload the folder to your webhost and set up a cron job to run the tool periodically.

In fact, it’s simple though it looks complicated. Try it yourself! Gonna be easy.

I am using Yahoo! Mail and a custom filter to store the database backups into a dedicated folder inside my Yahoo! Mailbox. Yahoo! has un-metered storage. So you can use this huge storage to have your databases backed up safely.

I am running the cron job once everyhour for testing purpose. I will set it to run once a day since I don’t have much database operations everyday. If your application sees frequent database changes, use a frequent cron job. Please consider checking out your control panel to know how to set a cron job if you don’t know already.

Enjoy!

Tagged , | 1 Comment

Coupling Zend Framework with CodeIgniter

CodeIgniter is a super cool web application framework for PHP. It is lightweight and lets you get the jobs done in a fashion. It is the first framework I have used and I am still using it. On the other hand, Zend Framework is from Zend, the PHP company. I appreciate the huge library and the full stack nature. I respect the fact that ZF is from the people who maintain PHP. But honestly, I don’t find it feasible for medium and small projects.

One of the brighter aspects of the Zend Framework is that it has many cool libraries. The framework itself is loosely tied and the components are available as stand alone. We can take this opportunity to integrate the powerful library of the Zend Framework into the beautiful CodeIgniter making ourselves more productive than before. Specially, we can relieve ourselves from writing and maintaining wrappers to different APIs.

Ok then, let’s see how do we integrate the Zend Framework libraries into CI.

1) Setup CodeIgniter.

2) Download the Zend Framework. Extract the archive.

3) From the ZF files, copy the “Zend” directory from inside the “library” directory.

4) Paste the directory into the “system/application/libraries” directory. So ultimately, the new location of the copied “Zend” directory would be “system/application/libraries/Zend”. If you’re on Linux/Unix, we need to deal with file permission. Make the Zend directory accessible by all. I don’t think I need to tell you how to do that with chmod, do I ? ;)

5) In the same “system/application/libraries/” directory, create a new file named “Zend.php” and put the following contents:

 
<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');}
 
class Zend
{
 
	function __construct()
	{
 
		ini_set('include_path',
		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');
 
	}
 
 
	function load($class)
	{
		require_once (string) $class . EXT;
 
	}
}
 
?>

:) We are done. That completes the integration. Now we can load any Zend component inside our controllers. Let’s make our hands dirty by modifying the default welcome controller. Open the “system/application/controllers/welcome.php” and put the following contents:

<?php
 
class Welcome extends Controller {
 
	function Welcome()
	{
		parent::Controller();
	}
 
	function index()
	{
		 $this->load->library('zend');
		 $this->zend->load('Zend/Service/Flickr');
 
		$flickr = new Zend_Service_Flickr('12e99caebb8f305fff5a943606ecde18');
 
		$results = $flickr->tagSearch('worldcup');
 
 
 
		foreach ($results as $result)
		{
 
                      $photo = $result->Small;
                      echo "<a href=\"{$photo->clickUri}\"><img src=\"{$photo->uri}\" /></a><br /><br />";
 
		}
 
	}
}
?>

If you read the codes above, you already know what it does :) If everything goes right, you’ll see a bunch of Flickr photos with the “worldcup” tag. Clicking on a photo will take you to the Flickr page of that photo.

Now, what we have seen is pretty straightforward. We don’t use any hooks or don’t go for any complexity. We simply put the Zend library in the application library. Then we write a loader class that loads Zend libraries. When we construct this “Zend Loader” object, it adds the Zend library directory to the include path. Then when we use the load() method of the object, it imports the library and adds the functionalities to the current scope :)

Enjoy the Zend Services with the cool CodeIgniter framework! Have fun :D

Tagged , | 11 Comments

CodeIgniter Code Completion with the Netbeans IDE for PHP

CodeIgniter is my favorite web application framework for PHP and Netbeans is the IDE I use for all sorts of web development. The latest version of Netbeans IDE (6.9) has support for both Symfony and Zend Framework. But it still has no official support for CodeIgniter. So, in the default installation, you will always miss the fantastic code completion feature of the IDE.

After Googling a while, I just learned a magic trick that can emulate this feature in Netbeans. The process is pretty simple. We feed Netbeans a php file that has a simple sample “Controller” class definition that has phpdoc specifying the necessary properties. We put this file in a place readable by the IDE by invisible or worthless for the CodeIgniter framework. The “nbproject” directory inside the project root could be a good place to put this file. What really happens is that Netbeans reads the phpdoc and offers the completion of the specified properties in any class that extends the Controller class. Hiding it from CodeIgniter helps not to mess up with the system.

This is what I did. I created a php file and named it “nb.php”. I filled this file with the following contents:

<?php
/**
* @property CI_Loader $load
* @property CI_Form_validation $form_validation
* @property CI_Input $input
* @property CI_Email $email
* @property CI_DB_active_record $db
* @property CI_DB_forge $dbforge
* @property CI_Table $table
* @property CI_Session $session
* @property CI_FTP $ftp
* ....
*/
Class Controller {
}
?>

And put the file inside my nbproject directory. Now I am getting code completion in my Netbeans for CodeIgniter.

Tagged , | 8 Comments

Changing Font Style in PHP Generated Image

To change the font style, you need to use different fonts. You can use the imagettftext() function to draw text on a php generated image using GD. Here’s a code snippet:

<?php
header('Content-type: image/png');
$im = imagecreatetruecolor(400, 300);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 299, $white);
$text = 'maSnun';
$font = '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf';
imagettftext($im, 50,180, 300, 130, $black, $font, $text);
imagepng($im);
imagedestroy($im);
?>

Have a look at the function’s doc on php.net to learn more. http://www.php.net/imagettftext :)

It’s not that hard! Put the file in the www directory of a ubuntu LAMP server and visit the url on a web browser :)

Tagged | Leave a comment

My First Gedit Plugin

I am now using Ubuntu 10.04. In an older post of mine, I described how you can use the PHP_Beautifier tool with Gedit to code php in a fashion. But the major drawback was that a shell output used to popup every time you used the external tool. I was looking for a solution and even after a while I could not find one.

I knew Gedit supports plugins and you could write plugins in C & Python. Blessed that I know some Python, I went through the plugin API and soon realized that gedit plugin development was not much hard. I took a sample snippet, scratched and played around and finally achieved what I wanted.

I named it “Shell Hider”. All it does is to disable the entire bottom panel so that the shell output don’t stay long. In fact, the shell window will popup for a second and then hide itself. On a fast machine, you probably won’t see the popup at all!

Download it from here: http://bit.ly/cQeTMx

Enjoy!

Tagged | 3 Comments

Text based Captcha with PHP

I needed text based captcha for my mobile web application to stop automated registrations. The mobile application was developed targeting the WAP devices without any fancy JS or iFrame support. So, I was forced to put some text based captcha. I set one up earlier which didn’t require any database but it was just an eye wash. If anyone examined the HTML source, s/he would know how to break it through.

This time I have come up with something better, something more effective. It is quite simple. Have a look at the source code and you’ll understand yourself.

The SQL for the Table:

CREATE TABLE IF NOT EXISTS `masnun_text_captcha` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `captcha` varchar(255) NOT NULL,
  `time` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

The TextCaptcha Class :

<?php
 
 
class TextCaptcha {
    public function getCaptcha($id) {
        $res = mysql_fetch_assoc(mysql_query("select captcha from masnun_text_captcha where id='{$id}'"));
        return $res['captcha'];
    }
 
    public function verifyCaptcha($id,$captcha) {
        $captchaFromId = $this->getCaptcha($id);
        if ( !empty ( $captchaFromId ) && $captchaFromId == $captcha ) {
            mysql_query("delete from masnun_text_captcha where id='{$id}'");
            return true;
        } else {
            return false;
        }
    }
 
    public function createNew() {
        $time = time();
        $salt = "mZs45#";
        $rand = rand(0,100);
        $hash = md5($time.$salt.$rand);
        $string = substr($hash, 0, 5);
        mysql_query("insert into masnun_text_captcha (captcha,time) values('$string','$time')");
        $id = mysql_insert_id();
        $data['id'] = $id;
        $data['captcha'] = $string;
        return (object) $data;
    }
}
 
?>

You might notice that I haven’t used the “time” field. It will be used to delete unused captcha via cron or in some other way. Didn’t get the time to code that.

And how to use it:

<?php
include 'textCaptcha.class.php';
 
// We must have an already open mysql connection to the database
mysql_connect("localhost","masnun","masnun");
mysql_select_db("text_captcha");
 
 
$TextCaptcha = new TextCaptcha(); # Construct the object
$captcha = $TextCaptcha->createNew(); # Create a new Captcha Object

/*
 * The Captcha Object has two properties:
 * id --> The ID of the Captcha. You use it as an identifier.
 * captcha --> The Text that is matched with the id to verify
 * 
 */
 
$bool = $TextCaptcha->verifyCaptcha($captcha->id, $captcha->captcha);
var_dump($bool); // Always true :) Alter the code to play yourself
?>

Have fun! If you don’t get anything, please place a question below.

1 Comment

Working with the Google Chart (Visualization) JavaScript APIs

For a current project at my workplace I need a good charting solution. I need a pie chart for now, on which people can actually click and interact. I found a few tools and went for the Google Visualization APIs. The APIs are a set of JS libraries which let you build quick charts and graphics out of data tables. I started trying the sample codes on the Google Ajax playground and quickly understood which way to go to get things right. First I must make it clear that, I’m no Javascript pro. I have coded with jQuery a few times before and I have no real experience with JS until today. It is just today I spent a good amount of time with the Facebook JS APIs. Who knows if it’s the brilliant documentation at the Google Code or my fast learning ability, it took me just one hour to learn the Visualization APIs and cook something up from scratch.

Here’s the source code:

google.load("visualization","1", {"packages":["piechart"]});
google.setOnLoadCallback(drawChart);
 
function drawChart() {
	table = new google.visualization.DataTable();
	table.addColumn("string","Languages");
	table.addColumn("number","Hours worked");
	table.addRows(3);
	table.setValue(0,0,"PHP");
	table.setValue(1,0,"Python");
	table.setValue(2,0,"JS");
	table.setValue(0,1,5);
	table.setValue(1,1,1);
	table.setValue(2,1,3);
 
	targetDiv = document.getElementById('chart');
	chart = new google.visualization.PieChart(targetDiv);
	chart.draw(table, {width: 400, height: 240, is3D: true, title: 'Languges Worked With (in hours)'});
 
	new google.visualization.events.addListener(chart, 'select', selectionHandler);
 
	function selectionHandler(e) {
			selectedData = chart.getSelection();
			row = selectedData[0].row;
			item = table.getValue(row,0);
			time = table.getValue(row,1);
			resultDiv = document.getElementById('res');
			resultDiv.innerHTML = "Selected Language: " + item + " / Working Hours: " + time + "<br>";
		}
 
 
	}

It’s very simple and easy. First we include the root javascript from: http://google.com/jsapi and then put the above codes in a script tag inside head.

We use the google loader to load the visualization package and then use it to build a PieChart. When the loading is done, the setOnLoadCallback() method invokes another function to proceed with further execution. We packed our main code inside a drawChart() function and set it as the callback.

To assemble the data, we first need a DataTable. A data table is an object with virtual columns and rows. First, we need to define the columns. We do that by calling the addColumn() method. The first parameter is the data type and the second one is the name. In our example, we added two columns.

Next, we call the addRows() passing an integer as the only parameter. This method creates “filler” or empty sets for putting data into.

Then, we use the setValue() call to insert/update data. The first parameter is the row number counted from 0. The second one is the index of column. Remember the sequence of the column definitions? Yes, follow that sequence. The first column is the index 0. The 3rd parameter is the actual value for that row and column.

table.setValue(2,1,"meaow")

The above call will insert the string “meaow” into the second column of the 3rd row. It’s easy! :)
PS: Please be aware of the data type of the column while inserting/updating data.

Now that we have a DataTable at our disposal, all we need to do is feed this data to a PieChart and draw it up. First, we created a new div with the id “chart”. This div will be holding the chart. Then we call the PieChart constructor with this div element. Then we call the draw() method of the chart object to paint it on the screen. The first parameter is the datatable and the second one is an object (dictionary/associative array like) defining the look and feel of the charts.

That draws the chart alright. But I need to let the users interact with the chart. So, I added a Listener to listen to any “select” events and call the handler function back. We get a event object but for select events, they don’t have any properties. That is they don’t tell you what the user clicked. You have to get the data by calling the getSelection() method of the chart. The returned object will have “row” and “column” values. For PieChart, alone the row value does the job. We get the row index. Then call the getValue() method of the data table to get the value of a certain column in a row. In this case, I just iterated over both columns. Built a text string out of the data and dynamically updated a div with that!

It’s pretty simple. It’s powerful and user friendly as well.

PS: I really liked the Google Ajax Playground. I am gonna play a lot in there from now on :)
I just realized I’m becoming a good coder as well. I wrote the above codes without any pretty printer or code formatter. It looks well indented to me :D

Tagged , | Leave a comment

Using The Facebook Graph API with js-sdk : An explanatory Tutorial

The facebook Graph API has a nice Javascript SDK to build applications using JS. The most important benefit is that with JS you could tightly integrate the Facebook Graph API with your web application.

Integration is quite easy. First we add a fbAsyncInit object to the window object for asynchronous initiating. The following code snippet was borrowed from the official docs and then slightly modified:

 
            window.fbAsyncInit = function() {
                FB.init({appId: appId, status: true, cookie: true, xfbml: true});
 
                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });
 
                FB.getLoginStatus(function(response) {
                    if (response.session) {
                        // logged in and connected user, someone you know
                        login();
                    }
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());
 
           function login() {
           alert('login');
           }
 
           function logout() {
           alert('logout');
           }

Thanks to the elegance of Javascript, we called the newly constructed object immediately after initiating, with a callback that loaded the JS sdk on our page. We registered the auth.login, auth.logout events and for initially looking for any logged in user, we made the getLoginStatus() call. In fact this code snippet initiates the facebook access on the page. Registering the events to our custom functions, we just made sure that, we know when something important happens. While iniating, if the user is already logged in, the login() function gets called because of the getLoginStatus() call. Later, after initiating, if the user logs in or logs out, the auth.login and auth.logout events get fired. Our registered handlers will be called in those cases.

To make things easy for the end user, you can use a fb:login-button tag from FBML. I believe Facebook app developers are already aware of that. Still, I was just reminding that you can still use those tags :D A login button is going to help you. Because, it’s mandatory that you call the FB.login() on an user event (like button click) because most browsers won’t allow opening a popup on a non-user event.

Now the user is logged in and authorized the apps, you can start customizing your contents for the user. You can always check for available users by calling the FB.getSession() function. It returns null if no user is available, otherwise, it returns a session object with access_token, app key and secret and most importantly the user uid.

session = FB.getSession()
if(session) {
    alert(session.uid);
        } else {
     alert('no user logged in');
}

You can use the dir() function on the session object to explore it on the Firebug console.

Now, you can make calls to the Graph API using the normal path pattern:

FB.api("/me/photos", function(response) { alert(response.data[0].link) });

The above code will alert() the user’s latest photo URI. Well, make sure that the applicaton has permissions to make the calls.

You can even mix up with the legacy API by passing an object with a “method” parameter pointing to the method name and related args. You can build the Facbook UIs using the FB.ui() call. Have a look how we use legacy API and UI to build a nifty sharing dialog box.

var share = {
   method: 'stream.share',
   u: 'http://masnun.com/'
 };
 
 FB.ui(share, function(response) { console.log(response); });

Here, instead of alert()ing the response, we logged it to the console :D

In this way, you can interact with the user the way you want. It’s plain and simple. So, start digging now and have fun.

The Offcial js-sdk docs can be found here: http://developers.facebook.com/docs/reference/javascript/

Happy developing! Happy Facebooking! :D :D :D

Tagged , | 2 Comments

Using the Facebook Graph API

I caught viral fever and decided to take the day off from work. To pass my leisure I decided to play with the Facebook APIs. I noticed that Facebook Platform has changed a lot. They have released the new “php-sdk” to let the devlopers integrate facebook into their own sites. Actually, they have released SDKs for other languages too (namely Python and JS). For playing with the toys at hand, I picked up the php-sdk and started browsing through the docs. Amazingly, Facebook has launched OAuth support. I am very happy about that. I no longer need to run my applications inside the facebook frame. Rather I can customize my contents for the facebook users. This is plain cool!

I downloaded the php-sdk and started off. But soon, I faced problem. The php-sdk is not well documented (in my opinion) and I had a very hard time figuring things out. It became even worse when I failed to test some of the features which are tightly integrated deep inside facebook. For example, I couldn’t find a way to construct some advanced URLs and also the sdk was not suitable for my debugging needs. The sdk is not poor, I later found it out to be strong but the main problem is it’s not much documented.

So, to try out things and to figure out how the Facebook OAuth works, I started writing my own codes. That helped though I struggled a bit to setup permissions. When I saw that the code is working fine, I chose to pack it up in a class file and rewrite the testing environment.

It took me 30 minutes to rewrite everything up. The package now contains the library and a console to test different methods.

You can download it from: http://masnun.googlecode.com/files/facebook-graph_API-oauth.zip

Extract it into a directory on your website. Register a facebook application. Go through the traditional setup. Please remember to add your domain name on the Connect tab of the application you created :) Edit the config.php and visit the index.php using your browser. You’ll be redirected to Facebook without a word. When you authorize and return, you get a fine console to test things out and see for yourself! :D

Lets see a quick intro to the library (facebook.php) :)

Facebook requires you to redirect the user to an authorization URL with your client id and the callback url. So, we first do this:

// Construct a Facebook object with your app id and secret
$facebook = new Facebook($client_id, $client_secret);
// Get the authorization url. $perms is an array of extended permission. See config.php
$url = $facebook->getAuthorizeUrl($callback_url, $perms);
// Redirect the user to that url
header("Location: {$url} ");

You have to ask for permissions on Authorization. I couldn’t get to make the user extend permissions on the post authorization phase. So, I have included **ALL** available permissions in the config.php. Permission is what I suffered with most. If you use my library, it’ll ask the user for all permissions so that you can test everything out. I know you won’t need all those permissions in production environment. Just comment out the ones you don’t want!

Facebook returns the user to the $callback_url with a GET parameter named “code” with others. By using this code with the application secret and callback url, we can get the access_token for the user :) We can do that easily using the client :

$facebook = new Facebook($client_id, $client_secret);
$data = $facebook->getAccessToken($callback_url, $code);
$facebook->setAccessToken($data['access_token']);
$response = $facebook->call_api("/me/feed", "post", "message=Hello, Facebook!");
print_r($response);

getAccessToken() retrieves the access_token from the facebook server. setAccessToken() adds the token to the facebook object and makes it ready to make api calls.

The $data is an array with the keys – access_token and expires. After we set the access token, we can make API calls from the client. For the details on API Paths, please visit: http://developers.facebook.com/docs/api :)

I really liked the new structure of the facebook API. The previous API was bloated and sometimes very hard to implement. I do thank Facebook very much for making things easy for the developers!

Tagged , | 9 Comments

Setting Up Twitter Bots with OAuth

Twitter has decided to kill Basic Authentication on the Twitter API from June 30. They have setup a nice website at http://www.countdowntooauth.com/ to let you all know and help you migrate your apps to use the OAuth :)

OAuth is cool. It’s safe and secure for the end user. It’s convenient for the developers as well. Basic Auth entirely depends on the username and password of the user. So, the developer can do whatever s/he wishes with the user account as long as the user doesn’t change the password. On the other hand, if the user for some reason changes his/her password, the application will no longer be able to access the account and provide the desired service. OAuth helps both parties here! When the user authenticates an app via OAuth, it provides the developer with an access token ( a key and a secret ) which is by no way related to the user’s password. It’s unique for every user and application pair. That is every user will have an unique access token only for that application. Now even if the user changes the password, the access token will remain unchanged. The developer can safely store the token and use that to access the user’s account without hassle. Similarly, if the user wants to revoke the access permitted to an application, he or she can easily do that. In that case, the access token becomes invalid and the application loses access to that account.

In the Basic Auth age, it was very easy to develop twitter bots. You just setup the username and password into a configuration file, call the REST API with the login details and you’re done! Yeah, it was quite easy. But it’s not harder now :) Don’t fret, OAuth is also very simple and easy to implement for twitter bots. While you need to go through a two phase OAuth dance to authorize other users, Twitter displays the access token of the developer directly into the dashboard! Thanks to Twitter for making things so plain for developers! With your own access token, you can authorize your apps directly without any further verification.

To get the access token, first go to : http://dev.twitter.com. Login if you’re not already logged in. Use the twitter ID you want to run as a bot. Go to http://dev.twitter.com/apps by clicking the “Your Apps” on top right corner. You will see a list of applications under the logged in twitter account. One big advantage of the basic auth was that you didn’t need to create applications. But now you need! Create an application if you don’t already have one created. In most cases you won’t have one since this is probably the first time you’re using OAuth. In that situation, please create an application. Note down the Consumer Key and Consumer Secret after visiting the application page by clicking on any of the application name. Now, on the right hand navigation bar, you’ll see “My Access Token”. Please visit that section and retrieve your Access Token and Access Token Secret. That’s all we needed. Now let’s do some coding to demonstrate the use of these keys and secrets.

We first need to get a Twitter Client library. If you’re already using one, just check to make sure that it has OAuth support. The work flow is simple. First construct the client with the consumer key and consumer secret. Then set the access token key and the access token secret. Now use the client to make Twitter API calls, in our case, to update statuses!

You can get the OAuth libraries from : http://dev.twitter.com/pages/oauth_libraries . But I recommend using Tweepy with Python and Abraham’s TwitterOAuth with PHP . They are not generic OAuth clients. They were built for Twitter and you don’t need to configure any extra parameters to make it work with Twitter.

Here’s the code samples on how to use the libraries to update status via OAuth.

PHP (Abraham’s TwitterOAuth)

<?php
$consumer_key = "";
$consumer_secret = "";
$access_key = "";
$access_secret = "";
 
require_once('twitteroauth/twitteroauth.php');
 
$connection = new TwitterOAuth ($consumer_key ,$consumer_secret , $access_key , $access_secret );
 
$connection->post('statuses/update', array('status' => "Hello Twitter OAuth!"));
?>

Python (Tweepy)

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
bot = tweepy.API(auth)
 
bot.update_status("Hello Twitter OAuth!")
Tagged , , | 4 Comments