]> git.mxchange.org Git - friendica-addons.git/blob - catavatar/catavatar.php
9c1f2290f1f3851f630e7a8bfffafe4729f12742
[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 use Friendica\Model\Contact;
17 use Friendica\Model\Photo;
18 use Friendica\Database\DBM;
19
20 define("CATAVATAR_SIZE", 256);
21
22 /**
23  * Installs the addon hook
24  */
25 function catavatar_install()
26 {
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');
30
31         logger('registered catavatar');
32 }
33
34 /**
35  * Removes the addon hook
36  */
37 function catavatar_uninstall()
38 {
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');
42
43         logger('unregistered catavatar');
44 }
45
46 /**
47  * Cat avatar user settings page
48  */
49 function catavatar_addon_settings(App $a, &$s)
50 {
51         if (!local_user()) {
52                 return;
53         }
54
55         $t = get_markup_template('settings.tpl', 'addon/catavatar/');
56         $s .= replace_macros ($t, [
57                 '$postpost' => !empty($_POST['catavatar-morecat']) || !empty($_POST['catavatar-emailcat']),
58                 '$uncache' => time(),
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'),
65         ]);
66 }
67
68 /**
69  * Cat avatar user settings POST handle
70  */
71 function catavatar_addon_settings_post(App $a, &$s)
72 {
73         if (!local_user()) {
74                 return;
75         }
76
77         // delete the current cached cat avatar
78         $user = dba::selectFirst('user', ['email'],
79                 [
80                         'uid' => $uid,
81                         'blocked' => 0,
82                         'account_expired' => 0,
83                         'account_removed' => 0,
84                 ]
85         );
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)) {
91                 unlink($cachefile);
92         }
93
94
95         if (!empty($_POST['catavatar-usecat'])) {
96                 $url = $a->get_baseurl() . '/catavatar/' . local_user() . '?ts=' . time();
97
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."));
101                         return;
102                 }
103
104                 Photo::importProfilePhoto($url, local_user(), $self['id']);
105
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.'));
110                         return;
111                 }
112
113                 dba::update('photo', ['profile' => false], ['profile' => true, 'uid' => local_user()]);
114
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']]);
117
118                 Photo::importProfilePhoto($url, local_user(), $self['id']);
119
120                 Contact::updateSelfFromUserID(local_user(), true);
121
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);
126                 }
127
128                 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
129
130                 info(L10n::t('Meow!'));
131                 return;
132         }
133
134
135
136         if (!empty($_POST['catavatar-morecat'])) {
137                 PConfig::set(local_user(), 'catavatar', 'seed', time());
138         }
139
140         if (!empty($_POST['catavatar-emailcat'])) {
141                 PConfig::delete(local_user(), 'catavatar', 'seed');
142         }
143 }
144
145
146 /**
147  * Returns the URL to the cat avatar
148  *
149  * @param $a array
150  * @param &$b array
151  */
152 function catavatar_lookup(App $a, &$b)
153 {
154         $user = dba::selectFirst('user', ['uid'], ['email' => $b['email']]);
155         $url = $a->get_baseurl() . '/catavatar/' . $user['uid'];
156
157         switch($b['size']) {
158                 case 175: $url .= "/4"; break;
159                 case 80: $url .= "/5"; break;
160                 case 47: $url .= "/6"; break;
161         }
162
163         $b['url'] = $url;
164         $b['success'] = true;
165 }
166
167
168 function catavatar_module(){}
169
170
171 /**
172  * Returns image for user id
173  *
174  * @throws NotFoundException
175  *
176  */
177 function catavatar_content(App $a)
178 {
179         if ($a->argc < 2 || $a->argc > 3) {
180                 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
181         }
182
183         $uid = intval($a->argv[1]);
184
185         $size = 0;
186         if ($a->argc == 3) {
187                 $size = intval($a->argv[2]);
188         }
189
190         $user = dba::selectFirst('user', ['email'],
191                 [
192                         'uid' => $uid,
193                         'blocked' => 0,
194                         'account_expired' => 0,
195                         'account_removed' => 0,
196                 ]
197         );
198
199         if ($user === false) {
200                 throw new NotFoundException();
201         }
202
203         $seed = PConfig::get($uid, "catavatar", "seed", md5(trim(strtolower($user['email']))));
204
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)
211
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);
219                 exit();
220         }
221
222         // ...Or start generation
223         ob_start();
224
225         // render the picture:
226         build_cat($seed, $size);
227
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());
232                 fclose($savedfile);
233                 chmod($cachefile, 0755);
234         }
235
236         ob_end_flush();
237
238         exit();
239 }
240
241
242
243 /**
244  * ====================
245  * CAT-AVATAR-GENERATOR
246  * ====================
247  *
248  * @authors: Andreas Gohr, David Revoy
249  *
250  * This PHP is licensed under the short and simple permissive:
251  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
252  *
253 **/
254
255 function build_cat($seed='', $size=0){
256
257         // init random seed
258         if($seed) srand( hexdec(substr(md5($seed),0,6)) );
259
260         // throw the dice for body parts
261         $parts = array(
262                 'body' => rand(1,15),
263                 'fur' => rand(1,10),
264                 'eyes' => rand(1,15),
265                 'mouth' => rand(1,10),
266                 'accessorie' => rand(1,20)
267         );
268
269         // create backgound
270         $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
271                 or die("GD image create failed");
272         $white = imagecolorallocate($cat, 255, 255, 255);
273         imagefill($cat,0,0,$white);
274
275         // add parts
276         foreach($parts as $part => $num){
277                 $file = dirname(__FILE__).'/avatars/'.$part.'_'.$num.'.png';
278
279                 $im = @imagecreatefrompng($file);
280                 if(!$im) die('Failed to load '.$file);
281                 imageSaveAlpha($im, true);
282                 imagecopy($cat,$im,0,0,0,0,CATAVATAR_SIZE,CATAVATAR_SIZE);
283                 imagedestroy($im);
284         }
285
286         // scale image
287         if ($size > 3 && $size < 7) {
288                 switch($size) {
289                         case 4: $size = 175; break;
290                         case 5: $size = 80; break;
291                         case 6: $size = 48; break;
292                 }
293
294                 $dest = imagecreatetruecolor($size, $size);
295                 imagealphablending($dest, false);
296                 imagesavealpha($dest, true);
297                 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
298                 imagedestroy($cat);
299                 $cat = $dest;
300         }
301
302         // restore random seed
303         if ($seed) {
304                 srand();
305         }
306
307         header('Pragma: public');
308         header('Cache-Control: max-age=86400');
309         header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
310         header('Content-Type: image/jpg');
311         imagejpeg($cat, NULL, 90);
312         imagedestroy($cat);
313 }
314
315