]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
Avoid local network communication / invalid url requests
[friendica.git] / src / Worker / OnePoll.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Worker;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Conversation;
31 use Friendica\Model\Item;
32 use Friendica\Model\Post;
33 use Friendica\Model\User;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Protocol\Activity;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43
44 class OnePoll
45 {
46         public static function execute(int $contact_id = 0, string $command = '')
47         {
48                 Logger::notice('Start polling/probing contact', ['id' => $contact_id, 'command' => $command]);
49
50                 $force = ($command == 'force');
51
52                 if (empty($contact_id)) {
53                         Logger::notice('no contact provided');
54                         return;
55                 }
56
57                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
58                 if (!DBA::isResult($contact)) {
59                         Logger::warning('Contact not found', ['id' => $contact_id]);
60                         return;
61                 }
62
63                 // We never probe mail contacts since their probing demands a mail from the contact in the inbox.
64                 // We don't probe feed accounts by default since they are polled in a higher frequency, but forced probes are okay.
65                 if ($force && ($contact['network'] == Protocol::FEED)) {
66                         $success = Contact::updateFromProbe($contact_id);
67                 } else {
68                         $success = true;
69                 }
70
71                 $importer_uid = $contact['uid'];
72
73                 $updated = DateTimeFormat::utcNow();
74
75                 // Possibly switch the remote contact to AP
76                 if ($success && ($contact['network'] === Protocol::OSTATUS)) {
77                         ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
78                 }
79
80                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
81
82                 if ($success && ($importer_uid != 0) && in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])
83                         && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
84                         $importer = User::getOwnerDataById($importer_uid);
85                         if (empty($importer)) {
86                                 Logger::warning('No self contact for user', ['uid' => $importer_uid]);
87
88                                 // set the last-update so we don't keep polling
89                                 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
90                                 return;
91                         }
92
93                         Logger::info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]);
94                         if ($contact['network'] === Protocol::FEED) {
95                                 $success = self::pollFeed($contact, $importer);
96                         } elseif ($contact['network'] === Protocol::MAIL) {
97                                 $success = self::pollMail($contact, $importer_uid, $updated);
98                         } else {
99                                 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
100                         }
101                         if (!$success) {
102                                 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
103                         }
104                 }
105
106                 if ($success) {
107                         self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
108                         Contact::unmarkForArchival($contact);
109                 } else {
110                         self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
111                         Contact::markForArchival($contact);
112                 }
113
114                 Logger::notice('End');
115                 return;
116         }
117
118         /**
119          * Updates a personal contact entry and the public contact entry
120          *
121          * @param array $contact The personal contact entry
122          * @param array $fields  The fields that are updated
123          *
124          * @return void
125          * @throws \Exception
126          */
127         private static function updateContact(array $contact, array $fields)
128         {
129                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
130                         // Update the user's contact
131                         Contact::update($fields, ['id' => $contact['id']]);
132
133                         // Update the public contact
134                         Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
135
136                         // Update the rest of the contacts that aren't polled
137                         Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
138                 } else {
139                         // Update all contacts
140                         Contact::update($fields, ['nurl' => $contact['nurl']]);
141                 }
142         }
143
144         /**
145          * Poll Feed contacts
146          *
147          * @param  array $contact The personal contact entry
148          * @param  array $importer
149          *
150          * @return bool   Success
151          * @throws \Exception
152          */
153         private static function pollFeed(array $contact, array $importer): bool
154         {
155                 // Are we allowed to import from this person?
156                 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
157                         Logger::notice('Contact is blocked or only a follower');
158                         return false;
159                 }
160
161                 if (!Network::isValidHttpUrl($contact['poll'])) {
162                         Logger::notice('Poll address is not valid', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'poll' => $contact['poll']]);
163                         return false;
164                 }
165
166                 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
167                 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
168                 unlink($cookiejar);
169
170                 if ($curlResult->isTimeout()) {
171                         Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
172                         return false;
173                 }
174
175                 $xml = $curlResult->getBody();
176                 if (empty($xml)) {
177                         Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
178                         return false;
179                 }
180
181                 if (!strstr($xml, '<')) {
182                         Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
183                         return false;
184                 }
185
186                 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
187
188                 return !empty(Feed::import($xml, $importer, $contact));
189         }
190
191         /**
192          * Poll Mail contacts
193          *
194          * @param  array   $contact      The personal contact entry
195          * @param  integer $importer_uid The UID of the importer
196          * @param  string  $updated      The updated date
197          *
198          * @return bool Success
199          * @throws \Exception
200          */
201         private static function pollMail(array $contact, int $importer_uid, string $updated): bool
202         {
203                 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
204
205                 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
206                 if ($mail_disabled) {
207                         Logger::notice('Mail is disabled');
208                         return false;
209                 }
210
211                 Logger::info('Mail is enabled');
212
213                 $mbox = null;
214                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
215
216                 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
217                 $mailconf = DBA::selectFirst('mailacct', [], $condition);
218                 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
219                         $mailbox = Email::constructMailboxName($mailconf);
220                         $password = '';
221                         openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
222                         $mbox = Email::connect($mailbox, $mailconf['user'], $password);
223                         unset($password);
224                         Logger::notice('Connect', ['user' => $mailconf['user']]);
225                         if ($mbox) {
226                                 $fields = ['last_check' => $updated];
227                                 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
228                                 Logger::notice('Connected', ['user' => $mailconf['user']]);
229                         } else {
230                                 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
231                                 return false;
232                         }
233                 }
234
235                 if (empty($mbox)) {
236                         return false;
237                 }
238
239                 $msgs = Email::poll($mbox, $contact['addr']);
240
241                 if (count($msgs)) {
242                         Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
243
244                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
245
246                         if (count($metas) != count($msgs)) {
247                                 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
248                         } else {
249                                 $msgs = array_combine($msgs, $metas);
250
251                                 foreach ($msgs as $msg_uid => $meta) {
252                                         Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
253
254                                         $datarray = [
255                                                 'uid'         => $importer_uid,
256                                                 'contact-id'  => $contact['id'],
257                                                 'verb'        => Activity::POST,
258                                                 'object-type' => Activity\ObjectType::NOTE,
259                                                 'network'     => Protocol::MAIL,
260                                                 'protocol'    => Conversation::PARCEL_IMAP,
261                                                 'direction'   => Conversation::PULL,
262                                         ];
263                                         $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
264
265                                         // $meta = Email::messageMeta($mbox, $msg_uid);
266
267                                         // Have we seen it before?
268                                         $fields = ['deleted', 'id'];
269                                         $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
270                                         $item = Post::selectFirst($fields, $condition);
271                                         if (DBA::isResult($item)) {
272                                                 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']);
273
274                                                 // Only delete when mails aren't automatically moved or deleted
275                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
276                                                         if ($meta->deleted && ! $item['deleted']) {
277                                                                 $fields = ['deleted' => true, 'changed' => $updated];
278                                                                 Item::update($fields, ['id' => $item['id']]);
279                                                         }
280
281                                                 switch ($mailconf['action']) {
282                                                         case 0:
283                                                                 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
284                                                                 break;
285
286                                                         case 1:
287                                                                 Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
288                                                                 imap_delete($mbox, $msg_uid, FT_UID);
289                                                                 break;
290
291                                                         case 2:
292                                                                 Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
293                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
294                                                                 break;
295
296                                                         case 3:
297                                                                 Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
298                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
299                                                                 if ($mailconf['movetofolder'] != '') {
300                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
301                                                                 }
302                                                                 break;
303                                                 }
304                                                 continue;
305                                         }
306
307                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
308                                         $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
309                                         if (!trim($raw_refs)) {
310                                                 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
311                                         }
312                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
313
314                                         if ($raw_refs) {
315                                                 $refs_arr = explode(' ', $raw_refs);
316                                                 if (count($refs_arr)) {
317                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
318                                                                 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
319                                                         }
320                                                 }
321                                                 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
322                                                 $parent = Post::selectFirst(['uri'], $condition);
323                                                 if (DBA::isResult($parent)) {
324                                                         $datarray['thr-parent'] = $parent['uri'];
325                                                 }
326                                         }
327
328                                         // Decoding the header
329                                         $subject = imap_mime_header_decode($meta->subject ?? '');
330                                         $datarray['title'] = "";
331                                         foreach ($subject as $subpart) {
332                                                 if ($subpart->charset != "default") {
333                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
334                                                 } else {
335                                                         $datarray['title'] .= $subpart->text;
336                                                 }
337                                         }
338                                         $datarray['title'] = trim($datarray['title']);
339
340                                         //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
341                                         $datarray['created'] = DateTimeFormat::utc($meta->date);
342
343                                         // Is it a reply?
344                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == 're:') ||
345                                                 (substr(strtolower($datarray['title']), 0, 3) == 're-') ||
346                                                 ($raw_refs != ''));
347
348                                         // Remove Reply-signs in the subject
349                                         $datarray['title'] = self::removeReply($datarray['title']);
350
351                                         // If it seems to be a reply but a header couldn't be found take the last message with matching subject
352                                         if (empty($datarray['thr-parent']) && $reply) {
353                                                 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
354                                                 $params = ['order' => ['created' => true]];
355                                                 $parent = Post::selectFirst(['uri'], $condition, $params);
356                                                 if (DBA::isResult($parent)) {
357                                                         $datarray['thr-parent'] = $parent['uri'];
358                                                 }
359                                         }
360
361                                         $headers = imap_headerinfo($mbox, $meta->msgno);
362
363                                         $object = [];
364
365                                         if (!empty($headers->from)) {
366                                                 $object['from'] = $headers->from;
367                                         }
368
369                                         if (!empty($headers->to)) {
370                                                 $object['to'] = $headers->to;
371                                         }
372
373                                         if (!empty($headers->reply_to)) {
374                                                 $object['reply_to'] = $headers->reply_to;
375                                         }
376
377                                         if (!empty($headers->sender)) {
378                                                 $object['sender'] = $headers->sender;
379                                         }
380
381                                         if (!empty($object)) {
382                                                 $datarray['object'] = json_encode($object);
383                                         }
384
385                                         $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
386                                         if (!empty($headers->from[0]->personal)) {
387                                                 $fromname = $headers->from[0]->personal;
388                                         }
389
390                                         $datarray['author-name'] = $fromname;
391                                         $datarray['author-link'] = 'mailto:' . $frommail;
392                                         $datarray['author-avatar'] = $contact['photo'];
393
394                                         $datarray['owner-name'] = $contact['name'];
395                                         $datarray['owner-link'] = 'mailto:' . $contact['addr'];
396                                         $datarray['owner-avatar'] = $contact['photo'];
397
398                                         if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
399                                                 $datarray['private'] = Item::PRIVATE;
400                                         }
401
402                                         if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
403                                                 $datarray['private'] = Item::PRIVATE;
404                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
405                                         }
406
407                                         $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
408                                         if (empty($datarray['body'])) {
409                                                 Logger::warning('Cannot fetch mail', ['msg-id' => $msg_uid, 'uid' => $mailconf['user']]);
410                                                 continue;
411                                         }
412
413                                         Logger::notice('Mail: Importing ' . $msg_uid . ' for ' . $mailconf['user']);
414
415                                         Item::insert($datarray);
416
417                                         switch ($mailconf['action']) {
418                                                 case 0:
419                                                         Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
420                                                         break;
421
422                                                 case 1:
423                                                         Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
424                                                         imap_delete($mbox, $msg_uid, FT_UID);
425                                                         break;
426
427                                                 case 2:
428                                                         Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
429                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
430                                                         break;
431
432                                                 case 3:
433                                                         Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
434                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
435                                                         if ($mailconf['movetofolder'] != '') {
436                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
437                                                         }
438                                                         break;
439                                         }
440                                 }
441                         }
442                 } else {
443                         Logger::notice('No mails', ['user' => $mailconf['user']]);
444                 }
445
446
447                 Logger::info('Closing connection', ['user' => $mailconf['user']]);
448                 imap_close($mbox);
449
450                 return true;
451         }
452
453         private static function removeReply(string $subject): string
454         {
455                 while (in_array(strtolower(substr($subject, 0, 3)), ['re:', 'aw:'])) {
456                         $subject = trim(substr($subject, 4));
457                 }
458
459                 return $subject;
460         }
461
462         /**
463          * @param string $url
464          * @param array  $importer
465          * @param array  $contact
466          * @param string $hubmode
467          *
468          * @return bool Success
469          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
470          */
471         private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe'): bool
472         {
473                 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
474
475                 // Use a single verify token, even if multiple hubs
476                 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
477
478                 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
479
480                 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
481
482                 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
483                         Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
484                 }
485
486                 $postResult = DI::httpClient()->post($url, $params);
487
488                 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
489
490                 return $postResult->isSuccess();
491         }
492 }