3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Logger;
8 use Friendica\Core\Protocol;
9 use Friendica\Database\DBA;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Item;
13 use Friendica\Model\User;
14 use Friendica\Protocol\Activity;
15 use Friendica\Protocol\ActivityPub;
16 use Friendica\Protocol\Email;
17 use Friendica\Protocol\PortableContact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\Strings;
21 use Friendica\Util\XML;
25 public static function execute($contact_id = 0, $command = '')
27 Logger::log('Start for contact ' . $contact_id);
31 if ($command == "force") {
36 Logger::log('no contact');
41 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
42 if (!DBA::isResult($contact)) {
43 Logger::log('Contact not found or cannot be used.');
47 if (($contact['network'] != Protocol::MAIL) || $force) {
48 Contact::updateFromProbe($contact_id, '', $force);
51 // Special treatment for wrongly detected local contacts
52 if (!$force && ($contact['network'] != Protocol::DFRN) && Contact::isLocalById($contact_id)) {
53 Contact::updateFromProbe($contact_id, Protocol::DFRN, true);
54 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
57 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
58 $protocol = Protocol::ACTIVITYPUB;
60 $protocol = $contact['network'];
63 $importer_uid = $contact['uid'];
65 $updated = DateTimeFormat::utcNow();
67 if ($importer_uid == 0) {
68 Logger::log('Ignore public contacts');
70 // set the last-update so we don't keep polling
71 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
75 // Possibly switch the remote contact to AP
76 if ($protocol === Protocol::OSTATUS) {
77 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
78 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
81 // load current friends if possible.
82 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
83 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
84 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
88 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
89 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && DI::config()->get('system', 'disable_polling')) {
90 Logger::log('Polling is disabled');
92 // set the last-update so we don't keep polling
93 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
97 // We don't poll AP contacts by now
98 if ($protocol === Protocol::ACTIVITYPUB) {
99 Logger::log("Don't poll AP contact");
101 // set the last-update so we don't keep polling
102 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
106 $importer = User::getOwnerDataById($importer_uid);
108 if (empty($importer)) {
109 Logger::log('No self contact for user '.$importer_uid);
111 // set the last-update so we don't keep polling
112 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
119 if ($contact['subhub']) {
120 $poll_interval = DI::config()->get('system', 'pushpoll_frequency', 3);
121 $contact['priority'] = intval($poll_interval);
124 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
131 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
135 if ($protocol === Protocol::DFRN) {
136 $xml = self::pollDFRN($contact, $updated);
137 } elseif (($protocol === Protocol::OSTATUS)
138 || ($protocol === Protocol::DIASPORA)
139 || ($protocol === Protocol::FEED)) {
140 $xml = self::pollFeed($contact, $protocol, $updated);
141 } elseif ($protocol === Protocol::MAIL) {
142 self::pollMail($contact, $importer_uid, $updated);
146 Logger::log('received xml : ' . $xml, Logger::DATA);
147 if (!strstr($xml, '<')) {
148 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
150 $fields = ['last-update' => $updated, 'failure_update' => $updated];
151 self::updateContact($contact, $fields);
152 Contact::markForArchival($contact);
157 Logger::log("Consume feed of contact ".$contact['id']);
159 consume_feed($xml, $importer, $contact, $hub);
161 // do it a second time for DFRN so that any children find their parents.
162 if ($protocol === Protocol::DFRN) {
163 consume_feed($xml, $importer, $contact, $hub);
166 $hubmode = 'subscribe';
167 if ($protocol === Protocol::DFRN || $contact['blocked']) {
168 $hubmode = 'unsubscribe';
171 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
179 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
181 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
182 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
183 $hubs = explode(',', $hub);
186 foreach ($hubs as $h) {
193 subscribe_to_hub($h, $importer, $contact, $hubmode);
198 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
199 Contact::unmarkForArchival($contact);
200 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
201 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
202 Contact::markForArchival($contact);
204 self::updateContact($contact, ['last-update' => $updated]);
211 private static function RemoveReply($subject)
213 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
214 $subject = trim(substr($subject, 4));
221 * Updates a personal contact entry and the public contact entry
223 * @param array $contact The personal contact entry
224 * @param array $fields The fields that are updated
227 private static function updateContact(array $contact, array $fields)
229 DBA::update('contact', $fields, ['id' => $contact['id']]);
230 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
236 * @param array $contact The personal contact entry
237 * @param string $updated The updated date
238 * @return string polled XML
241 private static function pollDFRN(array $contact, $updated)
243 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
244 if (intval($contact['duplex']) && $contact['dfrn-id']) {
245 $idtosend = '0:' . $orig_id;
247 if (intval($contact['duplex']) && $contact['issued-id']) {
248 $idtosend = '1:' . $orig_id;
251 // they have permission to write to us. We already filtered this in the contact query.
254 // But this may be our first communication, so set the writable flag if it isn't set already.
255 if (!intval($contact['writable'])) {
256 $fields = ['writable' => true];
257 DBA::update('contact', $fields, ['id' => $contact['id']]);
260 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
261 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
262 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
265 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
266 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
267 . '&type=data&last_update=' . $last_update
270 $curlResult = Network::curl($url);
272 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
273 // set the last-update so we don't keep polling
274 self::updateContact($contact, ['last-update' => $updated]);
275 Contact::markForArchival($contact);
276 Logger::log('Contact archived');
280 $handshake_xml = $curlResult->getBody();
281 $html_code = $curlResult->getReturnCode();
283 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
285 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
286 // dead connection - might be a transient event, or this might
287 // mean the software was uninstalled or the domain expired.
288 // Will keep trying for one month.
289 Logger::log("$url appears to be dead - marking for death ");
291 // set the last-update so we don't keep polling
292 $fields = ['last-update' => $updated, 'failure_update' => $updated];
293 self::updateContact($contact, $fields);
294 Contact::markForArchival($contact);
298 if (!strstr($handshake_xml, '<')) {
299 Logger::log('response from ' . $url . ' did not contain XML.');
301 $fields = ['last-update' => $updated, 'failure_update' => $updated];
302 self::updateContact($contact, $fields);
303 Contact::markForArchival($contact);
307 $res = XML::parseString($handshake_xml);
309 if (!is_object($res)) {
310 Logger::info('Unparseable response', ['url' => $url]);
312 $fields = ['last-update' => $updated, 'failure_update' => $updated];
313 self::updateContact($contact, $fields);
314 Contact::markForArchival($contact);
318 if (intval($res->status) == 1) {
319 // we may not be friends anymore. Will keep trying for one month.
320 Logger::log("$url replied status 1 - marking for death ");
322 // set the last-update so we don't keep polling
323 $fields = ['last-update' => $updated, 'failure_update' => $updated];
324 self::updateContact($contact, $fields);
325 Contact::markForArchival($contact);
326 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
327 Contact::unmarkForArchival($contact);
330 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
331 // set the last-update so we don't keep polling
332 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
333 Logger::log('Contact status is ' . $res->status);
337 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
338 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
339 DBA::update('contact', $fields, ['id' => $contact['id']]);
344 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
345 $challenge = hex2bin((string) $res->challenge);
349 if ($contact['duplex'] && strlen($contact['prvkey'])) {
350 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
351 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
353 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
354 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
357 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
359 if (strpos($final_dfrn_id, ':') == 1) {
360 $final_dfrn_id = substr($final_dfrn_id, 2);
363 // There are issues with the legacy DFRN transport layer.
364 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
365 if (empty($final_dfrn_id) || empty($orig_id)) {
366 Logger::log('Contact has got no ID - quitting');
370 if ($final_dfrn_id != $orig_id) {
371 // did not decode properly - cannot trust this site
372 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
374 // set the last-update so we don't keep polling
375 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
376 Contact::markForArchival($contact);
380 $postvars['dfrn_id'] = $idtosend;
381 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
382 $postvars['perm'] = 'rw';
384 return Network::post($contact['poll'], $postvars)->getBody();
388 * Poll Feed/OStatus contacts
390 * @param array $contact The personal contact entry
391 * @param string $protocol The used protocol of the contact
392 * @param string $updated The updated date
393 * @return string polled XML
396 private static function pollFeed(array $contact, $protocol, $updated)
398 // Upgrading DB fields from an older Friendica version
399 // Will only do this once per notify-enabled OStatus contact
400 // or if relationship changes
402 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
404 // Contacts from OStatus are always writable
405 if ($protocol === Protocol::OSTATUS) {
409 if ($stat_writeable != $contact['writable']) {
410 $fields = ['writable' => $stat_writeable];
411 DBA::update('contact', $fields, ['id' => $contact['id']]);
414 // Are we allowed to import from this person?
415 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
416 // set the last-update so we don't keep polling
417 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
418 Logger::log('Contact is blocked or only a follower');
422 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
423 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
426 if ($curlResult->isTimeout()) {
427 // set the last-update so we don't keep polling
428 self::updateContact($contact, ['last-update' => $updated]);
429 Contact::markForArchival($contact);
430 Logger::log('Contact archived');
434 return $curlResult->getBody();
440 * @param array $contact The personal contact entry
441 * @param integer $importer_uid The UID of the importer
442 * @param string $updated The updated date
445 private static function pollMail(array $contact, $importer_uid, $updated)
447 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
449 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
450 if ($mail_disabled) {
451 // set the last-update so we don't keep polling
452 self::updateContact($contact, ['last-update' => $updated]);
453 Contact::markForArchival($contact);
454 Logger::log('Contact archived');
458 Logger::log("Mail: Enabled", Logger::DEBUG);
461 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
463 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
464 $mailconf = DBA::selectFirst('mailacct', [], $condition);
465 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
466 $mailbox = Email::constructMailboxName($mailconf);
468 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
469 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
471 Logger::log("Mail: Connect to " . $mailconf['user']);
473 $fields = ['last_check' => $updated];
474 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
475 Logger::log("Mail: Connected to " . $mailconf['user']);
477 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
485 $msgs = Email::poll($mbox, $contact['addr']);
488 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
490 $metas = Email::messageMeta($mbox, implode(',', $msgs));
492 if (count($metas) != count($msgs)) {
493 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
495 $msgs = array_combine($msgs, $metas);
497 foreach ($msgs as $msg_uid => $meta) {
498 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
501 $datarray['uid'] = $importer_uid;
502 $datarray['contact-id'] = $contact['id'];
503 $datarray['verb'] = Activity::POST;
504 $datarray['object-type'] = Activity\ObjectType::NOTE;
505 $datarray['network'] = Protocol::MAIL;
506 // $meta = Email::messageMeta($mbox, $msg_uid);
508 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
510 // Have we seen it before?
511 $fields = ['deleted', 'id'];
512 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
513 $item = Item::selectFirst($fields, $condition);
514 if (DBA::isResult($item)) {
515 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
517 // Only delete when mails aren't automatically moved or deleted
518 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
519 if ($meta->deleted && ! $item['deleted']) {
520 $fields = ['deleted' => true, 'changed' => $updated];
521 Item::update($fields, ['id' => $item['id']]);
524 switch ($mailconf['action']) {
526 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
529 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
530 imap_delete($mbox, $msg_uid, FT_UID);
533 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
534 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
537 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
538 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
539 if ($mailconf['movetofolder'] != "") {
540 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
547 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
548 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
549 if (!trim($raw_refs)) {
550 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
552 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
555 $refs_arr = explode(' ', $raw_refs);
556 if (count($refs_arr)) {
557 for ($x = 0; $x < count($refs_arr); $x ++) {
558 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
561 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
562 $parent = Item::selectFirst(['parent-uri'], $condition);
563 if (DBA::isResult($parent)) {
564 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
568 // Decoding the header
569 $subject = imap_mime_header_decode($meta->subject ?? '');
570 $datarray['title'] = "";
571 foreach ($subject as $subpart) {
572 if ($subpart->charset != "default") {
573 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
575 $datarray['title'] .= $subpart->text;
578 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
580 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
581 $datarray['created'] = DateTimeFormat::utc($meta->date);
584 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
585 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
588 // Remove Reply-signs in the subject
589 $datarray['title'] = self::RemoveReply($datarray['title']);
591 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
592 if (empty($datarray['parent-uri']) && $reply) {
593 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
594 $params = ['order' => ['created' => true]];
595 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
596 if (DBA::isResult($parent)) {
597 $datarray['parent-uri'] = $parent['parent-uri'];
601 if (empty($datarray['parent-uri'])) {
602 $datarray['parent-uri'] = $datarray['uri'];
605 $headers = imap_headerinfo($mbox, $meta->msgno);
609 if (!empty($headers->from)) {
610 $object['from'] = $headers->from;
613 if (!empty($headers->to)) {
614 $object['to'] = $headers->to;
617 if (!empty($headers->reply_to)) {
618 $object['reply_to'] = $headers->reply_to;
621 if (!empty($headers->sender)) {
622 $object['sender'] = $headers->sender;
625 if (!empty($object)) {
626 $datarray['object'] = json_encode($object);
629 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
630 if (!empty($headers->from[0]->personal)) {
631 $fromname = $headers->from[0]->personal;
634 $datarray['author-name'] = $fromname;
635 $datarray['author-link'] = "mailto:".$frommail;
636 $datarray['author-avatar'] = $contact['photo'];
638 $datarray['owner-name'] = $contact['name'];
639 $datarray['owner-link'] = "mailto:".$contact['addr'];
640 $datarray['owner-avatar'] = $contact['photo'];
642 if ($datarray['parent-uri'] === $datarray['uri']) {
643 $datarray['private'] = 1;
646 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
647 $datarray['private'] = 1;
648 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
651 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
652 if (empty($datarray['body'])) {
653 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
657 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
659 Item::insert($datarray);
661 switch ($mailconf['action']) {
663 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
666 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
667 imap_delete($mbox, $msg_uid, FT_UID);
670 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
671 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
674 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
675 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
676 if ($mailconf['movetofolder'] != "") {
677 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
684 Logger::log("Mail: no mails for ".$mailconf['user']);
687 Logger::log("Mail: closing connection for ".$mailconf['user']);