How to use jQuery to select a radio button from parent element

January 9, 2009 4 comments

A friend asked me for some help on doing the following :
1. You have an unordered list – within each list item you have a radio input.
2. When you click on the list item (i.e. the entire container), it must a) select the radio input and b) add a css classname of “selected” to the list item.

You can find a demo here.

First, the html :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<!-- include our jquery scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
    <script src="js/radio.js" type="text/javascript"></script>
    <style type="text/css">
    	li { color: #000; }
    	li.selected { color: #FF0000; }
    </style>
</head>
<body>
	<div>
		<ul>
			<li class="test">Test 1 <input type="radio" name="test" /></li>
			<li class="test">Test 2 <input type="radio" name="test" /></li>
			<li class="test">Test 3 <input type="radio" name="test" /></li>
			<li class="test">Test 4 <input type="radio" name="test" /></li>
			<li class="test">Test 5 <input type="radio" name="test" /></li>
		</ul>
	</div>
</body>
</html>

There is nothing out of the ordinary here – just a simple unordered list of radio inputs.

Next, the js (radio.js) :

$(document).ready(function(){
	$('li').click( function(){
		$('li.selected').removeClass('selected');
		$(this).addClass('selected');
		$(this).children("input[type=radio]").click();
	});
});

1. First – we tell jQuery to execute the following code once the document has finished loading, ensuring that the DOM has been registered successfully.
2. Next we bind a click event to all list item elements on the page – you can of course change this to all list items with a class of “myselection” for example ( $(“li.myselection”).click… )
3. When a list item is clicked – we first need to remove the “selected” class from all other list items.
4. Now we need to add the “selected” class to the list item which fired the event ( $(this) ).
5. Finally, we need to make sure that the radio button inside the list item is “clicked” : we do this by using the .children() selector and executing a click() event on the input.

The important bit is the $(this).children(“input[type=radio]”) selector. What we’re doing here is telling jQuery to find all inputs of type radio (i.e. all radio inputs) inside “this” list item (i.e. the list item which was clicked on). We then use .click() to..as you guessed it… execute a click event on the returned element (in this case the radio input).

And that’s all there is to it. You can read up some more on jQuery selectors here.
I would also highly recommend reading the following article : Improve your jQuery – 25 excellent tips.

Jquery UI Layout Manager Plugin

December 31, 2008 Leave a comment

While working on my new framework the other day I came across this excellent Jquery Plugin : UI.Layout – The Ultimate Page Layout Manager.

What it does with minimal markup and some well written javascript is transform your html page into a professional pane based layout. Like most jQuery plugins, it’s incredibly simple to implement and through the use of CSS and a large number of options is highly customizable.

All in all, a very well rounded and executed use of the jQuery library. Kudos to Fabrizio.

You can check out some demos here

Search Engine Friendly URLs using PHP

December 11, 2008 5 comments

A little while ago I wrote a post on Django Inspired SEF urls. I’ve since put together a working example and am now making it available for download.

There are a couple of things to note :

  1. You’ll need to edit the necessary path and url info found inside index.php and .htaccess
  2. The sample code inside index.php is for demonstration purposes only – I strongly recommend using a proper gateway/bootstrap interface typically found in MVC based systems such as Zend Framework and CakePHP (though they of course have their own SEF url implementations).
  3. Edit urls.php to play around with the regular expressions. I’ll be the first to admit that my regexp skills are not the best in the world, so if you notice something that will work better, please let me know – I’d really appreciate it
  4. I’ve included a url generator inside the class to try and make your life easier – view index.php for example usage

That should do it. You can download the script here.

Please play around with it and if you make any improvements I’d love to hear about it.

Categories: PHP Tags: , , ,

Javascript / Jquery Bookmark script

November 3, 2008 28 comments

Ever needed to add a button or link to your site which allows the user to save your site to their bookmarks/favorites ?

Here’s just the script for you. Using jquery, it works in Firefox 2+(tested), IE 6 (not tested), IE7(tested) and Opera 7+ (not tested). Unfortunately not all browsers support the action, so a generic “alert” has been added to inform the user.

You can download the full script here and follow along if you’d like a further explanation of the code involved. A demo can be viewed here.

bookmark.js

The script itself is really very basic. Firstly what needs to happen is on page load, the script checks to see if the user is browsing the site with Opera. If so, we set the rel attribute of all our bookmark anchor tags (class=”jqbookmark”) to “sidebar” – this is a standard Opera technique for creating this type of link.

Next we add an event listener which will execute whenever an anchor tag of class “jqbookmark” is clicked. Simply put, it checks to see which browser is being used and executes the necessary code.

The nice thing here though is that you can set the script to bookmark any url with any title by specifying the href and title attributes respectively.

$(document).ready(function(){
	// add a "rel" attrib if Opera 7+
	if(window.opera) {
		if ($("a.jqbookmark").attr("rel") != ""){ // don't overwrite the rel attrib if already set
			$("a.jqbookmark").attr("rel","sidebar");
		}
	}

	$("a.jqbookmark").click(function(event){
		event.preventDefault(); // prevent the anchor tag from sending the user off to the link
		var url = this.href;
		var title = this.title;

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else if(window.opera) { // Opera 7+
			return false; // do nothing - the rel="sidebar" should do the trick
		} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
			 alert('Unfortunately, this browser does not support the requested action,'
			 + ' please bookmark this page manually.');
		}

	});
});

Demo.html

The html is straightforward. We include our two scripts (jquery and jqbookmark) and we add our links to the page. As mentioned above – the links need to have a class attribute with the value of “jqbookmark”, all other links will be ignored by the script.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<!-- include our jquery scripts -->
    <script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
    <script src="js/jqbookmark.js" type="text/javascript"></script>
</head>
<body>
<div>
<ul>
	<li><a href="http://www.google.com" title="Google.com" class="jqbookmark">Google bookmark</a></li>
	<li><a href="http://www.yahoo.com" title="Yahoo search engine" class="jqbookmark">Yahoo bookmark</a></li>
	<li><a href="https://calisza.wordpress.com" title="A wonderful Blog" class="jqbookmark">Blog bookmark</a></li>
	<li><a href="http://www.microsoft.com" title="Microsoft">Will not be bookmarked</a></ul>
</div>
</body>
</html>

I’d love to know if this functionality could be expanded to include Safari, but so far my good friend google has come up with nothing. At the very least, I hope that someone can find this script useful.

Writing dynamic classes with PHP

October 13, 2008 Leave a comment

I recently had the necessity to write a dynamic class (i.e. where methods, or properties of the class are determined during runtime) and in doing some research, stumbled on to this very helpful article :

Going dynamic with PHP

The author (Jack Herrington) goes to a lot of trouble explaining how the magic __get(), __set() and __call() methods work and how best to use them.

It does get a little bit complicated towards the end, but is a good example of a)why one should or need to use a dynamic class/object and b)how to implement it successfully within your application.

