Simplified code
[friendica-addons.git/.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
9 use Friendica\App;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Renderer;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
15 use Friendica\DI;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Photo;
18 use Friendica\Network\HTTPException\NotFoundException;
19
20 define("CATAVATAR_SIZE", 256);
21
22 /**
23  * Installs the addon hook
24  */
25 function catavatar_install()
26 {
27         Hook::register('avatar_lookup', 'addon/catavatar/catavatar.php', 'catavatar_lookup');
28         Hook::register('addon_settings', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings');
29         Hook::register('addon_settings_post', 'addon/catavatar/catavatar.php', 'catavatar_addon_settings_post');
30
31         Logger::log('registered catavatar');
32 }
33
34 /**
35  * Cat avatar user settings page
36  */
37 function catavatar_addon_settings(App $a, &$s)
38 {
39         if (!local_user()) {
40                 return;
41         }
42
43         $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/catavatar/');
44         $s .= Renderer::replaceMacros($t, [
45                 '$postpost' => !empty($_POST['catavatar-morecat']) || !empty($_POST['catavatar-emailcat']),
46                 '$uncache' => time(),
47                 '$uid' => local_user(),
48                 '$usecat' => DI::l10n()->t('Use Cat as Avatar'),
49                 '$morecat' => DI::l10n()->t('More Random Cat!'),
50                 '$emailcat' => DI::l10n()->t('Reset to email Cat'),
51                 '$seed' => DI::pConfig()->get(local_user(), 'catavatar', 'seed', false),
52                 '$header' => DI::l10n()->t('Cat Avatar Settings'),
53         ]);
54 }
55
56 /**
57  * Cat avatar user settings POST handle
58  */
59 function catavatar_addon_settings_post(App $a, &$s)
60 {
61         if (!local_user()) {
62                 return;
63         }
64
65         // delete the current cached cat avatar
66         $condition = ['uid' => local_user(), 'blocked' => false,
67                         'account_expired' => false, 'account_removed' => false];
68         $user = DBA::selectFirst('user', ['email'], $condition);
69
70         $seed = DI::pConfig()->get(local_user(), 'catavatar', 'seed', md5(trim(strtolower($user['email']))));
71
72         if (!empty($_POST['catavatar-usecat'])) {
73                 $url = DI::baseUrl()->get() . '/catavatar/' . local_user() . '?ts=' . time();
74
75                 $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
76                 if (!DBA::isResult($self)) {
77                         notice(DI::l10n()->t("The cat hadn't found itself."));
78                         return;
79                 }
80
81                 Photo::importProfilePhoto($url, local_user(), $self['id']);
82
83                 $condition = ['uid' => local_user(), 'contact-id' => $self['id']];
84                 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
85                 if (!DBA::isResult($photo)) {
86                         notice(DI::l10n()->t('There was an error, the cat ran away.'));
87                         return;
88                 }
89
90                 DBA::update('photo', ['profile' => false], ['profile' => true, 'uid' => local_user()]);
91
92                 $fields = ['profile' => true, 'album' => DI::l10n()->t('Profile Photos'), 'contact-id' => 0];
93                 DBA::update('photo', $fields, ['uid' => local_user(), 'resource-id' => $photo['resource-id']]);
94
95                 Photo::importProfilePhoto($url, local_user(), $self['id']);
96
97                 Contact::updateSelfFromUserID(local_user(), true);
98
99                 // Update global directory in background
100                 $url = DI::baseUrl()->get() . '/profile/' . $a->user['nickname'];
101                 if ($url && strlen(DI::config()->get('system', 'directory'))) {
102                         Worker::add(PRIORITY_LOW, 'Directory', $url);
103                 }
104
105                 Worker::add(PRIORITY_LOW, 'ProfileUpdate', local_user());
106
107                 info(DI::l10n()->t('Meow!'));
108                 return;
109         }
110
111         if (!empty($_POST['catavatar-morecat'])) {
112                 DI::pConfig()->set(local_user(), 'catavatar', 'seed', time());
113         }
114
115         if (!empty($_POST['catavatar-emailcat'])) {
116                 DI::pConfig()->delete(local_user(), 'catavatar', 'seed');
117         }
118 }
119
120 /**
121  * Returns the URL to the cat avatar
122  *
123  * @param $a array
124  * @param &$b array
125  */
126 function catavatar_lookup(App $a, &$b)
127 {
128         $user = DBA::selectFirst('user', ['uid'], ['email' => $b['email']]);
129         if (DBA::isResult($user)) {
130                 $url = DI::baseUrl()->get() . '/catavatar/' . $user['uid'];
131         } else {
132                 $url = DI::baseUrl()->get() . '/catavatar/' . md5(trim(strtolower($b['email'])));
133         }
134
135         switch($b['size']) {
136                 case 300: $url .= "/4"; break;
137                 case 80: $url .= "/5"; break;
138                 case 48: $url .= "/6"; break;
139         }
140
141         $b['url'] = $url;
142         $b['success'] = true;
143 }
144
145 function catavatar_module() {}
146
147 /**
148  * Returns image for user id
149  *
150  * @throws NotFoundException
151  *
152  */
153 function catavatar_content(App $a)
154 {
155         if ($a->argc < 2 || $a->argc > 3) {
156                 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
157         }
158
159         if (is_numeric($a->argv[1])) {
160                 $uid = intval($a->argv[1]);
161                 $condition = ['uid' => $uid,
162                                 'account_expired' => false, 'account_removed' => false];
163                 $user = DBA::selectFirst('user', ['email'], $condition);
164
165                 if ($user === false) {
166                         throw new NotFoundException();
167                 }
168
169                 $seed = DI::pConfig()->get($uid, "catavatar", "seed", md5(trim(strtolower($user['email']))));
170         } elseif (!empty($a->argv[1])) {
171                 $seed = $a->argv[1];
172         } else {
173                 throw new NotFoundException();
174         }
175
176         $size = 0;
177         if ($a->argc == 3) {
178                 $size = intval($a->argv[2]);
179         }
180
181         // ...Or start generation
182         ob_start();
183
184         // render the picture:
185         build_cat($seed, $size);
186
187         ob_end_flush();
188
189         exit();
190 }
191
192 /**
193  * ====================
194  * CAT-AVATAR-GENERATOR
195  * ====================
196  *
197  * @authors: Andreas Gohr, David Revoy
198  *
199  * This PHP is licensed under the short and simple permissive:
200  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
201  *
202 **/
203
204 function build_cat($seed = '', $size = 0)
205 {
206         // init random seed
207         if ($seed) {
208                 srand(hexdec(substr(md5($seed), 0, 6)));
209         }
210
211         // throw the dice for body parts
212         $parts = array(
213                 'body' => rand(1, 15),
214                 'fur' => rand(1, 10),
215                 'eyes' => rand(1, 15),
216                 'mouth' => rand(1, 10),
217                 'accessorie' => rand(1, 20)
218         );
219
220         // create backgound
221         $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
222                 or die("GD image create failed");
223         $white = imagecolorallocate($cat, 255, 255, 255);
224         imagefill($cat, 0, 0, $white);
225
226         // add parts
227         foreach ($parts as $part => $num) {
228                 $file = dirname(__FILE__) . '/avatars/' . $part . '_' . $num . '.png';
229
230                 $im = @imagecreatefrompng($file);
231                 if (!$im) {
232                         die('Failed to load ' . $file);
233                 }
234                 imageSaveAlpha($im, true);
235                 imagecopy($cat, $im, 0, 0, 0, 0, CATAVATAR_SIZE, CATAVATAR_SIZE);
236                 imagedestroy($im);
237         }
238
239         // scale image
240         if ($size > 3 && $size < 7) {
241                 switch ($size) {
242                         case 4:
243                                 $size = 300;
244                                 break;
245                         case 5:
246                                 $size = 80;
247                                 break;
248                         case 6:
249                                 $size = 48;
250                                 break;
251                 }
252
253                 $dest = imagecreatetruecolor($size, $size);
254                 imagealphablending($dest, false);
255                 imagesavealpha($dest, true);
256                 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
257                 imagedestroy($cat);
258                 $cat = $dest;
259         }
260
261         // restore random seed
262         if ($seed) {
263                 srand();
264         }
265
266         header('Pragma: public');
267         header('Cache-Control: max-age=86400');
268         header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
269         header('Content-Type: image/jpg');
270         imagejpeg($cat, NULL, 90);
271         imagedestroy($cat);
272 }