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