3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Config;
8 use Friendica\Core\Logger;
9 use Friendica\Core\Protocol;
10 use Friendica\Database\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Model\User;
15 use Friendica\Protocol\Activity;
16 use Friendica\Protocol\ActivityPub;
17 use Friendica\Protocol\Email;
18 use Friendica\Protocol\PortableContact;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Strings;
22 use Friendica\Util\XML;
26 public static function execute($contact_id = 0, $command = '')
28 Logger::log('Start for contact ' . $contact_id);
32 if ($command == "force") {
37 Logger::log('no contact');
41 Contact::updateFromProbe($contact_id, '', $force);
43 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
44 if (!DBA::isResult($contact)) {
45 Logger::log('Contact not found or cannot be used.');
49 // Special treatment for wrongly detected local contacts
50 if (!$force && ($contact['network'] != Protocol::DFRN) && Contact::isLocalById($contact_id)) {
51 Contact::updateFromProbe($contact_id, Protocol::DFRN, true);
52 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
55 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
56 $protocol = Protocol::ACTIVITYPUB;
58 $protocol = $contact['network'];
61 $importer_uid = $contact['uid'];
63 $updated = DateTimeFormat::utcNow();
65 if ($importer_uid == 0) {
66 Logger::log('Ignore public contacts');
68 // set the last-update so we don't keep polling
69 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
73 // Possibly switch the remote contact to AP
74 if ($protocol === Protocol::OSTATUS) {
75 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
76 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
79 // load current friends if possible.
80 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
81 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
82 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
86 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
87 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
88 Logger::log('Polling is disabled');
90 // set the last-update so we don't keep polling
91 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
95 // We don't poll AP contacts by now
96 if ($protocol === Protocol::ACTIVITYPUB) {
97 Logger::log("Don't poll AP contact");
99 // set the last-update so we don't keep polling
100 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
104 $importer = User::getOwnerDataById($importer_uid);
106 if (empty($importer)) {
107 Logger::log('No self contact for user '.$importer_uid);
109 // set the last-update so we don't keep polling
110 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
117 if ($contact['subhub']) {
118 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
119 $contact['priority'] = intval($poll_interval);
122 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
129 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
133 if ($protocol === Protocol::DFRN) {
134 $xml = self::pollDFRN($contact, $updated);
135 } elseif (($protocol === Protocol::OSTATUS)
136 || ($protocol === Protocol::DIASPORA)
137 || ($protocol === Protocol::FEED)) {
138 $xml = self::pollFeed($contact, $protocol, $updated);
139 } elseif ($protocol === Protocol::MAIL) {
140 self::pollMail($contact, $importer_uid, $updated);
144 Logger::log('received xml : ' . $xml, Logger::DATA);
145 if (!strstr($xml, '<')) {
146 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
148 $fields = ['last-update' => $updated, 'failure_update' => $updated];
149 self::updateContact($contact, $fields);
150 Contact::markForArchival($contact);
155 Logger::log("Consume feed of contact ".$contact['id']);
157 consume_feed($xml, $importer, $contact, $hub);
159 // do it a second time for DFRN so that any children find their parents.
160 if ($protocol === Protocol::DFRN) {
161 consume_feed($xml, $importer, $contact, $hub);
164 $hubmode = 'subscribe';
165 if ($protocol === Protocol::DFRN || $contact['blocked']) {
166 $hubmode = 'unsubscribe';
169 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
177 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
179 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
180 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
181 $hubs = explode(',', $hub);
184 foreach ($hubs as $h) {
191 subscribe_to_hub($h, $importer, $contact, $hubmode);
196 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
197 Contact::unmarkForArchival($contact);
198 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
199 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
200 Contact::markForArchival($contact);
202 self::updateContact($contact, ['last-update' => $updated]);
209 private static function RemoveReply($subject)
211 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
212 $subject = trim(substr($subject, 4));
219 * Updates a personal contact entry and the public contact entry
221 * @param array $contact The personal contact entry
222 * @param array $fields The fields that are updated
225 private static function updateContact(array $contact, array $fields)
227 DBA::update('contact', $fields, ['id' => $contact['id']]);
228 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
234 * @param array $contact The personal contact entry
235 * @param string $updated The updated date
236 * @return string polled XML
239 private static function pollDFRN(array $contact, $updated)
241 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
242 if (intval($contact['duplex']) && $contact['dfrn-id']) {
243 $idtosend = '0:' . $orig_id;
245 if (intval($contact['duplex']) && $contact['issued-id']) {
246 $idtosend = '1:' . $orig_id;
249 // they have permission to write to us. We already filtered this in the contact query.
252 // But this may be our first communication, so set the writable flag if it isn't set already.
253 if (!intval($contact['writable'])) {
254 $fields = ['writable' => true];
255 DBA::update('contact', $fields, ['id' => $contact['id']]);
258 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
259 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
260 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
263 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
264 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
265 . '&type=data&last_update=' . $last_update
268 $curlResult = Network::curl($url);
270 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
271 // set the last-update so we don't keep polling
272 self::updateContact($contact, ['last-update' => $updated]);
273 Contact::markForArchival($contact);
274 Logger::log('Contact archived');
278 $handshake_xml = $curlResult->getBody();
279 $html_code = $curlResult->getReturnCode();
281 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
283 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
284 // dead connection - might be a transient event, or this might
285 // mean the software was uninstalled or the domain expired.
286 // Will keep trying for one month.
287 Logger::log("$url appears to be dead - marking for death ");
289 // set the last-update so we don't keep polling
290 $fields = ['last-update' => $updated, 'failure_update' => $updated];
291 self::updateContact($contact, $fields);
292 Contact::markForArchival($contact);
296 if (!strstr($handshake_xml, '<')) {
297 Logger::log('response from ' . $url . ' did not contain XML.');
299 $fields = ['last-update' => $updated, 'failure_update' => $updated];
300 self::updateContact($contact, $fields);
301 Contact::markForArchival($contact);
305 $res = XML::parseString($handshake_xml);
307 if (!is_object($res)) {
308 Logger::info('Unparseable response', ['url' => $url]);
310 $fields = ['last-update' => $updated, 'failure_update' => $updated];
311 self::updateContact($contact, $fields);
312 Contact::markForArchival($contact);
316 if (intval($res->status) == 1) {
317 // we may not be friends anymore. Will keep trying for one month.
318 Logger::log("$url replied status 1 - marking for death ");
320 // set the last-update so we don't keep polling
321 $fields = ['last-update' => $updated, 'failure_update' => $updated];
322 self::updateContact($contact, $fields);
323 Contact::markForArchival($contact);
324 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
325 Contact::unmarkForArchival($contact);
328 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
329 // set the last-update so we don't keep polling
330 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
331 Logger::log('Contact status is ' . $res->status);
335 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
336 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
337 DBA::update('contact', $fields, ['id' => $contact['id']]);
342 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
343 $challenge = hex2bin((string) $res->challenge);
347 if ($contact['duplex'] && strlen($contact['prvkey'])) {
348 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
349 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
351 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
352 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
355 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
357 if (strpos($final_dfrn_id, ':') == 1) {
358 $final_dfrn_id = substr($final_dfrn_id, 2);
361 // There are issues with the legacy DFRN transport layer.
362 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
363 if (empty($final_dfrn_id) || empty($orig_id)) {
364 Logger::log('Contact has got no ID - quitting');
368 if ($final_dfrn_id != $orig_id) {
369 // did not decode properly - cannot trust this site
370 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
372 // set the last-update so we don't keep polling
373 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
374 Contact::markForArchival($contact);
378 $postvars['dfrn_id'] = $idtosend;
379 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
380 $postvars['perm'] = 'rw';
382 return Network::post($contact['poll'], $postvars)->getBody();
386 * Poll Feed/OStatus contacts
388 * @param array $contact The personal contact entry
389 * @param string $protocol The used protocol of the contact
390 * @param string $updated The updated date
391 * @return string polled XML
394 private static function pollFeed(array $contact, $protocol, $updated)
396 // Upgrading DB fields from an older Friendica version
397 // Will only do this once per notify-enabled OStatus contact
398 // or if relationship changes
400 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
402 // Contacts from OStatus are always writable
403 if ($protocol === Protocol::OSTATUS) {
407 if ($stat_writeable != $contact['writable']) {
408 $fields = ['writable' => $stat_writeable];
409 DBA::update('contact', $fields, ['id' => $contact['id']]);
412 // Are we allowed to import from this person?
413 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
414 // set the last-update so we don't keep polling
415 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
416 Logger::log('Contact is blocked or only a follower');
420 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
421 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
424 if ($curlResult->isTimeout()) {
425 // set the last-update so we don't keep polling
426 self::updateContact($contact, ['last-update' => $updated]);
427 Contact::markForArchival($contact);
428 Logger::log('Contact archived');
432 return $curlResult->getBody();
438 * @param array $contact The personal contact entry
439 * @param integer $importer_uid The UID of the importer
440 * @param string $updated The updated date
443 private static function pollMail(array $contact, $importer_uid, $updated)
445 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
447 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
448 if ($mail_disabled) {
449 // set the last-update so we don't keep polling
450 self::updateContact($contact, ['last-update' => $updated]);
451 Contact::markForArchival($contact);
452 Logger::log('Contact archived');
456 Logger::log("Mail: Enabled", Logger::DEBUG);
459 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
461 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
462 $mailconf = DBA::selectFirst('mailacct', [], $condition);
463 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
464 $mailbox = Email::constructMailboxName($mailconf);
466 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
467 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
469 Logger::log("Mail: Connect to " . $mailconf['user']);
471 $fields = ['last_check' => $updated];
472 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
473 Logger::log("Mail: Connected to " . $mailconf['user']);
475 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
483 $msgs = Email::poll($mbox, $contact['addr']);
486 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
488 $metas = Email::messageMeta($mbox, implode(',', $msgs));
490 if (count($metas) != count($msgs)) {
491 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
493 $msgs = array_combine($msgs, $metas);
495 foreach ($msgs as $msg_uid => $meta) {
496 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
499 $datarray['uid'] = $importer_uid;
500 $datarray['contact-id'] = $contact['id'];
501 $datarray['verb'] = Activity::POST;
502 $datarray['object-type'] = Activity\ObjectType::NOTE;
503 $datarray['network'] = Protocol::MAIL;
504 // $meta = Email::messageMeta($mbox, $msg_uid);
506 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
508 // Have we seen it before?
509 $fields = ['deleted', 'id'];
510 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
511 $item = Item::selectFirst($fields, $condition);
512 if (DBA::isResult($item)) {
513 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
515 // Only delete when mails aren't automatically moved or deleted
516 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
517 if ($meta->deleted && ! $item['deleted']) {
518 $fields = ['deleted' => true, 'changed' => $updated];
519 Item::update($fields, ['id' => $item['id']]);
522 switch ($mailconf['action']) {
524 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
527 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
528 imap_delete($mbox, $msg_uid, FT_UID);
531 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
532 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
535 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
536 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
537 if ($mailconf['movetofolder'] != "") {
538 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
545 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
546 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
547 if (!trim($raw_refs)) {
548 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
550 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
553 $refs_arr = explode(' ', $raw_refs);
554 if (count($refs_arr)) {
555 for ($x = 0; $x < count($refs_arr); $x ++) {
556 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
559 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
560 $parent = Item::selectFirst(['parent-uri'], $condition);
561 if (DBA::isResult($parent)) {
562 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
566 // Decoding the header
567 $subject = imap_mime_header_decode($meta->subject ?? '');
568 $datarray['title'] = "";
569 foreach ($subject as $subpart) {
570 if ($subpart->charset != "default") {
571 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
573 $datarray['title'] .= $subpart->text;
576 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
578 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
579 $datarray['created'] = DateTimeFormat::utc($meta->date);
582 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
583 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
586 // Remove Reply-signs in the subject
587 $datarray['title'] = self::RemoveReply($datarray['title']);
589 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
590 if (empty($datarray['parent-uri']) && $reply) {
591 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
592 $params = ['order' => ['created' => true]];
593 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
594 if (DBA::isResult($parent)) {
595 $datarray['parent-uri'] = $parent['parent-uri'];
599 if (empty($datarray['parent-uri'])) {
600 $datarray['parent-uri'] = $datarray['uri'];
603 $headers = imap_headerinfo($mbox, $meta->msgno);
607 if (!empty($headers->from)) {
608 $object['from'] = $headers->from;
611 if (!empty($headers->to)) {
612 $object['to'] = $headers->to;
615 if (!empty($headers->reply_to)) {
616 $object['reply_to'] = $headers->reply_to;
619 if (!empty($headers->sender)) {
620 $object['sender'] = $headers->sender;
623 if (!empty($object)) {
624 $datarray['object'] = json_encode($object);
627 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
628 if (!empty($headers->from[0]->personal)) {
629 $fromname = $headers->from[0]->personal;
632 $datarray['author-name'] = $fromname;
633 $datarray['author-link'] = "mailto:".$frommail;
634 $datarray['author-avatar'] = $contact['photo'];
636 $datarray['owner-name'] = $contact['name'];
637 $datarray['owner-link'] = "mailto:".$contact['addr'];
638 $datarray['owner-avatar'] = $contact['photo'];
640 if ($datarray['parent-uri'] === $datarray['uri']) {
641 $datarray['private'] = 1;
644 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
645 $datarray['private'] = 1;
646 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
649 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
650 if (empty($datarray['body'])) {
651 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
655 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
657 Item::insert($datarray);
659 switch ($mailconf['action']) {
661 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
664 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
665 imap_delete($mbox, $msg_uid, FT_UID);
668 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
669 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
672 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
673 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
674 if ($mailconf['movetofolder'] != "") {
675 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
682 Logger::log("Mail: no mails for ".$mailconf['user']);
685 Logger::log("Mail: closing connection for ".$mailconf['user']);