Getting started with Openlaszlo – Framework for developing flash apps

Openlaszlo is an open source framework which simplifies development of flash applications. Openlaszlo allows you to code your flash apps using xml style laszlo code, and thereafter you can compile your code to output a .swf file for production usage. I first came around openlaszlo while I was developing Alterplayer – open source flash mp3 player.

In this post I will demonstrate:

  • Getting started with Openlaszlo – Setting up your dev enviornment
  • Hello World! in Openlaszlo
  • Upcoming tutorials

Setting up Openlaszlo development environment

  1. Download the latest openlaszlo release 4.4 from http://openlaszlo.org/download or alternatively download directly from http://download.openlaszlo.org/4.4.0/openlaszlo-4.4.0-windows-dev-install.exe
  2. Double click and install the setup. For me on WinXP, it installs in the following location. C:Program FilesOpenLaszlo Server 4.4.0
  3. Upon installation tomcat server will start automatically. If it doesn’t, click the following file to start the tomcat server. C:Program FilesOpenLaszlo Server 4.4.0Serverlps-4.4.0lpsutilsstartTomcat.bat
  4. At any point in time when you want to stop the tomcat server, click the stopTomcat.bat file lying in the same folder.
  5. Browse to the following location on your firefox, to see the opening welcome screen http://127.0.0.1:8080/lps-4.4.0/laszlo-explorer/index.jsp
  6. Create a folder inside C:Program FilesOpenLaszlo Server 4.4.0Serverlps-4.4.0, called Workspace. We will do all our development in this directory.
  7. Create a folder called HelloWorld inside Workspace. We will start developing our first project straight away

Hello World! in OpenLaszlo
Like in any other language and framework, we will learn how to write a Hello World! program.

  1. Create a file helloworld.lzx inside the Hello World folder
  2. 
      Hello World!
    
  3. Browse to the following location on your browser: http://127.0.0.1:8080/lps-4.4.0/Workspace/HelloWorld/helloworld.lzx
  4. Did you see HelloWorld! ? Bingo

Hello World! Explained

  1. Each and every openlaszlo code file have an extension .lzx
  2. Each and every laszlo code is wrapped inside <canvas></canvas> tag
  3. <text></text> is a class used for non-editable text fields. Here it will simply display Hello World! on the browser.

Debugging in Openlaszlo
One of the strong feature which comes packaged with openlaszlo, is it’s support for debugging. When you visited the above link in your browser, along with Helllo World! text you must have seen a debugger window too. Mainly because we had <canvas debug=”true”>, debug true in our code.

If you might have noticed, I have given an id to out <text></text> node. Lets see how can we make use of it while debugging. Suppose you didn’t get what you really wanted out of your code, for instance suppose you mistyped Hello World! as Helo World!. Simply go ahead and type the element id in the debugger window.

For instance here I will type in the id of the element i want to inspect i.e. id=”helloworld”. As I press enter, debugger shows me all the details about my element of interest.
getting_started_with_openlaszlo

Another thing you can do from within the code is, print out your debug logs on the debugger screen. For instance modify the above code as follows and refresh your app on the browser:


  
    Hello World!
  
  

Above code will simply throw a string “I just printed a Hello World!” on the debugger string. In you application you can ever throw a variable value for debugging purpose.

Upcoming tutorial
In the next tutorials on openlaszlo, I will explain:

  1. How to create an alterplayer out of openlaszlo. Meanwhile I would like you to go through my previous post on openlaszlo: How to create a single button flash audio player using Openlaszlo?
  2. How to build an imoracle video player out of openlaszlo.

Both the projects will be opensource under GNU General Public License v3.

Also you may want to visit the following reference on openlaszlo official site:
http://www.openlaszlo.org/lps3/docs/reference/

XML Parsing in PHP, XPATH way – The best I know so far

If you are a PHP developer, you surely must have done XML parsing at some stage or the other. Over the years I myself have implemented XML Parsing in atleast 3-4 different ways. Finally I have stuck to this approach which I personally find far more better than the rest, Not only because it’s quite simple but also because it’s extendable. By extendable I mean, you don’t have to touch your code if the XML structure changes at a later stage or if you need to parse a new node at a later stage in the project. In this blog post we will try to parse my twitter timeline, using the XPATH way. To start with let’s see how a my twitter timeline look like:

XML Source:
http://twitter.com/statuses/user_timeline/imoracle.xml
You may want to open this XML structure in a separate window of your browser for reference, as we walk through various XML parsing techniques.

Data Requirement:
Before we proceed to parse this twitter timeline, lets decide what all data do we want to extract out of the XML. Each <status></status> node consists of two parts. Information about the tweet and information about the user.

Lets finalize the following list of nodes which we want about the tweets and also their corresponding XPATH’s:

  1. id: ../statuses/status/id
  2. text: ../statuses/status/text
  3. source: ../statuses/status/source

Further lets zero out on list of nodes we want about the user details:

  1. id: ../statuses/status/user/id
  2. name: ../statuses/status/user/name
  3. screen_name: ../statuses/status/user/screen_name

XML Parsing:
Let us create a file called xpath.php, which will contain xpath of various nodes which we have finalized above. The xpath.php file will look like:

xpath.php