PHP wrapper class for Zend View

October 7, 2008 2 comments

I recently posted an article with an example of a Zend Session wrapper I’ve been using for some of my projects.

In that same vein I’ve created a simple wrapper for Zend View. I found this useful in instances where I didn’t need to use Zend Framework’s whole MVC implementation. Zend View is extremely helpful in creating a quick templating system for smaller projects or custom frameworks.

Once again I’ll be assuming the following:

First our view wrapper/abstraction class (view.php) :

<?php
/**
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to calisza@gmail.com so we can send you a copy immediately.
 *
 * @package    FlexiDev_View
 * @copyright  Copyright (c) 2007 - 2008,  Flexible Developments - Barry Roodt (https://calisza.wordpress.com)
 * @license    New BSD License
 */
 class View {
 	public $tmplVars;
 	public $view;

 	/**
 		Constructor
 	*/
 	public function __construct(){
		
 		$this->tmplVars = array();
 		// Instantiate our Zend View
		$this->view = new Zend_View();
		
		/**
		 * reset our basepath and scriptpaths, this is because we don't need the 'scripts', 'helpers' and 'filters' sub folders 
		 * relative to this script - of course you could change this as your needs require
		 */
		$this->view->setBasePath("./view");
		$this->view->setScriptPath("./view");
		
		// set and assign some global vars to our template
		// this is just an example - you can add more here
		$globals  = array("base_url" => $_SERVER["HTTP_HOST"]);
		$this->view->assign($globals);
 	}
 	/**
	 * Method to add to our template variable stack 
	 * @param string variable name
	 * @param mixed value
	 */ 
 	public function addTmplVar($key, $value){
 		/* If our stack doesn't already exist, create a new array */
 		if (!is_array($this->tmplVars)){
 			$this->tmplVars = array($key=>$value); 			
 		} else {
 			// Add to our variable stack
 			$this->tmplVars[$key] = $value;
 		}
 	}
 	/**
	 * Method to render the required view/template
	 * @param string template script name
	 * @param bool (optional) clear variable stack (default=true)
	 */ 
 	public function getTemplate($tmpl, $clearVars=true){
 		/* Add our variable stack to the template */
		$this->view->assign($this->tmplVars); 
		/* If required, clear our stack so that we can start with a fresh template on the next call */
		if ($clearVars)
			$this->tmplVars = "";
			
		/* Return the rendered template */
		return $this->view->render($tmpl);
	}
	
 }

