Merge pull request #727 from annando/still-notices
[friendica-addons.git/.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\Addon;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
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         Addon::registerHook('prepare_body_content_filter', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body_content_filter', 10);
24         Addon::registerHook('addon_settings', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings');
25         Addon::registerHook('addon_settings_post', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings_post');
26 }
27
28 function langfilter_uninstall()
29 {
30         Addon::unregisterHook('prepare_body_content_filter', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body_content_filter');
31         Addon::unregisterHook('prepare_body', 'addon/langfilter/langfilter.php', 'langfilter_prepare_body');
32         Addon::unregisterHook('addon_settings', 'addon/langfilter/langfilter.php', 'langfilter_addon_settings');
33         Addon::unregisterHook('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         $enable_checked = (intval(PConfig::get(local_user(), 'langfilter', 'disable')) ? '' : ' checked="checked" ');
49         $languages      = PConfig::get(local_user(), 'langfilter', 'languages');
50         $minconfidence  = PConfig::get(local_user(), 'langfilter', 'minconfidence') * 100;
51         $minlength      = PConfig::get(local_user(), 'langfilter', 'minlength');
52
53         $t = get_markup_template("settings.tpl", "addon/langfilter/");
54         $s .= replace_macros($t, [
55                 '$title'         => L10n::t("Language Filter"),
56                 '$intro'         => 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.'),
57                 '$enabled'       => ['langfilter_enable', L10n::t('Use the language filter'), $enable_checked, ''],
58                 '$languages'     => ['langfilter_languages', L10n::t('Able to read'), $languages, L10n::t('List of abbreviations (iso2 codes) for languages you speak, comma separated. For example "de,it".')],
59                 '$minconfidence' => ['langfilter_minconfidence', L10n::t('Minimum confidence in language detection'), $minconfidence, 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.')],
60                 '$minlength'     => ['langfilter_minlength', L10n::t('Minimum length of message body'), $minlength, 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).')],
61                 '$submit'        => L10n::t('Save Settings'),
62         ]);
63
64         return;
65 }
66
67 /* Save the settings
68  * 1st check it's a logged in user calling
69  * 2nd check the langfilter form is to be saved
70  * 3rd save the settings to the DB for later usage
71  */
72
73 function langfilter_addon_settings_post(App $a, &$b)
74 {
75         if (!local_user()) {
76                 return;
77         }
78
79         if (!empty($_POST['langfilter-settings-submit'])) {
80                 PConfig::set(local_user(), 'langfilter', 'languages', trim($_POST['langfilter_languages']));
81                 $enable = (x($_POST, 'langfilter_enable') ? intval($_POST['langfilter_enable']) : 0);
82                 $disable = 1 - $enable;
83                 PConfig::set(local_user(), 'langfilter', 'disable', $disable);
84                 $minconfidence = 0 + $_POST['langfilter_minconfidence'];
85                 if (!$minconfidence) {
86                         $minconfidence = 0;
87                 } elseif ($minconfidence < 0) {
88                         $minconfidence = 0;
89                 } elseif ($minconfidence > 100) {
90                         $minconfidence = 100;
91                 }
92                 PConfig::set(local_user(), 'langfilter', 'minconfidence', $minconfidence / 100.0);
93
94                 $minlength = 0 + $_POST['langfilter_minlength'];
95                 if (!$minlength) {
96                         $minlength = 32;
97                 } elseif ($minlength < 0) {
98                         $minlength = 32;
99                 }
100                 PConfig::set(local_user(), 'langfilter', 'minlength', $minlength);
101
102                 info(L10n::t('Language Filter Settings saved.') . EOL);
103         }
104 }
105
106 /* Actually filter postings by their language
107  * 1st check if the user wants to filter postings
108  * 2nd get the user settings which languages shall be not filtered out
109  * 3rd extract the language of a posting
110  * 4th if the determined language does not fit to the spoken languages
111  *     of the user, then collapse the posting, but provide a link to
112  *     expand it again.
113  */
114
115 function langfilter_prepare_body_content_filter(App $a, &$hook_data)
116 {
117         $logged_user = local_user();
118         if (!$logged_user) {
119                 return;
120         }
121
122         // Never filter own messages
123         // TODO: find a better way to extract this
124         $logged_user_profile = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
125         if ($logged_user_profile == $hook_data['item']['author-link']) {
126                 return;
127         }
128
129         // Don't filter if language filter is disabled
130         if (PConfig::get($logged_user, 'langfilter', 'disable')) {
131                 return;
132         }
133
134         $naked_body = BBCode::toPlaintext($hook_data['item']['body'], false);
135
136         // Don't filter if body lenght is below minimum
137         $minlen = PConfig::get(local_user(), 'langfilter', 'minlength', 32);
138         if (!$minlen) {
139                 $minlen = 32;
140         }
141
142         if (strlen($naked_body) < $minlen) {
143                 return;
144         }
145
146         $read_languages_string = PConfig::get(local_user(), 'langfilter', 'languages');
147         $minconfidence = PConfig::get(local_user(), 'langfilter', 'minconfidence');
148
149         // Don't filter if no spoken languages are configured
150         if (!$read_languages_string) {
151                 return;
152         }
153         $read_languages_array = explode(',', $read_languages_string);
154
155         // Extract the language of the post
156         if (!empty($hook_data['item']['language'])) {
157                 $languages = json_decode($hook_data['item']['language'], true);
158                 if (!is_array($languages)) {
159                         return;
160                 }
161
162                 foreach ($languages as $iso2 => $confidence) {
163                         break;
164                 }
165
166                 if (empty($iso2)) {
167                         return;
168                 }
169
170                 $lang = Text_LanguageDetect_ISO639::code2ToName($iso2);
171         } else {
172                 $opts = $hook_data['item']['postopts'];
173                 if (!$opts) {
174                         // no options associated to post
175                         return;
176                 }
177
178                 if (!preg_match('/\blang=([^;]*);([^:]*)/', $opts, $matches)) {
179                         // no lang options associated to post
180                         return;
181                 }
182
183                 $lang = $matches[1];
184                 $confidence = $matches[2];
185
186                 $iso2 = Text_LanguageDetect_ISO639::nameToCode2($lang);
187         }
188
189         // Do not filter if language detection confidence is too low
190         if ($minconfidence && $confidence < $minconfidence) {
191                 return;
192         }
193
194         if (!$iso2) {
195                 return;
196         }
197
198         if (!in_array($iso2, $read_languages_array)) {
199                 $hook_data['filter_reasons'][] = L10n::t('Filtered language: %s', ucfirst($lang));
200         }
201 }