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;
17 define("CATAVATAR_SIZE", 256);
20 * Installs the addon hook
22 function catavatar_install()
24 Addon::registerHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
25 Addon::registerHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
26 Addon::registerHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
28 logger('registered catavatar');
32 * Removes the addon hook
34 function catavatar_uninstall()
36 Addon::unregisterHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
37 Addon::unregisterHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
38 Addon::unregisterHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
40 logger('unregistered catavatar');
44 * Cat avatar user settings page
46 function catavatar_addon_settings(App $a, &$s)
52 $t = get_markup_template('settings.tpl', 'addon/catavatar/');
53 $s = replace_macros ($t, [
54 '$postpost' => !empty($_POST['catavatar-morecat']) || !empty($_POST['catavatar-emailcat']),
56 '$uid' => local_user(),
57 '$usecat' => L10n::t('Use Cat as Avatar'),
58 '$morecat' => L10n::t('More Random Cat!'),
59 '$emailcat' => L10n::t('Reset to email Cat'),
60 '$seed' => PConfig::get(local_user(), 'catavatar', 'seed', false),
61 '$header' => L10n::t('Cat Avatar Settings'),
66 * Cat avatar user settings POST handle
68 function catavatar_addon_settings_post(App $a, &$s)
74 // delete the current cached cat avatar
75 $user = dba::selectFirst('user', ['email'],
79 'account_expired' => 0,
80 'account_removed' => 0,
83 $seed = PConfig::get(local_user(), 'catavatar', 'seed', md5(trim(strtolower($user['email']))));
84 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $seed);
85 $imageurl = substr($imageurl,0,35).'';
86 $cachefile = get_cachefile($imageurl);
87 if ($cachefile != "" && file_exists($cachefile)) {
92 if (!empty($_POST['catavatar-usecat'])) {
93 $url = $a->get_baseurl() . '/catavatar/' . local_user();
95 // set the catavatar url as avatar url in contact and default profile
96 // and set profile to 0 to current photo
97 // I'm not sure it's the correct way to do this...
98 $r = dba::update('contact',
99 ['photo' => $url . '/4', 'thumb' => $url . '/5', 'micro' => $url . '/6', 'avatar-date' => DateTimeFormat::utcNow()],
100 ['uid' => local_user(), 'self' => 1]
103 notice(L10n::t('There was an error, the cat ran away.'));
107 $r = dba::update('profile',
108 ['photo' => $url . '/4', 'thumb' => $url . '/5'],
109 ['uid' => local_user(), 'is-default' => 1]
112 notice(L10n::t('There was an error, the cat ran away.'));
116 $r = dba::update('photo',
118 ['uid' => local_user(), 'profile' => 1]
121 notice(L10n::t('There was an error, the cat ran away.'));
126 // Update global directory in background
127 $url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
128 if ($url && strlen(Config::get('system','directory'))) {
129 Worker::add(PRIORITY_LOW, 'Directory', $url);
132 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
134 info(L10n::t('Meow!'));
140 if (!empty($_POST['catavatar-morecat'])) {
141 PConfig::set(local_user(), 'catavatar', 'seed', time());
144 if (!empty($_POST['catavatar-emailcat'])) {
145 PConfig::delete(local_user(), 'catavatar', 'seed');
151 * Returns the URL to the cat avatar
156 function catavatar_lookup(App $a, &$b)
158 $user = dba::selectFirst('user', ['uid'], ['email' => $b['email']]);
159 $url = $a->get_baseurl() . '/catavatar/' . $user['uid'];
162 case 175: $url .= "/4"; break;
163 case 80: $url .= "/5"; break;
164 case 47: $url .= "/6"; break;
168 $b['success'] = true;
172 function catavatar_module(){}
176 * Returns image for user id
178 * @throws NotFoundException
181 function catavatar_content(App $a)
183 if ($a->argc < 2 || $a->argc > 3) {
184 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
187 $uid = intval($a->argv[1]);
191 $size = intval($a->argv[2]);
194 $user = dba::selectFirst('user', ['email'],
198 'account_expired' => 0,
199 'account_removed' => 0,
203 if ($user === false) {
204 throw new NotFoundException();
207 $seed = PConfig::get(local_user(), "catavatar", "seed", md5(trim(strtolower($user['email']))));
209 // from cat-avatar-generator.php
210 $imageurl = $seed . "-" . $size;
211 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $imageurl);
212 $imageurl = substr($imageurl,0,35) . '';
213 $cachefile = get_cachefile($imageurl);
214 $cachetime = 604800; # 1 week (1 day = 86400)
216 // Serve from the cache if it is younger than $cachetime
217 if ($cachefile != "" && file_exists($cachefile) && (time() - $cachetime) < filemtime($cachefile)) {
218 header('Pragma: public');
219 header('Cache-Control: max-age=86400');
220 header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
221 header('Content-Type: image/jpg');
222 readfile($cachefile);
226 // ...Or start generation
229 // render the picture:
230 build_cat($seed, $size);
232 // Save/cache the output to a file
233 if ($cachefile != "") {
234 $savedfile = fopen($cachefile, 'w+'); # w+ to be at start of the file, write mode, and attempt to create if not existing.
235 fwrite($savedfile, ob_get_contents());
237 chmod($cachefile, 0755);
248 * ====================
249 * CAT-AVATAR-GENERATOR
250 * ====================
252 * @authors: Andreas Gohr, David Revoy
254 * This PHP is licensed under the short and simple permissive:
255 * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
259 function build_cat($seed='', $size=0){
262 if($seed) srand( hexdec(substr(md5($seed),0,6)) );
264 // throw the dice for body parts
266 'body' => rand(1,15),
268 'eyes' => rand(1,15),
269 'mouth' => rand(1,10),
270 'accessorie' => rand(1,20)
274 $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
275 or die("GD image create failed");
276 $white = imagecolorallocate($cat, 255, 255, 255);
277 imagefill($cat,0,0,$white);
280 foreach($parts as $part => $num){
281 $file = dirname(__FILE__).'/avatars/'.$part.'_'.$num.'.png';
283 $im = @imagecreatefrompng($file);
284 if(!$im) 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) {
293 case 4: $size = 175; break;
294 case 5: $size = 80; break;
295 case 6: $size = 48; break;
298 $dest = imagecreatetruecolor($size, $size);
299 imagealphablending($dest, false);
300 imagesavealpha($dest, true);
301 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
306 // restore random seed
311 header('Pragma: public');
312 header('Cache-Control: max-age=86400');
313 header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
314 header('Content-Type: image/jpg');
315 imagejpeg($cat, NULL, 90);