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>
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Worker;
12 use Friendica\Core\PConfig;
13 use Friendica\Util\DateTimeFormat;
14 use Friendica\Network\HTTPException\NotFoundException;
16 define("CATAVATAR_SIZE", 256);
19 * Installs the addon hook
21 function catavatar_install() {
22 Addon::registerHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
23 Addon::registerHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
24 Addon::registerHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
26 logger("registered catavatar");
30 * Removes the addon hook
32 function catavatar_uninstall() {
33 Addon::unregisterHook('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
34 Addon::unregisterHook('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
35 Addon::unregisterHook('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
37 logger("unregistered catavatar");
41 function catavatar_addon_settings(&$a, &$s) {
45 $t = get_markup_template("settings.tpl", "addon/catavatar/" );
46 $s = replace_macros ($t, [
47 '$postpost' => x($_POST,"catavatar-morecat") || x($_POST,"catavatar-emailcat"),
49 '$uid' => local_user(),
50 '$usecat' => L10n::t('Use Cat as Avatar'),
51 '$morecat' => L10n::t('More Random Cat!'),
52 '$emailcat' => L10n::t('Reset to email Cat'),
53 '$seed' => PConfig::get(local_user(), "catavatar", "seed", false),
54 '$header' => L10n::t('Cat Avatar').' '.L10n::t('Settings'),
59 function catavatar_addon_settings_post(&$a, &$s) {
63 // delete the current cached cat avatar
64 $user = dba::selectFirst('user', ['email'],
68 'account_expired' => 0,
69 'account_removed' => 0,
72 $seed = PConfig::get(local_user(), "catavatar", "seed", md5(trim(strtolower($user['email']))));
73 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $seed);
74 $imageurl = substr($imageurl,0,35).'';
75 $cachefile = get_cachefile($imageurl);
76 if ($cachefile != "" && file_exists($cachefile)) {
81 if (x($_POST,"catavatar-usecat")) {
82 $url = $a->get_baseurl()."/catavatar/".local_user();
84 // set the catavatar url as avatar url in contact and default profile
85 // and set profile to 0 to current photo
86 // I'm not sure it's the correct way to do this...
87 $r = dba::update('contact',
88 ['photo'=>$url."/4", 'thumb'=>$url."/5", 'micro'=>$url."/6", 'avatar-date'=>DateTimeFormat::utcNow()],
89 ['uid'=>local_user(), 'self'=>1]
92 notice(L10n::t('There was an error, the cat ran away.'));
96 $r = dba::update('profile',
97 ['photo'=>$url."/4", 'thumb'=>$url."/5"],
98 ['uid'=>local_user(), 'is-default'=>1]
101 notice(L10n::t('There was an error, the cat ran away.'));
105 $r = dba::update('photo',
107 ['uid'=>local_user(), 'profile'=>1]
110 notice(L10n::t('There was an error, the cat ran away.'));
115 // Update global directory in background
116 $url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
117 if ($url && strlen(Config::get('system','directory'))) {
118 Worker::add(PRIORITY_LOW, "Directory", $url);
121 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
123 info(L10n::t("Meow!"));
129 if (x($_POST,"catavatar-morecat")) {
130 PConfig::set(local_user(), "catavatar", "seed", time());
133 if (x($_POST,"catavatar-emailcat")) {
134 PConfig::delete(local_user(), "catavatar", "seed");
140 * Returns the URL to the cat avatar
145 function catavatar_lookup($a, &$b) {
146 $user = dba::selectFirst('user', ['uid'],['email'=>$b['email']]);
148 $url = $a->get_baseurl().'/catavatar/'.$user['uid'];
151 case 175: $url.="/4"; break;
152 case 80: $url.="/5"; break;
153 case 47: $url.="/6"; break;
157 $b['success'] = true;
161 function catavatar_module(){}
165 * Returns image for user id
167 * @throws NotFoundException
169 * @TODO: support sizes
171 function catavatar_content($a) {
172 if ($a->argc < 2 || $a->argc > 3)
173 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
175 $uid = intval($a->argv[1]);
179 $size = intval($a->argv[2]);
182 $user = dba::selectFirst('user', ['email'],
186 'account_expired' => 0,
187 'account_removed' => 0,
192 throw new NotFoundException();
194 $seed = PConfig::get(local_user(), "catavatar", "seed", md5(trim(strtolower($user['email']))));
195 //echo "<pre>"; var_dump($hash); killme();
198 // from cat-avatar-generator.php
200 $imageurl = $seed."-".$size;
201 $imageurl = preg_replace('/[^A-Za-z0-9\._-]/', '', $imageurl);
202 $imageurl = substr($imageurl,0,35).'';
203 $cachefile = get_cachefile($imageurl);
204 $cachetime = 604800; # 1 week (1 day = 86400)
206 // Serve from the cache if it is younger than $cachetime
207 if ($cachefile != "" && file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
208 header('Pragma: public');
209 header('Cache-Control: max-age=86400');
210 header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
211 header('Content-Type: image/jpg');
212 readfile($cachefile);
216 // ...Or start generation
219 // render the picture:
220 build_cat($seed, $size);
222 // Save/cache the output to a file
224 $savedfile = fopen($cachefile, 'w+'); # w+ to be at start of the file, write mode, and attempt to create if not existing.
225 fwrite($savedfile, ob_get_contents());
227 chmod($cachefile, 0755);
237 * ====================
238 * CAT-AVATAR-GENERATOR
239 * ====================
241 * @authors: Andreas Gohr, David Revoy
243 * This PHP is licensed under the short and simple permissive:
244 * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
248 function build_cat($seed='', $size=0){
251 if($seed) srand( hexdec(substr(md5($seed),0,6)) );
253 // throw the dice for body parts
255 'body' => rand(1,15),
257 'eyes' => rand(1,15),
258 'mouth' => rand(1,10),
259 'accessorie' => rand(1,20)
263 $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
264 or die("GD image create failed");
265 $white = imagecolorallocate($cat, 255, 255, 255);
266 imagefill($cat,0,0,$white);
269 foreach($parts as $part => $num){
270 $file = dirname(__FILE__).'/avatars/'.$part.'_'.$num.'.png';
272 $im = @imagecreatefrompng($file);
273 if(!$im) die('Failed to load '.$file);
274 imageSaveAlpha($im, true);
275 imagecopy($cat,$im,0,0,0,0,CATAVATAR_SIZE,CATAVATAR_SIZE);
280 if ($size > 3 && $size < 7) {
282 case 4: $size = 175; break;
283 case 5: $size = 80; break;
284 case 6: $size = 48; break;
287 $dest = imagecreatetruecolor($size, $size);
288 imagealphablending($dest, false);
289 imagesavealpha($dest, true);
290 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
295 // restore random seed
298 header('Pragma: public');
299 header('Cache-Control: max-age=86400');
300 header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
301 header('Content-Type: image/jpg');
302 imagejpeg($cat, NULL, 90);