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