?>

Next for some example usage (index.php) :

<?php
require_once("View.php");
$items = array ("Name" => "Barry", "Surname" => "Roodt", "Title" => "Mr");
$view = new View();
$view->addTmplVar("myitems", $items);
echo $view->getTemplate("template.phtml");
?>

And finally our view template (template.phtml) :

<div>Hi <?php echo $this->myitems["name"]; ?></div>
<div>Here is some information for you
<?php foreach($this->myitems as $key=>$val) : ?>
    <p><strong><?php echo $key; ?>: </strong><?php echo $val; ?></p>
<?php endforeach; ?>
</div>
<div>You can also use Zend View's default helpers like so : <?php echo $this->escape($this->myitems["name"]); ?></div>

You can also view an example of this class in action here.

As always, comments, critiques and corrections welcome.

Spam proof Contact Form with Zend Framework, ReCaptcha and Akismet / TypePad Antispam

October 3, 2008 7 comments

Update : Download Source code here
Update : View Working Demo

Over the last few weeks I’ve blogged on using the Zend Framework’s Akismet Service to “spam proof” your generic, run of the mill contact form.

Of course, services like Akismet and TypePad Antispam only come into play after the form has been submitted, a “cure” so to speak.

What we really need is some form of robust “prevention”. Stop the spam bots right at the door. There’s nothing more irritating than getting bombarded by 10k submissions every hour on the hour – even if they’re being filtered out by your Akismet / TypePad service.

Which brings us to the now common place CAPTCHA component. Designed to stop automated spam bots in their tracks, its a pretty effective method. Ordinarily, it’s not too difficult to implement a CAPTCHA component to your form, but ReCaptcha and the Zend Framework have now made it child’s play.

ReCaptcha is an online service providing a free CAPTCHA API for you to use. What’s also really nifty is that while your users fill in the CAPTCHA form, they’re also helping develop OCR software used to digitize books and manuscripts.

As an example I’ve gone and written a basic contact form, zipped it up and made it available here. Inside the zip file is all the code necessary for a very basic and hopefully spam proof contact form.

The following Zend Framework components were used :

  • Zend Loader
  • Zend Config
  • Zend View
  • Zend Service ReCaptcha
  • Zend Service Akismet
  • Zend Mail
  • Zend Validate
  • Zend Filter
  • Zend Registry

I’ve also included a simple wrapper for Zend View, since I didn’t feel that it was necessary to go the whole MVC route on this one.

The code used is pretty straightforward and easy to follow with as many comments thrown in there as I could stomach, but if you have any questions please feel free to leave a comment or send a mail.

Before you begin, you’ll need the following:

To use, unzip the file (it already contains the Zend Framework v1.6), edit the config.xml file and then simply customize the view scripts (view/form.php, view/success.php, view/mail.php).

Unfortunately I haven’t had much time to test the example thoroughly as it was written in a bit of a hurry (only had about an hour or so), so if you find or even fix any bugs please let me know and I’ll sort it out as soon as I get an opportunity to do so.

