3 * Name: Cat Avatar Generator
4 * Description: Generate a default avatar based on David Revoy's cat-avatar-generator https://framagit.org/Deevad/cat-avatar-generator
6 * Author: Fabio <https://kirgroup.com/profile/fabrixxm>
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Worker;
13 use Friendica\Core\PConfig;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Network\HTTPException\NotFoundException;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Photo;
18 use Friendica\Database\DBM;
20 define("CATAVATAR_SIZE", 256);
23 * Installs the addon hook
25 function catavatar_install()
27 Addon::registerHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
28 Addon::registerHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
29 Addon::registerHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
31 logger('registered catavatar');
35 * Removes the addon hook
37 function catavatar_uninstall()
39 Addon::unregisterHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
40 Addon::unregisterHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
41 Addon::unregisterHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
43 logger('unregistered catavatar');
47 * Cat avatar user settings page
49 function catavatar_addon_settings(App $a, &$s)
55 $t = get_markup_template('settings.tpl', 'addon/catavatar/');
56 $s .= replace_macros ($t, [
57 '$postpost' => !empty($_POST['catavatar-morecat']) || !empty($_POST['catavatar-emailcat']),
59 '$uid' => local_user(),
60 '$usecat' => L10n::t('Use Cat as Avatar'),
61 '$morecat' => L10n::t('More Random Cat!'),
62 '$emailcat' => L10n::t('Reset to email Cat'),
63 '$seed' => PConfig::get(local_user(), 'catavatar', 'seed', false),
64 '$header' => L10n::t('Cat Avatar Settings'),
69 * Cat avatar user settings POST handle
71 function catavatar_addon_settings_post(App $a, &$s)
77 // delete the current cached cat avatar
78 $user = dba::selectFirst('user', ['email'],
82 'account_expired' => 0,
83 'account_removed' => 0,
86 $seed = PConfig::get(local_user(), 'catavatar', 'seed', md5(trim(strtolower($user['email']))));
87 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $seed);
88 $imageurl = substr($imageurl, 0, 35) . '';
89 $cachefile = get_cachefile($imageurl);
90 if ($cachefile != "" && file_exists($cachefile)) {
95 if (!empty($_POST['catavatar-usecat'])) {
96 $url = $a->get_baseurl() . '/catavatar/' . local_user() . '?ts=' . time();
98 $self = dba::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
99 if (!DBM::is_result($self)) {
100 notice(L10n::t("The cat hadn't found itself."));
104 Photo::importProfilePhoto($url, local_user(), $self['id']);
106 $condition = ['uid' => local_user(), 'contact-id' => $self['id']];
107 $photo = dba::selectFirst('photo', ['resource-id'], $condition);
108 if (!DBM::is_result($photo)) {
109 notice(L10n::t('There was an error, the cat ran away.'));
113 dba::update('photo', ['profile' => false], ['profile' => true, 'uid' => local_user()]);
115 $fields = ['profile' => true, 'album' => L10n::t('Profile Photos'), 'contact-id' => 0];
116 dba::update('photo', $fields, ['uid' => local_user(), 'resource-id' => $photo['resource-id']]);
118 Photo::importProfilePhoto($url, local_user(), $self['id']);
120 Contact::updateSelfFromUserID(local_user(), true);
122 // Update global directory in background
123 $url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
124 if ($url && strlen(Config::get('system', 'directory'))) {
125 Worker::add(PRIORITY_LOW, 'Directory', $url);
128 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
130 info(L10n::t('Meow!'));
136 if (!empty($_POST['catavatar-morecat'])) {
137 PConfig::set(local_user(), 'catavatar', 'seed', time());
140 if (!empty($_POST['catavatar-emailcat'])) {
141 PConfig::delete(local_user(), 'catavatar', 'seed');
147 * Returns the URL to the cat avatar
152 function catavatar_lookup(App $a, &$b)
154 $user = dba::selectFirst('user', ['uid'], ['email' => $b['email']]);
155 $url = $a->get_baseurl() . '/catavatar/' . $user['uid'];
158 case 175: $url .= "/4"; break;
159 case 80: $url .= "/5"; break;
160 case 47: $url .= "/6"; break;
164 $b['success'] = true;
168 function catavatar_module(){}
172 * Returns image for user id
174 * @throws NotFoundException
177 function catavatar_content(App $a)
179 if ($a->argc < 2 || $a->argc > 3) {
180 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
183 $uid = intval($a->argv[1]);
187 $size = intval($a->argv[2]);
190 $user = dba::selectFirst('user', ['email'],
194 'account_expired' => 0,
195 'account_removed' => 0,
199 if ($user === false) {
200 throw new NotFoundException();
203 $seed = PConfig::get($uid, "catavatar", "seed", md5(trim(strtolower($user['email']))));
205 // from cat-avatar-generator.php
206 $imageurl = $seed . "-" . $size;
207 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $imageurl);
208 $imageurl = substr($imageurl, 0, 35) . '';
209 $cachefile = get_cachefile($imageurl);
210 $cachetime = 604800; # 1 week (1 day = 86400)
212 // Serve from the cache if it is younger than $cachetime
213 if ($cachefile != "" && file_exists($cachefile) && (time() - $cachetime) < filemtime($cachefile)) {
214 header('Pragma: public');
215 header('Cache-Control: max-age=86400');
216 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
217 header('Content-Type: image/jpg');
218 readfile($cachefile);
222 // ...Or start generation
225 // render the picture:
226 build_cat($seed, $size);
228 // Save/cache the output to a file
229 if ($cachefile != "") {
230 $savedfile = fopen($cachefile, 'w+'); # w+ to be at start of the file, write mode, and attempt to create if not existing.
231 fwrite($savedfile, ob_get_contents());
233 chmod($cachefile, 0755);
244 * ====================
245 * CAT-AVATAR-GENERATOR
246 * ====================
248 * @authors: Andreas Gohr, David Revoy
250 * This PHP is licensed under the short and simple permissive:
251 * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
255 function build_cat($seed = '', $size = 0)
259 srand(hexdec(substr(md5($seed), 0, 6)));
262 // throw the dice for body parts
264 'body' => rand(1, 15),
265 'fur' => rand(1, 10),
266 'eyes' => rand(1, 15),
267 'mouth' => rand(1, 10),
268 'accessorie' => rand(1, 20)
272 $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
273 or die("GD image create failed");
274 $white = imagecolorallocate($cat, 255, 255, 255);
275 imagefill($cat, 0, 0, $white);
278 foreach ($parts as $part => $num){
279 $file = dirname(__FILE__) . '/avatars/' . $part . '_' . $num . '.png';
281 $im = @imagecreatefrompng($file);
283 die('Failed to load ' . $file);
285 imageSaveAlpha($im, true);
286 imagecopy($cat, $im, 0, 0, 0, 0, CATAVATAR_SIZE, CATAVATAR_SIZE);
291 if ($size > 3 && $size < 7) {
304 $dest = imagecreatetruecolor($size, $size);
305 imagealphablending($dest, false);
306 imagesavealpha($dest, true);
307 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
312 // restore random seed
317 header('Pragma: public');
318 header('Cache-Control: max-age=86400');
319 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
320 header('Content-Type: image/jpg');
321 imagejpeg($cat, NULL, 90);