]> git.mxchange.org Git - friendica.git/blob - src/Moderation/DomainPatternBlocklist.php
a57b5f04cbf2437a24ce5c45f02fbe979e822b15
[friendica.git] / src / Moderation / DomainPatternBlocklist.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Moderation;
23
24 use Exception;
25 use Friendica\App\BaseURL;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
27 use Friendica\Core\L10n;
28 use Friendica\Database\Database;
29 use Friendica\Network\HTTPException;
30 use Friendica\Util\Emailer;
31
32 class DomainPatternBlocklist
33 {
34         /** @var IManageConfigValues */
35         private $config;
36
37         /** @var Database */
38         private $db;
39
40         /** @var Emailer */
41         private $emailer;
42
43         /** @var L10n */
44         private $l10n;
45
46         /** @var BaseURL */
47         private $baseUrl;
48
49         public function __construct(IManageConfigValues $config, Database $db, Emailer $emailer, L10n $l10n, BaseURL $baseUrl)
50         {
51                 $this->config  = $config;
52                 $this->db      = $db;
53                 $this->emailer = $emailer;
54                 $this->l10n    = $l10n;
55                 $this->baseUrl = $baseUrl;
56         }
57
58         public function get(): array
59         {
60                 return $this->config->get('system', 'blocklist', []);
61         }
62
63         public function set(array $blocklist): bool
64         {
65                 $result = $this->config->set('system', 'blocklist', $blocklist);
66                 if ($result) {
67                         $this->notifyAll();
68                 }
69
70                 return $result;
71         }
72
73         /**
74          * @param string $pattern
75          * @param string $reason
76          * @return int 0 if the block list couldn't be saved, 1 if the pattern was added, 2 if it was updated in place
77          */
78         public function addPattern(string $pattern, string $reason): int
79         {
80                 $update = false;
81
82                 $blocklist = [];
83                 foreach ($this->get() as $blocked) {
84                         if ($blocked['domain'] === $pattern) {
85                                 $blocklist[] = [
86                                         'domain' => $pattern,
87                                         'reason' => $reason,
88                                 ];
89
90                                 $update = true;
91                         } else {
92                                 $blocklist[] = $blocked;
93                         }
94                 }
95
96                 if (!$update) {
97                         $blocklist[] = [
98                                 'domain' => $pattern,
99                                 'reason' => $reason,
100                         ];
101                 }
102
103                 return $this->set($blocklist) ? ($update ? 2 : 1) : 0;
104         }
105
106         /**
107          * @param string $pattern
108          * @return int 0 if the block list couldn't be saved, 1 if the pattern wasn't found, 2 if it was removed
109          */
110         public function removePattern(string $pattern): int
111         {
112                 $found = false;
113
114                 $blocklist = [];
115                 foreach ($this->get() as $blocked) {
116                         if ($blocked['domain'] === $pattern) {
117                                 $found = true;
118                         } else {
119                                 $blocklist[] = $blocked;
120                         }
121                 }
122
123                 return $found ? ($this->set($blocklist) ? 2 : 0) : 1;
124         }
125
126         public function exportToFile(string $filename)
127         {
128                 $fp = fopen($filename, 'w');
129                 if (!$fp) {
130                         throw new Exception(sprintf('The file "%s" could not be created.', $filename));
131                 }
132
133                 foreach ($this->get() as $domain) {
134                         fputcsv($fp, $domain);
135                 }
136         }
137
138         /**
139          * Appends to the local block list all the patterns from the provided list that weren't already present.
140          *
141          * @param array $blocklist
142          * @return int The number of patterns actually added to the block list
143          */
144         public function append(array $blocklist): int
145         {
146                 $localBlocklist = $this->get();
147                 $localPatterns  = array_column($localBlocklist, 'domain');
148
149                 $importedPatterns = array_column($blocklist, 'domain');
150
151                 $patternsToAppend = array_diff($importedPatterns, $localPatterns);
152
153                 if (count($patternsToAppend)) {
154                         foreach (array_keys($patternsToAppend) as $key) {
155                                 $localBlocklist[] = $blocklist[$key];
156                         }
157
158                         $this->set($localBlocklist);
159                 }
160
161                 return count($patternsToAppend);
162         }
163
164         /**
165          * Extracts a server domain pattern block list from the provided CSV file name. Deduplicates the list based on patterns.
166          *
167          * @param string $filename
168          * @return array
169          * @throws Exception
170          */
171         public static function extractFromCSVFile(string $filename): array
172         {
173                 $fp = fopen($filename, 'r');
174                 if ($fp === false) {
175                         throw new Exception(sprintf('The file "%s" could not be opened for importing', $filename));
176                 }
177
178                 $blocklist = [];
179                 while (($data = fgetcsv($fp, 1000)) !== false) {
180                         $item = [
181                                 'domain' => $data[0],
182                                 'reason' => $data[1] ?? '',
183                         ];
184                         if (!in_array($item, $blocklist)) {
185                                 $blocklist[] = $data;
186                         }
187                 }
188
189                 return $blocklist;
190         }
191
192         /**
193          * Sends a system email to all the node users about a change in the block list. Sends a single email to each unique
194          * email address among the valid users.
195          *
196          * @return int The number of recipients that were sent an email
197          * @throws HTTPException\InternalServerErrorException
198          * @throws HTTPException\UnprocessableEntityException
199          */
200         public function notifyAll(): int
201         {
202                 // Gathering all non-system parent users who verified their email address and aren't blocked or about to be deleted
203                 // We sort on language to minimize the number of actual language switches during the email build loop
204                 $recipients = $this->db->selectToArray(
205                         'user',
206                         ['username', 'email', 'language'],
207                         ['`uid` > 0 AND `parent-uid` = 0 AND `verified` AND NOT `account_removed` AND NOT `account_expired` AND NOT `blocked`'],
208                         ['group_by' => ['email'], 'order' => ['language']]
209                 );
210                 if (!$recipients) {
211                         return 0;
212                 }
213
214                 foreach ($recipients as $recipient) {
215                         $this->l10n->withLang($recipient['language']);
216                         $email = $this->emailer->newSystemMail()
217                                 ->withMessage(
218                                         $this->l10n->t('[%s] Notice of remote server domain pattern block list update', $this->emailer->getSiteEmailName()),
219                                         $this->l10n->t(
220                                                 'Dear %s,
221
222 You are receiving this email because the Friendica node at %s where you are registered as a user updated their remote server domain pattern block list.
223
224 Please review the updated list at %s at your earliest convenience.',
225                                                 $recipient['username'],
226                                                 $this->baseUrl->get(),
227                                                 $this->baseUrl . '/friendica'
228                                         )
229                                 )
230                                 ->withRecipient($recipient['email'])
231                                 ->build();
232                         $this->emailer->send($email);
233                 }
234
235                 return count($recipients);
236         }
237 }