<?php

  $user_status = array(
                      'status_id' => '../statuses/status/id',
                      'status_text' => '../statuses/status/text',
                      'status_source' => '../statuses/status/source',
                      'user_id' => '../statuses/status/user/id',
                      'user_name' => '../statuses/status/user/name',
                      'user_screen_name' => '../statuses/status/user/screen_name'
                      );

?>

parser.php

<?php

  // include the xpath file
  require_once("xpath.php");

  // read the xml source as string
  $str = file_get_contents("imoracle.xml");

  // load the string as xml object
  $xml = simplexml_load_string($str);

  // initialize the return array
  $result = array();

  // parse the xml nodes
  foreach($user_status as $key => $xpath) {
    $values = $xml->xpath("{$xpath}");
    foreach($values as $value) {
      $result[$key][] = (string)$value;
    }
  }

  // print the return array
  print_r($result);

?>

Results:
If we try to print out this $result on a browser screen, here is how the result will look like:

Array
(
    [status_id] => Array
        (
            [0] => 2499838341
            [1] => 2499780899
            [2] => 2499724163
            [3] => 2499607183
        )

    [status_text] => Array
        (
            [0] => 13 Beautiful WordPress Showcase Sites
            [1] => 55 Really Creative And Unique Blog Design Showcase
            [2] => Need PHP symfony developer to complete tvguide.com clone
            [3] => 22 Open Source PHP Frameworks To Shorten Your Development Time
        )

    [status_source] => Array
        (
            [0] => <a href="http://apiwiki.twitter.com/">API</a>
            [1] => <a href="http://apiwiki.twitter.com/">API</a>
            [2] => <a href="http://apiwiki.twitter.com/">API</a>
            [3] => <a href="http://apiwiki.twitter.com/">API</a>
        )

    [user_id] => Array
        (
            [0] => 14574588
            [1] => 14574588
            [2] => 14574588
            [3] => 14574588
        )

    [user_name] => Array
        (
            [0] => Abhinav Singh
            [1] => Abhinav Singh
            [2] => Abhinav Singh
            [3] => Abhinav Singh
        )

    [user_screen_name] => Array
        (
            [0] => imoracle
            [1] => imoracle
            [2] => imoracle
            [3] => imoracle
        )

)

The Best Part:
The best part of this approach is that, suppose in future our project demands extraction of the following nodes too:

  1. truncated: ../statuses/status/truncated
  2. favorited: ../statuses/status/truncated ../statuses/status/favorited
  3. location: ../statuses/status/user/location
  4. description: ../statuses/status/user/description

All we need to do is, simply add these xpaths in xpath.php file, without having to change the parser.php file. In case of a project you may want to create a function or a class out of the parser.php file so that you can request data from that.

Download the source code from here:
http://abhinavsingh.googlecode.com/files/xml-parser-xpath-way.rar

If you liked the post, do not forget to leave a comment and follow me on twitter.
Do let me know of better methods if you know any. Happy XML Parsing!

Facebook type image rotation and more using PHP and Javascript

If you are a facebook geek like me, you must have noticed till now the image rotate functionality in the photo albums. Facebook allows you to rotate images 90 degree clockwise and anti-clockwise after image upload. If you haven’t tried that till now, below is a screenshot for your convenience.

facebook-image-rotate

Question:
But the question is how does facebook team succeed doing this in one click. Today I tried looking around for a solution over internet and I came across the inbuilt imagerotate functionality in PHP.

Problem:
Unfortunately the problem is that even if you have GD Library extension enabled in PHP, imagerotate function just doesn’t work. After some research I found that to enable imagerotate function inside PHP, you need to compile and build PHP manually and enable imagerotate while installing PHP. You can check your PHP installation support for imagerotate using the following command line:

php -r "var_dump(function_exists('imagerotate'));"

Solution:
Since I didn’t want to touch my current installation of PHP, ImageMagick came to my rescue. Below I will show you how did I achieve cloning facebook’s 90 degree rotation functionality and also added a custom degree rotation (functionality usually seen in collage tools).

Demo:
You can try a live demo of the application here:
http://abhinavsingh.com/webdemos/imagerotate/

facebook-image-rotate-using-php-javascript

Source Code:
Before you go ahead and try this demo, you will need to install imagemagick on your system. On debian and ubuntu this can be achieved by the following command:

apt-get install imagemagick

To make sure installation is alright, run the following command from the shell:

convert -version

You should see something like this:

Version: ImageMagick 6.2.4 02/10/07 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2005 ImageMagick Studio LLC

Convert is a command line utility provided by imagemagick. Read more about convert here.

The source code consists of the following files and folders:

  • index.php : Generates the Frontend UI part for the application
  • action.php : Responsible for handling requests and rotating image using imagemagick library
  • style.css : Used for styling the UI
  • script.js : Used for handling the horizontal slider
  • images : This folder contains all the required images for the application. The image which we will be rotating left and right is “me.jpg”

