]> git.mxchange.org Git - friendica-addons.git/blob - birdavatar/birdavatar.php
[nsfw] Suppress warnings about failed regexp compilation
[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 (!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(App $a, &$s)
66 {
67         if (!DI::userSession()->getLocalUserId()) {
68                 return;
69         }
70
71         if (!empty($_POST['birdavatar-usebird'])) {
72                 $url = DI::baseUrl()->get() . '/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 $a array
118  * @param &$b array
119  */
120 function birdavatar_lookup(App $a, array &$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 /**
140  * This is a statement rather than an actual function definition. The simple
141  * existence of this method is checked to figure out if the addon offers a
142  * module.
143  */
144 function birdavatar_module() {}
145
146 /**
147  * Returns image for user id
148  *
149  * @throws NotFoundException
150  *
151  */
152 function birdavatar_content(App $a)
153 {
154         if (DI::args()->getArgc() < 2 || DI::args()->getArgc() > 3) {
155                 throw new NotFoundException(); // this should be catched on index and show default "not found" page.
156         }
157
158         if (is_numeric(DI::args()->getArgv()[1])) {
159                 $uid       = intval(DI::args()->getArgv()[1]);
160                 $condition = ['uid' => $uid,
161                         'account_expired'  => false, 'account_removed' => false];
162                 $user = DBA::selectFirst('user', ['email'], $condition);
163
164                 if ($user === false) {
165                         throw new NotFoundException();
166                 }
167
168                 $seed = DI::pConfig()->get($uid, "birdavatar", "seed", md5(trim(strtolower($user['email']))));
169         } elseif (!empty(DI::args()->getArgv()[1])) {
170                 $seed = DI::args()->getArgv()[1];
171         } else {
172                 throw new NotFoundException();
173         }
174
175         $size = 0;
176         if (DI::args()->getArgc() == 3) {
177                 $size = intval(DI::args()->getArgv()[2]);
178         }
179
180         // start generation
181         ob_start();
182
183         // render the picture:
184         build_bird($seed, $size);
185
186         ob_end_flush();
187
188         exit();
189 }
190
191 /**
192  * ====================
193  * BIRD-AVATAR-GENERATOR
194  * ====================
195  *
196  * @authors: Andreas Gohr, David Revoy
197  *
198  * This PHP is licensed under the short and simple permissive:
199  * [MIT License](https://en.wikipedia.org/wiki/MIT_License)
200  *
201  **/
202
203 function build_bird($seed = '', $size = 0)
204 {
205         // init random seed
206         if ($seed) {
207                 srand(hexdec(substr(md5($seed), 0, 6)));
208         }
209
210         // throw the dice for body parts
211         $parts = [
212                 'tail'       => rand(1,9),
213                 'hoop'       => rand(1,10),
214                 'body'       => rand(1,9),
215                 'wing'       => rand(1,9),
216                 'eyes'       => rand(1,9),
217                 'bec'        => rand(1,9),
218                 'accessorie' => rand(1,20)
219         ];
220
221         // create backgound
222         $bird = @imagecreatetruecolor(BIRDAVATAR_SIZE, BIRDAVATAR_SIZE)
223                 or die("GD image create failed");
224         $white = imagecolorallocate($bird, 255, 255, 255);
225         imagefill($bird, 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($bird, $im, 0, 0, 0, 0, BIRDAVATAR_SIZE, BIRDAVATAR_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) or die("GD image create failed");
255                 imagealphablending($dest, false);
256                 imagesavealpha($dest, true);
257                 imagecopyresampled($dest, $bird, 0, 0, 0, 0, $size, $size, BIRDAVATAR_SIZE, BIRDAVATAR_SIZE);
258                 imagedestroy($bird);
259                 $bird = $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($bird, null, 90);
272         imagedestroy($bird);
273 }