]> git.mxchange.org Git - friendica-addons.git/blob - catavatar/catavatar.php
f8a6d2f148ed61aa3e6f608d4f439b0dfeae6091
[friendica-addons.git] / catavatar / catavatar.php
1 <?php
2 /**
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
5  * Version: 1.1
6  * Author: Fabio <https://kirgroup.com/profile/fabrixxm>
7  */
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;
15
16 define("CATAVATAR_SIZE", 256);
17
18 /**
19  * Installs the addon hook
20  */
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');
25
26         logger("registered catavatar");
27 }
28
29 /**
30  * Removes the addon hook
31  */
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');
36         
37         logger("unregistered catavatar");
38 }
39
40
41 function catavatar_addon_settings(&$a, &$s) {
42         if(! local_user())
43                 return;
44
45         $t = get_markup_template("settings.tpl", "addon/catavatar/" );
46         $s = replace_macros ($t, [
47                 '$postpost' => x($_POST,"catavatar-morecat") || x($_POST,"catavatar-emailcat"),
48                 '$uncache' => time(),
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'),
55         ]);
56         return;
57 }
58
59 function catavatar_addon_settings_post(&$a, &$s) {
60         if(! local_user())
61                 return;
62                 
63         // delete the current cached cat avatar
64         $user = dba::selectFirst('user', ['email'],
65                 [
66                         'uid' => $uid,
67                         'blocked' => 0,
68                         'account_expired' => 0,
69                         'account_removed' => 0,
70                 ]
71         );
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)) {
77                 unlink($cachefile);
78         }
79                 
80                 
81         if (x($_POST,"catavatar-usecat")) {
82                 $url = $a->get_baseurl()."/catavatar/".local_user();
83                 
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]
90                 );
91                 if ($r===false) {
92                         notice(L10n::t('There was an error, the cat ran away.'));
93                         return;
94                 }
95
96                 $r = dba::update('profile', 
97                         ['photo'=>$url."/4", 'thumb'=>$url."/5"], 
98                         ['uid'=>local_user(), 'is-default'=>1]
99                 );
100                 if ($r===false) {
101                         notice(L10n::t('There was an error, the cat ran away.'));
102                         return;
103                 }
104
105                 $r = dba::update('photo', 
106                         ['profile'=>0], 
107                         ['uid'=>local_user(), 'profile'=>1]
108                 );
109                 if ($r===false) {
110                         notice(L10n::t('There was an error, the cat ran away.'));
111                         return;
112                 }
113
114
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);
119                 }
120
121                 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
122                 
123                 info(L10n::t("Meow!"));
124                 return;
125         }
126         
127
128
129         if (x($_POST,"catavatar-morecat")) {
130                 PConfig::set(local_user(), "catavatar", "seed", time());
131         }
132
133         if (x($_POST,"catavatar-emailcat")) {
134                 PConfig::delete(local_user(), "catavatar", "seed");
135         }
136 }
137
138
139 /**
140  * Returns the URL to the cat avatar
141  *
142  * @param $a array
143  * @param &$b array
144  */
145 function catavatar_lookup($a, &$b) {
146         $user = dba::selectFirst('user', ['uid'],['email'=>$b['email']]);
147         
148         $url = $a->get_baseurl().'/catavatar/'.$user['uid'];
149
150         switch($b['size']) {
151                 case 175: $url.="/4"; break;
152                 case 80: $url.="/5"; break;
153                 case 47: $url.="/6"; break;
154         }
155
156         $b['url'] = $url;
157         $b['success'] = true;
158 }
159
160
161 function catavatar_module(){}
162
163
164 /**
165  * Returns image for user id
166  *
167  * @throws NotFoundException
168  *
169  * @TODO: support sizes
170  */
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.
174
175         $uid = intval($a->argv[1]);
176         
177         $size = 0;
178         if ($a->argc == 3) {
179                 $size = intval($a->argv[2]);
180         }
181         
182         $user = dba::selectFirst('user', ['email'],
183                 [
184                         'uid' => $uid,
185                         'blocked' => 0,
186                         'account_expired' => 0,
187                         'account_removed' => 0,
188                 ]
189         );      
190         
191         if ($user === False)
192                 throw new NotFoundException();
193         
194         $seed = PConfig::get(local_user(), "catavatar", "seed", md5(trim(strtolower($user['email']))));
195         //echo "<pre>"; var_dump($hash); killme();
196
197         
198         // from cat-avatar-generator.php
199
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)
205
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);
213                 exit;
214         }
215
216         // ...Or start generation
217         ob_start(); 
218
219         // render the picture:
220         build_cat($seed, $size);
221
222         // Save/cache the output to a file
223         if ($cachefile!=""){
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());
226                 fclose($savedfile);
227                 chmod($cachefile, 0755);
228         }
229         ob_end_flush();
230
231         killme();
232 }
233
234
235
236 /**
237  * ====================
238  * CAT-AVATAR-GENERATOR
239  * ====================
240  * 
241  * @authors: Andreas Gohr, David Revoy
242  * 
243  * This PHP is licensed under the short and simple permissive:
244  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
245  * 
246 **/
247
248 function build_cat($seed='', $size=0){
249
250         // init random seed
251         if($seed) srand( hexdec(substr(md5($seed),0,6)) );
252
253         // throw the dice for body parts
254         $parts = array(
255                 'body' => rand(1,15),
256                 'fur' => rand(1,10),
257                 'eyes' => rand(1,15),
258                 'mouth' => rand(1,10),
259                 'accessorie' => rand(1,20)
260         );
261
262         // create backgound
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);
267
268         // add parts
269         foreach($parts as $part => $num){
270                 $file = dirname(__FILE__).'/avatars/'.$part.'_'.$num.'.png';
271
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);
276                 imagedestroy($im);
277         }
278
279         // scale image
280         if ($size > 3 && $size < 7) {
281                 switch($size) {
282                         case 4: $size = 175; break;
283                         case 5: $size = 80; break;
284                         case 6: $size = 48; break;
285                 }
286         
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);
291                 imagedestroy($cat);
292                 $cat = $dest;
293         }
294         
295         // restore random seed
296         if($seed) srand();
297
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);
303         imagedestroy($cat);
304 }
305
306