]> git.mxchange.org Git - friendica-addons.git/blob - catavatar/catavatar.php
Merge pull request 'CLD2: Use ISO-639-1 for the language detection' (#1433) from...
[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\Model\Profile;
19 use Friendica\Network\HTTPException\NotFoundException;
20
21 define("CATAVATAR_SIZE", 256);
22
23 /**
24  * Installs the addon hook
25  */
26 function catavatar_install()
27 {
28         Hook::register('avatar_lookup', __FILE__, 'catavatar_lookup');
29         Hook::register('addon_settings', __FILE__, 'catavatar_addon_settings');
30         Hook::register('addon_settings_post', __FILE__, 'catavatar_addon_settings_post');
31
32         Logger::notice('registered catavatar');
33 }
34
35 /**
36  * Cat avatar user settings page
37  */
38 function catavatar_addon_settings(array &$data)
39 {
40         if (!DI::userSession()->getLocalUserId()) {
41                 return;
42         }
43
44         $t    = Renderer::getMarkupTemplate('settings.tpl', 'addon/catavatar/');
45         $html = Renderer::replaceMacros($t, [
46                 '$uncache'      => time(),
47                 '$uid'          => DI::userSession()->getLocalUserId(),
48                 '$setrandomize' => DI::l10n()->t('Set default profile avatar or randomize the cat.'),
49         ]);
50
51         $data = [
52                 'addon'  => 'catavar',
53                 'title'  => DI::l10n()->t('Cat Avatar Settings'),
54                 'html'   => $html,
55                 'submit' => [
56                         'catavatar-usecat'   => DI::l10n()->t('Use Cat as Avatar'),
57                         'catavatar-morecat'  => DI::l10n()->t('Another random Cat!'),
58                         'catavatar-emailcat' => DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'catavatar', 'seed', false) ? DI::l10n()->t('Reset to email Cat') : null,
59                 ],
60         ];
61 }
62
63 /**
64  * Cat avatar user settings POST handle
65  */
66 function catavatar_addon_settings_post(&$s)
67 {
68         if (!DI::userSession()->getLocalUserId()) {
69                 return;
70         }
71
72         if (!empty($_POST['catavatar-usecat'])) {
73                 $url = DI::baseUrl() . '/catavatar/' . DI::userSession()->getLocalUserId() . '?ts=' . time();
74
75                 $self = DBA::selectFirst('contact', ['id'], ['uid' => DI::userSession()->getLocalUserId(), 'self' => true]);
76                 if (!DBA::isResult($self)) {
77                         DI::sysmsg()->addNotice(DI::l10n()->t("The cat hadn't found itself."));
78                         return;
79                 }
80
81                 Photo::importProfilePhoto($url, DI::userSession()->getLocalUserId(), $self['id']);
82
83                 $condition = ['uid' => DI::userSession()->getLocalUserId(), 'contact-id' => $self['id']];
84                 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
85                 if (!DBA::isResult($photo)) {
86                         DI::sysmsg()->addNotice(DI::l10n()->t('There was an error, the cat ran away.'));
87                         return;
88                 }
89
90                 DBA::update('photo', ['profile' => false], ['profile' => true, 'uid' => DI::userSession()->getLocalUserId()]);
91
92                 $fields = ['profile' => true, 'album' => DI::l10n()->t('Profile Photos'), 'contact-id' => 0];
93                 DBA::update('photo', $fields, ['uid' => DI::userSession()->getLocalUserId(), 'resource-id' => $photo['resource-id']]);
94
95                 Photo::importProfilePhoto($url, DI::userSession()->getLocalUserId(), $self['id']);
96
97                 Contact::updateSelfFromUserID(DI::userSession()->getLocalUserId(), true);
98
99                 // Update global directory in background
100                 Profile::publishUpdate(DI::userSession()->getLocalUserId());
101
102                 DI::sysmsg()->addInfo(DI::l10n()->t('Meow!'));
103                 return;
104         }
105
106         if (!empty($_POST['catavatar-morecat'])) {
107                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'catavatar', 'seed', time());
108         }
109
110         if (!empty($_POST['catavatar-emailcat'])) {
111                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'catavatar', 'seed');
112         }
113 }
114
115 /**
116  * Returns the URL to the cat avatar
117  *
118  * @param &$b array
119  */
120 function catavatar_lookup(array &$b)
121 {
122         $user = DBA::selectFirst('user', ['uid'], ['email' => $b['email']]);
123         if (DBA::isResult($user)) {
124                 $url = DI::baseUrl() . '/catavatar/' . $user['uid'];
125         } else {
126                 $url = DI::baseUrl() . '/catavatar/' . 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 catavatar_module() {}
145
146 /**
147  * Returns image for user id
148  *
149  * @throws NotFoundException
150  *
151  */
152 function catavatar_content()
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, "catavatar", "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         // ...Or start generation
181         ob_start();
182
183         // render the picture:
184         build_cat($seed, $size);
185
186         ob_end_flush();
187
188         exit();
189 }
190
191 /**
192  * ====================
193  * CAT-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_cat($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 = array(
212                 'body' => rand(1, 15),
213                 'fur' => rand(1, 10),
214                 'eyes' => rand(1, 15),
215                 'mouth' => rand(1, 10),
216                 'accessorie' => rand(1, 20)
217         );
218
219         // create backgound
220         $cat = @imagecreatetruecolor(CATAVATAR_SIZE, CATAVATAR_SIZE)
221                 or die("GD image create failed");
222         $white = imagecolorallocate($cat, 255, 255, 255);
223         imagefill($cat, 0, 0, $white);
224
225         // add parts
226         foreach ($parts as $part => $num) {
227                 $file = dirname(__FILE__) . '/avatars/' . $part . '_' . $num . '.png';
228
229                 $im = @imagecreatefrompng($file);
230                 if (!$im) {
231                         die('Failed to load ' . $file);
232                 }
233                 imageSaveAlpha($im, true);
234                 imagecopy($cat, $im, 0, 0, 0, 0, CATAVATAR_SIZE, CATAVATAR_SIZE);
235                 imagedestroy($im);
236         }
237
238         // scale image
239         if ($size > 3 && $size < 7) {
240                 switch ($size) {
241                         case 4:
242                                 $size = 300;
243                                 break;
244                         case 5:
245                                 $size = 80;
246                                 break;
247                         case 6:
248                                 $size = 48;
249                                 break;
250                 }
251
252                 $dest = imagecreatetruecolor($size, $size);
253                 imagealphablending($dest, false);
254                 imagesavealpha($dest, true);
255                 imagecopyresampled($dest, $cat, 0, 0, 0, 0, $size, $size, CATAVATAR_SIZE, CATAVATAR_SIZE);
256                 imagedestroy($cat);
257                 $cat = $dest;
258         }
259
260         // restore random seed
261         if ($seed) {
262                 srand();
263         }
264
265         header('Pragma: public');
266         header('Cache-Control: max-age=86400');
267         header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
268         header('Content-Type: image/jpg');
269         imagejpeg($cat, NULL, 90);
270         imagedestroy($cat);
271 }