forked from henrikbjorn/GravatarBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GravatarApi.php
98 lines (87 loc) · 2.85 KB
/
GravatarApi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Ornicar\GravatarBundle;
/**
* Simple wrapper to the gravatar API
* http://en.gravatar.com/site/implement/url
*
* Usage:
* \Bundle\GravatarBundle\GravatarApi::getUrl('[email protected]', 80, 'g', 'mm');
*
* @author Thibault Duplessis <[email protected]>
* @author Henrik Bjørnskov <[email protected]>
*/
class GravatarApi
{
/**
* @var array $defaults Array of default options that can be overriden with getters and in the construct.
*/
protected $defaults = array(
'size' => 80,
'rating' => 'g',
'default' => null,
'secure' => false,
);
/**
* Constructor
*
* @param array $options the array is merged with the defaults.
* @return void
*/
public function __construct(array $options = array())
{
$this->defaults = array_merge($this->defaults, $options);
}
/**
* Returns a url for a gravatar.
*
* @param string $email
* @param integer $size
* @param string $rating
* @param string $default
* @param Boolean $secure
* @return string
*/
public function getUrl($email, $size = null, $rating = null, $default = null, $secure = null)
{
$hash = md5(strtolower(trim($email)));
return $this->getUrlForHash($hash, $size, $rating, $default, $secure);
}
/**
* Returns a url for a gravatar for the given hash.
*
* @param string $hash
* @param integer $size
* @param string $rating
* @param string $default
* @param Boolean $secure
* @return string
*/
public function getUrlForHash($hash, $size = null, $rating = null, $default = null, $secure = null)
{
$map = array(
's' => $size ?: $this->defaults['size'],
'r' => $rating ?: $this->defaults['rating'],
'd' => $default ?: $this->defaults['default'],
);
$secure = $secure ?: $this->defaults['secure'];
return ($secure ? 'https://secure' : 'http://www') . '.gravatar.com/avatar/' . $hash . '?' . http_build_query(array_filter($map));
}
/**
* Checks if a gravatar exists for the email. It does this by checking for the presence of 404 in the header
* returned. Will return null if fsockopen fails, for example when the hostname cannot be resolved.
*
* @param string $email
* @return Boolean|null Boolean if we could connect, null if no connection to gravatar.com
*/
public function exists($email)
{
$path = $this->getUrl($email, null, null, '404');
if (!$sock = @fsockopen('gravatar.com', 80, $errorNo, $error)) {
return null;
}
fputs($sock, "HEAD " . $path . " HTTP/1.0\r\n\r\n");
$header = fgets($sock, 128);
fclose($sock);
return strpos($header, '404') ? false : true;
}
}