action.php

  // Image Path
  $image = "images/me.jpg";
  $original = "images/me-original.jpg";

  if($_POST['restore']) {
    exec("cp ".$original." ".$image);
  }
  else if($_GET['left'] == 1 || $_GET['right'] == 1 || $_POST['degree']) {
    // Rotation Degree
    if(isset($_GET['left'])) $degree = -90;
    if(isset($_GET['right'])) $degree = 90;
    if(isset($_POST['degree'])) $degree = $_POST['degree'];

    // rotate image
    if(is_numeric($degree)) exec("convert ".$image." -rotate ".$degree." ".$image);
  }

From the UI, a user can pass 4 kind of requests:

  • Rotate Image 90 degree clockwise by clicking the button on bottom right corner
  • Rotate Image 90 degree anti-clockwise by clicking the button on bottom right corner
  • Rotate Image x degree, by choosing the value of x using horizontal slider on bottom left
  • Restore the image back to the original self

action.php handles the incoming 4 cases, calculates $degree to rotate and passes as a parameters to the command line utility provided by imagemagick.

Download Code:
Download the complete source code from here:
http://abhinavsingh.googlecode.com/files/image-rotate-application.rar
Unzip into a folder, and make the images directory writable.
PS: Application not tested on IE browser

Don’t forget to share and leave a comment if you liked the post.
Cheers!

WordPress Toolbar v 2.1 – Adding support for tinyurl, sociable and a lot more

download-wordpress-plugin

WordPress Toolbar Version 2.0 allowed bloggers to catch their viewers on the go. It modifies all the internal/external links in the blog post (except those specified for exception), to open them with an attractive toolbar. Since wordpress toolbar used javascript to enable this functionality, your SEO always remain intact.

Moving forward, I accumulated all the suggestions posted in more than a 100 comments on the introductory blog post, and tried to include as many features as possible in version 2.1. A few features worth talking about are:

New in Version 2.1:

  • Plugin Size: Inspite of adding new features in version 2.1, plugin size has decreased from 100+ Kb to 50+ Kb. This is mainly because, plugin now uses site favicons fetched using Google S2 web service. It will allows for parallelization as your blog loads.
  • Tinyurl: Version 2.1 introduces support for tinyurl. If you are wondering what does that mean, scroll down to the bottom of this blog post and you will see tinyurl corresponding to this post. Enabling this feature inside admin panel will automatically submit your post to tinyurl and display it at the end of the blog post.
  • Sociable: Version 2.1 also introduces sociable. Enabling it inside the admin panel will put the social icons at the end of every blog post. You can choose icons from the admin panel. For an example scroll down to the bottom of this post.
  • target=”_blank”, was one of the most wished feature in all the posted comments. Enabling it from admin panel, will force open the url’s in your post into a new window.
  • New Toolbar Skin: Version 2.1 adds facebook toolbar skin into its kitty. From admin panel you can choose dark shade stumble upon skin or light blue facebook skin.
  • Add More Custom Skin: Yes, you read it right. I found a lot of bloggers using this plugin, wish to have their own custom toolbar skins. However, they just don’t want to tweak the code directly. Version 2.1 allows blog publishers to add their own custom skins without having to tweak the code manually. Read through to know how to add your custom skins
  • PHP4 Support: Last but not the least, support for PHP version 4.

Installation Guide:

  1. If you are trying to upgrade from version 2.0, you can either go for manual upgrade or automatic up using wordpress admin panel.
  2. Manual Upgrade: Deactivate version 2.0, Delete wordpress-toolbar folder from plugins directory, Download version 2.1, Copy wordpress-toolbar directory to plugins folder, Activate version 2.1, Visit wordpress toolbar administration panel
  3. Automatic Upgrade: Go to wordpress admin panel, click on plugins in left navigation bar, scroll down to wordpress-toolbar and click upgrade automatically

Version Change logs:

  1. Version 2.1.x : Enhancements added to version 2.0. Specifically it includes:
    • Support for tinyurl – url shortening service
    • Support for sociable – adding social share icons at the end of every post
    • Facebook skin added
    • target=”_blank” support added
    • Plugin is now PHP4 compatible
  2. Version 2.0 : Version was upgraded since 2.0 is a complete overhaul from 1.x series. Specifically it allows you to do the following:
    • You can now use auto upgrade for future releases without caring to move the plugin files everytime
    • Admin panel allows you to fully customize your toolbar
    • You can now ever choose social icons of your choice to be displayed on the toolbar
    • Choose domains for which you don’t want to activate this plugin
    • Unlike 1.x series, 2.0 do not change the href=”” urls. Instead now it uses javascript onclick event to activate toolbar and hence taking care of your SEO needs
  3. Version 1.1 : Include emergency CSS and HTML Validation fixes for IE browsers
  4. Version 1.0 : The first release of wordpress toolbar

How to add my own custom toolbar skin:
Before you go ahead and put in your custom skin, a little about various components populating that toolbar.

  1. home.gif: The left most home icon on the toolbar
  2. background.gif: The background image of your toolbar
  3. button_left.gif: The left cap image for “comment back” button
  4. button_right.gif: The right cap image for “comment back” button
  5. close.gif: The right most close icon on the toolbar

