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