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;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Model\User;
16 use Friendica\Protocol\Activity;
17 use Friendica\Protocol\ActivityPub;
18 use Friendica\Protocol\Email;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Strings;
23 use Friendica\Util\XML;
27 public static function execute($contact_id = 0, $command = '')
29 Logger::log('Start for contact ' . $contact_id);
33 if ($command == "force") {
38 Logger::log('no contact');
42 Contact::updateFromProbe($contact_id, '', $force);
44 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
45 if (!DBA::isResult($contact)) {
46 Logger::log('Contact not found or cannot be used.');
50 // Special treatment for wrongly detected local contacts
51 if (!$force && ($contact['network'] != Protocol::DFRN) && Contact::isLocalById($contact_id)) {
52 Contact::updateFromProbe($contact_id, Protocol::DFRN, true);
53 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
56 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
57 $protocol = Protocol::ACTIVITYPUB;
59 $protocol = $contact['network'];
62 $importer_uid = $contact['uid'];
64 $updated = DateTimeFormat::utcNow();
66 if ($importer_uid == 0) {
67 Logger::log('Ignore public contacts');
69 // set the last-update so we don't keep polling
70 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
74 // Possibly switch the remote contact to AP
75 if ($protocol === Protocol::OSTATUS) {
76 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
77 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
80 // load current friends if possible.
81 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
82 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
83 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
87 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
88 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
89 Logger::log('Polling is disabled');
91 // set the last-update so we don't keep polling
92 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
96 // We don't poll AP contacts by now
97 if ($protocol === Protocol::ACTIVITYPUB) {
98 Logger::log("Don't poll AP contact");
100 // set the last-update so we don't keep polling
101 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
105 $importer = User::getOwnerDataById($importer_uid);
107 if (empty($importer)) {
108 Logger::log('No self contact for user '.$importer_uid);
110 // set the last-update so we don't keep polling
111 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
118 if ($contact['subhub']) {
119 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
120 $contact['priority'] = intval($poll_interval);
123 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
130 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
134 if ($protocol === Protocol::DFRN) {
135 $xml = self::pollDFRN($contact, $updated);
136 } elseif (($protocol === Protocol::OSTATUS)
137 || ($protocol === Protocol::DIASPORA)
138 || ($protocol === Protocol::FEED)) {
139 $xml = self::pollFeed($contact, $protocol, $updated);
140 } elseif ($protocol === Protocol::MAIL) {
141 self::pollMail($contact, $importer_uid, $updated);
145 Logger::log('received xml : ' . $xml, Logger::DATA);
146 if (!strstr($xml, '<')) {
147 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
149 $fields = ['last-update' => $updated, 'failure_update' => $updated];
150 self::updateContact($contact, $fields);
151 Contact::markForArchival($contact);
156 Logger::log("Consume feed of contact ".$contact['id']);
158 consume_feed($xml, $importer, $contact, $hub);
160 // do it a second time for DFRN so that any children find their parents.
161 if ($protocol === Protocol::DFRN) {
162 consume_feed($xml, $importer, $contact, $hub);
165 $hubmode = 'subscribe';
166 if ($protocol === Protocol::DFRN || $contact['blocked']) {
167 $hubmode = 'unsubscribe';
170 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
178 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
180 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
181 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
182 $hubs = explode(',', $hub);
185 foreach ($hubs as $h) {
192 subscribe_to_hub($h, $importer, $contact, $hubmode);
197 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
198 Contact::unmarkForArchival($contact);
199 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
200 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
201 Contact::markForArchival($contact);
203 self::updateContact($contact, ['last-update' => $updated]);
210 private static function RemoveReply($subject)
212 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
213 $subject = trim(substr($subject, 4));
220 * @brief Updates a personal contact entry and the public contact entry
222 * @param array $contact The personal contact entry
223 * @param array $fields The fields that are updated
226 private static function updateContact(array $contact, array $fields)
228 DBA::update('contact', $fields, ['id' => $contact['id']]);
229 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
233 * @brief Poll DFRN contacts
235 * @param array $contact The personal contact entry
236 * @param string $updated The updated date
237 * @return string polled XML
240 private static function pollDFRN(array $contact, $updated)
242 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
243 if (intval($contact['duplex']) && $contact['dfrn-id']) {
244 $idtosend = '0:' . $orig_id;
246 if (intval($contact['duplex']) && $contact['issued-id']) {
247 $idtosend = '1:' . $orig_id;
250 // they have permission to write to us. We already filtered this in the contact query.
253 // But this may be our first communication, so set the writable flag if it isn't set already.
254 if (!intval($contact['writable'])) {
255 $fields = ['writable' => true];
256 DBA::update('contact', $fields, ['id' => $contact['id']]);
259 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
260 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
261 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
264 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
265 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
266 . '&type=data&last_update=' . $last_update
269 $curlResult = Network::curl($url);
271 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
272 // set the last-update so we don't keep polling
273 self::updateContact($contact, ['last-update' => $updated]);
274 Contact::markForArchival($contact);
275 Logger::log('Contact archived');
279 $handshake_xml = $curlResult->getBody();
280 $html_code = $curlResult->getReturnCode();
282 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
284 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
285 // dead connection - might be a transient event, or this might
286 // mean the software was uninstalled or the domain expired.
287 // Will keep trying for one month.
288 Logger::log("$url appears to be dead - marking for death ");
290 // set the last-update so we don't keep polling
291 $fields = ['last-update' => $updated, 'failure_update' => $updated];
292 self::updateContact($contact, $fields);
293 Contact::markForArchival($contact);
297 if (!strstr($handshake_xml, '<')) {
298 Logger::log('response from ' . $url . ' did not contain XML.');
300 $fields = ['last-update' => $updated, 'failure_update' => $updated];
301 self::updateContact($contact, $fields);
302 Contact::markForArchival($contact);
306 $res = XML::parseString($handshake_xml);
308 if (!is_object($res)) {
309 Logger::info('Unparseable response', ['url' => $url]);
311 $fields = ['last-update' => $updated, 'failure_update' => $updated];
312 self::updateContact($contact, $fields);
313 Contact::markForArchival($contact);
317 if (intval($res->status) == 1) {
318 // we may not be friends anymore. Will keep trying for one month.
319 Logger::log("$url replied status 1 - marking for death ");
321 // set the last-update so we don't keep polling
322 $fields = ['last-update' => $updated, 'failure_update' => $updated];
323 self::updateContact($contact, $fields);
324 Contact::markForArchival($contact);
325 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
326 Contact::unmarkForArchival($contact);
329 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
330 // set the last-update so we don't keep polling
331 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
332 Logger::log('Contact status is ' . $res->status);
336 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
337 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
338 DBA::update('contact', $fields, ['id' => $contact['id']]);
343 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
344 $challenge = hex2bin((string) $res->challenge);
348 if ($contact['duplex'] && strlen($contact['prvkey'])) {
349 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
350 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
352 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
353 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
356 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
358 if (strpos($final_dfrn_id, ':') == 1) {
359 $final_dfrn_id = substr($final_dfrn_id, 2);
362 // There are issues with the legacy DFRN transport layer.
363 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
364 if (empty($final_dfrn_id) || empty($orig_id)) {
365 Logger::log('Contact has got no ID - quitting');
369 if ($final_dfrn_id != $orig_id) {
370 // did not decode properly - cannot trust this site
371 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
373 // set the last-update so we don't keep polling
374 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
375 Contact::markForArchival($contact);
379 $postvars['dfrn_id'] = $idtosend;
380 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
381 $postvars['perm'] = 'rw';
383 return Network::post($contact['poll'], $postvars)->getBody();
387 * @brief Poll Feed/OStatus contacts
389 * @param array $contact The personal contact entry
390 * @param string $protocol The used protocol of the contact
391 * @param string $updated The updated date
392 * @return string polled XML
395 private static function pollFeed(array $contact, $protocol, $updated)
397 // Upgrading DB fields from an older Friendica version
398 // Will only do this once per notify-enabled OStatus contact
399 // or if relationship changes
401 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
403 // Contacts from OStatus are always writable
404 if ($protocol === Protocol::OSTATUS) {
408 if ($stat_writeable != $contact['writable']) {
409 $fields = ['writable' => $stat_writeable];
410 DBA::update('contact', $fields, ['id' => $contact['id']]);
413 // Are we allowed to import from this person?
414 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
415 // set the last-update so we don't keep polling
416 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
417 Logger::log('Contact is blocked or only a follower');
421 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
422 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
425 if ($curlResult->isTimeout()) {
426 // set the last-update so we don't keep polling
427 self::updateContact($contact, ['last-update' => $updated]);
428 Contact::markForArchival($contact);
429 Logger::log('Contact archived');
433 return $curlResult->getBody();
437 * @brief Poll Mail contacts
439 * @param array $contact The personal contact entry
440 * @param integer $importer_uid The UID of the importer
441 * @param string $updated The updated date
444 private static function pollMail(array $contact, $importer_uid, $updated)
446 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
448 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
449 if ($mail_disabled) {
450 // set the last-update so we don't keep polling
451 self::updateContact($contact, ['last-update' => $updated]);
452 Contact::markForArchival($contact);
453 Logger::log('Contact archived');
457 Logger::log("Mail: Enabled", Logger::DEBUG);
460 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
462 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
463 $mailconf = DBA::selectFirst('mailacct', [], $condition);
464 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
465 $mailbox = Email::constructMailboxName($mailconf);
467 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
468 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
470 Logger::log("Mail: Connect to " . $mailconf['user']);
472 $fields = ['last_check' => $updated];
473 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
474 Logger::log("Mail: Connected to " . $mailconf['user']);
476 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
484 $msgs = Email::poll($mbox, $contact['addr']);
487 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
489 $metas = Email::messageMeta($mbox, implode(',', $msgs));
491 if (count($metas) != count($msgs)) {
492 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
494 $msgs = array_combine($msgs, $metas);
496 foreach ($msgs as $msg_uid => $meta) {
497 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
500 $datarray['uid'] = $importer_uid;
501 $datarray['contact-id'] = $contact['id'];
502 $datarray['verb'] = Activity::POST;
503 $datarray['object-type'] = Activity\ObjectType::NOTE;
504 $datarray['network'] = Protocol::MAIL;
505 // $meta = Email::messageMeta($mbox, $msg_uid);
507 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
509 // Have we seen it before?
510 $fields = ['deleted', 'id'];
511 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
512 $item = Item::selectFirst($fields, $condition);
513 if (DBA::isResult($item)) {
514 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
516 // Only delete when mails aren't automatically moved or deleted
517 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
518 if ($meta->deleted && ! $item['deleted']) {
519 $fields = ['deleted' => true, 'changed' => $updated];
520 Item::update($fields, ['id' => $item['id']]);
523 switch ($mailconf['action']) {
525 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
528 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
529 imap_delete($mbox, $msg_uid, FT_UID);
532 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
533 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
536 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
537 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
538 if ($mailconf['movetofolder'] != "") {
539 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
546 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
547 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
548 if (!trim($raw_refs)) {
549 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
551 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
554 $refs_arr = explode(' ', $raw_refs);
555 if (count($refs_arr)) {
556 for ($x = 0; $x < count($refs_arr); $x ++) {
557 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
560 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
561 $parent = Item::selectFirst(['parent-uri'], $condition);
562 if (DBA::isResult($parent)) {
563 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
567 // Decoding the header
568 $subject = imap_mime_header_decode($meta->subject ?? '');
569 $datarray['title'] = "";
570 foreach ($subject as $subpart) {
571 if ($subpart->charset != "default") {
572 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
574 $datarray['title'] .= $subpart->text;
577 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
579 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
580 $datarray['created'] = DateTimeFormat::utc($meta->date);
583 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
584 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
587 // Remove Reply-signs in the subject
588 $datarray['title'] = self::RemoveReply($datarray['title']);
590 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
591 if (empty($datarray['parent-uri']) && $reply) {
592 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
593 $params = ['order' => ['created' => true]];
594 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
595 if (DBA::isResult($parent)) {
596 $datarray['parent-uri'] = $parent['parent-uri'];
600 if (empty($datarray['parent-uri'])) {
601 $datarray['parent-uri'] = $datarray['uri'];
604 $headers = imap_headerinfo($mbox, $meta->msgno);
608 if (!empty($headers->from)) {
609 $object['from'] = $headers->from;
612 if (!empty($headers->to)) {
613 $object['to'] = $headers->to;
616 if (!empty($headers->reply_to)) {
617 $object['reply_to'] = $headers->reply_to;
620 if (!empty($headers->sender)) {
621 $object['sender'] = $headers->sender;
624 if (!empty($object)) {
625 $datarray['object'] = json_encode($object);
628 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
629 if (!empty($headers->from[0]->personal)) {
630 $fromname = $headers->from[0]->personal;
633 $datarray['author-name'] = $fromname;
634 $datarray['author-link'] = "mailto:".$frommail;
635 $datarray['author-avatar'] = $contact['photo'];
637 $datarray['owner-name'] = $contact['name'];
638 $datarray['owner-link'] = "mailto:".$contact['addr'];
639 $datarray['owner-avatar'] = $contact['photo'];
641 if ($datarray['parent-uri'] === $datarray['uri']) {
642 $datarray['private'] = 1;
645 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
646 $datarray['private'] = 1;
647 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
650 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
651 if (empty($datarray['body'])) {
652 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
656 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
658 Item::insert($datarray);
660 switch ($mailconf['action']) {
662 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
665 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
666 imap_delete($mbox, $msg_uid, FT_UID);
669 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
670 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
673 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
674 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
675 if ($mailconf['movetofolder'] != "") {
676 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
683 Logger::log("Mail: no mails for ".$mailconf['user']);
686 Logger::log("Mail: closing connection for ".$mailconf['user']);