<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Abhi's Weblog</title>
	
	<link>http://abhinavsingh.com/blog</link>
	<description>PHP, Apache, MySQL, XMPP and Web Development</description>
	<lastBuildDate>Tue, 10 Nov 2009 21:28:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<creativeCommons:license>http://creativecommons.org/licenses/by/2.0/</creativeCommons:license><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/abhinavsingh" type="application/rss+xml" /><feedburner:emailServiceId>abhinavsingh</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>How to use JAXL (Jabber XMPP Library in PHP) to import Gtalk contacts of any user</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/sTzzx-XYqwo/</link>
		<comments>http://abhinavsingh.com/blog/2009/11/how-to-use-jaxl-jabber-xmpp-library-in-php-to-import-gtalk-contacts-of-any-user/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 14:31:19 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[XMPP]]></category>
		<category><![CDATA[Gtalk]]></category>
		<category><![CDATA[JAXL]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=550</guid>
		<description><![CDATA[JAXL is an open source Jabber XMPP Client library written in PHP.  It provides a self titled class JAXL which implements XMPP protocol. It can be extended to write custom event handler for every message or presence received. Developers are using JAXL for developing real time applications. Checkout 5 exciting gaming bots you can [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/LP-haCY-iOVYQy4P4X6w603LP8M/0/da"><img src="http://feedads.g.doubleclick.net/~a/LP-haCY-iOVYQy4P4X6w603LP8M/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/LP-haCY-iOVYQy4P4X6w603LP8M/1/da"><img src="http://feedads.g.doubleclick.net/~a/LP-haCY-iOVYQy4P4X6w603LP8M/1/di" border="0" ismap="true"></img></a></p><p><a href="http://code.google.com/p/jaxl" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/how-to-use-jaxl-jabber-xmpp-library-in-php-to-import-gtalk-contacts-of-any-user/&wp-toolbar-fromtitle=How to use JAXL (Jabber XMPP Library in PHP) to import Gtalk contacts of any user&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >JAXL</a> is an open source Jabber XMPP Client library written in PHP.  It provides a self titled class JAXL which implements XMPP protocol. It can be extended to write custom event handler for every message or presence received. Developers are using JAXL for developing real time applications. Checkout <a href="http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/">5 exciting gaming bots you can make using JAXL</a>.</p>
<p>However one thing which goes un-noticed is that JAXL can also be used to import Gtalk contacts of any user. This is infact one of the very first thing which JAXL class do, after successful authentication with the Gtalk servers i.e. import the authenticated user contact list. In this blog post I will demo a sample script to import any user contact list from google servers.</p>
<p><strong style="font-size:18px;"><u>Importing Gtalk contacts using JAXL</u></strong></p>
<ol>
<li>Download and extract <a href="http://jaxl.googlecode.com/files/jaxl-1.0.4.rar" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://jaxl.googlecode.com/files/jaxl-1.0.4.rar&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/how-to-use-jaxl-jabber-xmpp-library-in-php-to-import-gtalk-contacts-of-any-user/&wp-toolbar-fromtitle=How to use JAXL (Jabber XMPP Library in PHP) to import Gtalk contacts of any user&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >jaxl-1.0.4.rar</a></li>
<li>Edit <code>config.ini.php</code> and update credentials of the user whose contact list we are trying to import:
<pre class="php" name="code">  $key = array("prod"=>array("user"=>"mailsforabhinav",
                             "pass"=>"xxxxxx",
                             "host"=>"talk.google.com",
                             "port"=>5222,
                             "domain"=>"gmail.com"
                            ),
</pre>
</li>
<li>Open <code>jaxl.class.php</code> and modify the code as below:
<pre class="php" name="code">    function setStatus() {
      // Set a custom status or use $this->status
      $this->sendStatus($this->status);
      print "Setting Status...\n";
      print_r($this->rosterlist); // Print the contact list on the console
      print "Done\n";
      exit;
    }
</pre>
</li>
<li>Finally run from command line to retrieve gtalk contacts of the authenticated user.
<pre class="php" name="code">php index.php</pre>
</li>
</ol>
<p>One can easily modify the above code to save user contacts in a database.<br />
Also one can echo <code>json_encode($this->rosterlist)</code> in response to an Ajax call from the browser.</p>
<p>Enjoy and leave your comments.</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/sTzzx-XYqwo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/11/how-to-use-jaxl-jabber-xmpp-library-in-php-to-import-gtalk-contacts-of-any-user/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/11/how-to-use-jaxl-jabber-xmpp-library-in-php-to-import-gtalk-contacts-of-any-user/</feedburner:origLink></item>
		<item>
		<title>Writing a custom unix style tail in PHP using Libevent API on Mac OS X 10.5.x and other platforms</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/oeMKd94ss-4/</link>
		<comments>http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 16:56:01 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Libevent]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[OSX]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=545</guid>
		<description><![CDATA[Libevent is a library which provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. Many famous applications/frameworks/libraries like memcached are using libevent. In this blog post, I will demonstrate how to write a custom unix style tail script using Libevent [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/dWWNfKYpB6REUfnRGZmXG1u-u-w/0/da"><img src="http://feedads.g.doubleclick.net/~a/dWWNfKYpB6REUfnRGZmXG1u-u-w/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/dWWNfKYpB6REUfnRGZmXG1u-u-w/1/da"><img src="http://feedads.g.doubleclick.net/~a/dWWNfKYpB6REUfnRGZmXG1u-u-w/1/di" border="0" ismap="true"></img></a></p><p><a href="http://www.monkey.org/~provos/libevent/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.monkey.org/~provos/libevent/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/&wp-toolbar-fromtitle=Writing a custom unix style tail in PHP using Libevent API on Mac OS X 10.5.x and other platforms&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Libevent</a> is a library which provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. Many famous applications/frameworks/libraries like <a href="http://danga.com/memcached" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://danga.com/memcached&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/&wp-toolbar-fromtitle=Writing a custom unix style tail in PHP using Libevent API on Mac OS X 10.5.x and other platforms&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >memcached</a> are using libevent. In this blog post, I will demonstrate how to write a custom unix style tail script using Libevent API in PHP.</p>
<p><strong style="font-size:18px;"><u>Setting up the environment:</u></strong><br />
Setting up libevent with PHP is a little tricky. Below are the steps, I followed to make it work on Mac OSX 10.5. However the steps should be same for any other OS you choose to code on. Here we go:</p>
<ol>
<li>Check the version of libevent installed on your system. If you don&#8217;t have libevent or the installed version is < 1.4, you will need to compile libevent-1.4.x
<pre name="code" class="php">~ sabhinav$ port list | grep libevent
libevent                       @1.4.12         devel/libevent</pre>
</li>
<li>Uninstall existing libevent
<pre name="code" class="php">~ sabhinav$ port uninstall libevent</pre>
</li>
<li>Add the following into your .bash_profile file:
<pre name="code" class="php">export MACOSX_DEPLOYMENT_TARGET=10.5
export CFLAGS="-arch x86_64 -g -Os -pipe -no-cpp-precomp"
export CCFLAGS="-arch x86_64 -g -Os -pipe"
export CXXFLAGS="-arch x86_64 -g -Os -pipe"
export LDFLAGS="-arch x86_64 -bind_at_load"</pre>
</li>
<li>Open a new terminal window. Download and extract libevent-1.4.12-stable
<pre name="code" class="php">~ sabhinav$ wget http://www.monkey.org/~provos/libevent-1.4.12-stable.tar.gz
~ sabhinav$ tar -xvzf libevent-1.4.12-stable.tar.gz</pre>
</li>
<li>Compile libevent-1.4.12-stable
<pre class="php" name="code">~ sabhinav$ cd libevent-1.4.12-stable
~ sabhinav$ ./configure
~ sabhinav$ make
~ sabhinav$ sudo make install</pre>
</li>
<li>Assuming you have a successful installation, lets install <a href="http://pecl.php.net/package/libevent" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://pecl.php.net/package/libevent&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/&wp-toolbar-fromtitle=Writing a custom unix style tail in PHP using Libevent API on Mac OS X 10.5.x and other platforms&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >PECL package libevent-0.0.2</a>.
<pre name="code" class="php">~ sabhinav$ pecl download libevent-0.0.2
~ sabhinav$ tar -xvzf libevent-0.0.2.tgz libevent-0.0.2
~ sabhinav$ cd libevent-0.0.2
~ sabhinav$ phpize
~ sabhinav$ ./configure
~ sabhinav$ make
~ sabhinav$ sudo make install</pre>
</li>
<li>Enable libevent extension in your php.ini
<pre class="php" name="code">extension=libevent.so</pre>
</li>
<li>Reload apache server
<pre class="php" name="code">~ sabhinav$ sudo apachectl restart</pre>
</li>
<li>Confirm we have libevent extension enabled using phpinfo(); or
<pre class="php" name="code">~ sabhinav$ php -i | grep libevent</pre>
</li>
</ol>
<p><strong style="font-size:18px;"><u>Writing a custom unix style tail script in PHP (tail.php)</u></strong><br />
Below is a sample script which can be used as a base for writing custom unix style tail script. Comments in the code will help you understanding the flow of the code. Also do view official documentation for <a href="http://us3.php.net/manual/en/book.libevent.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://us3.php.net/manual/en/book.libevent.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/&wp-toolbar-fromtitle=Writing a custom unix style tail in PHP using Libevent API on Mac OS X 10.5.x and other platforms&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >PHP Libevent extension usage</a>.</p>
<pre class="php" name="code">&lt;?php

	// callback function called whenever the registered event is triggered
	function eventFd($fd, $events, $arg) {
		echo fread($fd, 4096);
	}

	// create event base
	$base_fd = event_base_new();

	// create a new event
	$event_fd = event_new();

	// resource to be monitored
	$fd = fopen($argv[1], 'r');

	// set event on passed file name
	event_set($event_fd, $fd, EV_WRITE | EV_PERSIST, 'eventFd', array($event_fd, $base_fd));

	// associate base with this event
	event_base_set($event_fd, $base_fd);

	// register event
	event_add($event_fd);

	// start event loop
	event_base_loop($base_fd);

?&gt;
</pre>
<p><strong style="font-size:18px;"><u>Trying out tail.php</u></strong><br />
Save the above code file and issue the following on the terminal:</p>
<pre class="php" name="code">~ sabhinav$ php tail.php /var/log/apache2/access_log</pre>
<p>Try accessing a page on your webserver and you should see the access log being tailed by the php script. <img src='http://abhinavsingh.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/oeMKd94ss-4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/11/writing-a-custom-unix-style-tail-in-php-using-libevent-api-on-mac-os-x-10-5-x-and-other-platforms/</feedburner:origLink></item>
		<item>
		<title>Web Security : Using crumbs to protect your PHP API (Ajax) call from Cross-site request forgery (CSRF/XSRF) and other vulnerabilities</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/jUWYlz4kW78/</link>
		<comments>http://abhinavsingh.com/blog/2009/10/web-security-using-crumbs-to-protect-your-php-api-ajax-call-from-cross-site-request-forgery-csrfxsrf-and-other-vulnerabilities/#comments</comments>
		<pubDate>Sun, 04 Oct 2009 19:13:18 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Spam]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=532</guid>
		<description><![CDATA[Have your API calls ever being used directly by someone without your permission? If yes, read on to find out how can we protect our API&#8217;s from such spammers and hackers. Before we go ahead and see a possible solution for this, lets try to list out a few cases, when our API&#8217;s can be [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/Xmgd-z6wVkO5XYX45C4Xx2lU_14/0/da"><img src="http://feedads.g.doubleclick.net/~a/Xmgd-z6wVkO5XYX45C4Xx2lU_14/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Xmgd-z6wVkO5XYX45C4Xx2lU_14/1/da"><img src="http://feedads.g.doubleclick.net/~a/Xmgd-z6wVkO5XYX45C4Xx2lU_14/1/di" border="0" ismap="true"></img></a></p><p>Have your API calls ever being used directly by someone without your permission? If yes, read on to find out how can we protect our API&#8217;s from such spammers and hackers. Before we go ahead and see a possible solution for this, lets try to list out a few cases, when our API&#8217;s can be accessed without our permissions.</p>
<p><strong style="font-size:18px;"><u>Common cases of vulnerable API/Ajax calls</u></strong></p>
<ul>
<li><u>Ajax calls having no user authentication</u>: This is the first place where a spammer will try to find out a loop hole. Take this example, suppose I created a group chat plugin for my blog. Since it&#8217;s a group chat plugin, I don&#8217;t really want the blog viewers to register before they can write a messages. Blog viewer only need to provide their name, email and url (just like wordpress comments). Thereafter, they can write messages which are submitted on the server side using ajax calls. And here is the &#8220;problem&#8221;. Anyone can pick up the ajax url, write a curl script, post the required parameters and fill up my database with millions of messages.</li>
<li><u>Ajax calls having user authentication</u>: One day I realize my group chat plugin has received more than 1 million messages last night (all spams). Hence I decide to make my blog viewers to register before they can post a message on the group chat plugin, simply because someone is filling up my database by simulating ajax calls through a curl script. Anyone can write a script, since these ajax call do not authenticate the user making the call. But are my ajax calls safe after forcing users to register? NO, a registered user too can simulate these ajax calls and passing authentication by sending the right cookies.</li>
</ul>
<p><strong style="font-size:18px;"><u>Possible solutions and their flaws</u></strong><br />
If you look around on web, you will find a bunch of solution to such problems. But then every solution have it&#8217;s own problem which forces you not to use them. Listed below are 2 possible solutions to our problem:</p>
<ul>
<li><u>Using X-Requested-With to protect ajax calls</u>: All famous javascript frameworks like JQuery, YUI, Mootools etc sends an additional header parameter while making an XHR request. These libraries set &#8220;X-Requested-With=XMLHttpRequest&#8221; header, which can then be used on the server side to detect if the call was made through an ajax call. But a programmer can easily pass these headers using a curl script, making the server believe that the call was made through an XHR request.</li>
<li><u>Using HTTP Referrer</u>: This solution comes in handy for cases when a spammer/hacker try to POST data into your site&#8217;s. We can check for the referrer page, before we go ahead and accept the POST data. If the POST data is coming from a page within your site, you go ahead and accept the data, otherwise reject it. But this solution again have it&#8217;s shortcomings. HTTP Referrer can be tampered in certain browsers using javascript and they can also be stripped away by some proxies and firewalls.</li>
</ul>
<p><strong style="font-size:18px"><u>Using crumbs</u></strong><br />
Finally the idea is to have crumbs. A unique electronic key which is shared between server and client, and which have a short life time. But how are these useful? Suppose, in my group chat module, upon page load i generate a crumb whose life time is 30 minutes (tunable). Why 30 minutes? Because, I assume my blog viewers to either engage into the group chat module or leave that specific blog post within 30 minutes.</p>
<p>Now whenever a user writes a message, this crumb is passed back to the server side. If user writes a message before 30 minutes, this crumb will be validated and user shout submitted. (30 minutes should take care of 99.99% of the cases). In response, server api sends back the new crumb which should be sent back with the next ajax call.</p>
<p>Now when a spammer try to simulate the ajax request using curl calls, he will not be able to succeed because of the absence of the crumb. But he can capture the crumb from the site and simulate the effect, right? YES he can, but we can take care of this by reducing the life time of the generated crumb.</p>
<p><strong style="font-size:18px;"><u>Generating crumbs using PHP</u></strong><br />
Here are the two functions, I use to generate and verify crumbs in PHP:</p>
<pre class="php" name="code">        // user for whom crumb is to be generated
        $uid = "mailsforabhinav@gmail.com";

        // usually $salt = DB_PASSWORD . DB_USER . DB_NAME . DB_HOST . ABSPATH;
        $salt = "abcdefghijklmnopqrstuvwxyz";

        function challenge($data) {
                global $salt;
                return hash_hmac('md5', $data, $salt);
        }

        function issue_crumb($ttl, $action = -1) {
                global $uid;

                // ttl
                $i = ceil(time() / $ttl);

                // log
                echo "Generating crumb at time:".time().", i:".$i.", action:".$action.", uid:".$uid.PHP_EOL;

                // return crumb
                return substr(challenge($i . $action . $uid), -12, 10);
        }

        function verify_crumb($ttl, $crumb, $action = -1) {
                global $uid;

                // ttl
                $i = ceil(time() / $ttl);

                // log
                echo "Verifying crumb:".$crumb." at time:".time().", i:".$i.", action:".$action.", uid:".$uid.PHP_EOL;

                // verify crumb
                if(substr(challenge($i . $action . $uid), -12, 10) == $crumb || substr(challenge(($i - 1) . $action . $uid), -12, 10) == $crumb)
                        return true;
                return false;
        }
</pre>
<p>I can generate crumbs with a simple call:</p>
<pre class="php" name="code">$crumb = issue_crumb(300, "group_chat_module");</pre>
<p>where $ttl = 300 (required), $action = &#8220;group_chat_module&#8221; (optional, defaults to -1)</p>
<p>Later on I can verify the crumb using another call:</p>
<pre class="php" name="code">var_dump(verify_crumb(300, $crumb, "group_chat_module"));</pre>
<p>I hope this helps you protecting your API&#8217;s. Let me know of better methods to stop such attacks.<br />
Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/jUWYlz4kW78" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/10/web-security-using-crumbs-to-protect-your-php-api-ajax-call-from-cross-site-request-forgery-csrfxsrf-and-other-vulnerabilities/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/10/web-security-using-crumbs-to-protect-your-php-api-ajax-call-from-cross-site-request-forgery-csrfxsrf-and-other-vulnerabilities/</feedburner:origLink></item>
		<item>
		<title>5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/mJ1bR_5uaKA/</link>
		<comments>http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 22:09:23 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[XMPP]]></category>
		<category><![CDATA[Bots]]></category>
		<category><![CDATA[JAXL]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=526</guid>
		<description><![CDATA[Jaxl is an open source XMPP client library written in PHP. The object oriented structure of JAXL allow developers to build various extensions using Jaxl library as their base. If used intelligently, JAXL client library is capable of doing more than just chat message transfers. Here are a few applications where developers have tried using [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/zx7VHcR3IG3ejAwu0E8D6q25w8g/0/da"><img src="http://feedads.g.doubleclick.net/~a/zx7VHcR3IG3ejAwu0E8D6q25w8g/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/zx7VHcR3IG3ejAwu0E8D6q25w8g/1/da"><img src="http://feedads.g.doubleclick.net/~a/zx7VHcR3IG3ejAwu0E8D6q25w8g/1/di" border="0" ismap="true"></img></a></p><p><a href="http://abhinavsingh.com/blog/2009/01/introducing-jaxl-open-source-jabber-xmpp-library/">Jaxl</a> is an open source <a href="http://xmpp.org" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://xmpp.org&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >XMPP</a> client library written in <a href="http://php.net" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://php.net&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >PHP</a>. The object oriented structure of JAXL allow developers to build various extensions using Jaxl library as their base. If used intelligently, JAXL client library is capable of doing more than just chat message transfers. Here are a few applications where developers have tried using JAXL for delivering more than just chat messages:</p>
<p><em>&#8220;I used your library to develop a prototype that connects dynamically some users to a XMPP server if an external event is detected. The script runs like a daemon. Because of your object-oriented class design it was very easy to set up dynamic number of parallel XMPP sessions. I would like to use your library as part of a software that integrates telephony and XMPP functionality. The software will also be licenced unter GPL. Thanks again for your great work.&#8221;</em></p>
<p><em>&#8220;I&#8217;m thinking on creating a symfony plugin for jaxl library. I&#8217;ve worked before with the Jabber php library. This one of yours is much nicer! And it is working really nice, good job! &#8220;</em></p>
<p>The possibilities are endless. In this blog post I will discuss various possible use cases of JAXL client library starting from, creating an 24&#215;7 online chat bot, broadcasting messages to gtalk friend list, rss feed aggregator, custom out of office email bot for gmail and google apps user, and finally a simple game using Jaxl client library. (similar to anagram gaming bot games@gtalkbots.com)</p>
<p><strong style="font-size:18px;"><u>Setting up the environment</u></strong><br />
Jaxl is hosted on <a href="http://code.google.com" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Google Code</a>. Checkout the latest version of JAXL client library:</p>
<pre name="code" class="php">svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only</pre>
<p>Alternately you can download the latest version of Jaxl from here:<br />
<a href="http://jaxl.googlecode.com/files/jaxl-1.0.4.rar" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://jaxl.googlecode.com/files/jaxl-1.0.4.rar&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://jaxl.googlecode.com/files/jaxl-1.0.4.rar</a></p>
<p>From here on I will assume you have all the library files in a folder called <strong>jaxl</strong>. You should see the following set of php files inside the jaxl folder:</p>
<ul>
<li><strong>config.ini.php</strong> : Holds your jabber account and mysql connection information</li>
<li><strong>mysql.class.php</strong> : Basic MySQL connection class used to insert received messages and presence into MySQL database</li>
<li><strong>logger.class.php</strong> : A very basic logger class which allows you to log all XML stanza&#8217;s send and received from jabber server</li>
<li><strong>xmpp.class.php</strong> : Base XMPP class library which implements the XMPP protocol</li>
<li><strong>jaxl.class.php</strong> : JAXL class which extends XMPP class library. Should be the starting point for your application</li>
<li><strong>index.php</strong> : After building your application in jaxl.class.php, you finally initialize and call your methods here</li>
</ul>
<p>You will also see a bunch of other php files: <code>jaxl4broadcast.class.php</code>, <code>jaxl4gmail.class.php</code>, <code>jaxl4dzone.class.php</code>, which are extensions written using Jaxl library as their base. We will discuss them all as we proceed on the blog.</p>
<p>Another point I would like to discuss before we go ahead, is the structure of Jaxl client library. XMPP class is written in <code>xmpp.class.php</code> php class file which implements the XMPP protocol. It takes care of user authentication, user presence (available, busy, idle), user status, sending and receiving messages and everything which we will see as we proceed on the blog. JAXL class extends XMPP class in <code>jaxl.class.php</code> php file. We will develop all our bots/applications in <code>jaxl.class.php</code> php file and will never require to touch the base <code>xmpp.class.php</code> file. Finally, <code>index.php</code> is the file which invokes our application written in <code>jaxl.class.php</code>. As a convention, we rename <code>jaxl.class.php</code> to <code>jaxl4app.class.php</code> where app is the name of our application.</p>
<p>XMPP class defined in <code>xmpp.class.php</code> passes program handle to various methods whenever an event occur. Following 4 methods are of our use, while developing an application inside <code>jaxl4app.class.php</code> file:</p>
<ul>
<li><strong>eventMessage($fromJid, $content, $offline = FALSE)</strong> : This is the method where XMPP class passes the handle, when it receives a message. The message can be either online or offline, which is indicated by the <code>$offline</code> parameter being passed to this method. Other two parameters received are <code>$fromJid</code> which is the jabber id of the user sending the message. e.g. jabberxmpplibrary@gmail.com, and <code>$content</code> which is the actual message sent by the user identified by <code>$fromJid</code></li>
<li><strong>eventPresence($fromJid, $status, $photo)</strong> : This is the method where XMPP class passes the handle, when it receives a presence i.e. notification about status change of a user. A change in status event is triggered by either user changing his status text or by user changing his online presence i.e. available, idle, busy. <code>$fromJid</code> is the parameter passed to this method which is the jabber id of the user who changed his status. <code>$status</code> is the new status set by the user.</li>
<li><strong>eventNewEMail($total, $thread, $url, $participation, $messages, $date, $senders, $labels, $subject, $snippet)</strong> : XMPP library also implements the Gmail Notification extension for XMPP protocol, and passes the handle to eventNewEMail() method when ever a new email is received on Gmail or Google Apps mail. One of the real life example of this protocol called <em>Gmail Notification</em> can be seen using Gtalk. <a href="http://www.google.com/talk/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.google.com/talk/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Gtalk</a> will pop up a window when ever you receive a new email on Gmail. For more detail about various parameters passed to this method refer the <a href="http://code.google.com/apis/talk/jep_extensions/gmail.html" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/apis/talk/jep_extensions/gmail.html&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Gmail Notification</a> documentation.</li>
<li><strong>setStatus()</strong> : XMPP class passes the handle to this method before setting the status of the bot/application we intent to run using Jaxl library. Customize this method for setting custom status messages on logon or anytime during the execution of the application.</li>
</ul>
<p>In 99.99% of the applications which we will intent to build, will not require handle to other events which happen in the background and handled by the base XMPP class. For more information about all the events refer this blog post. <a href="http://abhinavsingh.com/blog/2009/01/behind-the-scenes-how-and-what-xmls-are-exchanged-by-jaxl/">Behind the scenes – How and What XML’s are exchanged by JAXL</a></p>
<p>Jaxl also provide provisions to switch your bot between production and development environment by a simple change in the <code>config.ini.php</code> file. <code>$env</code> parameter (allowed values are &#8220;prod&#8221; or &#8220;devel&#8221;) decides what environment do you want to run this bot on. <code>$env</code> is set to &#8220;devel&#8221;, when you are developing your bot/application and don&#8217;t want to connect to a production jabber server repeatedly during development. Setting <code>$env</code> to &#8220;prod&#8221;, will configure the bot/application to connect to the production jabber server.</p>
<p><strong style="font-size:18px;"><u>1. My first bot: Creating an 24&#215;7 online status aggregation bot</u></strong><br />
This was how I started working on JAXL. I wanted to collect status messages of all my gtalk friends. I also wanted to plot on a graph, when and which of my gtalk friends come online or go offline. A basic example of this graph can be seen on <a href="http://gtalkbots.com/imoracle/timeline" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://gtalkbots.com/imoracle/timeline&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >my timeline at Gtalkbots</a>.</p>
<p>The good thing in Jaxl library is that, by default it comes with a built-in bot capable of doing the above tasks for us. (because this is how i started working on Jaxl, hence is the default behaviour). Here is how you can configure Jaxl for the same:</p>
<ul>
<li><strong>Choosing an environment</strong>: Open <code>config.ini.php</code> and choose an environment. Since we want to collect information about all our friends on gtalk, we will set <code>$env="prod"</code>. This will allow our bot to connect to the jabber servers hosted at talk.google.com (see config file). Also set <code>$logDB = TRUE;</code>, which will enable logging of user information to the MySQL database.</li>
<li><strong>Updating user credentials</strong>: Register a username at <a href="http://gmail.com" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://gmail.com&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Gmail</a> (if you don&#8217;t have one already) and update the username and password of this user in the config file. Our bot will use these credentials to authenticate with the google talk servers. Add a few friends using gtalk to start with. Also update your MySQL database hostname, username and password. Leave the database name as jaxl.</li>
<li><strong>Creating jaxl database</strong>: Run the <code>database.sql</code> file against your MySQL database. It will create a database called <em>jaxl</em> with two tables called <em>message</em> and <em>presence</em>. Our application will use these tables for storing information about our gtalk friends.</li>
<li><strong>Creating the bot</strong>: <code>jaxl.class.php</code> by default is ready to work as we want it to. It will log all your gtalk friend&#8217;s information in the MySQL database if <code>$logDB</code> is set to <code>TRUE</code> inside the <code>config.ini.php</code> file. Also by default it replies back a welcome message for every message received (online or offline). You may want to un-comment that section of the code as of now.</li>
<li><strong>Running the bot</strong>: Open command line (windows) or the terminal window (unix, mac) and migrate to the jaxl folder. (Remember you cannot run your application with something like http://localhost/jaxl in your browser. XMPP is a TCP-IP level protocol and not made for running directly using HTTP protocol i.e. browsers. However, we can use BOSH extension of XMPP protocol to make it run over HTTP. Jaxl currently doesn&#8217;t support BOSH extension. It&#8217;s currently under <a href="http://groups.google.co.in/group/jaxl/browse_thread/thread/1a0d0790a1f064db?hl=en" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://groups.google.co.in/group/jaxl/browse_thread/thread/1a0d0790a1f064db?hl=en&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >testing</a>). Now simply run the following command.
<pre class="php" name="code">sudo php index.php</pre>
<p> on the terminal. You should see something like this on your terminal: <img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/09/jaxl-jabber-xmpp-library-demo-1.png" alt="jaxl-jabber-xmpp-library-demo-1" title="jaxl-jabber-xmpp-library-demo-1" width="405" height="162" class="aligncenter size-full wp-image-527" /> </p>
<p>To debug more while development, you should enabled logging in the config file. Jaxl library will start logging every xmpp stanza sent or recieved to the google talk servers. This is also a good way of learning more about the internals of xmpp protocol.</li>
<li><strong>Running the bot 24&#215;7</strong>: One of the most common query i get (specially from college enthusiasts) is how to run their applications 24&#215;7. Just like the anagram gaming bot at <a href="http://gtalkbots.com" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://gtalkbots.com&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >gtalkbots</a> (games@gtalkbots.com). Run the following command on your terminal to run your application as a background process (only possible on unix or osx, not on windows):
<pre class="php" name="code">sudo nohup php index.php > log/logger.log &#038;</pre>
<p>. This will start the bot as a background process and hence the bot will not stop its execution even if you close the terminal window. When you want to kill your application, simply search for the process id of your application using:
<pre name="code" class="php">ps aux | grep index.php</pre>
<p>. Note the process id corresponding to your application and issue
<pre name="code" class="php">kill -9 process_id</pre>
<p> to kill the application.<br />
<img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/09/jaxl-jabber-xmpp-library-demo-3.png" alt="jaxl-jabber-xmpp-library-demo-3" title="jaxl-jabber-xmpp-library-demo-3" width="523" height="175" class="aligncenter size-full wp-image-529" /></li>
</ul>
<p><br/></p>
<p><strong style="font-size:18px;"><u>2. Broadcasting messages to your gtalk friend list</u></strong><br />
You might want to broadcast a message to your gtalk buddy list for a number of reasons. Extension <a href="http://code.google.com/p/jaxl/source/browse/trunk/jaxl4broadcast.class.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/source/browse/trunk/jaxl4broadcast.class.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >jaxl4broadcast.class.php</a> will do exactly the same for us. To run this extension you should checkout the latest <a href="http://code.google.com/p/jaxl/source/browse/trunk/xmpp.class.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/source/browse/trunk/xmpp.class.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >xmpp.class.php</a> file from the repository. Jaxl v 1.0.4 doesn&#8217;t support Gmail Extension. Leave your configuration file as it is form the previous example. Simply include <code>jaxl4broadcast.class.php</code> in your <code>index.php</code> file, instead of <code>jaxl.class.php</code>. Or you might also want to create separate index file for each application you build using Jaxl.</p>
<p>Now simply type in
<pre class="php" name="code">sudo php index.php</pre>
<p> on terminal window. You will see the following action logs on the terminal window:<br />
<img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/09/jaxl-jabber-xmpp-library-demo-4.png" alt="jaxl-jabber-xmpp-library-demo-4" title="jaxl-jabber-xmpp-library-demo-4" width="404" height="425" class="aligncenter size-full wp-image-530" /><br/><br />
The script broadcast the default message to everyone on the gtalk friend list. In the screen shot you can also see me receiving default message sent by our bot. If any of the friend(s) are offline, the bot sends an offline message to them.</p>
<p><strong style="font-size:18px;"><u>3. RSS feed aggregator bot</u></strong><br />
Here we will try to make a bot which keep processing RSS feeds in the background. We will also make provisions in this application to retrieve aggregated RSS feed results just by sending simple text messages to the bot. One such application build using Jaxl library is RSS feed integrator for <a href="http://dzone.com" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://dzone.com&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Dzone</a>. You can find this application in the jaxl folder if you have checked out the code from repository. Otherwise <a href="http://code.google.com/p/jaxl/source/browse/trunk/jaxl4dzone.class.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/source/browse/trunk/jaxl4dzone.class.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >download the application from here</a>.</p>
<p>Leave your configuration file as it is from previous applications and instead of <code>jaxl.class.php</code>, include <code>jaxl4dzone.class.php</code> inside <code>index.php</code>. As before simply run the following command on the terminal window:
<pre class="php" name="code">nohup php index.php > log/logger.log &#038;</pre>
<p>.</p>
<p>Read <a href="http://abhinavsingh.com/blog/2009/01/how-to-get-dzone-feeds-as-im-using-jaxl-add-dzonegtalkbotscom/">How to get dzone feeds as IM using JAXL? Add dzone@gtalkbots.com</a> for pre-requisites required before running this application and a complete list of provisions made for retrieving rss feeds from this running bot. Here are is a response from the bot, when I send a message reading &#8220;<em>php</em>&#8221; to the bot:<br />
<img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/09/jaxl-jabber-xmpp-library-demo-5.png" alt="jaxl-jabber-xmpp-library-demo-5" title="jaxl-jabber-xmpp-library-demo-5" width="429" height="631" class="aligncenter size-full wp-image-531" /><br/><br />
The application in the background, checks for the incoming message. Further it checks for a cached RSS feed in the cache folder. If the cache is stale or expired, it refetches the RSS feed from Dzone and throw back the results as seen in the screenshot above. If the bot finds a fresh cache of RSS feed in cache directory, it simply throw back the same RSS feed.</p>
<p><strong style="font-size:18px;"><u>4. Custom out-of-office email bot for gmail</u></strong><br />
<code>jaxl4gmail.class.php</code> is an extension which shows the power of Gmail Extension integration into Jaxl library. This extension allows you to send custom out-of-office email&#8217;s to your contacts. I might want to send out a custom out-of-office mail to my colleagues in office and a custom mail to my friends and family.</p>
<p>Download the extension from here, if not already present in the jaxl directory. Include jaxl4gmail.class.php in index.php. Finally run the bot using:
<pre class="php" name="code">nohup php index.php > log/logger.log &#038;</pre>
<p>For details information on how to customize this extension refer this blog post: <a href="http://abhinavsingh.com/blog/2009/02/programatically-control-your-google-mails-using-jaxl-v-104/">Programatically control your google mails using JAXL v 1.0.4 </a></p>
<p><strong style="font-size:18px;"><u>5. Building an online multi-user gaming bot</u></strong><br />
By now we know how to run our bot 24&#215;7 using Jaxl library. In this section we will develop a basic online multi-user gaming bot. Before we go ahead and code our bot, lets decide a few rules for our game:</p>
<p>Users worldwide can add our bot as buddy in gtalk (or using any other IM client). Below are the rules and actions a user can perform:</p>
<ul>
<li>Send a message &#8220;start&#8221; to enter the multi-user gaming arena.</li>
<li>Send a message &#8220;stop&#8221; to exit the gaming arena.</li>
<li>Send a message &#8220;options&#8221; to view available options for the gaming arena.</li>
<li>Any other message sent by the user, will be considered as his answer to the previously broadcasted question. We will make sure &#8220;start&#8221;, &#8220;stop&#8221; and &#8220;options&#8221; are not an answer to any of the question being broadcasted.</li>
<li>Whom-so-ever sends a right answer to the broadcasted question receives 5 points. Bot immediately notify everyone in the arena about right answer being received. Thereafter, bot will broadcast the next question to all the users in the arena.</li>
<li>Bot reads a list of questions from a file or database as soon as the bot is started. Thereafter, it will keep reading questions from the list of questions randomly and keep broadcasting them to users in the arena.</li>
<li>Bot keeps a track of jabber id for incoming (identified by &#8220;start&#8221;) and outgoing (identified by &#8220;stop&#8221;) users.</li>
<li>Bot also maintains the index of current question being broadcasted</li>
</ul>
<p>We will code our application in a file called <code>jaxl4gaming.class.php</code>. Here is how the final code will look like. See comments inside the code for more explanation:</p>
<p>jaxl4gaming.class.php (<a href="http://code.google.com/p/jaxl/source/browse/trunk/jaxl4gaming.class.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/source/browse/trunk/jaxl4gaming.class.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >download</a>)</p>
<pre class="php" name="code">  /* Include XMPP Class */
  include_once("xmpp.class.php");

  class JAXL extends XMPP {

    // List of question contained in an array
    var $questions = array();

    // List of answers corresponding to above questions
    var $answers = array();

    // list of answers which are not allowed for any question
    var $answers_not_allowed = array('start','stop','options');

    // last sent question key (basically index value of question in questions array)
    var $last_question_key = -1;

    // an associative array storing user scores
    var $user_scores = array();

    // stores jabber id of users currently in the arena
    var $user_jids = array();

    // game status
    var $game_status = FALSE;

    /* START OF STANDARD JAXL METHODS */
    function eventMessage($fromJid, $content, $offline = FALSE) {
      // Take action only if the message received is online
      if(!$offline) {
         // trim incoming content
         $content = trim($content);

         // get bare jid for the user
	 $fromJid = $this->getBareJid($fromJid);
	 switch($content) {
	   case 'start':
	     $this->add_user_to_arena($fromJid);
	     break;
	   case 'stop':
	     $this->remove_user_from_arena($fromJid);
	     break;
	   case 'options':
	     $this->display_options($fromJid);
	     break;
	   default:
	     $this->handle_user_message($fromJid, $content);
	     break;
	 }
      }
    }

    // not required for this gaming demo
    function eventPresence($fromJid, $status, $photo) {

    }

    // set the status for our gaming bot
    function setStatus() {
      // Set a custom status or use $this->status
      $this->sendStatus("Type *options* for getting started");
      print "Setting Status...\n";
      print "Done\n";

      // initialize game
      if(!$this->game_status) {
        $this->logger->logger('Initializing gaming arena....');
        $this->init();
        $this->game_status = TRUE;
      }
    }
    /* END OF STANDARD JAXL METHOD */

    /* START OF GAME CODE METHODS */
    function init() {
      // called when the bot starts
      // read the list of questions and their answers from a txt file
      // populate the $question and $answers array
      // HARDCODING arrays for DEMO purpose.
      $this->questions = array('q1','q2','q3','q4','q5');
      $this->answers = array('a1','a2','a3','a4','a5');
      return TRUE;
    }

    function broadcast_message($message, $except=array()) {
      foreach($this->user_jids as $jid => $info) {
	if(in_array($jid, $except)) continue;
   	else if($this->user_jids[$jid]['status'] == 'online') {
          $this->sendMessage($jid, $message);
        }
      }
      return TRUE;
    }

    function add_user_to_arena($jid) {
       // check if user visited the game before
       // you may want to send some custom welcome messages depending upon the user type
       if(!isset($this->user_jids[$jid])) {
         $this->logger->logger('Adding user_jids key for: '.$jid);
	 $this->user_jids[$jid] = array();
       }

       $this->user_jids[$jid]['status'] = 'online';
       $this->user_jids[$jid]['start_time'] = time();
       $this->logger->logger($jid.' joined the arena: '.json_encode($this->user_jids[$jid]));

       $this->send_current_question($jid);
       return TRUE;
    }

    function send_current_question($jid) {
      // is this the 1st user in the arena
      if($this->last_question_key == -1) $this->last_question_key++;
      $current_question = $this->questions[$this->last_question_key];

      $this->logger->logger('Sending current question at index: '.$this->last_question_key.', question: '.$current_question.' to: '.$jid);
      $this->sendMessage($jid, $current_question);
      return TRUE;
    }

    function broadcast_next_question($except=array()) {
      if($this->last_question_key == count($this->questions)-1) $this->last_question_key = 0;
      else $this->last_question_key++;

      $this->broadcast_message($this->questions[$this->last_question_key], $except);
      return TRUE;
    }

    function broadcast_right_answer($fromJid, $answer, $except) {
      $message = '*'.$fromJid.'* gave the right answer: '.$answer;
      $this->broadcast_message($message, array($fromJid));
      return TRUE;
    }

    function remove_user_from_arena($jid) {
       if(isset($this->user_jids[$jid])) {
	 $this->user_jids[$jid]['status'] = 'offline';
         $this->user_jids[$jid]['end_time'] = $this->user_jids[$jid]['start_time'];
       }
       return TRUE;
    }

    function display_options($jid) {
      $options = '*start* To join the arena, *stop* To quit the arena, *options* To display this help';
      $this->sendMessage($jid, $options);
      return TRUE;
    }

    function handle_user_message($jid, $message) {
      // check if user already exists in the arena
      if(!isset($this->user_jids[$jid]) || $this->user_jids[$jid]['status'] == 'offline') {
        $this->display_options($jid);
        return TRUE;
      }

      // we treat this message as an answer
      $current_answer = $this->answers[$this->last_question_key];
      if($message == $current_answer) {
        $this->increase_user_points($jid);
        $this->broadcast_right_answer($jid, $message, array($jid));
        $this->broadcast_next_question(array());
      }
      else {
        $message = $message.' is a wrong answer. Try again!';
        $this->sendMessage($jid, $message);
      }
      return TRUE;
    }

    function increase_user_points($jid) {
      if(!isset($this->user_jids[$jid]['points'])) $this->user_jids[$jid]['points']=0;
      $this->user_jids[$jid]['points'] += 1;
    }

  }
</pre>
<p>This is the basic game architecture which will generally be followed while you build games using Jaxl library.<br />
In brief here is the explanation to above code:</p>
<ul>
<li><strong>Initializing game</strong>: setStatus() is the last method called during the whole initialization process of bot. Hence this is a right choice to call our game initialization method init(). You can do a number of things in this method. For this demo, I simply hard code the questions and their answers in respective arrays. Once the game is initialized, these $questions and $answers will reside in program memory for the life time.</li>
<li><strong>Basic game flow</strong>: The flow is simple. I have customized the <code>eventMessage()</code> method provided by Jaxl class. I simply check for a number of cases and divert the flow of the game. If the incoming message is one of the available options, I simply do the respective action. (<em>start</em> triggers <code>add_user_to_arena()</code>, <em>stop</em> triggers <code>remove_user_from_arena()</code> and <em>options</em> trigger <code>display_options()</code> method). If incoming message doesn&#8217;t match any available options, I consider it as an attempt to answer the current question and redirect to <code>handle_user_message()</code>. However, if user is yet not a part of the gaming arena and he tries to answer a question, <code>handle_user_message()</code> function will simply redirect to <code>display_options()</code> method.</li>
<li><strong>User stats</strong>: I also maintain basic user stats in a variable called <code>$user_jids</code>. For each user, I maintain the following fields: <code>'status'</code> field value can be &#8216;online&#8217; or &#8216;offline&#8217; depending upon user availability in the arena. I also maintain a <code>'start_time'</code> field which indicates when did the user last joined the arena. You might want to have this for a number of reasons. Every time user quits the arena, I also save a field called <code>'end_time'</code> indicating when did the user last left the arena. Finally, I maintain user points in a field called <code>'points'</code>. This field is incremented by 1 for every correct answer by the user.</li>
<li><strong>Infinite questions</strong>: Every time a new question is broadcasted, I check the status of current question key. If it has reached the end of questions array, i simply reset it to 0. Hence the bot will keep serving the questions always. This logic is inside <code>broadcast_next_question()</code> method.</li>
<li><strong>Broadcasting messages</strong>: <code>broadcast_message()</code> is the main method which broadcast all message from the bot to users playing in the arena. It takes two values as parameters: $message i.e. the message you want to broadcast and $except array which contains user jid&#8217;s which you want to skip while broadcasting.</li>
</ul>
<p>Now how do we test our game. Simply follow the following steps:</p>
<ul>
<li>Download jaxl4gaming.class.php and include it inside index.php</li>
<li>Update the config.ini.php file with your production username and password. We will run this bot using gtalk user credentials.</li>
<li>Run the bot using
<pre class="php" name="code">sudo php index.php</pre>
</li>
<li>Add bot into your gtalk and try to send a message options to it. If everything is fine, you should be able to see the bot performing as we described in the game rules above.</li>
<li>Finally customize the methods inside jaxl4gaming.class.php and build your own games.</li>
</ul>
<p><strong style="font-size:18px;"><u>Debugging your Jaxl bot</u></strong><br />
In case you run into some error while trying to run Jaxl here are a few things you <strong>SHOULD</strong> do:</p>
<ul>
<li>Checkout the <a href="http://code.google.com/p/jaxl/issues/list?can=1&#038;q=&#038;colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&#038;cells=tiles" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/issues/list?can=1&#038;q=&#038;colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&#038;cells=tiles&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >open/closed issues</a> here. I get lot of queries specially from college enthusiasts and in 99% of the cases solution can be found on the issue&#8217;s link above.</li>
<li>Another thing you should do is, enable error logging in your <code>php.ini</code> and check the error logs.</li>
<li>If you are still unable to find a solution, <a href="http://code.google.com/p/jaxl/issues/entry" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jaxl/issues/entry&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >file a new issue</a> with relevant information here.</li>
<li>Search the jaxl forum and discuss with other users who must have encountered similar errors before. Jjoin other users on <a href="http://groups.google.com/group/jaxl" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://groups.google.com/group/jaxl&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/&wp-toolbar-fromtitle=5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >jaxl&#8217;s google group</a> here.</li>
<li>Finally, if nothing helps. Send a mail or IM me.</li>
</ul>
<p>All the best with Jaxl. <img src='http://abhinavsingh.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/mJ1bR_5uaKA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/09/5-exciting-gaming-bots-you-can-create-using-jaxl-jabber-xmpp-library-in-php/</feedburner:origLink></item>
		<item>
		<title>Introducing jSlider: A Content Slider plugin for JQuery</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/YNhjofS8Lrs/</link>
		<comments>http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 13:32:14 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[Open Source Projects]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jslider]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=524</guid>
		<description><![CDATA[jSlider is a light weight JQuery plugin for content sliding. By content we mean everything: HTML code, Images, Advertisements etc etc. jSlider allows to put our content in simple &#60;div&#62;&#8217;s, and then it automatically generates a content slider for you, which one can customize using various options provided.
Screenshot
Below is a screen shot of a content [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/HYMWaDn23tIwQdoxjqAL7_Onqmg/0/da"><img src="http://feedads.g.doubleclick.net/~a/HYMWaDn23tIwQdoxjqAL7_Onqmg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/HYMWaDn23tIwQdoxjqAL7_Onqmg/1/da"><img src="http://feedads.g.doubleclick.net/~a/HYMWaDn23tIwQdoxjqAL7_Onqmg/1/di" border="0" ismap="true"></img></a></p><p><a href="http://code.google.com/p/jslider" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jslider&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >jSlider</a> is a light weight <a href="http://jquery.com/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://jquery.com/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >JQuery</a> plugin for content sliding. By content we mean everything: HTML code, Images, Advertisements etc etc. jSlider allows to put our content in simple <code>&lt;div&gt;</code>&#8217;s, and then it automatically generates a content slider for you, which one can customize using various options provided.</p>
<p><strong style="font-size:18px;"><u>Screenshot</u></strong><br />
Below is a screen shot of a content slider using jSlider:<br />
<a href="http://abhinavsingh.com/webdemos/jslider" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.com/webdemos/jslider&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;"  style="text-decoration:none"><br />
<img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/08/jSlider.png" alt="jSlider" title="jSlider" width="614" height="229" class="aligncenter size-full wp-image-525" style="border:0px none;"/><br />
</a></p>
<p><strong style="font-size:18px;"><u>Download and Demo</u></strong><br />
jSlider is hosted at google code. Use the following links for demo and downloads:</p>
<ul>
<li><a href="http://code.google.com/p/jslider" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://code.google.com/p/jslider&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Download</a> the source code.</li>
<li>Click for a <a href="http://abhinavsingh.com/webdemos/jslider" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.com/webdemos/jslider&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >demo</a> of jSlider</li>
</ul>
<p><strong style="font-size:18px;"><u>Using jslider.jquery.js</u></strong><br />
Below is a sample html code which will be processed by jslider:</p>
<p><strong>Sample input to jslider</strong></p>
<pre name="code" class="php">
    &lt;div id="jslider"&gt;
      &lt;div&gt;
        &lt;input type="hidden" value="Title for Content 1"/&gt;
        &lt;div&gt;
          HTML Content # 1
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;input type="hidden" value="Title for Content 2"/&gt;
        &lt;div&gt;
          HTML Content # 2
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;input type="hidden" value="Title for Content 3"/&gt;
        &lt;div&gt;
          HTML Content # 3
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;input type="hidden" value="Title for Content 4"/&gt;
        &lt;div&gt;
          HTML Content # 4
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;input type="hidden" value="Title for Content 5"/&gt;
        &lt;div&gt;
          HTML Content # 5
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</pre>
<p>One must preserve the div structure as given in the example above. The hidden input values will be taken as heading for that block of content. If you want to have no heading or a common heading, fill this hidden input field appropriately.</p>
<p><strong>Sample output from jslider</strong></p>
<pre class="php" name="code">  &lt;div id="jslider"&gt;
    &lt;div class="slider"&gt;
      &lt;h2&gt;Title for Content 1&lt;/h2&gt;
      &lt;ul&gt;
        &lt;li class="selected"&gt;1&lt;/li&gt;
        &lt;li&gt;2&lt;/li&gt;
        &lt;li&gt;3&lt;/li&gt;
        &lt;li&gt;4&lt;/li&gt;
        &lt;li&gt;5&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
    &lt;div class="content"&gt;
      &lt;div class="block"&gt;
        &lt;input type="hidden" value="Title for Content 1"/&gt;
        HTML Content # 1
      &lt;/div&gt;
      &lt;div class="block"&gt;
        &lt;input type="hidden" value="Title for Content 2"/&gt;
        HTML Content # 2
      &lt;/div&gt;
      &lt;div class="block"&gt;
        &lt;input type="hidden" value="Title for Content 3"/&gt;
        HTML Content # 3
      &lt;/div&gt;
      &lt;div class="block"&gt;
        &lt;input type="hidden" value="Title for Content 4"/&gt;
        HTML Content # 4
      &lt;/div&gt;
      &lt;div class="block"&gt;
        &lt;input type="hidden" value="Title for Content 5"/&gt;
        HTML Content # 5
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;</pre>
<p><strong style="font-size:18px;"><u>Customizing jslider.jquery.js</u></strong><br />
jSlider provides following options for customization:</p>
<ol>
<li><u>width</u>: Width of jslider div above, defaults to &#8216;610px&#8217;</li>
<li><u>height</u>: Height of jslider div above, defaults to &#8216;225px&#8217;</li>
<li><u>slider_height</u>: Height of slider div above (navigation bar), defaults to &#8216;24px&#8217;</li>
<li><u>content_height</u>: Height of content div above, defaults to &#8216;180px&#8217;</li>
<li><u>block_width</u>: Width of block div inside content div&#8217;s above, defaults to &#8216;590px&#8217;</li>
<li><u>block_padding</u>: Padding of block div inside content div&#8217;s above, defaults to &#8216;10px&#8217;</li>
<li><u>animation_time</u>: Time taken by 1 slide of content, defaults to 300 msec</li>
<li><u>animation_type</u>: Animation type, defaults to &#8216;linear&#8217;. Other option is &#8217;swing&#8217;</li>
</ol>
<p>Rest of the options like various padding etc can be controlled using the css properties. <a href="http://abhinavsingh.com/webdemos/jslider" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.com/webdemos/jslider&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/&wp-toolbar-fromtitle=Introducing jSlider: A Content Slider plugin for JQuery&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >View demo</a> for more implementation details. This is my first jquery plugin and I am only 2 weeks old in jquery. If you find any bug or need any enhancement, you are most welcome.</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/YNhjofS8Lrs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/08/introducing-jslider-a-content-slider-plugin-for-jquery/</feedburner:origLink></item>
		<item>
		<title>Building a Custom PHP Framework with a custom template caching engine using Output Control functions</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/L19kwbicdGc/</link>
		<comments>http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 07:23:11 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Output Control]]></category>
		<category><![CDATA[Template Caching Engine]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=517</guid>
		<description><![CDATA[In past 1 year or so, I had opportunities of using a lot of php frameworks including zend, symfony, cakephp, codeigniter. All frameworks have their pros and cons, however that is out of scope of this blog post. You may want to checkout this comparison list of php frameworks here. 
In this blog post I [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/KNmB46Hi1cdi8GtdDRNuvtqPy-c/0/da"><img src="http://feedads.g.doubleclick.net/~a/KNmB46Hi1cdi8GtdDRNuvtqPy-c/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/KNmB46Hi1cdi8GtdDRNuvtqPy-c/1/da"><img src="http://feedads.g.doubleclick.net/~a/KNmB46Hi1cdi8GtdDRNuvtqPy-c/1/di" border="0" ismap="true"></img></a></p><p>In past 1 year or so, I had opportunities of using a lot of php frameworks including <a href="http://framework.zend.com/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://framework.zend.com/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >zend</a>, <a href="http://www.symfony-project.org/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.symfony-project.org/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >symfony</a>, <a href="http://cakephp.org/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://cakephp.org/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >cakephp</a>, <a href="http://codeigniter.com/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://codeigniter.com/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >codeigniter</a>. All frameworks have their pros and cons, however that is out of scope of this blog post. You may want to checkout this comparison list of php frameworks <a href="http://www.phpframeworks.com/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.phpframeworks.com/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >here</a>. </p>
<p>In this blog post I will build a custom PHP framework (MVC Architecture). Then go on to discuss in brief about the output control functions and finally show how to build a custom template caching engine using these functions for our framework.</p>
<p><strong style="font-size:18px"><u>Source Code</u></strong><br />
You may want to download the complete source code for this blog post <a href="http://abhinavsingh.googlecode.com/files/Custom%20PHP%20Framework%20with%20Custom%20Template%20Caching%20Engine.rar" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.googlecode.com/files/Custom%20PHP%20Framework%20with%20Custom%20Template%20Caching%20Engine.rar&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >from here</a>.</p>
<p><strong style="font-size:18px"><u>Building a custom PHP Framework</u></strong><br />
We will choose a MVC architecture for our framework. Here is a basic directory structure for our custom framework:</p>
<p>/index.php<br />
/.htaccess<br />
/config.ini.php<br />
/404.php<br />
<strong>/view</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;/view/test1.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;/view/test2.php<br />
<strong>/model</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;/model/model.class.php<br />
<strong>/controller</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;/controller/controller.class.php<br />
<strong>/log</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;/log/logger.class.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;/log/log.log<br />
<strong>/cache</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;/cache/cache.class.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;/cache/template.cache.class.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;<strong>/cache/template</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/cache/template/test1.php.tmp<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/cache/template/test2.php.tmp</p>
<p>The view, model, controller, log and cache directories contains the following framework modules respectively:</p>
<ol>
<li><strong>view</strong> directory contains our view level files. i.e. files containing our HTML, js, css code.</li>
<li><strong>model</strong> directory contains the model class responsible for interacting with database and other storages</li>
<li><strong>controller</strong> directory contains our controller class. Each incoming request is first received by the controller class constructor, which thereafter controls the flow of request in the framework</li>
<li><strong>log</strong> directory contains our logger class. This class is auto loaded for every request providing a basic <code>logger::log($log_message)</code> logger method throughout the framework. This class logs all data in a file called log.log.</li>
<li><strong>cache</strong> directory contains our cache class. For this blog tutorial, we will only write the <em>template caching engine class</em>. In production systems, we might have individual classes for other types of cache systems e.g. memcached (Read <a href="http://abhinavsingh.com/blog/2009/01/memcached-and-n-things-you-can-do-with-it/">Memcached and “N” things you can do with it – Part 1</a> to know more about memcached and <a href="http://abhinavsingh.com/blog/2009/01/mysql-query-cache-wp-cache-apc-memcache-what-to-choose/">MySQL Query Cache, WP-Cache, APC, Memcache – What to choose</a> for a complete comparison lists of various other caching techniques.</li>
</ol>
<p>Lets see in details, what all file each and every directory contain contains.</p>
<p><strong><u>Root directory files</u></strong><br />
We have 4 files in our root directory, namely .htaccess, index.php, config.ini.php and 404.php in order of relevance. Lets look through the content of these files:</p>
<p><u>.htaccess</u></p>
<pre name="code" class="php">RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php
</pre>
<ol>
<li>1st two lines essentially means that Switch on the apache rewrite module and set RewriteBase as / i.e. the root directory</li>
<li>Last 3 lines mean that, if incoming request is for a file or directory which physically exists under the root directory serve them otherwise route all other requests to index.php in the root directory</li>
</ol>
<p>Hence now for an incoming request like <a href="http://localhost/test1.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://localhost/test1.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://localhost/test1.php</a>, apache will route the request to <code>index.php</code> in the root directory because there is no <code>test1.php</code> under the root directory. Cool, lets see what <code>index.php</code> has to offer.</p>
<p><u>index.php</u></p>
<pre name="code" class="php">&lt;?php

  // include configuration file
  include_once("config.ini.php");

  // include controller files
  include_once("controller/controller.class.php");

?&gt;
</pre>
<p>index.php doesn&#8217;t do much except for including our core configuration file and controller class file. Controller class constructor is initiated as soon as the class file is included.</p>
<p><code>config.ini.php</code> is our core configuration file. It provides the framework with an array called <code>$config</code> containing various information like: mysql database credentials, requested url details and various other global parameters. Lets see what all parameter does it provide us with.</p>
<p><u>config.ini.php</u></p>
<pre name="code" class="php">&lt;?php

  $config = array(
                  'host'=&gt;array(
                                'name' =&gt; "http://".$_SERVER['HTTP_HOST'].'/',
                                'uri' =&gt; $_SERVER['REQUEST_URI'],
                                'url' =&gt; parse_url($_SERVER['REQUEST_URI']), // note it contains the parsed url contents
                               ),
                  'mysql'=&gt;array(
                                 'host' =&gt; 'localhost',
                                 'name'=&gt; 'testdb',
                                 'user' =&gt; 'root',
                                 'pass' =&gt; 'password',
                                ),
                  'cache'=>array(
                                 'template' => 'On', // template caching switched on by default
                                 'memcached' => 'Off', // switch off memcached caching
                                ),
                 );

?&gt;
</pre>
<p>$config['host'] array saves various parameter about the host itself, e.g. hostname, hosturi (the requested uri, hosturl (it contains the parse_url(hosturi)). </p>
<p>$config['mysql'] array contains mysql database parameters. However in this blog post we will not interact with databases.</p>
<p>$config['cache'] tells the framework what all caching modules are switched on.</p>
<p><u>404.php</u></p>
<pre name="code" class="php">&lt;html&gt;
  &lt;head&gt;

  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;404 Page&lt;/h1&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong><u>Controller directory files</u></strong><br />
For this blog post, controller directory consists of a single class file. i.e. <code>controller.class.php</code>. We saw this being included by <code>index.php</code> in the root folder above. As soon as controller class is included, it&#8217;s constructor is invoked. Before we dig in more, lets see the controller class file:</p>
<p><u>controller.class.php</u></p>
<pre name="code" class="php">&lt;?php

  // include logger class
  include_once("log/logger.class.php");

  // include cache class (contains template caching)
  include_once("cache/cache.class.php");

  // include model class
  include_once("model/model.class.php");

  class controller {

    function __construct($config) {
        global $config;

        // generate requested template name and path
        $config['template']['name'] = $config['host']['uri'] == '/' ? 'index.php' : substr($config['host']['uri'], 1, strlen($config['host']['uri']));
        $config['template']['path'] = "view/".$config['template']['name'];

        // check 404
        if(!file_exists($config['template']['path'])) {
            $config['template']['name'] = "404.php";
            $config['template']['path'] = "404.php";
        }
        logger::log("Requested template name ".$config['template']['name'].", path ".$config['template']['path']);

        // invoke template caching engine
        $template_cache = new template_cache();

        // include the template
        include_once($config['template']['path']);

        // cache template
        $template_cache-&gt;setTemplate();
    }

  }

  $controller = new controller($config);

?&gt;
</pre>
<p>At the top, controller class includes the <code>logger.class.php</code>, <code>cache.class.php</code> and <code>model.class.php</code> files. At the bottom, the controller object is instantiated.</p>
<p>The constructor performs the following 5 tasks:</p>
<ol>
<li>At first it generates a template name and a template path for the incoming request i.e. for <a href="http://localhost/" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://localhost/&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://localhost/</a>, <code>$config['template']['name']='index.php'</code> and for <a href="http://localhost/test1.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://localhost/test1.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://localhost/test1.php</a>, <code>$config['template']['name']='test1.php'</code>.</li>
<li>Second it checks for 404. For the above generated template path, e.g. <code>$config['template']['path']='view/test1.php'</code>, it checks whether this file exists inside root directory. If it doesn&#8217;t template path and names are set to <code>404.php</code></li>
<li>Thirdly, It invokes the template caching engine. i.e. <code>$template_cache = new template_cache();</code></li>
<li>Forth, it includes the generated template path above i.e. <code>include_once($config['template']['path']);</code></li>
<li>Fifth and finally, it caches the generated HTML, js, css code by the template file includes above. This is achieved by the following code, <code>$template_cache->setTemplate();</code></li>
</ol>
<p>Before we move our attention to, lets see in short the content of log and view directories.</p>
<p><strong><u>Log directory files</u></strong><br />
Log directory contains our logger class. This class is auto loaded for each incoming request that is being routed to index.php in the root directory (as we saw above). The <code>logger.class.php</code> provides a static <code>logger::log($log_message)</code> method, which can be used throughout the framework for logging messages. We will be using it everywhere.</p>
<p><u>logger.class.php</u></p>
<pre name="code" class="php">&lt;?php

  class logger {

    static $log_file = "log/log.log";

    static function log($log) {
      if($log != '') {
        $fh = fopen(self::$log_file, "a");
        fwrite($fh,date('Y-m-d H:i:s')."\n".$log."\n\n");
        fclose($fh);
      }
    }

  }

?&gt;
</pre>
<p>The logger class by default logs all data to a file called log.log.</p>
<p><strong><u>View directory files</u></strong><br />
For this blog post, we have two simple test pages in view directory namely <code>test1.php</code> and <code>test2.php</code>, which can be access by typing <a href="http://localhost/test1.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://localhost/test1.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://localhost/test1.php</a> and <a href="http://localhost/test2.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://localhost/test2.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >http://localhost/test2.php</a> respectively in the browser.</p>
<p><u>test1.php</u></p>
<pre name="code" class="php">&lt;html&gt;
  &lt;head&gt;

  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;
      &lt;?php echo model::test1data(); ?&gt;
    &lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>test1.php simply calls the model class method called model::test1data() (static method). This method extracts some dummy text from the database and returns it back.</p>
<p><strong><u>Model directory files</u></strong><br />
Model directory contains the model class file. In production systems, model class file will provide various methods to select and insert data in the databases. However for this blog post we will simply return some static dummy test.</p>
<p><u>model.class.php</u></p>
<pre name="code" class="php">&lt;?php

  class model {

    // This method will return data generally from a database table
    // To keep it simple for the post we return some dummy lipsum text
    static function test1data() {
      logger::log("Returning test1data() from database");
      return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut nulla ac risus viverra ornare. Nulla consectetur, metus eleifend pharetra posuere, lacus nibh elementum leo, in fermentum lectus lorem in ipsum. Nullam pulvinar purus at erat pharetra volutpat. Pellentesque egestas rutrum lectus, ut rutrum tellus tristique sed. Integer diam est, ornare ac ultricies vel, aliquam non mi. Etiam tempor leo eu lacus tempus sagittis sagittis turpis dictum. Sed leo sapien, pharetra sit amet faucibus et, mollis id nulla. Praesent feugiat mi nec dui scelerisque mollis vehicula magna feugiat. Aliquam erat volutpat. Curabitur quis velit ut nibh rhoncus convallis. Proin mauris nunc, rhoncus vel laoreet vel, aliquet quis nunc. Aenean interdum risus non neque blandit sed adipiscing ipsum mollis. Vivamus enim orci, ultrices at scelerisque vel, laoreet a turpis. Nullam posuere ante sed nisl porta porta aliquam metus suscipit. Fusce enim odio, iaculis at suscipit eget, vestibulum volutpat enim. Nam dictum turpis quis velit posuere in malesuada mi convallis. Donec faucibus, felis id dictum imperdiet, orci tortor tristique neque, vitae lobortis libero tellus sed lorem. Duis tellus magna, commodo eget blandit ut, auctor nec nibh. Maecenas ornare ornare risus nec ultrices. Pellentesque lectus eros, imperdiet ut rhoncus vel, tempus ut nisi.";
    }

    static function test2data() {
      logger::log("Returning test2data() from database");
      return "Vestibulum laoreet nibh sed nulla mollis cursus. Maecenas sodales mauris sit amet ligula euismod a lacinia turpis adipiscing. Nulla gravida porta augue, id adipiscing libero tincidunt ac. Morbi non velit id odio porta tempus id eget massa. Cras nibh purus, gravida sed suscipit ut, tincidunt eu neque. In id est eros, ac sodales orci. Ut lectus augue, feugiat sit amet consectetur id, pharetra quis tellus. Maecenas eget lobortis urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt eleifend neque. Aenean accumsan orci vitae erat blandit porttitor. Aliquam tristique dolor ac nibh elementum id lacinia diam cursus.";
    }

  }

?&gt;
</pre>
<p><strong><u>Cache directory files</u></strong><br />
For this blog post, cache directory contains the main cache.class.php file which in turn includes various other cache classes e.g. <code>template.cache.class.php</code></p>
<p><u>cache.class.php</u></p>
<pre name="code" class="php">&lt;?php

  // check for switched on cache modules
  foreach($config['cache'] as $key =&gt; $value) {
    // include all cache classes, which are swicted on
    if($value == 'On') {
      // naming convention is &lt;modulename.cache.class.php&gt;
      include_once('cache/'.$key.'.cache.class.php');
    }
  }

?&gt;
</pre>
<p><strong style="font-size:18px"><u>Output Control Functions</u></strong><br />
<a href="http://php.net" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://php.net&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >PHP</a> is a very simple language. You can write a Hello World! code or calculate similarity between two strings (see <a href="http://us2.php.net/manual/en/function.similar-text.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://us2.php.net/manual/en/function.similar-text.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >similar_text()</a>), both with a single line of code. And hence there are a lot of fundamental concepts of PHP, which not only beginners  but even some advanced coders can ignore. One such concept is <a href="http://in3.php.net/manual/en/intro.outcontrol.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/intro.outcontrol.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Output Control in PHP</a>.</p>
<p>The Output Control functions allow you to control when the output of your PHP script will be thrown to the browsers (console). i.e. You can pre-process the final html output (append, prepend, chip-chop, inserting ad-codes, url linking, keyword highlighting, template caching), which will otherwise be thrown on the browser. Interesting, isn&#8217;t it? Can you feel the power of Output Control functions? </p>
<ol>
<li><a href="http://in3.php.net/manual/en/function.ob-start.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-start.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_start</a>: This turns on output buffering. i.e. no output is sent from the script, instead the output is saved in an internal buffer. However output buffering doesn&#8217;t buffers your headers. <code>ob_start()</code> also takes an optional callback function name. The function is called when output buffer is flushed (see <a href="http://in3.php.net/manual/en/function.ob-flush.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-flush.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_flush()</a>) or cleaned (see <a href="http://in3.php.net/manual/en/function.ob-clean.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-clean.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_clean()</a>). We can access the this internal buffer using functions like <a href="http://in3.php.net/manual/en/function.ob-get-contents.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-get-contents.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_get_contents()</a></li>
<li><a href="http://in3.php.net/manual/en/function.ob-end-flush.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-end-flush.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_end_flush</a>: This function send the content of the buffer (if any) and turns off output buffering. We should always call functions like <a href="http://in3.php.net/manual/en/function.ob-get-contents.php" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in3.php.net/manual/en/function.ob-get-contents.php&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/&wp-toolbar-fromtitle=Building a Custom PHP Framework with a custom template caching engine using Output Control functions&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >ob_get_contents()</a> before <code>ob_end_flush()</code>, since any changes after this functions will not reflect on the browser</li>
</ol>
<p><strong style="font-size:18px"><u>Building a custom Template Caching Engine</u></strong><br />
We saw above some of the output control functions PHP has to offer. <code>ob_start()</code>, <code>ob_get_contents()</code> and <code>ob_end_flush();</code> are the 3 functions we will use to create our custom template caching engine.</p>
<p><u>template.cache.class.php</u></p>
<pre name="code" class="php">&lt;?php

  class template_cache {

    var $template_cache_file = FALSE;
    var $template_cache_file_ext = ".tmp";
    var $template_cache_dir = "cache/template/";
    var $template_cache_ttl = 300; // secs

    function __construct() {

      // initiate template caching
      $this-&gt;init();

    }

    function init() {
      // get template path
      $this-&gt;template_cache_file = $this-&gt;generateTemplatePath();

      // get template from cache if exists
      $this-&gt;getTemplate();

      // start output buffering
      ob_start();
    }

    function generateTemplatePath() {
      global $config;

      // generate template file name
      return $this-&gt;template_cache_dir.$config['template']['name'].$this-&gt;template_cache_file_ext;
    }

    function getTemplate() {
      global $config;

      // check if a cached template exists
      if(file_exists($this-&gt;template_cache_file)) {
        if(time() - filemtime($this-&gt;template_cache_file) &lt; $this-&gt;template_cache_ttl) {
          logger::log("Cache hit for template ".$config['template']['name']);
          $content = file_get_contents($this-&gt;template_cache_file);
          echo $content;
          exit;
        }
        else {
          logger::log("Cache stale for template ".$config['template']['name']);
          return FALSE;
        }
      }
      else {
        logger::log("Cache miss for template ".$config['template']['name']);
        return FALSE;
      }
    }

    function setTemplate() {
      global $config;

      // get buffer
      $content = ob_get_contents();

      // save template
      logger::log("Caching template ".$config['template']['name']);
      $fh = fopen($this-&gt;template_cache_file, 'w');
      fwrite($fh, $content);
      fclose($fh);

      // Flush the output buffer and turn off output buffering
      ob_end_flush();
    }

  }

?&gt;
</pre>
<p>As we saw above in controller class, the template engine class was instantiated before including the actual template file. Template engine constructor do the following 3 tasks:</p>
<ol>
<li>Generate a cached file name for the requested uri by calling the <code>$this->generateTemplatePath();</code> method. e.g. if <code>http://localhost/test1.php</code> is the requested uri, <code><strong>test1.php.tmp</strong></code> is it&#8217;s static cached template</li>
<li>Secondly, it tries to fetch the cached template file by calling the method <code>$this->getTemplate();</code> (read on for details of this method)</li>
<li>Finally it turns on output buffering by calling <code>ob_start();</code></li>
</ol>
<p>List of methods provided by template.cache.class.php are:</p>
<ol>
<li>generateTemplatePath() method generates a cache file name for incoming request. By default extension of all cached files in <strong>&#8220;.tmp&#8221;</strong> and are stored under the <strong>/cache/template</strong> directory.</li>
<li>getTemplate() method do a number of tasks. First, it checks if a cached template exists for the requested uri. If it does not exists or if it is not a fresh cache (see $template_cache_ttl), this method simply returns control back to controller which go ahead and include the actual template file. However if the file exists and is fresh it reads the content of the file and throw back to browser. At this point control is no longer transferred back to the controller, hence saving various un-necessary processing and database calls.</li>
<li>setTemplate() method is called by controller after including the actual template file from under the view directory. Point to note is that, before getTemplate() returns control back to controller (in case of missed or stale cache), the template cache class constructor does switch on output buffering. And when setTemplate() method is called, we can access this buffer using output functions like <code>ob_get_contents()</code> and then save the template for next incoming request. Bingo!. Finally this method throw away the buffer to the browser using <code>ob_end_flush();</code></li>
</ol>
<p><strong style="font-size:18px;"><u>Is it working?</u></strong><br />
To verify the flow of framework, I hit the url http://localhost/test1.php 3 times, with <code>$template_cache_ttl = 10;</code> (seconds).</p>
<ol>
<li>Once after clearing the template cache folder</li>
<li>Once within next 10 seconds</li>
<li>And finally after 10 seconds</li>
</ol>
<p>Here is how the log file looks like:</p>
<pre name="code" class="php">
2009-08-16 19:50:49
Requested template name test1.php, path view/test1.php (1st REQUEST)

2009-08-16 19:50:49
Cache miss for template test1.php

2009-08-16 19:50:49
Returning test1data() from database

2009-08-16 19:50:49
Caching template test1.php

2009-08-16 19:50:54
Requested template name test1.php, path view/test1.php (2nd REQUEST)

2009-08-16 19:50:54
Cache hit for template test1.php

2009-08-16 19:51:03
Requested template name test1.php, path view/test1.php (3rd REQUEST)

2009-08-16 19:51:03
Cache stale for template test1.php

2009-08-16 19:51:03
Returning test1data() from database

2009-08-16 19:51:03
Caching template test1.php
</pre>
<p><strong style="font-size:18px;"><u>Moving forward, What&#8217;s Next? Extending template.cache.class.php</u></strong><br />
Template cache class can be extended to do a lot more, other than caching the template files. For instance we might want to perform (chip-chop, append, prepend etc) a few tasks, before we cache the final template and throw back to the browser. Few tasks which look quite obvious to me are:</p>
<ol>
<li><strong>Short Codes:</strong> We can insert short codes in our HTML templates, which later on can be expanded into full fledged codes. e.g. For embedding a YouTube video, we can simply put something like <code>[[YouTube yjPBkvYh-ss]]</code> into test1.php. And in setTemplate() method we can call <em>helper/plugin methods</em> to process such short codes. More professionally, we can add hooks for various tasks we might want to perform before caching the template. Read <a href="http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/">How to add wordpress like add_filter hooks in your PHP framework</a> for a more professional approach.</li>
<li><strong>Inserting page header and footer:</strong> Instead of including page header and footer inside <code>test1.php</code>, we can simply put our main <code>&lt;body&gt;</code> code inside test1.php. Then before caching the template file, we can append and prepend header and footer modules to the buffer of each page. Thus avoiding including the same header and footer files across various pages.</li>
<li><strong>HTML module caching:</strong> There are several instances where we can have a common module across all pages. For instance, I can have a events module across all my pages, which basically displays a calendar with various events for the week or month marked on it. The event details are extracted from the database. Since this module of mine is a static HTML chunk for atleast a week, I would like to have a difference cache for this module. Intelligently hooking up these modules with template caching engine, can allow us to do module level caching</li>
</ol>
<p>I can probably write down 10-15 more such applications and probably there might be many more such applications of the above coded template caching engine. (Note: The power actually lies in Output Control Functions provided by PHP).</p>
<p>Let me know if you liked the post or any bug in it.</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/L19kwbicdGc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/08/building-a-custom-php-framework-with-a-custom-template-caching-engine-using-output-control-functions/</feedburner:origLink></item>
		<item>
		<title>fixed.js – Solution to IE6 “position:fixed” Bug</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/LB5HpxjZ-ec/</link>
		<comments>http://abhinavsingh.com/blog/2009/08/fixed-js-solution-to-ie6-positionfixed-bug/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 15:10:04 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[fixed.js]]></category>
		<category><![CDATA[IE6]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=521</guid>
		<description><![CDATA[IE6 has been a bane for all frontend developers for years. An element can be positioned relative to the browser window using the style position:fixed, it does not move when the page is scrolled. You can do nice layout things (e.g. facebook chat bar) with this in most modern browsers but not for IE6 in [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/486Ax762c05H0ulY7CTIA0kBei8/0/da"><img src="http://feedads.g.doubleclick.net/~a/486Ax762c05H0ulY7CTIA0kBei8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/486Ax762c05H0ulY7CTIA0kBei8/1/da"><img src="http://feedads.g.doubleclick.net/~a/486Ax762c05H0ulY7CTIA0kBei8/1/di" border="0" ismap="true"></img></a></p><p>IE6 has been a bane for all frontend developers for years. An element can be positioned relative to the browser window using the style <code>position:fixed</code>, it does not move when the page is scrolled. You can do nice layout things (e.g. facebook chat bar) with this in most modern browsers but not for IE6 in windows until you use <code>fixed.js</code></p>
<p><strong style="font-size:18px;"><u>Sample Code for Facebook Type Chat Bar</u></strong></p>
<pre name="code" class="php">&lt;html&gt;
  &lt;head&gt;
    &lt;style type="text/css"&gt;
      body {
        margin:0px;
        padding:0px;
        height:1600px;
        position:relative;
      }
      #shoutbox {
        position:fixed;
        background-color:#F2F2F2;
        border-top:1px solid #CCCCCC;
        bottom:0px;
        left:0px;
        width:100%;
        height:25px;
      }
    &lt;/style&gt;
    &lt;script type="text/javascript" src="fixed.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id="shoutbox"&gt;
      &lt;!-- Our Shoutbox --&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The above code will show you a bar at the bottom of the page, which remains fixed at the bottom even if you scroll the page.</p>
<p><strong style="font-size:18px;"><u>How does fixed.js help me?</u></strong></p>
<ol>
<li>fixed.js is smart enough to invoke only if the browser is IE6 on Windows machine. This is achieved by these two lines of code in fixed.js.
<pre class="javascript" name="code">/*@cc_on
@if (@_win32 &#038;&#038; @_jscript_version>4)</pre>
</li>
<li>It specifically tells IE6 how to render elements with <code>position:fixed</code> attributes. Which are otherwise ignored by IE6.</li>
<li>For remaining browsers, fixed.js go to sleep silently. Doesn&#8217;t do any processing.</li>
</ol>
<p><strong style="font-size:18px;"><u>Download fixed.js</u></strong><br />
fixed.js is developed and maintained at <a href="http://www.doxdesk.com/software/js/fixed.html" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.doxdesk.com/software/js/fixed.html&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/fixed-js-solution-to-ie6-positionfixed-bug/&wp-toolbar-fromtitle=fixed.js &#8211; Solution to IE6 &#8220;position:fixed&#8221; Bug&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >doxdesk.com</a>. Click here to <a href="http://www.doxdesk.com/file/software/js/fixed.js" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://www.doxdesk.com/file/software/js/fixed.js&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/fixed-js-solution-to-ie6-positionfixed-bug/&wp-toolbar-fromtitle=fixed.js &#8211; Solution to IE6 &#8220;position:fixed&#8221; Bug&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >download fixed.js</a></p>
<p>Happy Coding!</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/LB5HpxjZ-ec" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/08/fixed-js-solution-to-ie6-positionfixed-bug/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/08/fixed-js-solution-to-ie6-positionfixed-bug/</feedburner:origLink></item>
		<item>
		<title>How to generate random password like Wordpress using PHP?</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/VjQ_8W8ckQY/</link>
		<comments>http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 21:50:13 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=515</guid>
		<description><![CDATA[Wordpress Blogging Engine is a champion in a lot of way. One of the unique thing which you might have noticed is the random password generated by the wordpress, in case you try to generate a new password. Here are a few examples:

j0LH(WM9b_-q
wr^sqct1cmff
)P4-e531#-aL

Lets have a look at the code which can generate such random passwords [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/qn0fpA4sVPudSOwVzpraaUZA0wE/0/da"><img src="http://feedads.g.doubleclick.net/~a/qn0fpA4sVPudSOwVzpraaUZA0wE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/qn0fpA4sVPudSOwVzpraaUZA0wE/1/da"><img src="http://feedads.g.doubleclick.net/~a/qn0fpA4sVPudSOwVzpraaUZA0wE/1/di" border="0" ismap="true"></img></a></p><p><a href="http://wordpress.org" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://wordpress.org&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/&wp-toolbar-fromtitle=How to generate random password like Wordpress using PHP?&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Wordpress</a> Blogging Engine is a champion in a lot of way. One of the unique thing which you might have noticed is the random password generated by the wordpress, in case you try to generate a new password. Here are a few examples:</p>
<ul>
<li>j0LH(WM9b_-q</li>
<li>wr^sqct1cmff</li>
<li>)P4-e531#-aL</li>
</ul>
<p>Lets have a look at the code which can generate such random passwords for us. Later on we will dig deep into the code to understand each and every bit of it:</p>
<pre name="code" class="php">&lt;?php

  class utility {

    static $random = '';

    // generates a random password
    // By default of length 12 having special characters
    static function generate_password($length = 12, $special_chars=true) {
      $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      if($special_chars) $chars .= '!@#$%^&#038;*_-()';

      $password = '';
      for($i=0; $i&lt;$length; $i++)
        $password .= substr($chars, self::generate_random_number(0, strlen($chars)-1), 1);
      return $password;
    }

    // generates a random number between $min and $max
    static function generate_random_number($min=0, $max=0) {
      // generate seed. TO-DO: Look for a better seed value everytime
      $seed = mt_rand();

      // generate $random
      // special thing about random is that it is 32(md5) + 40(sha1) + 40(sha1) = 112 long
      // hence if we cut the 1st 8 characters everytime, we can get upto 14 random numbers
      // each time the length of $random decreases and when it is less than 8, new 112 long $random is generated
      if(strlen(self::$random) &lt; 8 ) {
        self::$random = md5(uniqid(microtime().mt_rand(), true).$seed);
        self::$random .= sha1(self::$random);
        self::$random .= sha1(self::$random.$seed);
      }

      // take first 8 characters
      $value = substr(self::$random, 0, 8);

      // strip first 8 character, leaving remainder for next call
      self::$random = substr(self::$random, 8);

      $value = abs(hexdec($value));
      // Reduce the value to be within the min - max range. 4294967295 = 0xffffffff = max random number
      if($max != 0) $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));
      return abs(intval($value));
    }

  }

  // print new random password
  echo utility::generate_password();

?&gt;
</pre>
<p><strong style="font-size:18px"><u>Lets dig into the code</u></strong><br />
<u>static function generate_password($length=12, $special_chars=true)</u> is a static method of our utility class. It accepts two parameters. $length who&#8217;s default value is 12 and $special_chars who&#8217;s default value is true. By turning on $special_chars, our random generated password will include characters like !@#$%^&#038;*_-()</p>
<p><u>static function generate_random_number($min=0, $max=0)</u> is yet another static function of the utility class. It generates random number between $min and $max, the two parameters which can be passed. Default value for both is 0. However internally, <code>generate_random_number()</code> do a lot of trick to get us some really random numbers.</p>
<p><strong style="font-size:18px"><u>Algorithm</u></strong><br />
<code>generate_random_number()</code> works with following variables:</p>
<ol>
<li><u>$seed</u>: which is equal to <code>mt_rand()</code></li>
<li><u>self::$random</u> is a static variable. To start with this variable equals to &#8221; (nothing). <code>generate_random_number()</code> checks for the length of <code>self::$random</code>. If its length is  < 8, it generates a new 112 character long random value (see the code above) and assign it to <code>self::$random</code>. From here on, every time a random number is requested, it uses a chunks of 8 characters from the starting of <code>self::$random</code>, which is then used to generate a random number (see the code above). After each iteration length of <code>self::$random</code> decreases by 8. Because <code>self::$random</code> is 112 characters long, we can use it 14 times to get a random number (14x8 = 112).</li>
<li><u>$value</u> is the actual 8 digit character extracted from the starting of <code>self::$random</code>, which is later on processed to generate a random number between $min and $max values.</li>
</ol>
<p>Further these methods can also be used to generate short url's like <a href="http://tinyurl.com" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://tinyurl.com&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/&wp-toolbar-fromtitle=How to generate random password like Wordpress using PHP?&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >tinyurl.com</a> or <a href="http://bit.ly" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://bit.ly&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/&wp-toolbar-fromtitle=How to generate random password like Wordpress using PHP?&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >bit.ly</a>.</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/VjQ_8W8ckQY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/08/how-to-generate-random-password-like-wordpress-using-php/</feedburner:origLink></item>
		<item>
		<title>Getting started with Autotools – GNU Build System on Debian</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/Fp3Rjwf3Gc0/</link>
		<comments>http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 09:28:35 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Autoconf]]></category>
		<category><![CDATA[Automake]]></category>
		<category><![CDATA[Autotools]]></category>
		<category><![CDATA[Debian]]></category>
		<category><![CDATA[GNU]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=512</guid>
		<description><![CDATA[
If you eat and drink open source, chances are high that you might have downloaded an open source project code, only to see files like: aclocal.m4, configure.ac, Makefile.am, Makefile.in and what not. You might have also used commands like ./configure, make etc but what are these files? Does they really belong to the project you [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/0C5cQLoqxrHqAFAWzethb8YWsrg/0/da"><img src="http://feedads.g.doubleclick.net/~a/0C5cQLoqxrHqAFAWzethb8YWsrg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/0C5cQLoqxrHqAFAWzethb8YWsrg/1/da"><img src="http://feedads.g.doubleclick.net/~a/0C5cQLoqxrHqAFAWzethb8YWsrg/1/di" border="0" ismap="true"></img></a></p><p><img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/08/The_GNU_logo-300x293.png" alt="The_GNU_logo" title="The_GNU_logo" style="float:left;width:140px;margin-right:10px;"/><br />
If you eat and drink open source, chances are high that you might have downloaded an open source project code, only to see files like: <code>aclocal.m4</code>, <code>configure.ac</code>, <code>Makefile.am</code>, <code>Makefile.in</code> and what not. You might have also used commands like <code>./configure</code>, <code>make</code> etc but what are these files? Does they really belong to the project you download? Do I need to understand them? In this blog post I look forward to answer all your question, as well as introduce you to not so popular <a href="http://en.wikipedia.org/wiki/GNU_build_system" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://en.wikipedia.org/wiki/GNU_build_system&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/&wp-toolbar-fromtitle=Getting started with Autotools &#8211; GNU Build System on Debian&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Autotools</a> &#8211; A GNU Build System.</p>
<p><strong style="font-size:18px"><u>Setting up Autotools on Debian?</u></strong><br />
Before we go ahead and understand what Autotools is, we will try building a HelloWorld package. Lets get started by setting up Autotools on debian machine.</p>
<ul>
<li>apt-get install build-essential</li>
<li>gcc &#8211;version (verifying install)</li>
<li>g++ &#8211;version (verifying install)</li>
<li>apt-get install automake autoconf</li>
</ul>
<p>You have your environment ready. Lets start packaging the HelloWorld package.</p>
<p><strong style="font-size:18px"><u>Hello World Source Code</u></strong><br />
<a href="http://abhinavsingh.googlecode.com/files/autotools-helloworld-1.0.tar.gz" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.googlecode.com/files/autotools-helloworld-1.0.tar.gz&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/&wp-toolbar-fromtitle=Getting started with Autotools &#8211; GNU Build System on Debian&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Download full source code from here</a></p>
<p>We will need to create 5 files for our basic HelloWorld package. Start by creating a directory structure like this:<br />
&#8211; <strong>HelloWorld</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; configure.ac<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; Makefile.am<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; README<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; <strong>src</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8211; Makefile.am<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8211; helloworld.c</p>
<p><strong><u>src/helloworld.c</u></strong></p>
<pre name="code" class="c">#include &lt;config.h&gt;
#include &lt;stdio.h&gt;

int main (void) {
    puts ("Hello World!");
    puts ("This is " PACKAGE_STRING ".");
    return 0;
}
</pre>
<p>Note we don&#8217;t have a <code>config.h</code> file but still we include it here. In actual <code>config.h</code> will be autogenerated by the autotools, when we build the package. Similarly, <code>PACKAGE_STRING</code> will be a pre-defined variable inside <code>config.h</code>.</p>
<p><strong><u>src/Makefile.am</u></strong></p>
<pre name="code" class="c">bin_PROGRAMS = helloworld
hello_SOURCES = helloworld.c</pre>
<p>Here we tell the build system to generate a binary named <code>helloworld</code> using the sources defined below i.e. <code>helloworld.c</code></p>
<p><strong><u>Makefile.am</u></strong></p>
<pre name="code" class="c">SUBDIRS=src
dist_doc_DATA=README</pre>
<p>Here we give information about the various sub-directory. For a bigger project you might have a <code>man</code> directory, <code>data</code> directory etc. Also we tell the build to package <code>README</code> file with the build.</p>
<p><strong><u>README</u></strong></p>
<pre name="code" class="c">This is a demonstration HelloWorld package for GNU Automake.
Type `info Automake' to read the Automake manual.</pre>
<p><strong><u>configure.ac</u></strong></p>
<pre name="code" class="c">AC_INIT([helloworld], [1.0], [emailid@provider.com])
AM_INIT_AUTOMAKE([-Wall -Werror foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
 Makefile
 src/Makefile
])
AC_OUTPUT
</pre>
<p>Don&#8217;t leave the post on seeing the above file. We will go through each and every one of them. <code>configure.ac</code> contains a series of <a href="http://en.wikipedia.org/wiki/M4_(computer_language)" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://en.wikipedia.org/wiki/M4_(computer_language)&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/&wp-toolbar-fromtitle=Getting started with Autotools &#8211; GNU Build System on Debian&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >M4 macros</a> that will expand to some shell code to finally generate the <code>configure</code> script. Autotools have utilities like <code>automake</code> and <code>autoconf</code> (details below) which read this file to generate intermediate and final build files. The variables starting with AC_ are Autoconf macros and those starting with AM_ are Automake macros.</p>
<ol>
<li>AC_INIT: Initializes autoconf. It takes 3 input parameters: Name of the package, Version of the package and Contact address for bug reports</li>
<li>AM_INIT_AUTOMAKE: Initializes automake. It can take a number of available input parameters. <code>-Wall</code> <code>-Werror</code> specifically tells automake to turn on all warnings and report them as error. While development we will keep error reporting turned on. <code>foreign</code> tells automake that this package doesn&#8217;t follow GNU standard. As per GNU standards we should also distribute files like <code>ChangeLog</code>, <code>AUTHORS</code> and at this stage we don&#8217;t want automake to complaint about them.</li>
<li>AC_PROG_CC: This line tells <code>configure</code> script to search available C compilers and define variable <code>CC</code> with its name. Later on many intermediate files will use this variable <code>CC</code> for building binary files.</li>
<li>AC_CONFIG_HEADERS: It tells the <code>configure</code> script to generate a <code>config.h</code> file which is pre-included by <code>helloworld.c</code>. Generated <code>config.h</code> will have content like this:
<pre name="code" class="c">/* config.h.  Generated from config.h.in by configure.  */
/* config.h.in.  Generated from configure.ac by autoheader.  */

/* Name of package */
#define PACKAGE "helloworld"

/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "emailid@provider.com"

/* Define to the full name of this package. */
#define PACKAGE_NAME "helloworld"</pre>
</li>
<li>AC_CONFIG_FILES: This tells <code>configure</code> script list of files from which it should generate it&#8217;s *.in templates. This variable is also used by <code>automake</code> utility to know list of <code>Makefile.am</code> it should process. (Note: Each directory should have a Makefile.am file and as you keep adding new directories keep adding them to AC_CONFIG_FILES, else build will not consider your new directories while building packages.</li>
<li>AC_OUTPUT: It is a closing command that actually produces the part of the script in charge of creating the files registered with AC_CONFIG_HEADERS and AC_CONFIG_FILES.</li>
</ol>
<p><strong style="font-size:18px"><u>Building a Hello World package for distribution</u></strong><br />
Lets create our first package for distribution.</p>
<ol>
<li>cd path/to/helloworld/directory: Migrate to the project directory</li>
<li>autoreconf &#8211;install: This command initiates the build system. You should see something like this as output:
<pre name="code" class="c">configure.ac:2: installing `./missing'
configure.ac:2: installing `./install-sh'
src/Makefile.am: installing `./depcomp'
</pre>
<p>Also if you scan through the <code>HelloWorld</code> directory, you will find a lot of new files being generated by the build system. Particularly you will see a <code>Makefile.in</code> being generated for each <code>Makefile.am</code>. Apart from these files of interest are <code>configure</code> and <code>config.h.in</code>.</li>
<li>./configure: It utilizes *.in files generated by the previous step to build the <code>Makefile</code>, <code>src/Makefile</code> and <code>config.h</code>. You should see something like this on your console:
<pre name="code" class="c">checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
</pre>
</li>
<li>make</li>
<li>src/helloworld: This will output this on the console.
<pre name="code" class="c">Hello World!
This is helloworld 1.0.</pre>
</li>
<li>make distcheck: This utility finally creates the helloworld-1.0.tar.gz package for distribution. You should see this on your console on running this utility:
<pre name="code" class="c">================================================
helloworld-1.0 archives ready for distribution:
helloworld-1.0.tar.gz
================================================</pre>
</li>
</ol>
<p><strong style="font-size:18px"><u>Installing distributed HelloWorld package</u></strong></p>
<ol>
<li>Copy the generated package into your temp directory and then issue the following commands</li>
<li>tar -xzvf helloworld-1.0.tar.gz</li>
<li>cd helloworld-1.0</li>
<li>./configure</li>
<li>make</li>
<li>make install</li>
</ol>
<p><code>make install</code> will copy the <code>helloworld</code> binary into the <code>/usr/local/bin</code> directory. Try running <code>helloworld</code> from command line and you should see a similar output, as we saw above while building the package. Further it also copies the <code>README</code> file under <code>/usr/local/share/doc/helloworld</code> directory. If your built package includes the <code>man</code> directory, it gets copied to <code>/usr/local/share/man</code> automatically.</p>
<p><strong style="font-size:18px"><u>What is Autotools?</u></strong><br />
Autotools is a build system developed by GNU which helps you distribute your source code across various Unix systems. The files you are wondering about are auto generated by the Autotools.</p>
<p>Autotools is a combination of several utilities made available by GNU, including:</p>
<ol>
<li>Autoconf</li>
<li>Automake</li>
</ol>
<p>There are many others which can be listed above, but for this blog post we will restrict ourselves to Automake and Autoconf only.</p>
<p><strong><u>Autoconf</u></strong><br />
autoconf process files like <code>configure.in</code> to generate a <code>configure</code> script. When we run the <code>configure</code> script, it reads other template files like <code>Makefile.in</code> to generate a final output file, in this case <code>Makefile</code></p>
<p><strong><u>Automake</u></strong><br />
It reads all <code>Makefile.am</code> and generate corresponding <code>Makefile.in</code>, used by the <code>configure</code> script as described above.</p>
<p>Happy Packaging!</p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/Fp3Rjwf3Gc0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/08/getting-started-with-autotools-gnu-build-system-on-debian/</feedburner:origLink></item>
		<item>
		<title>How to add wordpress like add_filter hooks in your PHP framework</title>
		<link>http://feedproxy.google.com/~r/abhinavsingh/~3/xAov63L2PSI/</link>
		<comments>http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 09:23:59 +0000</pubDate>
		<dc:creator>Abhinav Singh</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abhinavsingh.com/blog/?p=506</guid>
		<description><![CDATA[I simply love wordpress mainly because of the architectural design it follows to deliver the good. Wordpress provide a hook or filter functionality to almost everything that appears on your blog. If you are a wordpress plugin developer you surely must have used one of them, specially add_filter() hook.
add_filter functionality provides plugin developer a way [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/HX4-o1Qf4ssYUbDK98dxWJ2swJM/0/da"><img src="http://feedads.g.doubleclick.net/~a/HX4-o1Qf4ssYUbDK98dxWJ2swJM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/HX4-o1Qf4ssYUbDK98dxWJ2swJM/1/da"><img src="http://feedads.g.doubleclick.net/~a/HX4-o1Qf4ssYUbDK98dxWJ2swJM/1/di" border="0" ismap="true"></img></a></p><p>I simply love wordpress mainly because of the architectural design it follows to deliver the good. Wordpress provide a hook or filter functionality to almost everything that appears on your blog. If you are a wordpress plugin developer you surely must have used one of them, specially <a href="http://codex.wordpress.org/Function_Reference/add_filter" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://codex.wordpress.org/Function_Reference/add_filter&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/&wp-toolbar-fromtitle=How to add wordpress like add_filter hooks in your PHP framework&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >add_filter()</a> hook.</p>
<p>add_filter functionality provides plugin developer a way to apply custom hooks on various page sections. For instance <code>add_filter('the_content', 'HelloWorld')</code> will force the content to be passed through the <code>function HelloWorld($content)</code> before being displayed to your blog users.</p>
<p>In this blog post I will show you how can you achieve doing the same thing for your custom PHP frameworks. Otherwise you can also use this in your day to day projects. We will start with a simple directory structure, assuming this is all we have in our framework to start with:</p>
<p><strong style="font-size:18px;"><u>Files/Folder structure of our framework</u></strong><br />
&#8211; addHooks<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; index.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; applyHooks.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;&#8211; hooks<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8211; Subscribe.php<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8211; Signature.php</p>
<p><u>addHooks: </u>Our framework root directory.<br />
<u>index.php: </u>Homepage for our framework.<br />
<u>applyHooks.php: </u>Responsible for including and implementing various hooks.<br />
<u>hooks: </u>Our hooks directory. We will put all our hooks here.<br />
<u>Subscribe.php: </u>A simple hook which will add a subscribe my feed link.<br />
<u>Signature.php: </u>Another simple hook which adds my signature.</p>
<p><strong style="font-size:18px;"><u>Source code</u></strong><br />
<a href="http://abhinavsingh.googlecode.com/files/addHooks.rar" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://abhinavsingh.googlecode.com/files/addHooks.rar&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/&wp-toolbar-fromtitle=How to add wordpress like add_filter hooks in your PHP framework&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >Download the complete source code from here.</a></p>
<p><strong>index.php</strong></p>
<pre name="code" class="php">
  // define some content
  // in this demo i will show to how to apply hook to $content, similar to wordpress blog $content
  $content = "In this blog post I will show you how to add wordpress like add_filter hooks in your PHP framework.";

  // Include our hook management file
  require_once("applyHooks.php");
  </pre>
<p><strong>Subscribe.php</strong></p>
<pre name="code" class="php">
  function Subscribe($content) {
    $subscribe = '';
    $subscribe .= 'Subscribe to my RSS feed';
    $subscribe .= '<br/><br/>';

    return $subscribe.$content;
  }

  add_filter('the_content', 'Subscribe');
  </pre>
<p><strong>Signature.php</strong></p>
<pre name="code" class="php">
  function Signature($content) {
    $signature = '<br/><br/>';
    $signature .= 'Abhinav Singh<br/>';
    $signature .= 'Follow on twitter @imoracle<br/>';

    return $content.$signature;
  }

  add_filter('the_content', 'Signature');
  </pre>
<p><strong>applyHooks.php</strong></p>
<pre name="code" class="php">
  /* plugin directory */
  $hook_dir = "hooks/";

  /* get all plugin files */
  $hook_files = glob($hook_dir."*.php");

  /* array saving all our hooks on the_content */
  $hooks['the_content'] = array();

  /* add_filter functionality */
  function add_filter($on, $func) {
    global $hooks;
    array_push($hooks[$on], $func);
  }

  /* include plugin files */
  foreach($hook_files as $hook_file) {
    require_once($hook_file);
  }

  /* implement the hooks */
  foreach($hooks['the_content'] as $hook) {
    $content = call_user_func($hook, $content);
  }

  echo $content;
  </pre>
<p><strong style="font-size:18px;"><u>Final Result</u></strong><br />
When you try to visit your framework opening page on your browser, i.e. index.php. You will see your $content being filtered/modified and displayed as:<br />
<img src="http://abhinavsingh.com/blog/wp-content/uploads/2009/07/add_filter_output.png" alt="add_filter_output" title="add_filter_output" width="621" height="131" class="alignleft size-full wp-image-507" style="border:1px solid #777777; padding:4px;" /></p>
<p><strong style="font-size:18px;"><u>How does applyHooks.php works</u></strong><br />
So what allows us adding such hooks in our framework. <strong>call_user_func</strong> is a PHP function which allows you to call a user defined function. Here is in short how <strong>applyHooks.php</strong> work:</p>
<ol>
<li>applyHooks.php adds a method called <code>add_filter($on, $func)</code> before including the hook files</li>
<li>add_filter() essentially takes input as <em>$on = the element on which you want to apply the hook</em> and <em>$func = the hook you want to apply $on element</em>.</li>
<li>If you see our Signature.php code, you will find <code>add_filter('the_content', 'Signature');</code>. Which essentially means, apply the filter called $func=&#8217;Signature&#8217;, $on=&#8217;the_content&#8217;</li>
<li>The applyHooks.php file keep registering these hooks and save them in $hooks array</li>
<li>Finally it implement all hook one by one by calling the <a href="http://in2.php.net/call_user_func" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in2.php.net/call_user_func&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/&wp-toolbar-fromtitle=How to add wordpress like add_filter hooks in your PHP framework&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >call_user_func</a> function (PS: You may also want to use <a href="http://in2.php.net/call_user_func_array" onclick="window.open('http://abhinavsingh.com/blog/wp-content/plugins/wordpress-toolbar/toolbar.php?wp-toolbar-tourl=http://in2.php.net/call_user_func_array&wp-toolbar-fromurl=http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/&wp-toolbar-fromtitle=How to add wordpress like add_filter hooks in your PHP framework&wp-toolbar-blogurl=http://abhinavsingh.com/blog&wp-toolbar-blogtitle=Abhi\'s Weblog','wordpress-toolbar');return false;" >call_user_func_array</a>)</li>
</ol>
<p><strong style="font-size:18px;"><u>Extending applyHooks.php</u></strong><br />
In this blog post I have shown a demo, how you can create a add_filter type functionality. You may want to extend this to include hooks like:</p>
<ul>
<li>remove_filter</li>
<li>add_shortcode</li>
</ul>
<p>and others.</p>
<p>Hope this will help you making your web apps more expendable and manageable. <img src='http://abhinavsingh.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/abhinavsingh/~4/xAov63L2PSI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://abhinavsingh.com/blog/2009/07/how-to-add-wordpress-like-add_filter-hooks-in-your-php-framework/</feedburner:origLink></item>
	</channel>
</rss>
