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 $a = BaseObject::getApp();
31 Logger::log('Start for contact ' . $contact_id);
35 if ($command == "force") {
40 Logger::log('no contact');
45 Contact::updateFromProbe($contact_id, true);
48 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
49 if (!DBA::isResult($contact)) {
50 Logger::log('Contact not found or cannot be used.');
54 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
55 $protocol = Protocol::ACTIVITYPUB;
57 $protocol = $contact['network'];
60 $importer_uid = $contact['uid'];
62 $updated = DateTimeFormat::utcNow();
64 if ($importer_uid == 0) {
65 Logger::log('Ignore public contacts');
67 // set the last-update so we don't keep polling
68 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
72 // Possibly switch the remote contact to AP
73 if ($protocol === Protocol::OSTATUS) {
74 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
75 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
78 // load current friends if possible.
79 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
80 if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
81 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
85 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
86 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
87 Logger::log('Polling is disabled');
89 // set the last-update so we don't keep polling
90 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
94 // We don't poll AP contacts by now
95 if ($protocol === Protocol::ACTIVITYPUB) {
96 Logger::log("Don't poll AP contact");
98 // set the last-update so we don't keep polling
99 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
103 $importer = User::getOwnerDataById($importer_uid);
105 if (empty($importer)) {
106 Logger::log('No self contact for user '.$importer_uid);
108 // set the last-update so we don't keep polling
109 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
116 if ($contact['subhub']) {
117 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
118 $contact['priority'] = intval($poll_interval);
121 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
128 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
132 if ($protocol === Protocol::DFRN) {
133 $xml = self::pollDFRN($contact, $updated);
134 } elseif (($protocol === Protocol::OSTATUS)
135 || ($protocol === Protocol::DIASPORA)
136 || ($protocol === Protocol::FEED)) {
137 $xml = self::pollFeed($contact, $protocol, $updated);
138 } elseif ($protocol === Protocol::MAIL) {
139 self::pollMail($contact, $importer_uid, $updated);
143 Logger::log('received xml : ' . $xml, Logger::DATA);
144 if (!strstr($xml, '<')) {
145 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
147 $fields = ['last-update' => $updated, 'failure_update' => $updated];
148 self::updateContact($contact, $fields);
149 Contact::markForArchival($contact);
154 Logger::log("Consume feed of contact ".$contact['id']);
156 consume_feed($xml, $importer, $contact, $hub);
158 // do it a second time for DFRN so that any children find their parents.
159 if ($protocol === Protocol::DFRN) {
160 consume_feed($xml, $importer, $contact, $hub);
163 $hubmode = 'subscribe';
164 if ($protocol === Protocol::DFRN || $contact['blocked']) {
165 $hubmode = 'unsubscribe';
168 if (($protocol === Protocol::OSTATUS || $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
176 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
178 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
179 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
180 $hubs = explode(',', $hub);
183 foreach ($hubs as $h) {
190 subscribe_to_hub($h, $importer, $contact, $hubmode);
195 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
196 DBA::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
197 Contact::unmarkForArchival($contact);
198 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
199 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
200 DBA::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
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 (intval($res->status) == 1) {
309 // we may not be friends anymore. Will keep trying for one month.
310 Logger::log("$url replied status 1 - marking for death ");
312 // set the last-update so we don't keep polling
313 $fields = ['last-update' => $updated, 'failure_update' => $updated];
314 self::updateContact($contact, $fields);
315 Contact::markForArchival($contact);
316 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
317 Contact::unmarkForArchival($contact);
320 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
321 // set the last-update so we don't keep polling
322 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
323 Logger::log('Contact status is ' . $res->status);
327 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
328 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
329 DBA::update('contact', $fields, ['id' => $contact['id']]);
334 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
335 $challenge = hex2bin((string) $res->challenge);
339 if ($contact['duplex'] && strlen($contact['prvkey'])) {
340 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
341 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
343 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
344 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
347 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
349 if (strpos($final_dfrn_id, ':') == 1) {
350 $final_dfrn_id = substr($final_dfrn_id, 2);
353 // There are issues with the legacy DFRN transport layer.
354 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
355 if (empty($final_dfrn_id) || empty($orig_id)) {
356 Logger::log('Contact has got no ID - quitting');
360 if ($final_dfrn_id != $orig_id) {
361 // did not decode properly - cannot trust this site
362 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
364 // set the last-update so we don't keep polling
365 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
366 Contact::markForArchival($contact);
370 $postvars['dfrn_id'] = $idtosend;
371 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
372 $postvars['perm'] = 'rw';
374 return Network::post($contact['poll'], $postvars)->getBody();
378 * @brief Poll Feed/OStatus contacts
380 * @param array $contact The personal contact entry
381 * @param string $protocol The used protocol of the contact
382 * @param string $updated The updated date
383 * @return string polled XML
386 private static function pollFeed(array $contact, $protocol, $updated)
388 // Upgrading DB fields from an older Friendica version
389 // Will only do this once per notify-enabled OStatus contact
390 // or if relationship changes
392 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
394 // Contacts from OStatus are always writable
395 if ($protocol === Protocol::OSTATUS) {
399 if ($stat_writeable != $contact['writable']) {
400 $fields = ['writable' => $stat_writeable];
401 DBA::update('contact', $fields, ['id' => $contact['id']]);
404 // Are we allowed to import from this person?
405 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
406 // set the last-update so we don't keep polling
407 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
408 Logger::log('Contact is blocked or only a follower');
412 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
413 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
416 if ($curlResult->isTimeout()) {
417 // set the last-update so we don't keep polling
418 self::updateContact($contact, ['last-update' => $updated]);
419 Contact::markForArchival($contact);
420 Logger::log('Contact archived');
424 return $curlResult->getBody();
428 * @brief Poll Mail contacts
430 * @param array $contact The personal contact entry
431 * @param integer $importer_uid The UID of the importer
432 * @param string $updated The updated date
435 private static function pollMail(array $contact, $importer_uid, $updated)
437 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
439 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
440 if ($mail_disabled) {
441 // set the last-update so we don't keep polling
442 self::updateContact($contact, ['last-update' => $updated]);
443 Contact::markForArchival($contact);
444 Logger::log('Contact archived');
448 Logger::log("Mail: Enabled", Logger::DEBUG);
451 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
453 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
454 $mailconf = DBA::selectFirst('mailacct', [], $condition);
455 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
456 $mailbox = Email::constructMailboxName($mailconf);
458 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
459 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
461 Logger::log("Mail: Connect to " . $mailconf['user']);
463 $fields = ['last_check' => $updated];
464 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
465 Logger::log("Mail: Connected to " . $mailconf['user']);
467 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
475 $msgs = Email::poll($mbox, $contact['addr']);
478 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
480 $metas = Email::messageMeta($mbox, implode(',', $msgs));
482 if (count($metas) != count($msgs)) {
483 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
485 $msgs = array_combine($msgs, $metas);
487 foreach ($msgs as $msg_uid => $meta) {
488 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
491 $datarray['verb'] = ACTIVITY_POST;
492 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
493 $datarray['network'] = Protocol::MAIL;
494 // $meta = Email::messageMeta($mbox, $msg_uid);
496 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
498 // Have we seen it before?
499 $fields = ['deleted', 'id'];
500 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
501 $item = Item::selectFirst($fields, $condition);
502 if (DBA::isResult($item)) {
503 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
505 // Only delete when mails aren't automatically moved or deleted
506 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
507 if ($meta->deleted && ! $item['deleted']) {
508 $fields = ['deleted' => true, 'changed' => $updated];
509 Item::update($fields, ['id' => $item['id']]);
512 switch ($mailconf['action']) {
514 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
517 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
518 imap_delete($mbox, $msg_uid, FT_UID);
521 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
522 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
525 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
526 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
527 if ($mailconf['movetofolder'] != "") {
528 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
535 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
536 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
537 if (!trim($raw_refs)) {
538 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
540 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
543 $refs_arr = explode(' ', $raw_refs);
544 if (count($refs_arr)) {
545 for ($x = 0; $x < count($refs_arr); $x ++) {
546 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
549 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
550 $parent = Item::selectFirst(['parent-uri'], $condition);
551 if (DBA::isResult($parent)) {
552 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
556 // Decoding the header
557 $subject = imap_mime_header_decode($meta->subject);
558 $datarray['title'] = "";
559 foreach ($subject as $subpart) {
560 if ($subpart->charset != "default") {
561 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
563 $datarray['title'] .= $subpart->text;
566 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
568 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
569 $datarray['created'] = DateTimeFormat::utc($meta->date);
572 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
573 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
576 // Remove Reply-signs in the subject
577 $datarray['title'] = self::RemoveReply($datarray['title']);
579 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
580 if (empty($datarray['parent-uri']) && $reply) {
581 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
582 $params = ['order' => ['created' => true]];
583 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
584 if (DBA::isResult($parent)) {
585 $datarray['parent-uri'] = $parent['parent-uri'];
589 if (empty($datarray['parent-uri'])) {
590 $datarray['parent-uri'] = $datarray['uri'];
593 $r = Email::getMessage($mbox, $msg_uid, $reply);
595 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
598 $datarray['body'] = Strings::escapeHtml($r['body']);
599 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
601 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
603 /// @TODO Adding a gravatar for the original author would be cool
605 $from = imap_mime_header_decode($meta->from);
607 foreach ($from as $frompart) {
608 if ($frompart->charset != "default") {
609 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
611 $fromdecoded .= $frompart->text;
615 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->getHostName());
617 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
619 if (isset($fromarr[0]->personal)) {
620 $fromname = $fromarr[0]->personal;
622 $fromname = $frommail;
625 $datarray['author-name'] = $fromname;
626 $datarray['author-link'] = "mailto:".$frommail;
627 $datarray['author-avatar'] = $contact['photo'];
629 $datarray['owner-name'] = $contact['name'];
630 $datarray['owner-link'] = "mailto:".$contact['addr'];
631 $datarray['owner-avatar'] = $contact['photo'];
633 $datarray['uid'] = $importer_uid;
634 $datarray['contact-id'] = $contact['id'];
635 if ($datarray['parent-uri'] === $datarray['uri']) {
636 $datarray['private'] = 1;
638 if (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
639 $datarray['private'] = 1;
640 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
643 Item::insert($datarray);
645 switch ($mailconf['action']) {
647 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
650 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
651 imap_delete($mbox, $msg_uid, FT_UID);
654 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
655 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
658 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
659 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
660 if ($mailconf['movetofolder'] != "") {
661 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
668 Logger::log("Mail: no mails for ".$mailconf['user']);
671 Logger::log("Mail: closing connection for ".$mailconf['user']);