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\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;
24 require_once 'include/dba.php';
28 public static function execute($contact_id = 0, $command = '')
30 $a = BaseObject::getApp();
32 require_once 'include/items.php';
42 if ($command == "force") {
47 Logger::log('no contact');
51 $d = DateTimeFormat::utcNow();
53 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
54 if (!DBA::isResult($contact)) {
55 Logger::log('Contact not found or cannot be used.');
59 $importer_uid = $contact['uid'];
61 // Possibly switch the remote contact to AP
62 if ($contact['network'] === Protocol::OSTATUS) {
63 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
64 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
67 // We currently don't do anything with AP here
68 if ($contact['network'] === Protocol::ACTIVITYPUB) {
72 // load current friends if possible.
73 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
74 $r = q("SELECT count(*) AS total FROM glink
75 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
76 intval($contact['id'])
78 if (DBA::isResult($r)) {
79 if (!$r[0]['total']) {
80 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
85 // Diaspora users, archived users and followers are only checked if they still exist.
86 if ($contact['archive'] || ($contact["network"] == Protocol::DIASPORA) || ($contact["rel"] == Contact::FOLLOWER)) {
87 $last_updated = PortableContact::lastUpdated($contact["url"], true);
88 $updated = DateTimeFormat::utcNow();
91 Logger::log('Contact '.$contact['id'].' had last update on '.$last_updated, Logger::DEBUG);
93 // The last public item can be older than the last item we got
94 if ($last_updated < $contact['last-item']) {
95 $last_updated = $contact['last-item'];
98 $fields = ['last-item' => DateTimeFormat::utc($last_updated), 'last-update' => $updated, 'success_update' => $updated];
99 self::updateContact($contact, $fields);
100 Contact::unmarkForArchival($contact);
102 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
103 Contact::markForArchival($contact);
104 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
112 $t = $contact['last-update'];
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($t . " + 1 day")) {
126 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
127 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
128 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
131 // Update the contact entry
132 if (($contact['network'] === Protocol::OSTATUS) || ($contact['network'] === Protocol::DIASPORA) || ($contact['network'] === Protocol::DFRN)) {
133 if (!PortableContact::reachable($contact['url'])) {
134 Logger::log("Skipping probably dead contact ".$contact['url']);
136 // set the last-update so we don't keep polling
137 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
141 if (!Contact::updateFromProbe($contact["id"])) {
142 Contact::markForArchival($contact);
143 Logger::log('Contact is marked dead');
145 // set the last-update so we don't keep polling
146 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
149 Contact::unmarkForArchival($contact);
153 if (!in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && Config::get('system', 'disable_polling')) {
157 if ($importer_uid == 0) {
158 Logger::log('Ignore public contacts');
160 // set the last-update so we don't keep polling
161 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
165 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
166 intval($importer_uid)
169 if (!DBA::isResult($r)) {
170 Logger::log('No self contact for user '.$importer_uid);
172 // set the last-update so we don't keep polling
173 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
180 Logger::log("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
182 if ($contact['network'] === Protocol::DFRN) {
183 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
184 if (intval($contact['duplex']) && $contact['dfrn-id']) {
185 $idtosend = '0:' . $orig_id;
187 if (intval($contact['duplex']) && $contact['issued-id']) {
188 $idtosend = '1:' . $orig_id;
191 // they have permission to write to us. We already filtered this in the contact query.
194 // But this may be our first communication, so set the writable flag if it isn't set already.
196 if (!intval($contact['writable'])) {
197 $fields = ['writable' => true];
198 DBA::update('contact', $fields, ['id' => $contact['id']]);
201 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
202 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
203 . '&type=data&last_update=' . $last_update
206 $curlResult = Network::curl($url);
208 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
209 // set the last-update so we don't keep polling
210 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
211 Contact::markForArchival($contact);
215 $handshake_xml = $curlResult->getBody();
216 $html_code = $curlResult->getReturnCode();
218 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
220 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
221 Logger::log("$url appears to be dead - marking for death ");
223 // dead connection - might be a transient event, or this might
224 // mean the software was uninstalled or the domain expired.
225 // Will keep trying for one month.
227 Contact::markForArchival($contact);
229 // set the last-update so we don't keep polling
230 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
231 self::updateContact($contact, $fields);
235 if (!strstr($handshake_xml, '<')) {
236 Logger::log('response from ' . $url . ' did not contain XML.');
238 Contact::markForArchival($contact);
240 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
241 self::updateContact($contact, $fields);
246 $res = XML::parseString($handshake_xml);
248 if (intval($res->status) == 1) {
249 Logger::log("$url replied status 1 - marking for death ");
251 // we may not be friends anymore. Will keep trying for one month.
252 // set the last-update so we don't keep polling
253 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
254 self::updateContact($contact, $fields);
256 Contact::markForArchival($contact);
257 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
258 Logger::log("$url back from the dead - removing mark for death");
259 Contact::unmarkForArchival($contact);
262 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
263 // set the last-update so we don't keep polling
264 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
268 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
269 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
270 DBA::update('contact', $fields, ['id' => $contact['id']]);
275 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
276 $challenge = hex2bin((string) $res->challenge);
280 if ($contact['duplex'] && strlen($contact['prvkey'])) {
281 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
282 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
284 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
285 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
288 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
290 if (strpos($final_dfrn_id, ':') == 1) {
291 $final_dfrn_id = substr($final_dfrn_id, 2);
294 if ($final_dfrn_id != $orig_id) {
295 // did not decode properly - cannot trust this site
296 Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
298 // set the last-update so we don't keep polling
299 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
300 Contact::markForArchival($contact);
304 $postvars['dfrn_id'] = $idtosend;
305 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
306 $postvars['perm'] = 'rw';
308 $xml = Network::post($contact['poll'], $postvars)->getBody();
310 } elseif (($contact['network'] === Protocol::OSTATUS)
311 || ($contact['network'] === Protocol::DIASPORA)
312 || ($contact['network'] === Protocol::FEED)) {
314 // Upgrading DB fields from an older Friendica version
315 // Will only do this once per notify-enabled OStatus contact
316 // or if relationship changes
318 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
320 // Contacts from OStatus are always writable
321 if ($contact['network'] === Protocol::OSTATUS) {
325 if ($stat_writeable != $contact['writable']) {
326 $fields = ['writable' => $stat_writeable];
327 DBA::update('contact', $fields, ['id' => $contact['id']]);
330 // Are we allowed to import from this person?
332 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
333 // set the last-update so we don't keep polling
334 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
338 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
339 $curlResult = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
342 if ($curlResult->isTimeout()) {
343 // set the last-update so we don't keep polling
344 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
345 Contact::markForArchival($contact);
349 $xml = $curlResult->getBody();
351 } elseif ($contact['network'] === Protocol::MAIL) {
352 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
354 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
355 if ($mail_disabled) {
356 // set the last-update so we don't keep polling
357 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
358 Contact::markForArchival($contact);
362 Logger::log("Mail: Enabled", Logger::DEBUG);
365 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
367 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
368 $mailconf = DBA::selectFirst('mailacct', [], $condition);
369 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
370 $mailbox = Email::constructMailboxName($mailconf);
372 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
373 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
375 Logger::log("Mail: Connect to " . $mailconf['user']);
377 $fields = ['last_check' => DateTimeFormat::utcNow()];
378 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
379 Logger::log("Mail: Connected to " . $mailconf['user']);
381 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
386 $msgs = Email::poll($mbox, $contact['addr']);
389 Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
391 $metas = Email::messageMeta($mbox, implode(',', $msgs));
393 if (count($metas) != count($msgs)) {
394 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
396 $msgs = array_combine($msgs, $metas);
398 foreach ($msgs as $msg_uid => $meta) {
399 Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
402 $datarray['verb'] = ACTIVITY_POST;
403 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
404 $datarray['network'] = Protocol::MAIL;
405 // $meta = Email::messageMeta($mbox, $msg_uid);
407 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
409 // Have we seen it before?
410 $fields = ['deleted', 'id'];
411 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
412 $item = Item::selectFirst($fields, $condition);
413 if (DBA::isResult($item)) {
414 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
416 // Only delete when mails aren't automatically moved or deleted
417 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
418 if ($meta->deleted && ! $item['deleted']) {
419 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
420 Item::update($fields, ['id' => $item['id']]);
423 switch ($mailconf['action']) {
425 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
428 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
429 imap_delete($mbox, $msg_uid, FT_UID);
432 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
433 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
436 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
437 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
438 if ($mailconf['movetofolder'] != "") {
439 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
447 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
448 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
449 if (!trim($raw_refs)) {
450 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
452 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
455 $refs_arr = explode(' ', $raw_refs);
456 if (count($refs_arr)) {
457 for ($x = 0; $x < count($refs_arr); $x ++) {
458 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
461 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
462 $parent = Item::selectFirst(['parent-uri'], $condition);
463 if (DBA::isResult($parent)) {
464 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
468 // Decoding the header
469 $subject = imap_mime_header_decode($meta->subject);
470 $datarray['title'] = "";
471 foreach ($subject as $subpart) {
472 if ($subpart->charset != "default") {
473 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
475 $datarray['title'] .= $subpart->text;
478 $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
480 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
481 $datarray['created'] = DateTimeFormat::utc($meta->date);
484 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
485 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
488 // Remove Reply-signs in the subject
489 $datarray['title'] = self::RemoveReply($datarray['title']);
491 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
492 if (empty($datarray['parent-uri']) && $reply) {
493 $condition = ['title' => $datarray['title'], 'uid' => importer_uid, 'network' => Protocol::MAIL];
494 $params = ['order' => ['created' => true]];
495 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
496 if (DBA::isResult($parent)) {
497 $datarray['parent-uri'] = $parent['parent-uri'];
501 if (empty($datarray['parent-uri'])) {
502 $datarray['parent-uri'] = $datarray['uri'];
505 $r = Email::getMessage($mbox, $msg_uid, $reply);
507 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
510 $datarray['body'] = Strings::escapeHtml($r['body']);
511 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
513 Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
515 /// @TODO Adding a gravatar for the original author would be cool
517 $from = imap_mime_header_decode($meta->from);
519 foreach ($from as $frompart) {
520 if ($frompart->charset != "default") {
521 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
523 $fromdecoded .= $frompart->text;
527 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->getHostName());
529 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
531 if (isset($fromarr[0]->personal)) {
532 $fromname = $fromarr[0]->personal;
534 $fromname = $frommail;
537 $datarray['author-name'] = $fromname;
538 $datarray['author-link'] = "mailto:".$frommail;
539 $datarray['author-avatar'] = $contact['photo'];
541 $datarray['owner-name'] = $contact['name'];
542 $datarray['owner-link'] = "mailto:".$contact['addr'];
543 $datarray['owner-avatar'] = $contact['photo'];
545 $datarray['uid'] = $importer_uid;
546 $datarray['contact-id'] = $contact['id'];
547 if ($datarray['parent-uri'] === $datarray['uri']) {
548 $datarray['private'] = 1;
550 if (($contact['network'] === Protocol::MAIL) && !PConfig::get($importer_uid, 'system', 'allow_public_email_replies')) {
551 $datarray['private'] = 1;
552 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
555 $stored_item = Item::insert($datarray);
557 switch ($mailconf['action']) {
559 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
562 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
563 imap_delete($mbox, $msg_uid, FT_UID);
566 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
567 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
570 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
571 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
572 if ($mailconf['movetofolder'] != "") {
573 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
580 Logger::log("Mail: no mails for ".$mailconf['user']);
583 Logger::log("Mail: closing connection for ".$mailconf['user']);
589 Logger::log('received xml : ' . $xml, Logger::DATA);
590 if (!strstr($xml, '<')) {
591 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
593 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
594 self::updateContact($contact, $fields);
595 Contact::markForArchival($contact);
600 Logger::log("Consume feed of contact ".$contact['id']);
602 consume_feed($xml, $importer, $contact, $hub);
604 // do it a second time for DFRN so that any children find their parents.
605 if ($contact['network'] === Protocol::DFRN) {
606 consume_feed($xml, $importer, $contact, $hub);
609 $hubmode = 'subscribe';
610 if ($contact['network'] === Protocol::DFRN || $contact['blocked']) {
611 $hubmode = 'unsubscribe';
614 if (($contact['network'] === Protocol::OSTATUS || $contact['network'] == Protocol::FEED) && (! $contact['hub-verify'])) {
622 Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
624 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $contact['network'] == Protocol::FEED)) {
625 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
626 $hubs = explode(',', $hub);
629 foreach ($hubs as $h) {
636 subscribe_to_hub($h, $importer, $contact, $hubmode);
641 $updated = DateTimeFormat::utcNow();
643 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
644 DBA::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
645 Contact::unmarkForArchival($contact);
646 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
647 $updated = DateTimeFormat::utcNow();
649 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
650 DBA::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
651 Contact::markForArchival($contact);
653 $updated = DateTimeFormat::utcNow();
654 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
660 private static function RemoveReply($subject)
662 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
663 $subject = trim(substr($subject, 4));
670 * @brief Updates a personal contact entry and the public contact entry
672 * @param array $contact The personal contact entry
673 * @param array $fields The fields that are updated
675 private static function updateContact(array $contact, array $fields)
677 DBA::update('contact', $fields, ['id' => $contact['id']]);
678 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);