Gravatar Helper

By Graham Weldon (predominant)
From the Gravatar Website:
A gravatar, or globally recognized avatar, is quite simply an avatar image that follows you from weblog to weblog appearing beside your name when you comment on gravatar enabled sites. Avatars help identify your posts on web forums, so why not on weblogs?

Gravatars are a great addition to any blog, or indeed any user submitted content. This helper is designed to provide gravatar output without the fuss

Introduction

This is my first community posted code. Criticism welcome, but please be kind.

There isn't much to this Helper, so I will jump right in.


Usage

More than likely you just want to use the thing... Well, its as simple as this:


Including the helper in your application

As with any helper, ensure that it is included in the helpers array in your controller. This will allow you access to it when you need it, in your views.


Controller
Download code class MyController extends AppController {
  public $helpers = array('Gravatar');
  // ...
}

View

Basic Gravatar with default settings:

Download code <?php echo $gravatar->image('someone@cakeisawesome.com'); ?>

Altering the default gravatar:

Download code <?php echo $gravatar->image(
  
'someone@cakeisawesome.com',
  array(
    
'default' => 'identicon'
  
); ?>

Altering the default gravatar with a custom image:

Download code <?php echo $gravatar->image(
  
'someone@cakeisawesome.com',
  array(
    
'default' => 'http://mysite.com/defaultavatar.png'
  
); ?>

Changing the gravatar size:

Download code <?php echo $gravatar->image(
  
'someone@cakeisawesome.com',
  array(
    
'default' => 'identicon',
    
'size' => 120
  
); ?>

Adjusting the gravatar ratings to display:

Download code <?php echo $gravatar->image(
  
'someone@cakeisawesome.com',
  array(
    
'rating' => 'x'
  
); ?>

Including image filename extension on the generated URL:

Download code <?php echo $gravatar->image(
  
'someone@cakeisawesome.com',
  array(
    
'default' => 'identicon',
    
'ext' => true
  
); ?>

Options

The options and their valid values are as follows:


default


size

  • Minimum value 1
  • Maximum value 512
In the event that your Gravatar size is outside these bounds, the helper will adjust it to be size 1 or 512, depending which side of the allowed range your specified value was.


rating

  • 'g'
  • 'pg'
  • 'r'
  • 'x'
If rating is either invalid or not specified, Gravatars will automatically be delivered for the 'g' rating. These ratings should be reasonably self explainatory.


ext

  • true
  • false
If not supplied, an image filename extension will not be included as part of the gravatar generation.


Helper Code

Helper Class:

Download code <?php 
/**
 * A CakePHP View Helper for the display of Gravatar images (http://www.gravatar.com)
 *
 * Copyright 2009, Graham Weldon
 * http://grahamweldon.com
 * Newcastle, Australia
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright 2008, Graham Weldon
 * @version 1.1
 * @author Graham Weldon <graham@grahamweldon.com>
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 */
App::import(array('Security''Validation'));

class 
GravatarHelper extends AppHelper {
        private 
$__url 'http://www.gravatar.com/avatar/';
        private 
$__hashType 'md5';
        private 
$__allowedRatings = array('g''pg''r''x');
        private 
$__defaultIcons = array('identicon''monsterid''wavatar');
        private 
$__default = array('default' => 'identicon''size' => null'rating' => null'ext' => false);

        public 
$helpers = array('Html');

        public function 
image($email$options = array()) {
                
$options $this->__cleanOptions(am($this->__default$options));

                
$ext $options['ext'];
                unset(
$options['ext']);

                
$imageUrl $this->__url $this->__emailHash(strtolower($email), $this->__hashType) . ($ext '.jpg' '') . $this->__buildOptions($options);
                unset(
$options['default'], $options['size'], $options['rating']);

                return 
$this->Html->image($imageUrl$options);
        }

        private function 
__cleanOptions($options) {
                if (!
$options['size']) {
                        unset(
$options['size']);
                } else {
                        if (
$options['size'] < 1) {
                                
$options['size'] = 1;
                        } elseif (
$options['size'] > 512) {
                                
$options['size'] = 512;
                        }
                }

                if (!
$options['rating'] || !in_array($options['rating'], $this->__allowedRatings)) {
                        unset(
$options['rating']);
                }

                if (!
$options['default']) {
                        unset(
$options['default']);
                } else {
                        if (!
in_array($options['default'], $this->__defaultIcons) && !Validation::url($options['default'])) {
                                unset(
$options['default']);
                        }
                }

                return 
$options;
        }

        private function 
__emailHash($email$type) {
                return 
Security::hash($email$type);
        }

        private function 
__buildOptions($options) {
                if (
count($options)) {
                        
$optionArray = array();
                        foreach (
$options as $k => $v) {
                                
$optionArray[] = $k '=' $v;
                        }
                        return 
'?' implode('&amp;'$optionArray);
                }
                return 
'';
        }

}
?>

Final Note

My final note is with regard to the options provided to the helper. Given that the HTML helper already deals extensively with images, it is used to process the actual image tage and return it. Thus, providing any Html Helper image options will ensure they are passed through the gravatar component and onto the Html component, rendering as you would naturally expect from the core Html helper.

Comments and suggestions are encouraged.

If you are using this on your site, let me know!

 

Comments 832

CakePHP Team Comments Author Comments
 

Comment

1 Nicely done

Thank you for posting this. I'll offer a small suggestion, as the URL isn't properly encoded. On line 94, change:

$optionString = implode('&', $optionArray);
To:

$optionString = implode('&amp;', $optionArray);
Posted Nov 30, 2008 by Tyler Seymour
 

Question

2 How to implement the code?

Hi there.
I'm a newbe and would like to know how to place this code in a html page?
Do I need a seperate php page with script for each persons Gravatar?
Do I place the script like this below directly into the html page??

image(
'someone@cakeisawesome.com',
array(
'rating' => 'x'
); ?>
Posted Jan 7, 2009 by Will
 

Comment

3 Code Implementation example

Do I need a seperate php page with script for each persons Gravatar?
Do I place the script like this below directly into the html page??

image(
'someone@cakeisawesome.com',
array(
'rating' => 'x'
); ?>

You actually spotted an error in the code samples there, as there is a missing close bracket, but you can place this into any view .ctp file in your CakePHP Application / Plugin.

The simplest and easiest way to display a gravatar is to do:

View Template:


echo $gravatar->image('someone@cakeisawesome.com');

And just ensure you include the Gravatar helper in your controller (or AppController), like this:

Controller Class:

<?php 
public $helpers = array('Html''Gravatar');
?>
Posted Jan 11, 2009 by Graham Weldon
 

Bug

4 Hash method should be case-insensitive

This is a pretty nice helper you wrote!

You should update your code to reflect Tyler's suggestion about encoding the URL properly.

Also, your hashing method is not taking into account the fact that Gravatar is expecting the email to be hashed in its lower-case form. Hence, the following change should be applied...

Change this:

Helper Class:

<?php 
return Security::hash($email$type);
?>

To this:

Helper Class:

<?php 
return Security::hash(strtolower($email), $type);
?>

That's all there is to it. :)
Posted Jun 10, 2009 by Ben Pesso
 

Comment

5 Helper code updates

Updates applied:
  1. HTML Encoding corrected (Thhanks Tyler)
  2. EMail addresses forced lowercase (Thanks Ben)
  3. Moved to PHP 5 only.
  4. Various code cleanup

Thanks for the suggestions and help with this helpers code. And enjoy the updates.
Posted Jun 10, 2009 by Graham Weldon
 

Comment

6 Well done

Clean and simple, just the way we like it.

Great work Graham!
Posted Jun 21, 2009 by Hannibal Lecter