]> git.mxchange.org Git - friendica-addons.git/blob - catavatar/catavatar.php
3a29cc69c3786a5b65c735f750806229fec521fe
[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\App;
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
17 define("CATAVATAR_SIZE", 256);
18
19 /**
20  * Installs the addon hook
21  */
22 function catavatar_install()
23 {
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');
27
28         logger('registered catavatar');
29 }
30
31 /**
32  * Removes the addon hook
33  */
34 function catavatar_uninstall()
35 {
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');
39
40         logger('unregistered catavatar');
41 }
42
43 /**
44  * Cat avatar user settings page
45  */
46 function catavatar_addon_settings(App $a, &$s)
47 {
48         if (!local_user()) {
49                 return;
50         }
51
52         $t = get_markup_template('settings.tpl', 'addon/catavatar/');
53         $s = replace_macros ($t, [
54                 '$postpost' => !empty($_POST['catavatar-morecat']) || !empty($_POST['catavatar-emailcat']),
55                 '$uncache' => time(),
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'),
62         ]);
63 }
64
65 /**
66  * Cat avatar user settings POST handle
67  */
68 function catavatar_addon_settings_post(App $a, &$s)
69 {
70         if (!local_user()) {
71                 return;
72         }
73
74         // delete the current cached cat avatar
75         $user = dba::selectFirst('user', ['email'],
76                 [
77                         'uid' => $uid,
78                         'blocked' => 0,
79                         'account_expired' => 0,
80                         'account_removed' => 0,
81                 ]
82         );
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)) {
88                 unlink($cachefile);
89         }
90
91
92         if (!empty($_POST['catavatar-usecat'])) {
93                 $url = $a->get_baseurl() . '/catavatar/' . local_user();
94
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]
101                 );
102                 if ($r===false) {
103                         notice(L10n::t('There was an error, the cat ran away.'));
104                         return;
105                 }
106
107                 $r = dba::update('profile',
108                         ['photo' => $url . '/4', 'thumb' => $url . '/5'],
109                         ['uid' => local_user(), 'is-default' => 1]
110                 );
111                 if ($r===false) {
112                         notice(L10n::t('There was an error, the cat ran away.'));
113                         return;
114                 }
115
116                 $r = dba::update('photo',
117                         ['profile' => 0],
118                         ['uid' => local_user(), 'profile' => 1]
119                 );
120                 if ($r === false) {
121                         notice(L10n::t('There was an error, the cat ran away.'));
122                         return;
123                 }
124
125
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);
130                 }
131
132                 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
133
134                 info(L10n::t('Meow!'));
135                 return;
136         }
137
138
139
140         if (!empty($_POST['catavatar-morecat'])) {
141                 PConfig::set(local_user(), 'catavatar', 'seed', time());
142         }
143
144         if (!empty($_POST['catavatar-emailcat'])) {
145                 PConfig::delete(local_user(), 'catavatar', 'seed');
146         }
147 }
148
149
150 /**
151  * Returns the URL to the cat avatar
152  *
153  * @param $a array
154  * @param &$b array
155  */
156 function catavatar_lookup(App $a, &$b)
157 {
158         $user = dba::selectFirst('user', ['uid'], ['email' => $b['email']]);
159         $url = $a->get_baseurl() . '/catavatar/' . $user['uid'];
160
161         switch($b['size']) {
162                 case 175: $url .= "/4"; break;
163                 case 80: $url .= "/5"; break;
164                 case 47: $url .= "/6"; break;
165         }
166
167         $b['url'] = $url;
168         $b['success'] = true;
169 }
170
171
172 function catavatar_module(){}
173
174
175 /**
176  * Returns image for user id
177  *
178  * @throws NotFoundException
179  *
180  */
181 function catavatar_content(App $a)
182 {
183         if ($a->argc < 2 || $a->argc > 3) {
184                 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
185         }
186
187         $uid = intval($a->argv[1]);
188
189         $size = 0;
190         if ($a->argc == 3) {
191                 $size = intval($a->argv[2]);
192         }
193
194         $user = dba::selectFirst('user', ['email'],
195                 [
196                         'uid' => $uid,
197                         'blocked' => 0,
198                         'account_expired' => 0,
199                         'account_removed' => 0,
200                 ]
201         );
202
203         if ($user === false) {
204                 throw new NotFoundException();
205         }
206
207         $seed = PConfig::get(local_user(), "catavatar", "seed", md5(trim(strtolower($user['email']))));
208
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)
215
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);
223                 exit();
224         }
225
226         // ...Or start generation
227         ob_start();
228
229         // render the picture:
230         build_cat($seed, $size);
231
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());
236                 fclose($savedfile);
237                 chmod($cachefile, 0755);
238         }
239
240         ob_end_flush();
241
242         exit();
243 }
244
245
246
247 /**
248  * ====================
249  * CAT-AVATAR-GENERATOR
250  * ====================
251  *
252  * @authors: Andreas Gohr, David Revoy
253  *
254  * This PHP is licensed under the short and simple permissive:
255  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
256  *
257 **/
258
259 function build_cat($seed='', $size=0){
260
261         // init random seed
262         if($seed) srand( hexdec(substr(md5($seed),0,6)) );
263
264         // throw the dice for body parts
265         $parts = array(
266                 'body' => rand(1,15),
267                 'fur' => rand(1,10),
268                 'eyes' => rand(1,15),
269                 'mouth' => rand(1,10),
270                 'accessorie' => rand(1,20)
271         );
272
273         // create backgound
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);
278
279         // add parts
280         foreach($parts as $part => $num){
281                 $file = dirname(__FILE__).'/avatars/'.$part.'_'.$num.'.png';
282
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);
287                 imagedestroy($im);
288         }
289
290         // scale image
291         if ($size > 3 && $size < 7) {
292                 switch($size) {
293                         case 4: $size = 175; break;
294                         case 5: $size = 80; break;
295                         case 6: $size = 48; break;
296                 }
297
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);
302                 imagedestroy($cat);
303                 $cat = $dest;
304         }
305
306         // restore random seed
307         if ($seed) {
308                 srand();
309         }
310
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);
316         imagedestroy($cat);
317 }
318
319