Update: I’ve amended 3 bugs thanks to comments from Mark. Affected files can be downloaded separately here, or you can download the full source again here. I’ve also created a working demo here.

  1. In view/form.php line 23 : “$this->TextArea” has been changed to “$this->Textarea”. TextArea works on my local host, but not when uploaded to my demo server.
  2. In view/form.php line 25-27 : Added a new paragraph containing “$this->captcha” to output the ReCaptcha element. This was not included in the zip file’s form.php for some inexplicable reason – my apologies
  3. In library/FlexiDev/Process.php line 122 : Logic error preventing ReCaptcha from verifying correctly. $recaptcha->verify(…) returns an object and not a boolean value – amended to $result = $recaptcha->verify(…); return $result->isValid();

One last note : the code is provided under the New BSD License, so have fun.

Adding TypePad Anti Spam to your Contact Form with Zend Framework

September 24, 2008 3 comments

About 2 weeks ago, I posted a quick tutorial on how to implement Akismet.com’s anti-spam checks to your contact form using the excellent Zend Framework. I was fortunate enough to have Anil Dash from Six Apart (the creators of TypePad) drop by and post a comment asking me if I’d be interested in giving TypePad’s Antispam service a try.

I’m happy to report that TypePad Antispam is just as effective as Akismet, with the bonus of there being no restrictions on usage (that I could find in any case).

With all of that in mind – I simply copied the current Zend/Service/Akismet.php class – renamed it to Zend/Service/TypePadAntiSpam.php and did a simple search and replace. The two services are so alike in implementation, that’s all it took.

The code posted below makes the following assumptions :

Firstly the TypePad Antispam Class. Simply save this file to the following folder inside your Zend Framework installation : Zend/Service/TypePadAntiSpam.php (should be in the same folder as Akismet.php)

<?php
/**
 * Please note that this is NOT an official Zend Framework package.
 * This is essentially a copy-paste-modification of the original Zend Framework's Service/Akismet.php class to
 * work with the TypePad Anti Spam service. If you find this class useful or find an error etc, please leave a
 * comment at https://calisza.wordpress.com - all feedback is welcome.
 * 
 * All original/offical headers have been left intact. Thanks to all the devs who have made the Zend Framework
 * the wonderful product that it is.
 */

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage TypePadAntiSpam
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @see Zend_Version
 */
require_once 'Zend/Version.php';

/**   
 * @see Zend_Service_Abstract
 */
require_once 'Zend/Service/Abstract.php';


