<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2011 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flGravatar Class
 *
 * Class to look up a gravatar and either generate an image link to it or
 * collect the profile information.
 *
 * @package fusionLib
 */
class flGravatar {

	/**
	 * The default size of the gravatar image to get.
	 *
	 * @var int
	 */
	private $size = 80;

	/**
	 * The default rating level to accept.
	 *
	 * @var string
	 */
	private $rating = 'g';

	/**
	 * Caclulate the hash of the gravatar from the email address.
	 * @param string $email The email address to get the gravatar for.
	 * @return string the hash value for the gravatar.
	 */
	protected function hash($email) {
		return md5(strtolower(trim($email)));
	}

	/**
	 * Set the image size required when getting a gravatar image.
	 *
	 * @param int $size The size in pixels between 1 and 512.
	 * @return flGravatar This object.
	 */
	function setImageSize($size) {
		$this->size = $size > 512 ? 512 : $size < 1 ? 1 : $size;
		return $this;
	}

	/**
	 * Set the the rating level to accept.
	 *
	 * @param string $rating The max rating level, 'g', 'pg', 'r' or 'x'
	 * @return flGravatar This object.
	 */
	function setRating($rating) {
		$this->rating = $rating;
		return $this;
	}

	/**
	 * Get the URI to the gravatar image.
	 *
	 * @param string $email The email to get the gravatar for.
	 * @return string The garvatar URI.
	 */
	function getImage($email) {
		return 'https://secure.gravatar.com/avatar/' . $this->hash($email) . '?d=identicon&amp;r=' . $this->rating . '&amp;s=' . $this->size;
	}

	/**
	 * Get the profile data from gravatar.
	 *
	 * @param string $email The array holding the profile data.
	 * @return string The array holding the profile data or false if no data available.
	 */
	function getProfile($email) {
		$http = new flHttpClient('http://www.gravatar.com/' . $this->hash($email) . '.php');
		if($http->sendRequest() && $http->getResponseCode() == 200) {
			$profile = unserialize($http->getBody());
			return $profile['entry'][0];
		}
		else
			return false;
	}
}