So by now you know, to add your custom skin to the toolbar all you need is 5 images. Lets see what all I did to add facebook skin in this release.

  1. First of all you must choose a short name and full name for your skin. I chose a shortname “fb” and fullname “facebook” for the facebook custom skin
  2. Go to plugins/wordpress-toolbar/extra/skins folder and create a folder. Name it “fb” (the shortname for your skin)
  3. Inside this folder drop your 5 images. (Remember names of the images must be same as above)
  4. Along with the images you need to drop a stylesheet named style.css to customize the font family, font sizes etc appearing on the toolbar. For reference see the style.css file inside “fb” folder bundled with this plugin
  5. Finally you need to create a “readme.txt” file inside “fb” folder. Open it and type in your skin’s fullname inside this file. This file will be used more extensively in future releases.

Now go to your admin panel and if you did it right you must see an option to choose your custom skin next to “choose a skin” option. Wasn’t that easy!

Planned Future Releases:

  1. The plugin is still not compatible with the Google Analytics and Shadow Box Plugin, mainly due to similar nature in which all the plugin’s operate. Need to work on that.
  2. Waiting for more suggestions and feedbacks from the plugin users on how we can evolve this plugin to serve the open source community

Do leave a comment or any suggestion for improvement and don’t forget to give a rating at http://wordpress.org/extend/plugins/wordpress-toolbar/.

SEO Analyzer v 1.2 – Adding support for Bing along with Google and Yahoo

On May 28, 2009 Microsoft announced Bing which has now replaced Live search. And within 2 week of it’s release, Bing seems to have leapfrog Yahoo search in U.S.

With Bing coming up as a strong contender to Google and Yahoo search engines, I have added support for Bing in SEO Analyzer v 1.2. This will enable you to analyze a site’s ranking for a particular keyword on Bing search engine, along with Yahoo and Google search engines.

seoanalyzer-bing-support

SEO Analyzer Future Roadmap:

  • Saving reports on spreadsheets
  • Comparing two sites for a list of keywords
  • Keyword density extraction tool

Happy SEO Analysis!

How to broadcast a message to your Gtalk friends using JAXL?

In this era of social media we all look forward to easy and utility tools to easily market our site and blogs. In this post I will demonstrate a ready to use script, which will help you broadcast your message to everyone on your gtalk friend list in one go.

jaxl4broadcast.class.php
jaxl4broadcast.class.php is an extension of JAXL library. This extension simply saves all your buddy list in an array while connecting with Gtalk servers, and then send out your custom message to all of them in one go. The code that will do the task:

    function setStatus() {
      $this->sendStatus($this->status);
      print "Setting Status...n";
      print "Donen";

      foreach($this->rosterList as $buddy) {
        print "Sending message to ".$buddy."n";
        $this->sendMessage($buddy,"Message broadcasted using *JAXL Library http://code.google.com/p/jaxl*");
        sleep(1);
      }

      /* Now loggout of the system */
      exit;
    }

PS: You need to checkout the latest version of xmpp.class.php for jaxl4broadcast.class.php to work. jaxl-1.0.4 doesn’t include the latest checked in xmpp.class.php

Using jaxl4broadcast.class.php

  • Checkout the latest version of JAXL library from here
  • Open config.ini.php, replace myproductionuser => gmail id and password => gmail password
  • Open index.php, replace jaxl.class.php => jaxl4broadcast.class.php
  • Open command line window (for windows) and shell prompt (for *nix). Navigate to the checked out directory
  • From command prompt run php index.php
  • If everything goes alright, you will see something like the image below
  • See list of known issues if you are new to JAXL and having trouble

jaxl4broadcast

Other JAXL Extensions you may want to checkout:

  • [email protected] (Source Code)
  • Sending custom out-of-office mails in Gmail (Source Code)

Happy Broadcasting!

WordPress Toolbar Plugin

Checkout WordPress Toolbar Version 2.2 Release Blog.

This plugin is a result of day to day observations of my wordpress blog stat. I analyzed that 75% of my blog’s visitors were leaving my blog posts by clicking one of the out going links either to my code.google project pages or to an external source of information. However, I doubt how many of them were coming back to leave a comment or to bookmark/share my blog post on one of the social bookmarking sites. I can say this because, even I too forget to press the browser back button and visit the blog again.

However I observed that I was clicking the link back on stumble floating toolbars and facebook external links toolbar. And hence came WordPress Toolbar Plugin (upgrade to 2.0 with Admin Panel). In short:

download-wordpress-plugin

WordPress Toolbar is a unique plugin which will automatically enable a toolbar for all outgoing links from your blog post, similar to stumbleupon and facebook. Often the visitors on your blog clicks one of the outgoing link for more information. However, s/he often forgets to comment back or social bookmark your blog. WordPress toolbar will float on the top of all these outgoing links from your blog post, showing options for either visit back your blog post from where s/he came from, comment back on your blog, social bookmark you blog in one of the famous bookmarking sites and finally an option to leave this toolbar.

This is my first wordpress plugin and I have just got my subversion repository access on wordpress.org. I have checked in this version of plugin and you can download the same from the download link above. You can experience the wordpress toolbar by clicking this link: http://abhinavsingh.com . As you click this, you will see a brownish black toolbar floating at the top of the yahoo.com page using which either the users can come back to comment on this blog post or they can use one of the social bookmarking images to share this blog post.