/**
 * Typepad Anti Spam REST service implementation
 *
 * @uses       Zend_Service_Abstract
 * @category   Zend
 * @package    Zend_Service
 * @subpackage TypePadAntiSpam
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_TypePadAntiSpam extends Zend_Service_Abstract
{
    /**
     * TypePadAntiSpam API key
     * @var string
     */
    protected $_apiKey;

    /**
     * Blog URL
     * @var string
     */
    protected $_blogUrl;

    /**
     * Charset used for encoding
     * @var string
     */
    protected $_charset = 'UTF-8';

    /**
     * TCP/IP port to use in requests
     * @var int
     */
    protected $_port = 80;

    /**
     * User Agent string to send in requests
     * @var string
     */
    protected $_userAgent;

    /**
     * Constructor
     *
     * @param string $apiKey TypePadAntiSpam API key
     * @param string $blog Blog URL
     * @return void
     */
    public function __construct($apiKey, $blog)
    {
        $this->setBlogUrl($blog)
             ->setApiKey($apiKey)
             ->setUserAgent('Zend Framework/' . Zend_Version::VERSION . ' | TypePadAntiSpam/1.1');
    }

    /**
     * Retrieve blog URL
     *
     * @return string
     */
    public function getBlogUrl()
    {
        return $this->_blogUrl;
    }

    /**
     * Set blog URL
     *
     * @param string $blogUrl
     * @return Zend_Service_TypePadAntiSpam
     * @throws Zend_Service_Exception if invalid URL provided
     */
    public function setBlogUrl($blogUrl)
    {
        require_once 'Zend/Uri.php';
        if (!Zend_Uri::check($blogUrl)) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid url provided for blog');
        }

        $this->_blogUrl = $blogUrl;
        return $this;
    }

    /**
     * Retrieve API key
     *
     * @return string
     */
    public function getApiKey()
    {
        return $this->_apiKey;
    }

    /**
     * Set API key
     *
     * @param string $apiKey
     * @return Zend_Service_TypePadAntiSpam
     */
    public function setApiKey($apiKey)
    {
        $this->_apiKey = $apiKey;
        return $this;
    }

    /**
     * Retrieve charset
     *
     * @return string
     */
    public function getCharset()
    {
        return $this->_charset;
    }

    /**
     * Set charset
     *
     * @param string $charset
     * @return Zend_Service_TypePadAntiSpam
     */
    public function setCharset($charset)
    {
        $this->_charset = $charset;
        return $this;
    }

    /**
     * Retrieve TCP/IP port
     *
     * @return int
     */
    public function getPort()
    {
        return $this->_port;
    }

    /**
     * Set TCP/IP port
     *
     * @param int $port
     * @return Zend_Service_TypePadAntiSpam
     * @throws Zend_Service_Exception if non-integer value provided
     */
    public function setPort($port)
    {
        if (!is_int($port)) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid port');
        }

        $this->_port = $port;
        return $this;
    }

    /**
     * Retrieve User Agent string
     *
     * @return string
     */
    public function getUserAgent()
    {
        return $this->_userAgent;
    }

    /**
     * Set User Agent
     *
     * Should be of form "Some user agent/version | TypePadAntiSpam/version"
     *
     * @param string $userAgent
     * @return Zend_Service_TypePadAntiSpam
     * @throws Zend_Service_Exception with invalid user agent string
     */
    public function setUserAgent($userAgent)
    {
        if (!is_string($userAgent)
            || !preg_match(":^[^\n/]*/[^ ]* \| TypePadAntiSpam/[0-9\.]*$:i", $userAgent))
        {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid User Agent string; must be of format "Application name/version | TypePadAntiSpam/version"');
        }

        $this->_userAgent = $userAgent;
        return $this;
    }

    /**
     * Post a request
     *
     * @param string $host
     * @param string $path
     * @param array  $params
     * @return mixed
     */
    protected function _post($host, $path, array $params)
    {
        $uri    = 'http://' . $host . ':' . $this->getPort() . $path;
        $client = self::getHttpClient();
        $client->setUri($uri);
        $client->setConfig(array(
            'useragent'    => $this->getUserAgent(),
        ));

        $client->setHeaders(array(
            'Host'         => $host,
            'Content-Type' => 'application/x-www-form-urlencoded; charset=' . $this->getCharset()
        ));
        $client->setParameterPost($params);

        $client->setMethod(Zend_Http_Client::POST);
        return $client->request();
    }

    /**
     * Verify an API key

     *
     * @param string $key Optional; API key to verify
     * @param string $blog Optional; blog URL against which to verify key
     * @return boolean
     */
    public function verifyKey($key = null, $blog = null)
    {
        if (null === $key) {
            $key = $this->getApiKey();
        }

        if (null === $blog) {
            $blog = $this->getBlogUrl();
        }

        $response = $this->_post('api.antispam.typepad.com', '/1.1/verify-key', array(
            'key'  => $key,
            'blog' => $blog
        ));

        return ('valid' == $response->getBody());
    }

    /**
     * Perform an API call
     *
     * @param string $path
     * @param array $params
     * @return Zend_Http_Response
     * @throws Zend_Service_Exception if missing user_ip or user_agent fields
     */
    protected function _makeApiCall($path, $params)
    {
        if (empty($params['user_ip']) || empty($params['user_agent'])) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Missing required TypePadAntiSpam fields (user_ip and user_agent are required)');
        }

        if (!isset($params['blog'])) {
            $params['blog'] = $this->getBlogUrl();
        }

        return $this->_post($this->getApiKey() . '.api.antispam.typepad.com', $path, $params);
    }

    /**
     * Check a comment for spam
     *
     * Checks a comment to see if it is spam. $params should be an associative
     * array with one or more of the following keys (unless noted, all keys are
     * optional):
     * - blog: URL of the blog. If not provided, uses value returned by {@link getBlogUrl()}
     * - user_ip (required): IP address of comment submitter
     * - user_agent (required): User Agent used by comment submitter
     * - referrer: contents of HTTP_REFERER header
     * - permalink: location of the entry to which the comment was submitted
     * - comment_type: typically, one of 'blank', 'comment', 'trackback', or 'pingback', but may be any value
     * - comment_author: name submitted with the content
     * - comment_author_email: email submitted with the content
     * - comment_author_url: URL submitted with the content
     * - comment_content: actual content
     *
     * Additionally, TypePadAntiSpam suggests returning the key/value pairs in the
     * $_SERVER array, and these may be included in the $params.
     *
     * This method implements the TypePadAntiSpam comment-check REST method.
     *
     * @param array $params
     * @return boolean
     * @throws Zend_Service_Exception with invalid API key
     */
    public function isSpam($params)
    {
        $response = $this->_makeApiCall('/1.1/comment-check', $params);

        $return = trim($response->getBody());

        if ('invalid' == $return) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid API key');
        }

        if ('true' == $return) {
            return true;
        }

        return false;
    }

    /**
     * Submit spam
     *
     * Takes the same arguments as {@link isSpam()}.
     *
     * Submits known spam content to TypePadAntiSpam to help train it.
     *
     * This method implements TypePadAntiSpam's submit-spam REST method.
     *
     * @param array $params
     * @return void
     * @throws Zend_Service_Exception with invalid API key
     */
    public function submitSpam($params)
    {
        $response = $this->_makeApiCall('/1.1/submit-spam', $params);
        $value    = trim($response->getBody());
        if ('invalid' == $value) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid API key');
        }
    }

    /**
     * Submit ham
     *
     * Takes the same arguments as {@link isSpam()}.
     *
     * Submits a comment that has been falsely categorized as spam by TypePadAntiSpam
     * as a false positive, telling TypePadAntiSpam's filters not to filter such
     * comments as spam in the future.
     *
     * Unlike {@link submitSpam()} and {@link isSpam()}, a valid API key is
     * never necessary; as a result, this method never throws an exception
     * (unless an exception happens with the HTTP client layer).
     *
     * this method implements TypePadAntiSpam's submit-ham REST method.
     *
     * @param array $params
     * @return void
     */
    public function submitHam($params)
    {
        $response = $this->_makeApiCall('/1.1/submit-ham', $params);
    }
}

