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