3 * @file src/Worker/OnePoll.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Protocol\Activity;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Protocol\Email;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
24 use Friendica\Util\XML;
28 public static function execute($contact_id = 0, $command = '')
30 Logger::log('Start for contact ' . $contact_id);
34 if ($command == "force") {
39 Logger::log('no contact');
44 Contact::updateFromProbe($contact_id, '', true);
47 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
48 if (!DBA::isResult($contact)) {
49 Logger::log('Contact not found or cannot be used.');
53 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
54 $protocol = Protocol::ACTIVITYPUB;
56 $protocol = $contact['network'];
59 $importer_uid = $contact['uid'];
61 $updated = DateTimeFormat::utcNow();
63 if ($importer_uid == 0) {
64 Logger::log('Ignore public contacts');
66 // set the last-update so we don't keep polling
67 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
71 // Possibly switch the remote contact to AP
72 if ($protocol === Protocol::OSTATUS) {
73 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
74 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
77 // load current friends if possible.
78 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
79 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
80 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
84 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
85 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
86 Logger::log('Polling is disabled');
88 // set the last-update so we don't keep polling
89 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
93 // We don't poll AP contacts by now
94 if ($protocol === Protocol::ACTIVITYPUB) {
95 Logger::log("Don't poll AP contact");
97 // set the last-update so we don't keep polling
98 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
102 $importer = User::getOwnerDataById($importer_uid);
104 if (empty($importer)) {
105 Logger::log('No self contact for user '.$importer_uid);
107 // set the last-update so we don't keep polling
108 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
115 if ($contact['subhub']) {
116 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
117 $contact['priority'] = intval($poll_interval);
120 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
127 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
131 if ($protocol === Protocol::DFRN) {
132 $xml = self::pollDFRN($contact, $updated);
133 } elseif (($protocol === Protocol::OSTATUS)
134 || ($protocol === Protocol::DIASPORA)
135 || ($protocol === Protocol::FEED)) {
136 $xml = self::pollFeed($contact, $protocol, $updated);
137 } elseif ($protocol === Protocol::MAIL) {
138 self::pollMail($contact, $importer_uid, $updated);
142 Logger::log('received xml : ' . $xml, Logger::DATA);
143 if (!strstr($xml, '<')) {
144 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
146 $fields = ['last-update' => $updated, 'failure_update' => $updated];
147 self::updateContact($contact, $fields);
148 Contact::markForArchival($contact);
153 Logger::log("Consume feed of contact ".$contact['id']);
155 consume_feed($xml, $importer, $contact, $hub);
157 // do it a second time for DFRN so that any children find their parents.
158 if ($protocol === Protocol::DFRN) {
159 consume_feed($xml, $importer, $contact, $hub);
162 $hubmode = 'subscribe';
163 if ($protocol === Protocol::DFRN || $contact['blocked']) {
164 $hubmode = 'unsubscribe';
167 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
175 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
177 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
178 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
179 $hubs = explode(',', $hub);
182 foreach ($hubs as $h) {
189 subscribe_to_hub($h, $importer, $contact, $hubmode);
194 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
195 Contact::unmarkForArchival($contact);
196 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
197 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
198 Contact::markForArchival($contact);
200 self::updateContact($contact, ['last-update' => $updated]);
207 private static function RemoveReply($subject)
209 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
210 $subject = trim(substr($subject, 4));
217 * @brief Updates a personal contact entry and the public contact entry
219 * @param array $contact The personal contact entry
220 * @param array $fields The fields that are updated
223 private static function updateContact(array $contact, array $fields)
225 DBA::update('contact', $fields, ['id' => $contact['id']]);
226 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
230 * @brief Poll DFRN contacts
232 * @param array $contact The personal contact entry
233 * @param string $updated The updated date
234 * @return string polled XML
237 private static function pollDFRN(array $contact, $updated)
239 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
240 if (intval($contact['duplex']) && $contact['dfrn-id']) {
241 $idtosend = '0:' . $orig_id;
243 if (intval($contact['duplex']) && $contact['issued-id']) {
244 $idtosend = '1:' . $orig_id;
247 // they have permission to write to us. We already filtered this in the contact query.
250 // But this may be our first communication, so set the writable flag if it isn't set already.
251 if (!intval($contact['writable'])) {
252 $fields = ['writable' => true];
253 DBA::update('contact', $fields, ['id' => $contact['id']]);
256 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
257 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
258 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
261 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
262 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
263 . '&type=data&last_update=' . $last_update
266 $curlResult = Network::curl($url);
268 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
269 // set the last-update so we don't keep polling
270 self::updateContact($contact, ['last-update' => $updated]);
271 Contact::markForArchival($contact);
272 Logger::log('Contact archived');
276 $handshake_xml = $curlResult->getBody();
277 $html_code = $curlResult->getReturnCode();
279 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
281 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
282 // dead connection - might be a transient event, or this might
283 // mean the software was uninstalled or the domain expired.
284 // Will keep trying for one month.
285 Logger::log("$url appears to be dead - marking for death ");
287 // set the last-update so we don't keep polling
288 $fields = ['last-update' => $updated, 'failure_update' => $updated];
289 self::updateContact($contact, $fields);
290 Contact::markForArchival($contact);
294 if (!strstr($handshake_xml, '<')) {
295 Logger::log('response from ' . $url . ' did not contain XML.');
297 $fields = ['last-update' => $updated, 'failure_update' => $updated];
298 self::updateContact($contact, $fields);
299 Contact::markForArchival($contact);
303 $res = XML::parseString($handshake_xml);
305 if (!is_object($res)) {
306 Logger::info('Unparseable response', ['url' => $url]);
308 $fields = ['last-update' => $updated, 'failure_update' => $updated];
309 self::updateContact($contact, $fields);
310 Contact::markForArchival($contact);
314 if (intval($res->status) == 1) {
315 // we may not be friends anymore. Will keep trying for one month.
316 Logger::log("$url replied status 1 - marking for death ");
318 // set the last-update so we don't keep polling
319 $fields = ['last-update' => $updated, 'failure_update' => $updated];
320 self::updateContact($contact, $fields);
321 Contact::markForArchival($contact);
322 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
323 Contact::unmarkForArchival($contact);
326 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
327 // set the last-update so we don't keep polling
328 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
329 Logger::log('Contact status is ' . $res->status);
333 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
334 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
335 DBA::update('contact', $fields, ['id' => $contact['id']]);
340 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
341 $challenge = hex2bin((string) $res->challenge);
345 if ($contact['duplex'] && strlen($contact['prvkey'])) {
346 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
347 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
349 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
350 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
353 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
355 if (strpos($final_dfrn_id, ':') == 1) {
356 $final_dfrn_id = substr($final_dfrn_id, 2);
359 // There are issues with the legacy DFRN transport layer.
360 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
361 if (empty($final_dfrn_id) || empty($orig_id)) {
362 Logger::log('Contact has got no ID - quitting');
366 if ($final_dfrn_id != $orig_id) {
367 // did not decode properly - cannot trust this site
368 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
370 // set the last-update so we don't keep polling
371 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
372 Contact::markForArchival($contact);
376 $postvars['dfrn_id'] = $idtosend;
377 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
378 $postvars['perm'] = 'rw';
380 return Network::post($contact['poll'], $postvars)->getBody();
384 * @brief Poll Feed/OStatus contacts
386 * @param array $contact The personal contact entry
387 * @param string $protocol The used protocol of the contact
388 * @param string $updated The updated date
389 * @return string polled XML
392 private static function pollFeed(array $contact, $protocol, $updated)
394 // Upgrading DB fields from an older Friendica version
395 // Will only do this once per notify-enabled OStatus contact
396 // or if relationship changes
398 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
400 // Contacts from OStatus are always writable
401 if ($protocol === Protocol::OSTATUS) {
405 if ($stat_writeable != $contact['writable']) {
406 $fields = ['writable' => $stat_writeable];
407 DBA::update('contact', $fields, ['id' => $contact['id']]);
410 // Are we allowed to import from this person?
411 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
412 // set the last-update so we don't keep polling
413 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
414 Logger::log('Contact is blocked or only a follower');
418 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
419 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
422 if ($curlResult->isTimeout()) {
423 // set the last-update so we don't keep polling
424 self::updateContact($contact, ['last-update' => $updated]);
425 Contact::markForArchival($contact);
426 Logger::log('Contact archived');
430 return $curlResult->getBody();
434 * @brief Poll Mail contacts
436 * @param array $contact The personal contact entry
437 * @param integer $importer_uid The UID of the importer
438 * @param string $updated The updated date
441 private static function pollMail(array $contact, $importer_uid, $updated)
443 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
445 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
446 if ($mail_disabled) {
447 // set the last-update so we don't keep polling
448 self::updateContact($contact, ['last-update' => $updated]);
449 Contact::markForArchival($contact);
450 Logger::log('Contact archived');
454 Logger::log("Mail: Enabled", Logger::DEBUG);
457 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
459 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
460 $mailconf = DBA::selectFirst('mailacct', [], $condition);
461 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
462 $mailbox = Email::constructMailboxName($mailconf);
464 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
465 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
467 Logger::log("Mail: Connect to " . $mailconf['user']);
469 $fields = ['last_check' => $updated];
470 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
471 Logger::log("Mail: Connected to " . $mailconf['user']);
473 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
481 $msgs = Email::poll($mbox, $contact['addr']);
484 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
486 $metas = Email::messageMeta($mbox, implode(',', $msgs));
488 if (count($metas) != count($msgs)) {
489 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
491 $msgs = array_combine($msgs, $metas);
493 foreach ($msgs as $msg_uid => $meta) {
494 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
497 $datarray['uid'] = $importer_uid;
498 $datarray['contact-id'] = $contact['id'];
499 $datarray['verb'] = Activity::POST;
500 $datarray['object-type'] = Activity\ObjectType::NOTE;
501 $datarray['network'] = Protocol::MAIL;
502 // $meta = Email::messageMeta($mbox, $msg_uid);
504 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
506 // Have we seen it before?
507 $fields = ['deleted', 'id'];
508 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
509 $item = Item::selectFirst($fields, $condition);
510 if (DBA::isResult($item)) {
511 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
513 // Only delete when mails aren't automatically moved or deleted
514 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
515 if ($meta->deleted && ! $item['deleted']) {
516 $fields = ['deleted' => true, 'changed' => $updated];
517 Item::update($fields, ['id' => $item['id']]);
520 switch ($mailconf['action']) {
522 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
525 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
526 imap_delete($mbox, $msg_uid, FT_UID);
529 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
530 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
533 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
534 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
535 if ($mailconf['movetofolder'] != "") {
536 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
543 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
544 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
545 if (!trim($raw_refs)) {
546 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
548 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
551 $refs_arr = explode(' ', $raw_refs);
552 if (count($refs_arr)) {
553 for ($x = 0; $x < count($refs_arr); $x ++) {
554 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
557 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
558 $parent = Item::selectFirst(['parent-uri'], $condition);
559 if (DBA::isResult($parent)) {
560 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
564 // Decoding the header
565 $subject = imap_mime_header_decode($meta->subject ?? '');
566 $datarray['title'] = "";
567 foreach ($subject as $subpart) {
568 if ($subpart->charset != "default") {
569 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
571 $datarray['title'] .= $subpart->text;
574 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
576 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
577 $datarray['created'] = DateTimeFormat::utc($meta->date);
580 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
581 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
584 // Remove Reply-signs in the subject
585 $datarray['title'] = self::RemoveReply($datarray['title']);
587 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
588 if (empty($datarray['parent-uri']) && $reply) {
589 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
590 $params = ['order' => ['created' => true]];
591 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
592 if (DBA::isResult($parent)) {
593 $datarray['parent-uri'] = $parent['parent-uri'];
597 if (empty($datarray['parent-uri'])) {
598 $datarray['parent-uri'] = $datarray['uri'];
601 $headers = imap_headerinfo($mbox, $meta->msgno);
605 if (!empty($headers->from)) {
606 $object['from'] = $headers->from;
609 if (!empty($headers->to)) {
610 $object['to'] = $headers->to;
613 if (!empty($headers->reply_to)) {
614 $object['reply_to'] = $headers->reply_to;
617 if (!empty($headers->sender)) {
618 $object['sender'] = $headers->sender;
621 if (!empty($object)) {
622 $datarray['object'] = json_encode($object);
625 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
626 if (!empty($headers->from[0]->personal)) {
627 $fromname = $headers->from[0]->personal;
630 $datarray['author-name'] = $fromname;
631 $datarray['author-link'] = "mailto:".$frommail;
632 $datarray['author-avatar'] = $contact['photo'];
634 $datarray['owner-name'] = $contact['name'];
635 $datarray['owner-link'] = "mailto:".$contact['addr'];
636 $datarray['owner-avatar'] = $contact['photo'];
638 if ($datarray['parent-uri'] === $datarray['uri']) {
639 $datarray['private'] = 1;
642 if (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
643 $datarray['private'] = 1;
644 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
647 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
648 if (empty($datarray['body'])) {
649 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
653 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
655 Item::insert($datarray);
657 switch ($mailconf['action']) {
659 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
662 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
663 imap_delete($mbox, $msg_uid, FT_UID);
666 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
667 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
670 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
671 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
672 if ($mailconf['movetofolder'] != "") {
673 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
680 Logger::log("Mail: no mails for ".$mailconf['user']);
683 Logger::log("Mail: closing connection for ".$mailconf['user']);