]> git.mxchange.org Git - friendica-addons.git/blob - langfilter/langfilter.php
abd3c7045783e82155a3bd9627aa059642861f53
[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 require __DIR__ . '/vendor/autoload.php';
17
18 /* Define the hooks we want to use
19  * that is, we have settings, we need to save the settings and we want
20  * to modify the content of a posting when friendica prepares it.
21  */
22
23 function langfilter_install()
24 {
25         Hook::register('prepare_body_content_filter', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body_content_filter', 10);
26         Hook::register('addon_settings', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings');
27         Hook::register('addon_settings_post', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings_post');
28 }
29
30 /* The settings
31  * 1st check if somebody logged in is calling
32  * 2nd get the current settings
33  * 3rd parse a SMARTY3 template, replacing some translateable strings for the form
34  */
35
36 function langfilter_addon_settings(App $a, &$s)
37 {
38         if (!local_user()) {
39                 return;
40         }
41
42         $enabled = DI::pConfig()->get(local_user(), 'langfilter', 'enable',
43                 !DI::pConfig()->get(local_user(), 'langfilter', 'disable'));
44
45         $enable_checked = $enabled ? ' checked="checked"' : '';
46         $languages      = DI::pConfig()->get(local_user(), 'langfilter', 'languages');
47         $minconfidence  = DI::pConfig()->get(local_user(), 'langfilter', 'minconfidence', 0) * 100;
48         $minlength      = DI::pConfig()->get(local_user(), 'langfilter', 'minlength'    , 32);
49
50         $t = Renderer::getMarkupTemplate("settings.tpl", "addon/langfilter/");
51         $s .= Renderer::replaceMacros($t, [
52                 '$title'         => DI::l10n()->t("Language Filter"),
53                 '$intro'         => DI::l10n()->t('This addon tries to identify the language posts are writen in. If it does not match any language specifed below, posts will be hidden by collapsing them.'),
54                 '$enabled'       => ['langfilter_enable', DI::l10n()->t('Use the language filter'), $enable_checked, ''],
55                 '$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".')],
56                 '$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.')],
57                 '$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).')],
58                 '$submit'        => DI::l10n()->t('Save Settings'),
59         ]);
60
61         return;
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(App $a, &$b)
71 {
72         if (!local_user()) {
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(local_user(), 'langfilter', 'enable'       , $enable);
86                 DI::pConfig()->set(local_user(), 'langfilter', 'languages'    , $languages);
87                 DI::pConfig()->set(local_user(), 'langfilter', 'minconfidence', $minconfidence);
88                 DI::pConfig()->set(local_user(), '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(App $a, &$hook_data)
102 {
103         $logged_user = local_user();
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()->get() . '/profile/' . $a->user['nickname'];
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 = BBCode::toPlaintext($hook_data['item']['body'], false);
123
124         // Don't filter if body lenght is below minimum
125         $minlen = DI::pConfig()->get(local_user(), 'langfilter', 'minlength', 32);
126         if (!$minlen) {
127                 $minlen = 32;
128         }
129
130         if (strlen($naked_body) < $minlen) {
131                 return;
132         }
133
134         $read_languages_string = DI::pConfig()->get(local_user(), 'langfilter', 'languages');
135         $minconfidence = DI::pConfig()->get(local_user(), 'langfilter', 'minconfidence');
136
137         // Don't filter if no spoken languages are configured
138         if (!$read_languages_string) {
139                 return;
140         }
141         $read_languages_array = explode(',', $read_languages_string);
142
143         $iso639 = new Matriphe\ISO639\ISO639;
144
145         // Extract the language of the post
146         if (!empty($hook_data['item']['language'])) {
147                 $languages = json_decode($hook_data['item']['language'], true);
148                 if (!is_array($languages)) {
149                         return;
150                 }
151
152                 foreach ($languages as $iso2 => $confidence) {
153                         break;
154                 }
155
156                 if (empty($iso2)) {
157                         return;
158                 }
159
160                 $lang = $iso639->languageByCode1($iso2);
161         } else {
162                 $opts = $hook_data['item']['postopts'];
163                 if (!$opts) {
164                         // no options associated to post
165                         return;
166                 }
167
168                 if (!preg_match('/\blang=([^;]*);([^:]*)/', $opts, $matches)) {
169                         // no lang options associated to post
170                         return;
171                 }
172
173                 $lang = $matches[1];
174                 $confidence = $matches[2];
175
176                 $iso2 = $iso639->code1ByLanguage($lang);
177         }
178
179         // Do not filter if language detection confidence is too low
180         if ($minconfidence && $confidence < $minconfidence) {
181                 return;
182         }
183
184         if (!$iso2) {
185                 return;
186         }
187
188         if (!in_array($iso2, $read_languages_array)) {
189                 $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered language: %s', ucfirst($lang));
190         }
191 }