Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Created December 5, 2010 13:59
Show Gist options
  • Save Mikulas/729100 to your computer and use it in GitHub Desktop.
Save Mikulas/729100 to your computer and use it in GitHub Desktop.
Gravatar cache for nette
<?php
class GravatarPresenter extends \Nette\Application\UI\Presenter
{
public function actionDefault($email, $size = 80)
{
$this->sendResponse(new GravatarResponse($email, $size));
}
}
<?php
use Nette\Image;
use Nette\Object;
use Nette\Application\IResponse;
use Nette\Environment;
use Nette\Http\IRequest as HttpRequest;
use Nette\Http\IResponse as HttpResponse;
use Nette\InvalidArgumentException;
/**
* Gravatar image response
*
* @author Mikulas Dite, Martin Sadovy
*/
class GravatarResponse extends Object implements IResponse
{
/** @var string uri */
const URI = 'http://www.gravatar.com/avatar/';
/** @var int */
const EXPIRATION = 172800; // two days
/** @var string|Nette\Image */
private $image;
/** @var string */
private $type;
/**
* @param string email
* @param int size 1-512
* @param string path
*/
public function __construct($email, $size = 80, $defaultImage = NULL)
{
if ((int) $size < 1 || (int) $size > 512) {
throw new \InvalidArgumentException('Unsupported size `' . $size . '`, Gravatar API expects `1 - 512`.');
}
$arguments = array(
's' => (int) $size, // size
'd' => '404', // e404 if not found
'r' => 'g', // inclusive rating
);
$hash = md5(strtolower(trim($email)));
$file = TEMP_DIR . '/cache/gravatar/' . $hash . '_' . $size . '.jpeg';
if (!file_exists($file) || filemtime($file) < time() - self::EXPIRATION) {
if (!file_exists(TEMP_DIR . '/cache/gravatar')) {
mkdir(TEMP_DIR . '/cache/gravatar');
}
$query = http_build_query($arguments);
$img = @file_get_contents(self::URI . $hash . '?' . $query);
if ($img != NULL) {
file_put_contents($file, $img);
} else {
file_put_contents($defaultImage, $img);
}
}
$this->image = Image::fromFile($file);
$this->type = Image::JPEG;
}
/**
* Returns the path to a file or Nette\Image instance.
* @return string|Nette\Image
*/
final public function getImage()
{
return $this->image;
}
/**
* Returns the type of a image.
* @return string
*/
final public function getType()
{
return $this->type;
}
/**
* Sends response to output.
* @return void
*/
public function send (HttpRequest $httpRequest, HttpResponse $httpResponse)
{
echo $this->image->send($this->type, 85);
// ideálně nastavit content type pomocí $httpResponse->setContentType();
/** @see http://api.nette.org/2.0/Nette.Web.IHttpResponse.html#_setContentType */
}
}
@Mikulas
Copy link
Author

Mikulas commented Dec 5, 2010

Usage in template:
<img src="{plink Gravatar:, '[email protected]', 32}">

or with using the default size of 80:
<img src="{plink Gravatar:, '[email protected]'}">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment