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