]> git.mxchange.org Git - friendica-addons.git/blob - langfilter/langfilter.php
invidious/invidious.php aktualisiert
[friendica-addons.git] / langfilter / langfilter.php
1 <?php
2 /*
3  * Name: Language Filter
4  * Version: 0.1
5  * Description: Filters out postings in languages not spoken by the users
6  * Author: Tobias Diekershoff <https://f.diekershoff.de/u/tobias>
7  * License: MIT
8  */
9
10 use Friendica\App;
11 use Friendica\Content\Text\BBCode;
12 use Friendica\Core\Hook;
13 use Friendica\Core\Renderer;
14 use Friendica\DI;
15
16 /* Define the hooks we want to use
17  * that is, we have settings, we need to save the settings and we want
18  * to modify the content of a posting when friendica prepares it.
19  */
20
21 function langfilter_install()
22 {
23         Hook::register('prepare_body_content_filter', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body_content_filter', 10);
24         Hook::register('addon_settings', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings');
25         Hook::register('addon_settings_post', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings_post');
26 }
27
28 /* The settings
29  * 1st check if somebody logged in is calling
30  * 2nd get the current settings
31  * 3rd parse a SMARTY3 template, replacing some translateable strings for the form
32  */
33
34 function langfilter_addon_settings(array &$data)
35 {
36         if (!DI::userSession()->getLocalUserId()) {
37                 return;
38         }
39
40         $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'enable',
41                 !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'disable'));
42
43         $languages     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'languages');
44         $minconfidence = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'minconfidence', 0) * 100;
45         $minlength     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'minlength', 32);
46
47         $t    = Renderer::getMarkupTemplate('settings.tpl', 'addon/langfilter/');
48         $html = Renderer::replaceMacros($t, [
49                 '$intro'         => DI::l10n()->t('This addon tries to identify the language posts are written in. If it does not match any language specified below, posts will be hidden by collapsing them.'),
50                 '$enabled'       => ['langfilter_enable', DI::l10n()->t('Use the language filter'), $enabled],
51                 '$languages'     => ['langfilter_languages', DI::l10n()->t('Able to read'), $languages, DI::l10n()->t('List of abbreviations (ISO 639-1 codes) for languages you speak, comma separated. For example "de,it".')],
52                 '$minconfidence' => ['langfilter_minconfidence', DI::l10n()->t('Minimum confidence in language detection'), $minconfidence, DI::l10n()->t('Minimum confidence in language detection being correct, from 0 to 100. Posts will not be filtered when the confidence of language detection is below this percent value.')],
53                 '$minlength'     => ['langfilter_minlength', DI::l10n()->t('Minimum length of message body'), $minlength, DI::l10n()->t('Minimum number of characters in message body for filter to be used. Posts shorter than this will not be filtered. Note: Language detection is unreliable for short content (<200 characters).')],
54         ]);
55
56         $data = [
57                 'addon'  => 'langfilter',
58                 'title'  => DI::l10n()->t('Language Filter'),
59                 'html'   => $html,
60                 'submit' => ['langfilter-settings-submit' => DI::l10n()->t('Save Settings')],
61         ];
62 }
63
64 /* Save the settings
65  * 1st check it's a logged in user calling
66  * 2nd check the langfilter form is to be saved
67  * 3rd save the settings to the DB for later usage
68  */
69
70 function langfilter_addon_settings_post(array &$b)
71 {
72         if (!DI::userSession()->getLocalUserId()) {
73                 return;
74         }
75
76         if (!empty($_POST['langfilter-settings-submit'])) {
77                 $enable        = intval($_POST['langfilter_enable'] ?? 0);
78                 $languages     = trim($_POST['langfilter_languages'] ?? '');
79                 $minconfidence = max(0, min(100, intval($_POST['langfilter_minconfidence'] ?? 0))) / 100;
80                 $minlength     = intval($_POST['langfilter_minlength'] ?? 32);
81                 if ($minlength <= 0) {
82                         $minlength = 32;
83                 }
84
85                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'langfilter', 'enable'       , $enable);
86                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'langfilter', 'languages'    , $languages);
87                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'langfilter', 'minconfidence', $minconfidence);
88                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'langfilter', 'minlength'    , $minlength);
89         }
90 }
91
92 /* Actually filter postings by their language
93  * 1st check if the user wants to filter postings
94  * 2nd get the user settings which languages shall be not filtered out
95  * 3rd extract the language of a posting
96  * 4th if the determined language does not fit to the spoken languages
97  *     of the user, then collapse the posting, but provide a link to
98  *     expand it again.
99  */
100
101 function langfilter_prepare_body_content_filter(&$hook_data)
102 {
103         $logged_user = DI::userSession()->getLocalUserId();
104         if (!$logged_user) {
105                 return;
106         }
107
108         // Never filter own messages
109         // TODO: find a better way to extract this
110         $logged_user_profile = DI::baseUrl() . '/profile/' . DI::userSession()->getLocalUserNickname();
111         if ($logged_user_profile == $hook_data['item']['author-link']) {
112                 return;
113         }
114
115         // Don't filter if language filter is disabled
116         if (!DI::pConfig()->get($logged_user, 'langfilter', 'enable',
117                 !DI::pConfig()->get($logged_user, 'langfilter', 'disable'))
118         ) {
119                 return;
120         }
121
122         $naked_body = strip_tags(
123                 $hook_data['item']['rendered-html']
124                 ??''?: // Equivalent of !empty()
125                 BBCode::convertForUriId($hook_data['item']['uri-id'], $hook_data['item']['body'], BBCode::ACTIVITYPUB)
126         );
127
128         $naked_body = preg_replace('#\s+#', ' ', trim($naked_body));
129
130         // Don't filter if body lenght is below minimum
131         $minlen = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'minlength', 32);
132         if (!$minlen) {
133                 $minlen = 32;
134         }
135
136         if (strlen($naked_body) < $minlen) {
137                 return;
138         }
139
140         $read_languages_string = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'languages');
141         $minconfidence = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'langfilter', 'minconfidence');
142
143         // Don't filter if no spoken languages are configured
144         if (!$read_languages_string) {
145                 return;
146         }
147         $read_languages_array = explode(',', $read_languages_string);
148
149         $iso639 = new Matriphe\ISO639\ISO639;
150
151         // Extract the language of the post
152         if (!empty($hook_data['item']['language'])) {
153                 $languages = json_decode($hook_data['item']['language'], true);
154                 if (!is_array($languages)) {
155                         return;
156                 }
157
158                 foreach ($languages as $iso2 => $confidence) {
159                         break;
160                 }
161
162                 if (empty($iso2)) {
163                         return;
164                 }
165
166                 $lang = $iso639->languageByCode1(substr($iso2, 0, 2));
167         } else {
168                 $opts = $hook_data['item']['postopts'];
169                 if (!$opts) {
170                         // no options associated to post
171                         return;
172                 }
173
174                 if (!preg_match('/\blang=([^;]*);([^:]*)/', $opts, $matches)) {
175                         // no lang options associated to post
176                         return;
177                 }
178
179                 $lang = $matches[1];
180                 $confidence = $matches[2];
181
182                 $iso2 = $iso639->code1ByLanguage($lang);
183         }
184
185         // Do not filter if language detection confidence is too low
186         if ($minconfidence && $confidence < $minconfidence) {
187                 return;
188         }
189
190         if (!$iso2) {
191                 return;
192         }
193
194         if (!in_array($iso2, $read_languages_array)) {
195                 $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered language: %s', ucfirst($lang));
196         }
197 }