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