3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Config;
8 use Friendica\Core\Logger;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\Protocol;
11 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');
42 Contact::updateFromProbe($contact_id, '', true);
45 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
46 if (!DBA::isResult($contact)) {
47 Logger::log('Contact not found or cannot be used.');
51 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
52 $protocol = Protocol::ACTIVITYPUB;
54 $protocol = $contact['network'];
57 $importer_uid = $contact['uid'];
59 $updated = DateTimeFormat::utcNow();
61 if ($importer_uid == 0) {
62 Logger::log('Ignore public contacts');
64 // set the last-update so we don't keep polling
65 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
69 // Possibly switch the remote contact to AP
70 if ($protocol === Protocol::OSTATUS) {
71 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
72 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
75 // load current friends if possible.
76 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
77 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
78 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
82 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
83 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
84 Logger::log('Polling is disabled');
86 // set the last-update so we don't keep polling
87 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
91 // We don't poll AP contacts by now
92 if ($protocol === Protocol::ACTIVITYPUB) {
93 Logger::log("Don't poll AP contact");
95 // set the last-update so we don't keep polling
96 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
100 $importer = User::getOwnerDataById($importer_uid);
102 if (empty($importer)) {
103 Logger::log('No self contact for user '.$importer_uid);
105 // set the last-update so we don't keep polling
106 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
113 if ($contact['subhub']) {
114 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
115 $contact['priority'] = intval($poll_interval);
118 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
125 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
129 if ($protocol === Protocol::DFRN) {
130 $xml = self::pollDFRN($contact, $updated);
131 } elseif (($protocol === Protocol::OSTATUS)
132 || ($protocol === Protocol::DIASPORA)
133 || ($protocol === Protocol::FEED)) {
134 $xml = self::pollFeed($contact, $protocol, $updated);
135 } elseif ($protocol === Protocol::MAIL) {
136 self::pollMail($contact, $importer_uid, $updated);
140 Logger::log('received xml : ' . $xml, Logger::DATA);
141 if (!strstr($xml, '<')) {
142 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
144 $fields = ['last-update' => $updated, 'failure_update' => $updated];
145 self::updateContact($contact, $fields);
146 Contact::markForArchival($contact);
151 Logger::log("Consume feed of contact ".$contact['id']);
153 consume_feed($xml, $importer, $contact, $hub);
155 // do it a second time for DFRN so that any children find their parents.
156 if ($protocol === Protocol::DFRN) {
157 consume_feed($xml, $importer, $contact, $hub);
160 $hubmode = 'subscribe';
161 if ($protocol === Protocol::DFRN || $contact['blocked']) {
162 $hubmode = 'unsubscribe';
165 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
173 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
175 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
176 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
177 $hubs = explode(',', $hub);
180 foreach ($hubs as $h) {
187 subscribe_to_hub($h, $importer, $contact, $hubmode);
192 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
193 Contact::unmarkForArchival($contact);
194 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
195 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
196 Contact::markForArchival($contact);
198 self::updateContact($contact, ['last-update' => $updated]);
205 private static function RemoveReply($subject)
207 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
208 $subject = trim(substr($subject, 4));
215 * @brief Updates a personal contact entry and the public contact entry
217 * @param array $contact The personal contact entry
218 * @param array $fields The fields that are updated
221 private static function updateContact(array $contact, array $fields)
223 DBA::update('contact', $fields, ['id' => $contact['id']]);
224 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
228 * @brief Poll DFRN contacts
230 * @param array $contact The personal contact entry
231 * @param string $updated The updated date
232 * @return string polled XML
235 private static function pollDFRN(array $contact, $updated)
237 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
238 if (intval($contact['duplex']) && $contact['dfrn-id']) {
239 $idtosend = '0:' . $orig_id;
241 if (intval($contact['duplex']) && $contact['issued-id']) {
242 $idtosend = '1:' . $orig_id;
245 // they have permission to write to us. We already filtered this in the contact query.
248 // But this may be our first communication, so set the writable flag if it isn't set already.
249 if (!intval($contact['writable'])) {
250 $fields = ['writable' => true];
251 DBA::update('contact', $fields, ['id' => $contact['id']]);
254 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
255 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
256 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
259 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
260 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
261 . '&type=data&last_update=' . $last_update
264 $curlResult = Network::curl($url);
266 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
267 // set the last-update so we don't keep polling
268 self::updateContact($contact, ['last-update' => $updated]);
269 Contact::markForArchival($contact);
270 Logger::log('Contact archived');
274 $handshake_xml = $curlResult->getBody();
275 $html_code = $curlResult->getReturnCode();
277 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
279 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
280 // dead connection - might be a transient event, or this might
281 // mean the software was uninstalled or the domain expired.
282 // Will keep trying for one month.
283 Logger::log("$url appears to be dead - marking for death ");
285 // set the last-update so we don't keep polling
286 $fields = ['last-update' => $updated, 'failure_update' => $updated];
287 self::updateContact($contact, $fields);
288 Contact::markForArchival($contact);
292 if (!strstr($handshake_xml, '<')) {
293 Logger::log('response from ' . $url . ' did not contain XML.');
295 $fields = ['last-update' => $updated, 'failure_update' => $updated];
296 self::updateContact($contact, $fields);
297 Contact::markForArchival($contact);
301 $res = XML::parseString($handshake_xml);
303 if (!is_object($res)) {
304 Logger::info('Unparseable response', ['url' => $url]);
306 $fields = ['last-update' => $updated, 'failure_update' => $updated];
307 self::updateContact($contact, $fields);
308 Contact::markForArchival($contact);
312 if (intval($res->status) == 1) {
313 // we may not be friends anymore. Will keep trying for one month.
314 Logger::log("$url replied status 1 - marking for death ");
316 // set the last-update so we don't keep polling
317 $fields = ['last-update' => $updated, 'failure_update' => $updated];
318 self::updateContact($contact, $fields);
319 Contact::markForArchival($contact);
320 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
321 Contact::unmarkForArchival($contact);
324 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
325 // set the last-update so we don't keep polling
326 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
327 Logger::log('Contact status is ' . $res->status);
331 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
332 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
333 DBA::update('contact', $fields, ['id' => $contact['id']]);
338 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
339 $challenge = hex2bin((string) $res->challenge);
343 if ($contact['duplex'] && strlen($contact['prvkey'])) {
344 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
345 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
347 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
348 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
351 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
353 if (strpos($final_dfrn_id, ':') == 1) {
354 $final_dfrn_id = substr($final_dfrn_id, 2);
357 // There are issues with the legacy DFRN transport layer.
358 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
359 if (empty($final_dfrn_id) || empty($orig_id)) {
360 Logger::log('Contact has got no ID - quitting');
364 if ($final_dfrn_id != $orig_id) {
365 // did not decode properly - cannot trust this site
366 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
368 // set the last-update so we don't keep polling
369 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
370 Contact::markForArchival($contact);
374 $postvars['dfrn_id'] = $idtosend;
375 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
376 $postvars['perm'] = 'rw';
378 return Network::post($contact['poll'], $postvars)->getBody();
382 * @brief Poll Feed/OStatus contacts
384 * @param array $contact The personal contact entry
385 * @param string $protocol The used protocol of the contact
386 * @param string $updated The updated date
387 * @return string polled XML
390 private static function pollFeed(array $contact, $protocol, $updated)
392 // Upgrading DB fields from an older Friendica version
393 // Will only do this once per notify-enabled OStatus contact
394 // or if relationship changes
396 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
398 // Contacts from OStatus are always writable
399 if ($protocol === Protocol::OSTATUS) {
403 if ($stat_writeable != $contact['writable']) {
404 $fields = ['writable' => $stat_writeable];
405 DBA::update('contact', $fields, ['id' => $contact['id']]);
408 // Are we allowed to import from this person?
409 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
410 // set the last-update so we don't keep polling
411 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
412 Logger::log('Contact is blocked or only a follower');
416 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
417 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
420 if ($curlResult->isTimeout()) {
421 // set the last-update so we don't keep polling
422 self::updateContact($contact, ['last-update' => $updated]);
423 Contact::markForArchival($contact);
424 Logger::log('Contact archived');
428 return $curlResult->getBody();
432 * @brief Poll Mail contacts
434 * @param array $contact The personal contact entry
435 * @param integer $importer_uid The UID of the importer
436 * @param string $updated The updated date
439 private static function pollMail(array $contact, $importer_uid, $updated)
441 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
443 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
444 if ($mail_disabled) {
445 // set the last-update so we don't keep polling
446 self::updateContact($contact, ['last-update' => $updated]);
447 Contact::markForArchival($contact);
448 Logger::log('Contact archived');
452 Logger::log("Mail: Enabled", Logger::DEBUG);
455 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
457 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
458 $mailconf = DBA::selectFirst('mailacct', [], $condition);
459 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
460 $mailbox = Email::constructMailboxName($mailconf);
462 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
463 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
465 Logger::log("Mail: Connect to " . $mailconf['user']);
467 $fields = ['last_check' => $updated];
468 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
469 Logger::log("Mail: Connected to " . $mailconf['user']);
471 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
479 $msgs = Email::poll($mbox, $contact['addr']);
482 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
484 $metas = Email::messageMeta($mbox, implode(',', $msgs));
486 if (count($metas) != count($msgs)) {
487 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
489 $msgs = array_combine($msgs, $metas);
491 foreach ($msgs as $msg_uid => $meta) {
492 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
495 $datarray['uid'] = $importer_uid;
496 $datarray['contact-id'] = $contact['id'];
497 $datarray['verb'] = Activity::POST;
498 $datarray['object-type'] = Activity\ObjectType::NOTE;
499 $datarray['network'] = Protocol::MAIL;
500 // $meta = Email::messageMeta($mbox, $msg_uid);
502 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
504 // Have we seen it before?
505 $fields = ['deleted', 'id'];
506 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
507 $item = Item::selectFirst($fields, $condition);
508 if (DBA::isResult($item)) {
509 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
511 // Only delete when mails aren't automatically moved or deleted
512 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
513 if ($meta->deleted && ! $item['deleted']) {
514 $fields = ['deleted' => true, 'changed' => $updated];
515 Item::update($fields, ['id' => $item['id']]);
518 switch ($mailconf['action']) {
520 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
523 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
524 imap_delete($mbox, $msg_uid, FT_UID);
527 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
528 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
531 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
532 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
533 if ($mailconf['movetofolder'] != "") {
534 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
541 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
542 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
543 if (!trim($raw_refs)) {
544 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
546 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
549 $refs_arr = explode(' ', $raw_refs);
550 if (count($refs_arr)) {
551 for ($x = 0; $x < count($refs_arr); $x ++) {
552 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
555 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
556 $parent = Item::selectFirst(['parent-uri'], $condition);
557 if (DBA::isResult($parent)) {
558 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
562 // Decoding the header
563 $subject = imap_mime_header_decode($meta->subject ?? '');
564 $datarray['title'] = "";
565 foreach ($subject as $subpart) {
566 if ($subpart->charset != "default") {
567 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
569 $datarray['title'] .= $subpart->text;
572 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
574 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
575 $datarray['created'] = DateTimeFormat::utc($meta->date);
578 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
579 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
582 // Remove Reply-signs in the subject
583 $datarray['title'] = self::RemoveReply($datarray['title']);
585 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
586 if (empty($datarray['parent-uri']) && $reply) {
587 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
588 $params = ['order' => ['created' => true]];
589 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
590 if (DBA::isResult($parent)) {
591 $datarray['parent-uri'] = $parent['parent-uri'];
595 if (empty($datarray['parent-uri'])) {
596 $datarray['parent-uri'] = $datarray['uri'];
599 $headers = imap_headerinfo($mbox, $meta->msgno);
603 if (!empty($headers->from)) {
604 $object['from'] = $headers->from;
607 if (!empty($headers->to)) {
608 $object['to'] = $headers->to;
611 if (!empty($headers->reply_to)) {
612 $object['reply_to'] = $headers->reply_to;
615 if (!empty($headers->sender)) {
616 $object['sender'] = $headers->sender;
619 if (!empty($object)) {
620 $datarray['object'] = json_encode($object);
623 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
624 if (!empty($headers->from[0]->personal)) {
625 $fromname = $headers->from[0]->personal;
628 $datarray['author-name'] = $fromname;
629 $datarray['author-link'] = "mailto:".$frommail;
630 $datarray['author-avatar'] = $contact['photo'];
632 $datarray['owner-name'] = $contact['name'];
633 $datarray['owner-link'] = "mailto:".$contact['addr'];
634 $datarray['owner-avatar'] = $contact['photo'];
636 if ($datarray['parent-uri'] === $datarray['uri']) {
637 $datarray['private'] = 1;
640 if (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
641 $datarray['private'] = 1;
642 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
645 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
646 if (empty($datarray['body'])) {
647 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
651 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
653 Item::insert($datarray);
655 switch ($mailconf['action']) {
657 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
660 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
661 imap_delete($mbox, $msg_uid, FT_UID);
664 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
665 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
668 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
669 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
670 if ($mailconf['movetofolder'] != "") {
671 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
678 Logger::log("Mail: no mails for ".$mailconf['user']);
681 Logger::log("Mail: closing connection for ".$mailconf['user']);