Next, some code to implement our new class :

<?php
/*
* Basic function to check for spam
* @param items : associative array for containing form field values
* @return boolean : true if spam, false if clean
*/
function spamCheck($items){
 	require_once 'Zend/Service/TypePadAntiSpam.php'; // include the required class file - change path if necessary
 	$url = "http://url.to.my.blog.or.form"; // url associated with API key
	$api = "432dsjk890"; // TypePad Antispam API key
 	$spam = new Zend_Service_TypePadAntiSpam($api, $url ); // create new instance of our TypePadAntiSpam Service class

	if ($spam->verifyKey()){ // make sure the API key if valid before performing check
	 	$params = array(); // check the comments for the isSpam() method in Zend/Service/TypePadAntiSpam.php for more information on available parameters
	 	$params["user_ip"] = $_SERVER['REMOTE_ADDR']; // required by TypePadAntiSpam
	 	$params["user_agent"] = $_SERVER['HTTP_USER_AGENT']; // required by TypePadAntiSpam
	 	$params["referrer"] = $_SERVER[ 'HTTP_REFERER'];
	 	$params["comment_type"] = "comment";
	 	$params["comment_author"] = $items["name"];
	 	$params["comment_author_email"] = $items["email"];
	 	$params["comment_content"] = $items["comments"];

	 	return $spam->isSpam($params); // submits api call and returns true if spam, false if clean

	} else {
 		return false;
 	}
 }

// to make use of our spam check function try the following :
$items = sanitize($_POST); // sanitize is your own built-in function to sanitize user submitted data

// only mail the form contents if not spam
if (!spamCheck($items)){
	// insert code to mail form contents here
}
?>

That should do it. You should now have a robust, easy to use anti-spam solution for your contact forms.

Simple PHP wrapper class for Zend Session

