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\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');
43 Contact::updateFromProbe($contact_id, true);
46 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
47 if (!DBA::isResult($contact)) {
48 Logger::log('Contact not found or cannot be used.');
52 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
53 $protocol = Protocol::ACTIVITYPUB;
55 $protocol = $contact['network'];
58 $importer_uid = $contact['uid'];
60 $updated = DateTimeFormat::utcNow();
62 if ($importer_uid == 0) {
63 Logger::log('Ignore public contacts');
65 // set the last-update so we don't keep polling
66 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
70 // Possibly switch the remote contact to AP
71 if ($protocol === Protocol::OSTATUS) {
72 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
73 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
76 // load current friends if possible.
77 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
78 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
79 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
83 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
84 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
85 Logger::log('Polling is disabled');
87 // set the last-update so we don't keep polling
88 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
92 // We don't poll AP contacts by now
93 if ($protocol === Protocol::ACTIVITYPUB) {
94 Logger::log("Don't poll AP contact");
96 // set the last-update so we don't keep polling
97 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
101 $importer = User::getOwnerDataById($importer_uid);
103 if (empty($importer)) {
104 Logger::log('No self contact for user '.$importer_uid);
106 // set the last-update so we don't keep polling
107 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
114 if ($contact['subhub']) {
115 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
116 $contact['priority'] = intval($poll_interval);
119 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
126 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
130 if ($protocol === Protocol::DFRN) {
131 $xml = self::pollDFRN($contact, $updated);
132 } elseif (($protocol === Protocol::OSTATUS)
133 || ($protocol === Protocol::DIASPORA)
134 || ($protocol === Protocol::FEED)) {
135 $xml = self::pollFeed($contact, $protocol, $updated);
136 } elseif ($protocol === Protocol::MAIL) {
137 self::pollMail($contact, $importer_uid, $updated);
141 Logger::log('received xml : ' . $xml, Logger::DATA);
142 if (!strstr($xml, '<')) {
143 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
145 $fields = ['last-update' => $updated, 'failure_update' => $updated];
146 self::updateContact($contact, $fields);
147 Contact::markForArchival($contact);
152 Logger::log("Consume feed of contact ".$contact['id']);
154 consume_feed($xml, $importer, $contact, $hub);
156 // do it a second time for DFRN so that any children find their parents.
157 if ($protocol === Protocol::DFRN) {
158 consume_feed($xml, $importer, $contact, $hub);
161 $hubmode = 'subscribe';
162 if ($protocol === Protocol::DFRN || $contact['blocked']) {
163 $hubmode = 'unsubscribe';
166 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
174 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
176 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
177 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
178 $hubs = explode(',', $hub);
181 foreach ($hubs as $h) {
188 subscribe_to_hub($h, $importer, $contact, $hubmode);
193 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
194 Contact::unmarkForArchival($contact);
195 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
196 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
197 Contact::markForArchival($contact);
199 self::updateContact($contact, ['last-update' => $updated]);
206 private static function RemoveReply($subject)
208 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
209 $subject = trim(substr($subject, 4));
216 * @brief Updates a personal contact entry and the public contact entry
218 * @param array $contact The personal contact entry
219 * @param array $fields The fields that are updated
222 private static function updateContact(array $contact, array $fields)
224 DBA::update('contact', $fields, ['id' => $contact['id']]);
225 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
229 * @brief Poll DFRN contacts
231 * @param array $contact The personal contact entry
232 * @param string $updated The updated date
233 * @return string polled XML
236 private static function pollDFRN(array $contact, $updated)
238 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
239 if (intval($contact['duplex']) && $contact['dfrn-id']) {
240 $idtosend = '0:' . $orig_id;
242 if (intval($contact['duplex']) && $contact['issued-id']) {
243 $idtosend = '1:' . $orig_id;
246 // they have permission to write to us. We already filtered this in the contact query.
249 // But this may be our first communication, so set the writable flag if it isn't set already.
250 if (!intval($contact['writable'])) {
251 $fields = ['writable' => true];
252 DBA::update('contact', $fields, ['id' => $contact['id']]);
255 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
256 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
257 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
260 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
261 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
262 . '&type=data&last_update=' . $last_update
265 $curlResult = Network::curl($url);
267 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
268 // set the last-update so we don't keep polling
269 self::updateContact($contact, ['last-update' => $updated]);
270 Contact::markForArchival($contact);
271 Logger::log('Contact archived');
275 $handshake_xml = $curlResult->getBody();
276 $html_code = $curlResult->getReturnCode();
278 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
280 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
281 // dead connection - might be a transient event, or this might
282 // mean the software was uninstalled or the domain expired.
283 // Will keep trying for one month.
284 Logger::log("$url appears to be dead - marking for death ");
286 // set the last-update so we don't keep polling
287 $fields = ['last-update' => $updated, 'failure_update' => $updated];
288 self::updateContact($contact, $fields);
289 Contact::markForArchival($contact);
293 if (!strstr($handshake_xml, '<')) {
294 Logger::log('response from ' . $url . ' did not contain XML.');
296 $fields = ['last-update' => $updated, 'failure_update' => $updated];
297 self::updateContact($contact, $fields);
298 Contact::markForArchival($contact);
302 $res = XML::parseString($handshake_xml);
304 if (intval($res->status) == 1) {
305 // we may not be friends anymore. Will keep trying for one month.
306 Logger::log("$url replied status 1 - marking for death ");
308 // set the last-update so we don't keep polling
309 $fields = ['last-update' => $updated, 'failure_update' => $updated];
310 self::updateContact($contact, $fields);
311 Contact::markForArchival($contact);
312 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
313 Contact::unmarkForArchival($contact);
316 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
317 // set the last-update so we don't keep polling
318 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
319 Logger::log('Contact status is ' . $res->status);
323 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
324 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
325 DBA::update('contact', $fields, ['id' => $contact['id']]);
330 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
331 $challenge = hex2bin((string) $res->challenge);
335 if ($contact['duplex'] && strlen($contact['prvkey'])) {
336 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
337 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
339 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
340 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
343 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
345 if (strpos($final_dfrn_id, ':') == 1) {
346 $final_dfrn_id = substr($final_dfrn_id, 2);
349 // There are issues with the legacy DFRN transport layer.
350 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
351 if (empty($final_dfrn_id) || empty($orig_id)) {
352 Logger::log('Contact has got no ID - quitting');
356 if ($final_dfrn_id != $orig_id) {
357 // did not decode properly - cannot trust this site
358 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
360 // set the last-update so we don't keep polling
361 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
362 Contact::markForArchival($contact);
366 $postvars['dfrn_id'] = $idtosend;
367 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
368 $postvars['perm'] = 'rw';
370 return Network::post($contact['poll'], $postvars)->getBody();
374 * @brief Poll Feed/OStatus contacts
376 * @param array $contact The personal contact entry
377 * @param string $protocol The used protocol of the contact
378 * @param string $updated The updated date
379 * @return string polled XML
382 private static function pollFeed(array $contact, $protocol, $updated)
384 // Upgrading DB fields from an older Friendica version
385 // Will only do this once per notify-enabled OStatus contact
386 // or if relationship changes
388 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
390 // Contacts from OStatus are always writable
391 if ($protocol === Protocol::OSTATUS) {
395 if ($stat_writeable != $contact['writable']) {
396 $fields = ['writable' => $stat_writeable];
397 DBA::update('contact', $fields, ['id' => $contact['id']]);
400 // Are we allowed to import from this person?
401 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
402 // set the last-update so we don't keep polling
403 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
404 Logger::log('Contact is blocked or only a follower');
408 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
409 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
412 if ($curlResult->isTimeout()) {
413 // set the last-update so we don't keep polling
414 self::updateContact($contact, ['last-update' => $updated]);
415 Contact::markForArchival($contact);
416 Logger::log('Contact archived');
420 return $curlResult->getBody();
424 * @brief Poll Mail contacts
426 * @param array $contact The personal contact entry
427 * @param integer $importer_uid The UID of the importer
428 * @param string $updated The updated date
431 private static function pollMail(array $contact, $importer_uid, $updated)
433 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
435 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
436 if ($mail_disabled) {
437 // set the last-update so we don't keep polling
438 self::updateContact($contact, ['last-update' => $updated]);
439 Contact::markForArchival($contact);
440 Logger::log('Contact archived');
444 Logger::log("Mail: Enabled", Logger::DEBUG);
447 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
449 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
450 $mailconf = DBA::selectFirst('mailacct', [], $condition);
451 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
452 $mailbox = Email::constructMailboxName($mailconf);
454 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
455 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
457 Logger::log("Mail: Connect to " . $mailconf['user']);
459 $fields = ['last_check' => $updated];
460 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
461 Logger::log("Mail: Connected to " . $mailconf['user']);
463 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
471 $msgs = Email::poll($mbox, $contact['addr']);
474 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
476 $metas = Email::messageMeta($mbox, implode(',', $msgs));
478 if (count($metas) != count($msgs)) {
479 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
481 $msgs = array_combine($msgs, $metas);
483 foreach ($msgs as $msg_uid => $meta) {
484 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
487 $datarray['verb'] = ACTIVITY_POST;
488 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
489 $datarray['network'] = Protocol::MAIL;
490 // $meta = Email::messageMeta($mbox, $msg_uid);
492 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
494 // Have we seen it before?
495 $fields = ['deleted', 'id'];
496 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
497 $item = Item::selectFirst($fields, $condition);
498 if (DBA::isResult($item)) {
499 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
501 // Only delete when mails aren't automatically moved or deleted
502 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
503 if ($meta->deleted && ! $item['deleted']) {
504 $fields = ['deleted' => true, 'changed' => $updated];
505 Item::update($fields, ['id' => $item['id']]);
508 switch ($mailconf['action']) {
510 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
513 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
514 imap_delete($mbox, $msg_uid, FT_UID);
517 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
518 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
521 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
522 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
523 if ($mailconf['movetofolder'] != "") {
524 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
531 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
532 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
533 if (!trim($raw_refs)) {
534 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
536 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
539 $refs_arr = explode(' ', $raw_refs);
540 if (count($refs_arr)) {
541 for ($x = 0; $x < count($refs_arr); $x ++) {
542 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
545 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
546 $parent = Item::selectFirst(['parent-uri'], $condition);
547 if (DBA::isResult($parent)) {
548 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
552 // Decoding the header
553 $subject = imap_mime_header_decode($meta->subject);
554 $datarray['title'] = "";
555 foreach ($subject as $subpart) {
556 if ($subpart->charset != "default") {
557 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
559 $datarray['title'] .= $subpart->text;
562 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
564 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
565 $datarray['created'] = DateTimeFormat::utc($meta->date);
568 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
569 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
572 // Remove Reply-signs in the subject
573 $datarray['title'] = self::RemoveReply($datarray['title']);
575 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
576 if (empty($datarray['parent-uri']) && $reply) {
577 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
578 $params = ['order' => ['created' => true]];
579 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
580 if (DBA::isResult($parent)) {
581 $datarray['parent-uri'] = $parent['parent-uri'];
585 if (empty($datarray['parent-uri'])) {
586 $datarray['parent-uri'] = $datarray['uri'];
589 $r = Email::getMessage($mbox, $msg_uid, $reply);
591 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
594 $datarray['body'] = Strings::escapeHtml($r['body']);
595 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
597 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
599 /// @TODO Adding a gravatar for the original author would be cool
601 $from = imap_mime_header_decode($meta->from);
603 foreach ($from as $frompart) {
604 if ($frompart->charset != "default") {
605 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
607 $fromdecoded .= $frompart->text;
611 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, BaseObject::getApp()->getHostName());
613 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
615 if (isset($fromarr[0]->personal)) {
616 $fromname = $fromarr[0]->personal;
618 $fromname = $frommail;
621 $datarray['author-name'] = $fromname;
622 $datarray['author-link'] = "mailto:".$frommail;
623 $datarray['author-avatar'] = $contact['photo'];
625 $datarray['owner-name'] = $contact['name'];
626 $datarray['owner-link'] = "mailto:".$contact['addr'];
627 $datarray['owner-avatar'] = $contact['photo'];
629 $datarray['uid'] = $importer_uid;
630 $datarray['contact-id'] = $contact['id'];
631 if ($datarray['parent-uri'] === $datarray['uri']) {
632 $datarray['private'] = 1;
634 if (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
635 $datarray['private'] = 1;
636 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
639 Item::insert($datarray);
641 switch ($mailconf['action']) {
643 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
646 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
647 imap_delete($mbox, $msg_uid, FT_UID);
650 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
651 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
654 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
655 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
656 if ($mailconf['movetofolder'] != "") {
657 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
664 Logger::log("Mail: no mails for ".$mailconf['user']);
667 Logger::log("Mail: closing connection for ".$mailconf['user']);