Introductory Features of WordPress Toolbar:

  1. A link back to your blog home
  2. A link back to your blog post from where he visited the external link
  3. A comment back link to originating blog post
  4. Various social bookmarking links to share, promote and bookmark your blog post
  5. Finally a close button, with which he will exit the wordpress toolbar
  6. An admin panel to configure and customize all of the above options

How to install WordPress Toolbar:

  1. Before proceeding with this version 2.x, you should DEACTIVATE any active 1.x series plugin
  2. Remove /blog/toolbar.php which you must have copied while activating 1.x version
  3. Remove /blog/wp-content/plugins/wp-toolbar directory fully. You will no longer need this
  4. Download the plugin
  5. Extract the plugin into `/wp-content/plugins/wordpress-toolbar` directory
  6. You will see one directory named `extra` which contains required images and css (DO-NOT-TOUCH-THIS-FOLDER)
  7. You will see 2 files named: wp-toolbar.php and toolbar.php (DONT MOVE THEM ANYWHERE)
  8. Activate the plugin
  9. Go to WPAdmin => settings => `wordpress toolbar` and customize the toolbar
  10. Bingo!

Version Change logs:

  1. Version 2.0 : Version was upgraded since 2.0 is a complete overhaul from 1.x series. Specifically it allows you to do the following:
    • You can now use auto upgrade for future releases without caring to move the plugin files everytime
    • Admin panel allows you to fully customize your toolbar
    • You can now ever choose social icons of your choice to be displayed on the toolbar
    • Choose domains for which you don’t want to activate this plugin
    • Unlike 1.x series, 2.0 do not change the href=”” urls. Instead now it uses javascript onclick event to activate toolbar and hence taking care of your SEO needs
  2. Version 1.1 : Include emergency CSS and HTML Validation fixes for IE browsers
  3. Version 1.0 : The first release of wordpress toolbar

Planned Future Releases:

  1. Include support for wordpress blogs hosted on PHP4, currently they are facing issues
  2. Include an options for inserting target=”_blank” for all outgoing links
  3. Club Socialble plugin into wordpress toolbar – Since wordpress toolbar already consists of all the social networking favicons, you may want to have a similar copy for a different plugin. Hence one of the next releases will include support for inserting social icons on your blog
  4. Club Google Analytics plugin into wordpress toolbar – Currently wordpress toolbar plugin inserts a onclick=”” event for all out going links which enables the toolbar for the link. However if you are a user of Google Analytics Plugin, then you might face a few issues. Mainly because Google Analytics Plugin too tries to insert an onclick=”” event for all outgoing links. Which finally clashes with wordpress toolbar onclick=”” event. Clubing both will allow you to enjoy plus points of both the plugins.

Do leave a comment or any suggestion for improvement.

Programatically control your google mails using JAXL v 1.0.4

Google has released an API for almost all of their products including maps, feedburner and gadgets. However one of the API’s which every developer would have loved to make use of is “Google Mail API” which is still missing (available for premium google apps user only). Here in this post I would demonstrate how one can programatically control his/her google mails using JAXL without being a premium user of google mail account.

For those who have landed on this post straight and have little knowledge about what JAXL is “JAXL stands for Jabber XMPP Library and for fun you may call it Just Another XMPP Library. It is written in PHP and can be downloaded from http://code.google.com/p/jaxl“. To know more about JAXL, read the introductory post here. If you want to dig deep and know how JAXL works, read the gtalk case study here. Finally, after reading this post you may also want to check how you can fetch any social networking feed right into your gtalk messenger using JAXL.

Version 1.0.4 of JAXL included support for “Gmail Notification Extension of XMPP“. If you are a daily Gtalk user like me, then you have surely seen this extension in action. Just recall Gtalk notifying you of a new mail in your inbox, through a pop-up in the bottom right corner. Also those who see this in action everyday will agree with me that this notification comes even before the mail has actually appeared in you inbox. Simply because of the PUSH technology used by XMPP protocol.

