]> git.mxchange.org Git - friendica-addons.git/blob - birdavatar/birdavatar.php
Merge pull request 'translation updates' (#1448) from tobias/friendica-addons:2023121...
[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(array &$data)
38 {
39         if (!DI::userSession()->getLocalUserId()) {
40                 return;
41         }
42
43         $t    = Renderer::getMarkupTemplate('settings.tpl', 'addon/birdavatar/');
44         $html = Renderer::replaceMacros($t, [
45                 '$uncache'      => time(),
46                 '$uid'          => DI::userSession()->getLocalUserId(),
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(DI::userSession()->getLocalUserId(), '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(&$s)
66 {
67         if (!DI::userSession()->getLocalUserId()) {
68                 return;
69         }
70
71         if (!empty($_POST['birdavatar-usebird'])) {
72                 $url = DI::baseUrl() . '/birdavatar/' . DI::userSession()->getLocalUserId() . '?ts=' . time();
73
74                 $self = DBA::selectFirst('contact', ['id'], ['uid' => DI::userSession()->getLocalUserId(), 'self' => true]);
75                 if (!DBA::isResult($self)) {
76                         DI::sysmsg()->addNotice(DI::l10n()->t("The bird has not found itself."));
77                         return;
78                 }
79
80                 Photo::importProfilePhoto($url, DI::userSession()->getLocalUserId(), $self['id']);
81
82                 $condition = ['uid' => DI::userSession()->getLocalUserId(), 'contact-id' => $self['id']];
83                 $photo     = DBA::selectFirst('photo', ['resource-id'], $condition);
84                 if (!DBA::isResult($photo)) {
85                         DI::sysmsg()->addNotice(DI::l10n()->t('There was an error, the bird flew away.'));
86                         return;
87                 }
88
89                 DBA::update('photo', ['profile' => false], ['profile' => true, 'uid' => DI::userSession()->getLocalUserId()]);
90
91                 $fields = ['profile' => true, 'album' => DI::l10n()->t('Profile Photos'), 'contact-id' => 0];
92                 DBA::update('photo', $fields, ['uid' => DI::userSession()->getLocalUserId(), 'resource-id' => $photo['resource-id']]);
93
94                 Photo::importProfilePhoto($url, DI::userSession()->getLocalUserId(), $self['id']);
95
96                 Contact::updateSelfFromUserID(DI::userSession()->getLocalUserId(), true);
97
98                 // Update global directory in background
99                 Profile::publishUpdate(DI::userSession()->getLocalUserId());
100
101                 DI::sysmsg()->addInfo(DI::l10n()->t('Meow!'));
102                 return;
103         }
104
105         if (!empty($_POST['birdavatar-morebird'])) {
106                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'birdavatar', 'seed', time());
107         }
108
109         if (!empty($_POST['birdavatar-emailbird'])) {
110                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'birdavatar', 'seed');
111         }
112 }
113
114 /**
115  * Returns the URL to the bird avatar
116  *
117  * @param &$b array
118  */
119 function birdavatar_lookup(array &$b)
120 {
121         $user = DBA::selectFirst('user', ['uid'], ['email' => $b['email']]);
122         if (DBA::isResult($user)) {
123                 $url = DI::baseUrl() . '/birdavatar/' . $user['uid'];
124         } else {
125                 $url = DI::baseUrl() . '/birdavatar/' . md5(trim(strtolower($b['email'])));
126         }
127
128         switch ($b['size']) {
129                 case 300: $url .= "/4"; break;
130                 case 80: $url .= "/5"; break;
131                 case 48: $url .= "/6"; break;
132         }
133
134         $b['url']     = $url;
135         $b['success'] = true;
136 }
137
138 /**
139  * This is a statement rather than an actual function definition. The simple
140  * existence of this method is checked to figure out if the addon offers a
141  * module.
142  */
143 function birdavatar_module() {}
144
145 /**
146  * Returns image for user id
147  *
148  * @throws NotFoundException
149  *
150  */
151 function birdavatar_content()
152 {
153         if (DI::args()->getArgc() < 2 || DI::args()->getArgc() > 3) {
154                 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
155         }
156
157         if (is_numeric(DI::args()->getArgv()[1])) {
158                 $uid       = intval(DI::args()->getArgv()[1]);
159                 $condition = ['uid' => $uid,
160                         'account_expired'  => false, 'account_removed' => false];
161                 $user = DBA::selectFirst('user', ['email'], $condition);
162
163                 if ($user === false) {
164                         throw new NotFoundException();
165                 }
166
167                 $seed = DI::pConfig()->get($uid, "birdavatar", "seed", md5(trim(strtolower($user['email']))));
168         } elseif (!empty(DI::args()->getArgv()[1])) {
169                 $seed = DI::args()->getArgv()[1];
170         } else {
171                 throw new NotFoundException();
172         }
173
174         $size = 0;
175         if (DI::args()->getArgc() == 3) {
176                 $size = intval(DI::args()->getArgv()[2]);
177         }
178
179         // start generation
180         ob_start();
181
182         // render the picture:
183         build_bird($seed, $size);
184
185         ob_end_flush();
186
187         exit();
188 }
189
190 /**
191  * ====================
192  * BIRD-AVATAR-GENERATOR
193  * ====================
194  *
195  * @authors: Andreas Gohr, David Revoy
196  *
197  * This PHP is licensed under the short and simple permissive:
198  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
199  *
200  **/
201
202 function build_bird($seed = '', $size = 0)
203 {
204         // init random seed
205         if ($seed) {
206                 srand(hexdec(substr(md5($seed), 0, 6)));
207         }
208
209         // throw the dice for body parts
210         $parts = [
211                 'tail'       => rand(1,9),
212                 'hoop'       => rand(1,10),
213                 'body'       => rand(1,9),
214                 'wing'       => rand(1,9),
215                 'eyes'       => rand(1,9),
216                 'bec'        => rand(1,9),
217                 'accessorie' => rand(1,20)
218         ];
219
220         // create backgound
221         $bird = @imagecreatetruecolor(BIRDAVATAR_SIZE, BIRDAVATAR_SIZE)
222                 or die("GD image create failed");
223         $white = imagecolorallocate($bird, 255, 255, 255);
224         imagefill($bird, 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($bird, $im, 0, 0, 0, 0, BIRDAVATAR_SIZE, BIRDAVATAR_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) or die("GD image create failed");
254                 imagealphablending($dest, false);
255                 imagesavealpha($dest, true);
256                 imagecopyresampled($dest, $bird, 0, 0, 0, 0, $size, $size, BIRDAVATAR_SIZE, BIRDAVATAR_SIZE);
257                 imagedestroy($bird);
258                 $bird = $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($bird, null, 90);
271         imagedestroy($bird);
272 }