3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Worker;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Protocol\Activity;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Protocol\Email;
34 use Friendica\Protocol\PortableContact;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
42 public static function execute($contact_id = 0, $command = '')
44 Logger::log('Start for contact ' . $contact_id);
48 if ($command == "force") {
53 Logger::log('no contact');
58 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
59 if (!DBA::isResult($contact)) {
60 Logger::log('Contact not found or cannot be used.');
64 if (($contact['network'] != Protocol::MAIL) || $force) {
65 Contact::updateFromProbe($contact_id, '', $force);
68 // Special treatment for wrongly detected local contacts
69 if (!$force && ($contact['network'] != Protocol::DFRN) && Contact::isLocalById($contact_id)) {
70 Contact::updateFromProbe($contact_id, Protocol::DFRN, true);
71 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
74 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
75 $protocol = Protocol::ACTIVITYPUB;
77 $protocol = $contact['network'];
80 $importer_uid = $contact['uid'];
82 $updated = DateTimeFormat::utcNow();
84 if ($importer_uid == 0) {
85 Logger::log('Ignore public contacts');
87 // set the last-update so we don't keep polling
88 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
92 // Possibly switch the remote contact to AP
93 if ($protocol === Protocol::OSTATUS) {
94 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
95 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
98 // load current friends if possible.
99 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
100 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
101 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
105 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
106 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && DI::config()->get('system', 'disable_polling')) {
107 Logger::log('Polling is disabled');
109 // set the last-update so we don't keep polling
110 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
114 // We don't poll AP contacts by now
115 if ($protocol === Protocol::ACTIVITYPUB) {
116 Logger::log("Don't poll AP contact");
118 // set the last-update so we don't keep polling
119 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
123 $importer = User::getOwnerDataById($importer_uid);
125 if (empty($importer)) {
126 Logger::log('No self contact for user '.$importer_uid);
128 // set the last-update so we don't keep polling
129 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
136 if ($contact['subhub']) {
137 $poll_interval = DI::config()->get('system', 'pushpoll_frequency', 3);
138 $contact['priority'] = intval($poll_interval);
141 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
148 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
152 if ($protocol === Protocol::DFRN) {
153 $xml = self::pollDFRN($contact, $updated);
154 } elseif (($protocol === Protocol::OSTATUS)
155 || ($protocol === Protocol::DIASPORA)
156 || ($protocol === Protocol::FEED)) {
157 $xml = self::pollFeed($contact, $protocol, $updated);
158 } elseif ($protocol === Protocol::MAIL) {
159 self::pollMail($contact, $importer_uid, $updated);
163 Logger::log('received xml : ' . $xml, Logger::DATA);
164 if (!strstr($xml, '<')) {
165 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
167 $fields = ['last-update' => $updated, 'failure_update' => $updated];
168 self::updateContact($contact, $fields);
169 Contact::markForArchival($contact);
174 Logger::log("Consume feed of contact ".$contact['id']);
176 consume_feed($xml, $importer, $contact, $hub);
178 // do it a second time for DFRN so that any children find their parents.
179 if ($protocol === Protocol::DFRN) {
180 consume_feed($xml, $importer, $contact, $hub);
183 $hubmode = 'subscribe';
184 if ($protocol === Protocol::DFRN || $contact['blocked']) {
185 $hubmode = 'unsubscribe';
188 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
196 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
198 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
199 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
200 $hubs = explode(',', $hub);
203 foreach ($hubs as $h) {
210 subscribe_to_hub($h, $importer, $contact, $hubmode);
215 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
216 Contact::unmarkForArchival($contact);
217 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
218 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
219 Contact::markForArchival($contact);
221 self::updateContact($contact, ['last-update' => $updated]);
228 private static function RemoveReply($subject)
230 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
231 $subject = trim(substr($subject, 4));
238 * Updates a personal contact entry and the public contact entry
240 * @param array $contact The personal contact entry
241 * @param array $fields The fields that are updated
244 private static function updateContact(array $contact, array $fields)
246 DBA::update('contact', $fields, ['id' => $contact['id']]);
247 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
253 * @param array $contact The personal contact entry
254 * @param string $updated The updated date
255 * @return string polled XML
258 private static function pollDFRN(array $contact, $updated)
260 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
261 if (intval($contact['duplex']) && $contact['dfrn-id']) {
262 $idtosend = '0:' . $orig_id;
264 if (intval($contact['duplex']) && $contact['issued-id']) {
265 $idtosend = '1:' . $orig_id;
268 // they have permission to write to us. We already filtered this in the contact query.
271 // But this may be our first communication, so set the writable flag if it isn't set already.
272 if (!intval($contact['writable'])) {
273 $fields = ['writable' => true];
274 DBA::update('contact', $fields, ['id' => $contact['id']]);
277 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
278 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
279 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
282 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
283 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
284 . '&type=data&last_update=' . $last_update
287 $curlResult = Network::curl($url);
289 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
290 // set the last-update so we don't keep polling
291 self::updateContact($contact, ['last-update' => $updated]);
292 Contact::markForArchival($contact);
293 Logger::log('Contact archived');
297 $handshake_xml = $curlResult->getBody();
298 $html_code = $curlResult->getReturnCode();
300 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
302 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
303 // dead connection - might be a transient event, or this might
304 // mean the software was uninstalled or the domain expired.
305 // Will keep trying for one month.
306 Logger::log("$url appears to be dead - marking for death ");
308 // set the last-update so we don't keep polling
309 $fields = ['last-update' => $updated, 'failure_update' => $updated];
310 self::updateContact($contact, $fields);
311 Contact::markForArchival($contact);
315 if (!strstr($handshake_xml, '<')) {
316 Logger::log('response from ' . $url . ' did not contain XML.');
318 $fields = ['last-update' => $updated, 'failure_update' => $updated];
319 self::updateContact($contact, $fields);
320 Contact::markForArchival($contact);
324 $res = XML::parseString($handshake_xml);
326 if (!is_object($res)) {
327 Logger::info('Unparseable response', ['url' => $url]);
329 $fields = ['last-update' => $updated, 'failure_update' => $updated];
330 self::updateContact($contact, $fields);
331 Contact::markForArchival($contact);
335 if (intval($res->status) == 1) {
336 // we may not be friends anymore. Will keep trying for one month.
337 Logger::log("$url replied status 1 - marking for death ");
339 // set the last-update so we don't keep polling
340 $fields = ['last-update' => $updated, 'failure_update' => $updated];
341 self::updateContact($contact, $fields);
342 Contact::markForArchival($contact);
343 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
344 Contact::unmarkForArchival($contact);
347 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
348 // set the last-update so we don't keep polling
349 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
350 Logger::log('Contact status is ' . $res->status);
354 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
355 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
356 DBA::update('contact', $fields, ['id' => $contact['id']]);
361 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
362 $challenge = hex2bin((string) $res->challenge);
366 if ($contact['duplex'] && strlen($contact['prvkey'])) {
367 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
368 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
370 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
371 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
374 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
376 if (strpos($final_dfrn_id, ':') == 1) {
377 $final_dfrn_id = substr($final_dfrn_id, 2);
380 // There are issues with the legacy DFRN transport layer.
381 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
382 if (empty($final_dfrn_id) || empty($orig_id)) {
383 Logger::log('Contact has got no ID - quitting');
387 if ($final_dfrn_id != $orig_id) {
388 // did not decode properly - cannot trust this site
389 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
391 // set the last-update so we don't keep polling
392 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
393 Contact::markForArchival($contact);
397 $postvars['dfrn_id'] = $idtosend;
398 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
399 $postvars['perm'] = 'rw';
401 return Network::post($contact['poll'], $postvars)->getBody();
405 * Poll Feed/OStatus contacts
407 * @param array $contact The personal contact entry
408 * @param string $protocol The used protocol of the contact
409 * @param string $updated The updated date
410 * @return string polled XML
413 private static function pollFeed(array $contact, $protocol, $updated)
415 // Upgrading DB fields from an older Friendica version
416 // Will only do this once per notify-enabled OStatus contact
417 // or if relationship changes
419 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
421 // Contacts from OStatus are always writable
422 if ($protocol === Protocol::OSTATUS) {
426 if ($stat_writeable != $contact['writable']) {
427 $fields = ['writable' => $stat_writeable];
428 DBA::update('contact', $fields, ['id' => $contact['id']]);
431 // Are we allowed to import from this person?
432 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
433 // set the last-update so we don't keep polling
434 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
435 Logger::log('Contact is blocked or only a follower');
439 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
440 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
443 if ($curlResult->isTimeout()) {
444 // set the last-update so we don't keep polling
445 self::updateContact($contact, ['last-update' => $updated]);
446 Contact::markForArchival($contact);
447 Logger::log('Contact archived');
451 return $curlResult->getBody();
457 * @param array $contact The personal contact entry
458 * @param integer $importer_uid The UID of the importer
459 * @param string $updated The updated date
462 private static function pollMail(array $contact, $importer_uid, $updated)
464 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
466 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
467 if ($mail_disabled) {
468 // set the last-update so we don't keep polling
469 self::updateContact($contact, ['last-update' => $updated]);
470 Contact::markForArchival($contact);
471 Logger::log('Contact archived');
475 Logger::log("Mail: Enabled", Logger::DEBUG);
478 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
480 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
481 $mailconf = DBA::selectFirst('mailacct', [], $condition);
482 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
483 $mailbox = Email::constructMailboxName($mailconf);
485 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
486 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
488 Logger::log("Mail: Connect to " . $mailconf['user']);
490 $fields = ['last_check' => $updated];
491 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
492 Logger::log("Mail: Connected to " . $mailconf['user']);
494 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
502 $msgs = Email::poll($mbox, $contact['addr']);
505 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
507 $metas = Email::messageMeta($mbox, implode(',', $msgs));
509 if (count($metas) != count($msgs)) {
510 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
512 $msgs = array_combine($msgs, $metas);
514 foreach ($msgs as $msg_uid => $meta) {
515 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
518 $datarray['uid'] = $importer_uid;
519 $datarray['contact-id'] = $contact['id'];
520 $datarray['verb'] = Activity::POST;
521 $datarray['object-type'] = Activity\ObjectType::NOTE;
522 $datarray['network'] = Protocol::MAIL;
523 // $meta = Email::messageMeta($mbox, $msg_uid);
525 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
527 // Have we seen it before?
528 $fields = ['deleted', 'id'];
529 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
530 $item = Item::selectFirst($fields, $condition);
531 if (DBA::isResult($item)) {
532 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
534 // Only delete when mails aren't automatically moved or deleted
535 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
536 if ($meta->deleted && ! $item['deleted']) {
537 $fields = ['deleted' => true, 'changed' => $updated];
538 Item::update($fields, ['id' => $item['id']]);
541 switch ($mailconf['action']) {
543 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
546 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
547 imap_delete($mbox, $msg_uid, FT_UID);
550 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
551 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
554 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
555 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
556 if ($mailconf['movetofolder'] != "") {
557 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
564 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
565 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
566 if (!trim($raw_refs)) {
567 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
569 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
572 $refs_arr = explode(' ', $raw_refs);
573 if (count($refs_arr)) {
574 for ($x = 0; $x < count($refs_arr); $x ++) {
575 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
578 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
579 $parent = Item::selectFirst(['parent-uri'], $condition);
580 if (DBA::isResult($parent)) {
581 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
585 // Decoding the header
586 $subject = imap_mime_header_decode($meta->subject ?? '');
587 $datarray['title'] = "";
588 foreach ($subject as $subpart) {
589 if ($subpart->charset != "default") {
590 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
592 $datarray['title'] .= $subpart->text;
595 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
597 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
598 $datarray['created'] = DateTimeFormat::utc($meta->date);
601 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
602 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
605 // Remove Reply-signs in the subject
606 $datarray['title'] = self::RemoveReply($datarray['title']);
608 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
609 if (empty($datarray['parent-uri']) && $reply) {
610 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
611 $params = ['order' => ['created' => true]];
612 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
613 if (DBA::isResult($parent)) {
614 $datarray['parent-uri'] = $parent['parent-uri'];
618 if (empty($datarray['parent-uri'])) {
619 $datarray['parent-uri'] = $datarray['uri'];
622 $headers = imap_headerinfo($mbox, $meta->msgno);
626 if (!empty($headers->from)) {
627 $object['from'] = $headers->from;
630 if (!empty($headers->to)) {
631 $object['to'] = $headers->to;
634 if (!empty($headers->reply_to)) {
635 $object['reply_to'] = $headers->reply_to;
638 if (!empty($headers->sender)) {
639 $object['sender'] = $headers->sender;
642 if (!empty($object)) {
643 $datarray['object'] = json_encode($object);
646 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
647 if (!empty($headers->from[0]->personal)) {
648 $fromname = $headers->from[0]->personal;
651 $datarray['author-name'] = $fromname;
652 $datarray['author-link'] = "mailto:".$frommail;
653 $datarray['author-avatar'] = $contact['photo'];
655 $datarray['owner-name'] = $contact['name'];
656 $datarray['owner-link'] = "mailto:".$contact['addr'];
657 $datarray['owner-avatar'] = $contact['photo'];
659 if ($datarray['parent-uri'] === $datarray['uri']) {
660 $datarray['private'] = 1;
663 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
664 $datarray['private'] = 1;
665 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
668 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
669 if (empty($datarray['body'])) {
670 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
674 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
676 Item::insert($datarray);
678 switch ($mailconf['action']) {
680 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
683 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
684 imap_delete($mbox, $msg_uid, FT_UID);
687 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
688 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
691 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
692 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
693 if ($mailconf['movetofolder'] != "") {
694 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
701 Logger::log("Mail: no mails for ".$mailconf['user']);
704 Logger::log("Mail: closing connection for ".$mailconf['user']);