]> git.mxchange.org Git - friendica.git/blob - src/Moderation/DomainPatternBlocklist.php
Minor l10n issue
[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          *
77          * @return int 0 if the block list couldn't be saved, 1 if the pattern was added, 2 if it was updated in place
78          */
79         public function addPattern(string $pattern, string $reason): int
80         {
81                 $update = false;
82
83                 $blocklist = [];
84                 foreach ($this->get() as $blocked) {
85                         if ($blocked['domain'] === $pattern) {
86                                 $blocklist[] = [
87                                         'domain' => $pattern,
88                                         'reason' => $reason,
89                                 ];
90
91                                 $update = true;
92                         } else {
93                                 $blocklist[] = $blocked;
94                         }
95                 }
96
97                 if (!$update) {
98                         $blocklist[] = [
99                                 'domain' => $pattern,
100                                 'reason' => $reason,
101                         ];
102                 }
103
104                 return $this->set($blocklist) ? ($update ? 2 : 1) : 0;
105         }
106
107         /**
108          * @param string $pattern
109          *
110          * @return int 0 if the block list couldn't be saved, 1 if the pattern wasn't found, 2 if it was removed
111          */
112         public function removePattern(string $pattern): int
113         {
114                 $found = false;
115
116                 $blocklist = [];
117                 foreach ($this->get() as $blocked) {
118                         if ($blocked['domain'] === $pattern) {
119                                 $found = true;
120                         } else {
121                                 $blocklist[] = $blocked;
122                         }
123                 }
124
125                 return $found ? ($this->set($blocklist) ? 2 : 0) : 1;
126         }
127
128         /**
129          * @param string $filename
130          *
131          * @return void
132          * @throws Exception
133          */
134         public function exportToFile(string $filename)
135         {
136                 $fp = fopen($filename, 'w');
137                 if (!$fp) {
138                         throw new Exception(sprintf('The file "%s" could not be created.', $filename));
139                 }
140
141                 foreach ($this->get() as $domain) {
142                         fputcsv($fp, $domain);
143                 }
144         }
145
146         /**
147          * Appends to the local block list all the patterns from the provided list that weren't already present.
148          *
149          * @param array $blocklist
150          *
151          * @return int The number of patterns actually added to the block list
152          */
153         public function append(array $blocklist): int
154         {
155                 $localBlocklist = $this->get();
156                 $localPatterns  = array_column($localBlocklist, 'domain');
157
158                 $importedPatterns = array_column($blocklist, 'domain');
159
160                 $patternsToAppend = array_diff($importedPatterns, $localPatterns);
161
162                 if (count($patternsToAppend)) {
163                         foreach (array_keys($patternsToAppend) as $key) {
164                                 $localBlocklist[] = $blocklist[$key];
165                         }
166
167                         $this->set($localBlocklist);
168                 }
169
170                 return count($patternsToAppend);
171         }
172
173         /**
174          * Extracts a server domain pattern block list from the provided CSV file name. Deduplicates the list based on patterns.
175          *
176          * @param string $filename
177          *
178          * @return array
179          * @throws Exception
180          */
181         public static function extractFromCSVFile(string $filename): array
182         {
183                 $fp = fopen($filename, 'r');
184                 if ($fp === false) {
185                         throw new Exception(sprintf('The file "%s" could not be opened for importing', $filename));
186                 }
187
188                 $blocklist = [];
189                 while (($data = fgetcsv($fp, 1000)) !== false) {
190                         $item = [
191                                 'domain' => $data[0],
192                                 'reason' => $data[1] ?? '',
193                         ];
194                         if (!in_array($item, $blocklist)) {
195                                 $blocklist[] = $data;
196                         }
197                 }
198
199                 return $blocklist;
200         }
201
202         /**
203          * Sends a system email to all the node users about a change in the block list. Sends a single email to each unique
204          * email address among the valid users.
205          *
206          * @return int The number of recipients that were sent an email
207          * @throws HTTPException\InternalServerErrorException
208          * @throws HTTPException\UnprocessableEntityException
209          */
210         public function notifyAll(): int
211         {
212                 // Gathering all non-system parent users who verified their email address and aren't blocked or about to be deleted
213                 // We sort on language to minimize the number of actual language switches during the email build loop
214                 $recipients = $this->db->selectToArray(
215                         'user',
216                         ['username', 'email', 'language'],
217                         ['`uid` > 0 AND `parent-uid` = 0 AND `verified` AND NOT `account_removed` AND NOT `account_expired` AND NOT `blocked`'],
218                         ['group_by' => ['email'], 'order' => ['language']]
219                 );
220                 if (!$recipients) {
221                         return 0;
222                 }
223
224                 foreach ($recipients as $recipient) {
225                         $l10n  = $this->l10n->withLang($recipient['language']);
226                         $email = $this->emailer->newSystemMail()
227                                 ->withMessage(
228                                         $l10n->t('[%s] Notice of remote server domain pattern block list update', $this->emailer->getSiteEmailName()),
229                                         $l10n->t(
230                                                 'Dear %s,
231
232 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.
233
234 Please review the updated list at %s at your earliest convenience.',
235                                                 $recipient['username'],
236                                                 $this->baseUrl->get(),
237                                                 $this->baseUrl . '/friendica'
238                                         )
239                                 )
240                                 ->withRecipient($recipient['email'])
241                                 ->build();
242                         $this->emailer->send($email);
243                 }
244
245                 return count($recipients);
246         }
247 }