September 23, 2008 6 comments

I’ve been rather busy lately writing a new personal CMS based loosely on the excellent Zend Framework.

One of the decisions I had to make was on how to handle session data, usually an overlooked yet very important aspect to any interactive website today. Fortunately, Zend Framework makes this a very easy decision to make with the introduction of their Zend_Session management component.

The problem with frameworks though, is that you risk tying your code up too tightly with that of the framework itself. What happens when that bigger, better and shinier framework comes out ? Do you rewrite everything – again, or do you just resign yourself to using the old system until it’s well past it’s sell by date ?

While you cannot avoid the entanglement all together (you do need to make use of the framework after all), you can add abstraction layers – within reason.

It’s with this in mind that I created the following abstraction class. If I ever decided to use some other package/component to manage my sessions, I’d only have to edit code in one place – the class itself.

Keep in mind that this is an extremely basic example and should be treated as such.
I’m also going to assume the following:

First our session wrapper/abstraction class :

<?php
require_once("Zend/Session.php");

class SessionWrapper {
    protected static $_instance;
    public $namespace = null;
	
	private function __construct() {
			/* Explicitly start the session */
			Zend_Session::start();
			
			/* Create our Session namespace - using 'Default' namespace */
			$this->namespace = new Zend_Session_Namespace();

			/** Check that our namespace has been initialized - if not, regenerate the session id 
			 * Makes Session fixation more difficult to achieve
 			 */	
			if (!isset($this->namespace->initialized)) {
			    Zend_Session::regenerateId();
			    $this->namespace->initialized = true;
			}
	}
	
	/**
	 * Implementation of the singleton design pattern
	 * See http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html 
	 */	
	public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    /**
     * Public method to retrieve a value stored in the session
     * return $default if $var not found in session namespace
     * @param $var string
     * @param $default string
     * @return string
     */
    public function getSessVar($var, $default=null){
    	return (isset($this->namespace->$var)) ? $this->namespace->$var : $default;
    }
    
    /**
     * Public function to save a value to the session
     * @param $var string
     * @param $value
     */ 
    public function setSessVar($var, $value){
    	if (!empty($var) && !empty($value)){
    		$this->namespace->$var = $value;
    	}
    }
}
?>

Note that the class takes advantage of the Singleton Design Pattern. What this means is that you only need to create an instance of the class once. You can then access that instance from anywhere within your project without having to either create yet another instance or include “global” objects/variables. You can do some further reading here for a good tutorial and explanation on implementing the Singleton Design Pattern in PHP.

Also note that the class starts the session explicitly. This means that you’ll need to include and instantiate this class before ANY headers are sent to the browser (though this should be obvious to the more seasoned coder). If you get any “Cannot modify header information – headers already sent” errors, please go back and read the manual, make sure you understand how PHP Sessions work and then come back to this post.

Now for some example usage :

<?php
// make sure SessionWrapper::getInstance() is called at least once in your bootstrap script
// to make sure that the session is created before any headers are sent to browser
$mySession = SessionWrapper::getInstance();

// Set a session value
$mySession->setSessVar("example", "my value");
// this is the same as saying 
$_SESSION["Default"]["example"] = "my value";

// Print a session var to screen
echo $mySession->getSessVar("example", "default value");
// outputs "my value" - same as saying the following
echo $_SESSION["Default"]["example"];

// You can also use the following notation :
SessionWrapper::getInstance()->getSessVar("example");

// You can use the above code inside a function without having to 'global' $mySession
function myExample(){
	return SessionWrapper::getInstance()->getSessVar("example");
}

?>

So, this may all seem pretty pointless at the moment, since you can access the Session directly through either $_SESSION or create a new instance of Zend_Session_Namespace(). But – if for some reason you find a better session management package and want to move away from Zend_Session – all you have to do is modify the SessionWrapper constructor method and it’s finished. No exhaustive search and replace necessary.

Stylish Javascript / Jquery panel navigation part two

September 16, 2008 1 comment

A little while ago, I posted an entry on the stylish jkpanel plugin for jquery. While useful, it didn’t quite meet my needs at the time and I made certain adjustments. I’ve since made further updates making the implementation of the script more unobtrusive and hopefully far simpler.

