Merge branch '2.0'
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / data / user / avatar / Gravatar.class.php
1 <?php
2 namespace wcf\data\user\avatar;
3 use wcf\system\exception\SystemException;
4 use wcf\system\request\LinkHandler;
5 use wcf\system\WCF;
6 use wcf\util\FileUtil;
7
8 /**
9 * Represents a gravatar.
10 *
11 * @author Marcel Werk
12 * @copyright 2001-2014 WoltLab GmbH
13 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
14 * @package com.woltlab.wcf
15 * @subpackage data.user.avatar
16 * @category Community Framework
17 * @see http://www.gravatar.com
18 */
19 class Gravatar extends DefaultAvatar {
20 /**
21 * gravatar base url
22 * @var string
23 */
24 const GRAVATAR_BASE = 'http://gravatar.com/avatar/%s?s=%d&r=g&d=%s';
25
26 /**
27 * gravatar local cache location
28 * @var string
29 */
30 const GRAVATAR_CACHE_LOCATION = 'images/avatars/gravatars/%s-%s.png';
31
32 /**
33 * gravatar expire time (days)
34 * @var integer
35 */
36 const GRAVATAR_CACHE_EXPIRE = 7;
37
38 /**
39 * user id
40 * @var integer
41 */
42 public $userID = 0;
43
44 /**
45 * gravatar e-mail address
46 * @var string
47 */
48 public $gravatar = '';
49
50 /**
51 * urls of this gravatar
52 * @var array<string>
53 */
54 protected $url = array();
55
56 /**
57 * Creates a new Gravatar object.
58 *
59 * @param integer $userID
60 * @param string $gravatar
61 */
62 public function __construct($userID, $gravatar) {
63 $this->userID = $userID;
64 $this->gravatar = $gravatar;
65 }
66
67 /**
68 * @see \wcf\data\user\avatar\IUserAvatar::getURL()
69 */
70 public function getURL($size = null) {
71 if ($size === null) $size = $this->size;
72
73 if (!isset($this->url[$size])) {
74 // try to use cached gravatar
75 $cachedFilename = sprintf(self::GRAVATAR_CACHE_LOCATION, md5(mb_strtolower($this->gravatar)), $size);
76 if (file_exists(WCF_DIR.$cachedFilename) && filemtime(WCF_DIR.$cachedFilename) > (TIME_NOW - (self::GRAVATAR_CACHE_EXPIRE * 86400))) {
77 $this->url[$size] = WCF::getPath().$cachedFilename;
78 }
79 else {
80 $this->url[$size] = LinkHandler::getInstance()->getLink('GravatarDownload', array(
81 'forceFrontend' => true
82 ), 'userID='.$this->userID.'&size='.$size);
83 }
84 }
85
86 return $this->url[$size];
87 }
88
89 /**
90 * Checks a given email address for gravatar support.
91 *
92 * @param string $email
93 * @return boolean
94 */
95 public static function test($email) {
96 $gravatarURL = sprintf(self::GRAVATAR_BASE, md5(mb_strtolower($email)), 80, '404');
97 try {
98 $tmpFile = FileUtil::downloadFileFromHttp($gravatarURL, 'gravatar');
99 @unlink($tmpFile);
100 return true;
101 }
102 catch (SystemException $e) {
103 return false;
104 }
105 }
106
107 /**
108 * @see \wcf\data\user\avatar\IUserAvatar::canCrop()
109 */
110 public function canCrop() {
111 return false;
112 }
113 }