So why would you in first place be interested in accessing your google mails programatically. A quick thought on this brings me to the following real life scenarios:

  • Suppose your are out of vacation and you want to set a custom auto-reply message for your family and friends, while you want to set a general out-of-office message for your colleagues. The limitation in gmail is that you can’t really do this. Further in this post, I will show you how can you achieve this using JAXL.
  • Suppose you are a google app user and your company has organized an online programming contest. Further you want to mail each question to the contestants only if they has answered the previous question. JAXL provide you a way to access key information about your incoming mails like: sender email id, subject, number of threads in the mail, time at which mail was sent, mail url and mail snippet. Which is enough for you to code a bot which can check for incoming mail and then send in next question to the contestant who sent this mail
    1. Further there can be a thousand use cases where you would you like to have such a control over you google mails but before discussing them, lets see a demonstration on how can we use JAXL to achieve this.

      Sending Custom Auto-Reply Mails using JAXL
      Along with extendable functions like eventMessage() and eventPresence(), JAXL’s latest version now also provide another extendable function called eventNewEMail(). So everytime you receive a new mail(s) in your google account, the control is passed to this function along with all informations about the incoming mails.

      Various data passed to this function are:

      • $total: Tells you about total number of unread mails.
      • $thread: The thread id of all the unread threads. Note: In Gmail you have threads in your inbox which can contain more than a single mail.
      • $url: The mail.google.com url for the new mail
      • $participation: This can be 0, 1 or 2. 0 indicates that you have not participated, 1 indicates that you are one of the many recipients and 2 indicates that you are the sole recipient for messages in this thread
      • $message: The number of messages in the thread. For instance you can have more than one unread mail in a thread.
      • $date: A timestamp of the most recent unread message, in milliseconds since the UNIX epoch
      • $senders: Email Id of all the senders in the current thread
      • $labels: Label if any to which this mail thread belongs to
      • $subject: The subject of the mail threads
      • $snippet: The mail snippet of the incoming mail

      So thats a lot of information really, with which we can automate things to a certain extent. Lets see how I use it to send custom auto-reply mails when I am out on vacation. Here is the extendable jaxl class for gmail:

      jaxl4gmail.class.php (Download)

        /* Include PHP Mailer Class */
        include_once("class.phpmailer.php");
      
        /* Include XMPP Class */
        include_once("xmpp.class.php");
      
        class JAXL extends XMPP {
      
          /* Define custom mail groups */
          var $family = array("[email protected]","[email protected]");
          var $colleague = array("[email protected]","[email protected]");
      
          /* Define custom mail subject and message */
          var $familySubject = "Hi, Will get back to you";
          var $familyMessage = "Hey, I am currently out on vacation at my grannies house in Delhi. I will return back home by next monday.
      Reach out to me at +91-987654321.

      With Love,
      Abhinav Singh"; /* Define custom mail subject and message */ var $colleagueSubject = "[Auto-Reply] Out of Office"; var $colleagueMessage = "Hi, I am on vacation in my village with very limited access to internet and phone. I will return back home by next monday.

      Regards,
      Abhinav Singh"; function eventMessage($fromJid, $content, $offline = FALSE) { } function eventPresence($fromJid, $status, $photo) { } function eventNewEMail($total,$thread,$url,$participation,$messages,$date,$senders,$labels,$subject,$snippet) { // We only want to send auto-reply message to latest sender $sender = $senders[0]; // Check if the user lie in any category, and send appropriate mail if(in_array($sender["address"],$this->family)) { $mail = new PHPMailer(); $mail->From = "[email protected]"; $mail->FromName = "Your Name"; $mail->Subject = $this->familySubject; $mail->MsgHTML($this->familyMessage."

      Powered by Jaxl http://code.google.com/p/jaxl"); $mail->IsHTML(true); $mail->AddAddress($sender["address"],$sender["name"]); if(!$mail->Send()) $this->logger->logger("Error occured while sending mail to ".$sender["address"]); else $this->logger->logger("Mail sent successfully to ".$sender["address"]); } else if(in_array($sender["address"],$this->colleague)) { $mail = new PHPMailer(); $mail->From = "[email protected]"; $mail->FromName = "Your Name"; $mail->Subject = $this->colleagueSubject; $mail->MsgHTML($this->colleagueMessage."

      Powered by Jaxl http://code.google.com/p/jaxl"); $mail->IsHTML(true); $mail->AddAddress($sender["address"],$sender["name"]); if(!$mail->Send()) $this->logger->logger("Error occured while sending mail to ".$sender["address"]); else $this->logger->logger("Mail sent successfully to ".$sender["address"]); } else { // Do nothing, will handle later on $this->logger->logger("No handler for this email id..."); } } function setStatus() { print "Setting Status...n"; $this->sendStatus("Available"); print "Requesting new mails...n"; $this->getNewEMail(); print "Donen"; } }

      The only variables you would like to change in above class are:

      1. $family : An array of email id of your family member
      2. $colleague : An array of email id of your colleagues
      3. $familySubject : Subject with which you want to send mails to your family members
      4. $familyMessage : Mail message which you want to send to you family
      5. $colleagueSubject : Subject with which you want to send mails to your colleagues
      6. $colleagueMessage : Mail message which you want to send to you colleagues

      For further customization, you may want to add more groups and their respective subjects and messages.

      Further you may want to create your own custom bots using JAXL for one of the other use case described above. Join official JAXL Google Group for future updates and enhancements.

      Do let me know if you build any custom bot using JAXL, I will be more than happy to list your bot on official JAXL google code page.

      Enjoy!

How to get dzone feeds as IM using JAXL? Add [email protected]

The most funny part of knowing XMPP protocol is that you can execute all your daily web needs using it. Be it playing anagram online or achieving your status messages. And your life gets easy if you are using an XMPP Client Library like JAXL.

Here I have tried to create a simple bot which allows you to read newest links posted on dzone category wise. Simply add [email protected] in your gtalk messenger and start by typing options.

Available options are:

  • frontpage: Will send you latest links on frontpage.
  • queue: Will send you latest links in queue.
  • tag: Send in a tag e.g. php,java,xml and you will get latest links for the particular tag

Here is modified eventMessage() method of JAXL library powering [email protected]:

    function eventMessage($fromJid, $content, $offline = FALSE) {

      // If the message is not an offliner
      if(!$offline) {
        if($this->restrictJid && !in_array($this->getBareJid($fromJid),$this->authorizedJid)) { // Block un-authorized users
          $this->logger->logger($fromJid." tried using this service by sending:n".$content);
          $message = 'You are not authorized to use this service';
          $this->sendMessage($fromJid,$message);
          return TRUE;
        }
        else {
          $content = strtolower(trim($content));

          // Build RSS Feed URL depending upon passed IM
          if($content == "options") {
            $message = "Available options are:n";
            $message .= "*1. frontpage:* Will send you latest links on frontpage.n";
            $message .= "*2. queue:* Will send you latest links in queue.n";
            $message .= "*3. tag:* Send in a tag e.g. php,java,xml and you will get latest links for the particular tagn";
            $this->sendMessage($fromJid,$message);
            return TRUE;
          }
          else if($content == "frontpage") $url = "http://www.dzone.com/links/feed/frontpage/rss.xml";
          else if($content == "queue") $url = "http://www.dzone.com/links/feed/queue/rss.xml";
          else $url = "http://www.dzone.com/links/feed/frontpage/".$content."/rss.xml";

          // Generate cache file location
          $cache_file = "cache/dzone/".md5($url)."-".$content.".rss";

          // If cache file is not older than 900 seconds (15 min)
          if(file_exists($cache_file) && (filemtime($cache_file) > time() - 900)) {
            $this->logger->logger("RSS already found cached...");
          }
          else { // else fetch a fresh copy of RSS
            $this->logger->logger("Fetching RSS for url:n".$url);
            $head = $this->fetchWebURL($url);
            if($head['errno'] == 0 && $head['http_code'] == 200) {
              $this->logger->logger("Fetched successfully...");
              $data = $head['content'];
              $fh = fopen($cache_file,"w");
              fwrite($fh,$data);
              fclose($fh);
            }
            else {
              // Send a message saying no such feed exists
              $this->logger->logger("Failed to fetch the RSS feed...");
              $message = 'No feed exists for the passed keyword: '.$content;
              $this->sendMessage($fromJid,$message);
              return TRUE;
            }
          }

          // Parse RSS Feed
          $r = &new XML_RSS($cache_file);
          $r->parse();
          $NumberOfFeeds = count($r->getItems());
          if($NumberOfFeeds > 0) {
            $message = '';
            foreach($r->getItems() as $key => $item) {
              if($this->count < $this->maxResults) {
                $message .= "*".$item["title"]."*n";
                $message .= $item["link"]."n";
                $message .= $item["description"]."nn";
                $this->count++;
              }
              else {
                break;
              }
            }
            $message .= "powered by *Jaxl* http://code.google.com/p/jaxl"."nn";
            $this->sendMessage($fromJid,$message);
            $this->count = 0;
            return TRUE;
          }
          else {
            // Send a message saying no feed found
            $message = 'No feed was found for passed keyword: '.$content;
            $this->sendMessage($fromJid,$message);
            return TRUE;
          }
        }
      }
      else {
        // Send an appropriate message
        $this->logger->logger($fromJid." sent an offliner saying:n".$content);
        return TRUE;
      }
    }

To run this sample application you need:

  • JAXL Library (http://code.google.com/p/jaxl)
  • XML_RSS Package (pear install XML_RSS)
  • Create a directory cache/dzone where this application will cache all rss files
  • Include jaxl4dzone.class.php in index.php, instead of jaxl.class.php and run ‘php index.php’ from command line to start this application

Checkout the complete code and JAXL library from http://code.google.com/p/jaxl.

Now browse new links even when dzone is down for maintenance 😛
Do let me know about your feedbacks 🙂

Introducing JAXL – Open Source Jabber XMPP Library

Introduction

JAXL stands for “Jabber XMPP Library“. For fun, it stands for “Just Another XMPP Library

This library currently supports following features:

  • Connect to a Jabber Server (e.g. Gtalk)
  • TLS Encryption
  • DIGEST-MD5 and PLAIN authentication mechanisms
  • Roster Support

Library comes with the following class files:

  1. config.ini.php : Holds your jabber account and mysql connection information
  2. mysql.class.php : Basic MySQL connection class used to insert received messages and presence into MySQL database
  3. logger.class.php : A very basic logger class which allows you to log all XML stanza’s send and received from jabber server
  4. xmpp.class.php : Base XMPP class library which implements the XMPP protocol
  5. jaxl.class.php : JAXL class which extends XMPP class library. Should be the starting point for your application.
  6. index.php : After building your application in jaxl.class.php, you finally initializa and call your methods here

Source Code
JAXL is hosted at Google Code. Checkout full source code from here:
http://code.google.com/p/jaxl

Google Groups
jaxl
Visit this group

How to use JAXL:
JAXL Client Library is highly structured. There is a base XMPP class library (xmpp.class.php) and a JAXL class library (jaxl.class.php) which is derived from the base XMPP class library.

Base XMPP class library implements the XMPP protocol and it also provides you with two extendable methods named eventMessage() and eventPresence(). These methods are internally called when a message or presence XML Stanza is received from the Jabber server.

Jaxl.class.php must be the starting point for all your applications. Simply customize the eventMessage() and eventPresence() Method for your application. Other methods which might interest you while customizing them are:

  1. sendMessage($jid,$message) : For sending message to a particular Jid
  2. sendStatus() : To set your status message
  3. roster(‘get’) : To get list of roster
  4. roster(‘add’,$jid) : Add a new contact in roster list
  5. roster(‘remove’,$jid) : Remove a contact from roster list
  6. roster(‘update’,$jid,$name,$groups) : Update a particular contact in roster
  7. subscribe($jid) : Subscribe for presence of a particular $jid

This library includes the following files:

Config File (config.ini.php)
You specify all your jabber account username and password in this file. For development environment keep $env = “devel” and for production simply change it to $env = “prod”

  // Set an enviornment
  $env = "prod";

  // Log Level for logger class
  $logEnable = TRUE;

  // Log in MySQL database
  $logDB = FALSE;

  $key = array("prod"=>array("user"=>"myproductionuser",
                             "pass"=>"password",
                             "host"=>"talk.google.com",
                             "port"=>5222,
                             "domain"=>"gmail.com"
                            ),
              "devel"=>array("user"=>"mydevelopmentuser",
                             "pass"=>"password",
                             "host"=>"localhost",
                             "port"=>5222,
                             "domain"=>"localhost"
                            )
              );

  $db = array("prod"=>array("dbuser"=>"root",
                            "dbpass"=>"password",
                            "dbhost"=>"localhost",
                            "dbname"=>"jaxl"
                           ),
             "devel"=>array("dbuser"=>"root",
                            "dbpass"=>"password",
                            "dbhost"=>"localhost",
                            "dbname"=>"jaxl"
                           )
             );


MySQL Class (mysql.class.php)
This is a basic MySQL connection class used to insert received messages and presence into MySQL database

Base XMPP Class (xmpp.class.php)
You should not worry about this class. Until and unless you are aware of what are you trying to achieve you should not touch this class file.

Logger Class (logger.class.php)
This is a basic logger class. It help you log XML send to and received from jabber server. Might prove helpful in debugging and if you are interested in learning the core of XMPP Protocol.

Extended JAXL Class (jaxl.class.php)
You will be customizing eventMessage() and eventPresence() methods here.

    function eventMessage($fromJid, $content, $offline = FALSE) {
      if($offline) {
        $this->sendMessage($fromJid,"Hi, Thanks for your offline message");
      }
      else {
        $this->sendMessage($fromJid,"Hi, Thanks for your message");
      }

      if($this->logDB) {
        // Save the message in the database
        $timestamp = date('Y-m-d H:i:s');
        $query = "INSERT INTO message (FromJid,Message,Timestamp) value ('$fromJid','$content','$timestamp')";
        $this->mysql->setData($query);
      }
    }

    function eventPresence($fromJid, $status, $photo) {
      // Change your status message to your friend's status
      $this->sendStatus($status);

      if($this->logDB) {
        // Save the presence in the database
        $timestamp = date('Y-m-d H:i:s');
        $query = "INSERT INTO presence (FromJid,Status,Timestamp) value ('$fromJid','$status','$timestamp')";
        $this->mysql->setData($query);
      }
    }

In above example I have done 4 things:

  • Sends back a message saying “Hi, Thanks for your offline message”, when I receive a offliner.
  • Sends back a message saying “Hi, Thanks for your message”, when I receive an IM from my friend.
  • Change my status message, as and when I receive a status update from my friends.
  • Save messages and presence into database if $logDB = TRUE in config.ini.php

Final Call (index.php)

  /* Include Key file */
  include_once("config.ini.php");

  /* Include JAXL Class */
  include_once("jaxl.class.php");

  /* Create an instance of XMPP Class */
  $jaxl = new JAXL($key[$env]['host'],    // Jabber Server Hostname
                   $key[$env]['port'],    // Jabber Server Port
                   $key[$env]['user'],    // Jabber User
                   $key[$env]['pass'],    // Jabber Password
                   $key[$env]['domain'],  // Jabber Domain
                   $db[$env]['dbhost'],   // MySQL DB Host
                   $db[$env]['dbname'],   // MySQL DB Name
                   $db[$env]['dbuser'],   // MySQL DB User
                   $db[$env]['dbpass'],   // MySQL DB Pass
                   $logEnable,            // Enable Logging
                   $logDB                 // Enable MySQL Inserts
                  );

  try {
    /* Initiate the connection */
    $jaxl->connect();

    /* Communicate with Jabber Server */
    while($jaxl->isConnected) {
      $jaxl->getXML();
    }
  }
  catch(Exception $e) {
    die($e->getMessage());
  }

Instant Messenger Powered by JAXL
I am pleased to announce 3 months after release of JAXL, 1st Instant Messenger powered by JAXL. Currently the instant messenger is in testing phase and will be released after some 3-4 weeks of thorough testing. Meanwhile here is the first clip shot:

Disclaimer
Currently this library is being developed and used at Gtalkbots.com . Though it is thoroughly tested and being used, I still recommend not to use it on production servers. Mainly, since it is heavily customized for Gtalkbot’s usage. I am releasing it, as I see it of use for the community worldwide. If you want to use it, use at your own risk. Let me know of any changes you make to this library. In future I look to make this library more generic.

Enjoy and let me know of any bugs, feedbacks, enhancements or any abuse you may want to pass through if it doesn’t work for you 😛

You should be running index.php using command line and not browser (recommended). This class is currently highly customized for Gtalkbots usage and works perfectly with Gtalk Servers.