]> git.mxchange.org Git - friendica-addons.git/blob - langfilter/langfilter.php
Merge pull request #1007 from annando/notice-info
[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 function langfilter_uninstall()
29 {
30         Hook::unregister('prepare_body_content_filter', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body_content_filter');
31         Hook::unregister('prepare_body', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body');
32         Hook::unregister('addon_settings', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings');
33         Hook::unregister('addon_settings_post', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings_post');
34 }
35
36 /* The settings
37  * 1st check if somebody logged in is calling
38  * 2nd get the current settings
39  * 3rd parse a SMARTY3 template, replacing some translateable strings for the form
40  */
41
42 function langfilter_addon_settings(App $a, &$s)
43 {
44         if (!local_user()) {
45                 return;
46         }
47
48         $enabled = DI::pConfig()->get(local_user(), 'langfilter', 'enable',
49                 !DI::pConfig()->get(local_user(), 'langfilter', 'disable'));
50
51         $enable_checked = $enabled ? ' checked="checked"' : '';
52         $languages      = DI::pConfig()->get(local_user(), 'langfilter', 'languages');
53         $minconfidence  = DI::pConfig()->get(local_user(), 'langfilter', 'minconfidence', 0) * 100;
54         $minlength      = DI::pConfig()->get(local_user(), 'langfilter', 'minlength'    , 32);
55
56         $t = Renderer::getMarkupTemplate("settings.tpl", "addon/langfilter/");
57         $s .= Renderer::replaceMacros($t, [
58                 '$title'         => DI::l10n()->t("Language Filter"),
59                 '$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.'),
60                 '$enabled'       => ['langfilter_enable', DI::l10n()->t('Use the language filter'), $enable_checked, ''],
61                 '$languages'     => ['langfilter_languages', DI::l10n()->t('Able to read'), $languages, DI::l10n()->t('List of abbreviations (iso2 codes) for languages you speak, comma separated. For example "de,it".')],
62                 '$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.')],
63                 '$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).')],
64                 '$submit'        => DI::l10n()->t('Save Settings'),
65         ]);
66
67         return;
68 }
69
70 /* Save the settings
71  * 1st check it's a logged in user calling
72  * 2nd check the langfilter form is to be saved
73  * 3rd save the settings to the DB for later usage
74  */
75
76 function langfilter_addon_settings_post(App $a, &$b)
77 {
78         if (!local_user()) {
79                 return;
80         }
81
82         if (!empty($_POST['langfilter-settings-submit'])) {
83                 $enable        = intval($_POST['langfilter_enable'] ?? 0);
84                 $languages     = trim($_POST['langfilter_languages'] ?? '');
85                 $minconfidence = max(0, min(100, intval($_POST['langfilter_minconfidence'] ?? 0))) / 100;
86                 $minlength     = intval($_POST['langfilter_minlength'] ?? 32);
87                 if ($minlength <= 0) {
88                         $minlength = 32;
89                 }
90
91                 DI::pConfig()->set(local_user(), 'langfilter', 'enable'       , $enable);
92                 DI::pConfig()->set(local_user(), 'langfilter', 'languages'    , $languages);
93                 DI::pConfig()->set(local_user(), 'langfilter', 'minconfidence', $minconfidence);
94                 DI::pConfig()->set(local_user(), 'langfilter', 'minlength'    , $minlength);
95         }
96 }
97
98 /* Actually filter postings by their language
99  * 1st check if the user wants to filter postings
100  * 2nd get the user settings which languages shall be not filtered out
101  * 3rd extract the language of a posting
102  * 4th if the determined language does not fit to the spoken languages
103  *     of the user, then collapse the posting, but provide a link to
104  *     expand it again.
105  */
106
107 function langfilter_prepare_body_content_filter(App $a, &$hook_data)
108 {
109         $logged_user = local_user();
110         if (!$logged_user) {
111                 return;
112         }
113
114         // Never filter own messages
115         // TODO: find a better way to extract this
116         $logged_user_profile = DI::baseUrl()->get() . '/profile/' . $a->user['nickname'];
117         if ($logged_user_profile == $hook_data['item']['author-link']) {
118                 return;
119         }
120
121         // Don't filter if language filter is disabled
122         if (!DI::pConfig()->get($logged_user, 'langfilter', 'enable',
123                 !DI::pConfig()->get($logged_user, 'langfilter', 'disable'))
124         ) {
125                 return;
126         }
127
128         $naked_body = BBCode::toPlaintext($hook_data['item']['body'], false);
129
130         // Don't filter if body lenght is below minimum
131         $minlen = DI::pConfig()->get(local_user(), '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(local_user(), 'langfilter', 'languages');
141         $minconfidence = DI::pConfig()->get(local_user(), '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         // Extract the language of the post
150         if (!empty($hook_data['item']['language'])) {
151                 $languages = json_decode($hook_data['item']['language'], true);
152                 if (!is_array($languages)) {
153                         return;
154                 }
155
156                 foreach ($languages as $iso2 => $confidence) {
157                         break;
158                 }
159
160                 if (empty($iso2)) {
161                         return;
162                 }
163
164                 $lang = Text_LanguageDetect_ISO639::code2ToName($iso2);
165         } else {
166                 $opts = $hook_data['item']['postopts'];
167                 if (!$opts) {
168                         // no options associated to post
169                         return;
170                 }
171
172                 if (!preg_match('/\blang=([^;]*);([^:]*)/', $opts, $matches)) {
173                         // no lang options associated to post
174                         return;
175                 }
176
177                 $lang = $matches[1];
178                 $confidence = $matches[2];
179
180                 $iso2 = Text_LanguageDetect_ISO639::nameToCode2($lang);
181         }
182
183         // Do not filter if language detection confidence is too low
184         if ($minconfidence && $confidence < $minconfidence) {
185                 return;
186         }
187
188         if (!$iso2) {
189                 return;
190         }
191
192         if (!in_array($iso2, $read_languages_array)) {
193                 $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered language: %s', ucfirst($lang));
194         }
195 }