First, the modified script ( jkpanel.js ) :

//Drop Down Panel script (March 29th, 08'): By JavaScript Kit: http://www.javascriptkit.com
// Modified by Barry Roodt (September 08) : https://calisza.wordpress.com

var jkpanel={
	controltext: 'Close Panel',
	$mainpanel: null, contentdivheight: 0,
	$contentdiv: null, $controldiv: null,

	openclose:function($){
		this.$mainpanel.stop() //stop any animation
		if (this.$mainpanel.attr('openstate')=='closed'){
			this.$mainpanel.animate({top: 0}, 500).attr({openstate: 'open'});
			this.$controldiv.show();
		} else {
			this.$mainpanel.animate({top: -this.contentdivheight+'px'}, 500).attr({openstate: 'closed'});
			this.$controldiv.hide();
		}
	},
	
	loadfile:function($, file, height, openpanel){
		jkpanel.$contentdiv.load(file, '', function($){
					var heightattr=isNaN(parseInt(height))? 'auto' : parseInt(height)+'px';
					jkpanel.$contentdiv.css({height: heightattr});
					jkpanel.contentdivheight=parseInt(jkpanel.$contentdiv.get(0).offsetHeight);
					jkpanel.$mainpanel.css({top:-jkpanel.contentdivheight+'px', visibility:'visible'});
					jkpanel.$controldiv.css({cursor:'hand', cursor:'pointer'});
					if (openpanel){
						jkpanel.openclose($);
					}
					return true;
		})
		
		return false;
	},
	
	init:function(file, height){
		jQuery(document).ready(function($){
			jkpanel.$mainpanel=$('<div id="dropdownpanel"><div id="jkcontentdiv"></div><div id="jkcontrol">'+jkpanel.controltext+'</div></div>').prependTo('body');
			jkpanel.$contentdiv=jkpanel.$mainpanel.find('#jkcontentdiv');
			jkpanel.$controldiv=jkpanel.$mainpanel.find('#jkcontrol').css({cursor: 'wait', display: 'none'});
			jkpanel.loadfile($,file, height, false);
			jkpanel.$mainpanel.attr('openstate', 'closed');
			$('#jkcontrol').click(function(){jkpanel.openclose($)});
			$('.panelbutton').click(function(){
				var pfile = this.href;
				var pheight = this.rel || false;
				jkpanel.loadfile($,pfile, pheight, true);
				return false;
			});
					
		})
	}
}

Next, the updated css ( jkpanel.css ):

#dropdownpanel{ /*Outermost Panel DIV*/
position: absolute;
width: 100%;
left: 0;
top: 0;
visibility:hidden;
}

#jkcontentdiv{ /*Div containing Ajax content*/
background: white;
width: auto;
color: black;
padding: 10px;
margin: 0px auto;
}

#jkcontrol{ /*Div containing panel button*/
border-top: 5px solid #ECECEC;
color: white;
font-weight: bold;
text-align: center;
background: transparent url("../images/panel.gif") center center no-repeat; /*change panel.gif to your own if desired*/
padding-bottom: 3px; /* 21px + 3px should equal height of "panel.gif" */
height: 21px; /* 21px + 3 px should equal height of "panel.gif" */
line-height: 21px; /* 21px + 3px should equal height of "panel.gif" */
}

And lastly, a usage example :

<html>
<head>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jkpanel.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/jkpanel.css" type="text/css" />
<script type="text/javascript">
  jkpanel.init('initialcontent.htm', '200px');
</script>
</head>
<body>
<p> Some text <a href="someothercontent.htm" rel="500px" class="panelbutton">my link</a></p>
</body>
</html>

You will need to take note of the following :

  • Use class=”panelbutton” to enable the jkpanel for your link
  • Tell jkpanel which content to load by specifying the path in the href attribute
  • Specify a height for the panel using the “rel” attribute. You can set this to rel=”auto” to tell the panel to automatically match the height of it’s contents
  • Make sure to read the terms of usage on jkpanel’s home page, you can also obtain the panel button from the same page

This is of course a simple example and I plan on posting a proper, working demo shortly.