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\PConfig;
11 use Friendica\Core\Protocol;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Protocol\Email;
16 use Friendica\Protocol\ActivityPub;
17 use Friendica\Protocol\PortableContact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\XML;
22 require_once 'include/dba.php';
26 public static function execute($contact_id = 0, $command = '')
28 $a = BaseObject::getApp();
30 require_once 'include/items.php';
40 if ($command == "force") {
49 $d = DateTimeFormat::utcNow();
51 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
52 if (!DBA::isResult($contact)) {
53 logger('Contact not found or cannot be used.');
57 $importer_uid = $contact['uid'];
59 // Possibly switch the remote contact to AP
60 if ($contact['network'] === Protocol::OSTATUS) {
61 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
62 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
65 // We currently don't do anything with AP here
66 if ($contact['network'] === Protocol::ACTIVITYPUB) {
70 // load current friends if possible.
71 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
72 $r = q("SELECT count(*) AS total FROM glink
73 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
74 intval($contact['id'])
76 if (DBA::isResult($r)) {
77 if (!$r[0]['total']) {
78 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
83 // Diaspora users, archived users and followers are only checked if they still exist.
84 if ($contact['archive'] || ($contact["network"] == Protocol::DIASPORA) || ($contact["rel"] == Contact::FOLLOWER)) {
85 $last_updated = PortableContact::lastUpdated($contact["url"], true);
86 $updated = DateTimeFormat::utcNow();
89 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
91 // The last public item can be older than the last item we got
92 if ($last_updated < $contact['last-item']) {
93 $last_updated = $contact['last-item'];
96 $fields = ['last-item' => DateTimeFormat::utc($last_updated), 'last-update' => $updated, 'success_update' => $updated];
97 self::updateContact($contact, $fields);
98 Contact::unmarkForArchival($contact);
100 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
101 Contact::markForArchival($contact);
102 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
110 $t = $contact['last-update'];
112 if ($contact['subhub']) {
113 $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
114 $contact['priority'] = intval($poll_interval);
117 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
124 $last_update = (($contact['last-update'] <= NULL_DATE)
125 ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
126 : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
129 // Update the contact entry
130 if (($contact['network'] === Protocol::OSTATUS) || ($contact['network'] === Protocol::DIASPORA) || ($contact['network'] === Protocol::DFRN)) {
131 if (!PortableContact::reachable($contact['url'])) {
132 logger("Skipping probably dead contact ".$contact['url']);
134 // set the last-update so we don't keep polling
135 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
139 if (!Contact::updateFromProbe($contact["id"])) {
140 Contact::markForArchival($contact);
141 logger('Contact is marked dead');
143 // set the last-update so we don't keep polling
144 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
147 Contact::unmarkForArchival($contact);
151 if ($importer_uid == 0) {
152 logger('Ignore public contacts');
154 // set the last-update so we don't keep polling
155 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
159 $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",
160 intval($importer_uid)
163 if (!DBA::isResult($r)) {
164 logger('No self contact for user '.$importer_uid);
166 // set the last-update so we don't keep polling
167 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
174 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
176 if ($contact['network'] === Protocol::DFRN) {
177 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
178 if (intval($contact['duplex']) && $contact['dfrn-id']) {
179 $idtosend = '0:' . $orig_id;
181 if (intval($contact['duplex']) && $contact['issued-id']) {
182 $idtosend = '1:' . $orig_id;
185 // they have permission to write to us. We already filtered this in the contact query.
188 // But this may be our first communication, so set the writable flag if it isn't set already.
190 if (!intval($contact['writable'])) {
191 $fields = ['writable' => true];
192 DBA::update('contact', $fields, ['id' => $contact['id']]);
195 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
196 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
197 . '&type=data&last_update=' . $last_update
200 $curlResult = Network::curl($url);
202 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
203 // set the last-update so we don't keep polling
204 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
205 Contact::markForArchival($contact);
209 $handshake_xml = $curlResult->getBody();
210 $html_code = $curlResult->getReturnCode();
212 logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
214 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
215 logger("$url appears to be dead - marking for death ");
217 // dead connection - might be a transient event, or this might
218 // mean the software was uninstalled or the domain expired.
219 // Will keep trying for one month.
221 Contact::markForArchival($contact);
223 // set the last-update so we don't keep polling
224 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
225 self::updateContact($contact, $fields);
229 if (!strstr($handshake_xml, '<')) {
230 logger('response from ' . $url . ' did not contain XML.');
232 Contact::markForArchival($contact);
234 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
235 self::updateContact($contact, $fields);
240 $res = XML::parseString($handshake_xml);
242 if (intval($res->status) == 1) {
243 logger("$url replied status 1 - marking for death ");
245 // we may not be friends anymore. Will keep trying for one month.
246 // set the last-update so we don't keep polling
247 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
248 self::updateContact($contact, $fields);
250 Contact::markForArchival($contact);
251 } elseif ($contact['term-date'] > NULL_DATE) {
252 logger("$url back from the dead - removing mark for death");
253 Contact::unmarkForArchival($contact);
256 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
257 // set the last-update so we don't keep polling
258 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
262 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
263 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
264 DBA::update('contact', $fields, ['id' => $contact['id']]);
269 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
270 $challenge = hex2bin((string) $res->challenge);
274 if ($contact['duplex'] && strlen($contact['prvkey'])) {
275 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
276 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
278 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
279 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
282 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
284 if (strpos($final_dfrn_id, ':') == 1) {
285 $final_dfrn_id = substr($final_dfrn_id, 2);
288 if ($final_dfrn_id != $orig_id) {
289 // did not decode properly - cannot trust this site
290 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
292 // set the last-update so we don't keep polling
293 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
294 Contact::markForArchival($contact);
298 $postvars['dfrn_id'] = $idtosend;
299 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
300 $postvars['perm'] = 'rw';
302 $xml = Network::post($contact['poll'], $postvars)->getBody();
304 } elseif (($contact['network'] === Protocol::OSTATUS)
305 || ($contact['network'] === Protocol::DIASPORA)
306 || ($contact['network'] === Protocol::FEED)) {
308 // Upgrading DB fields from an older Friendica version
309 // Will only do this once per notify-enabled OStatus contact
310 // or if relationship changes
312 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
314 // Contacts from OStatus are always writable
315 if ($contact['network'] === Protocol::OSTATUS) {
319 if ($stat_writeable != $contact['writable']) {
320 $fields = ['writable' => $stat_writeable];
321 DBA::update('contact', $fields, ['id' => $contact['id']]);
324 // Are we allowed to import from this person?
326 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
327 // set the last-update so we don't keep polling
328 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
332 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
333 $curlResult = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
336 if (!$curlResult->isTimeout()) {
337 // set the last-update so we don't keep polling
338 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
339 Contact::markForArchival($contact);
343 $xml = $curlResult->getBody();
345 } elseif ($contact['network'] === Protocol::MAIL) {
346 logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
348 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
349 if ($mail_disabled) {
350 // set the last-update so we don't keep polling
351 DBA::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
352 Contact::markForArchival($contact);
356 logger("Mail: Enabled", LOGGER_DEBUG);
359 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
361 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
362 $mailconf = DBA::selectFirst('mailacct', [], $condition);
363 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
364 $mailbox = Email::constructMailboxName($mailconf);
366 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
367 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
369 logger("Mail: Connect to " . $mailconf['user']);
371 $fields = ['last_check' => DateTimeFormat::utcNow()];
372 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
373 logger("Mail: Connected to " . $mailconf['user']);
375 logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
380 $msgs = Email::poll($mbox, $contact['addr']);
383 logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
385 $metas = Email::messageMeta($mbox, implode(',', $msgs));
387 if (count($metas) != count($msgs)) {
388 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
390 $msgs = array_combine($msgs, $metas);
392 foreach ($msgs as $msg_uid => $meta) {
393 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
396 $datarray['verb'] = ACTIVITY_POST;
397 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
398 $datarray['network'] = Protocol::MAIL;
399 // $meta = Email::messageMeta($mbox, $msg_uid);
401 $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
403 // Have we seen it before?
404 $fields = ['deleted', 'id'];
405 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
406 $item = Item::selectFirst($fields, $condition);
407 if (DBA::isResult($item)) {
408 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
410 // Only delete when mails aren't automatically moved or deleted
411 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
412 if ($meta->deleted && ! $item['deleted']) {
413 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
414 Item::update($fields, ['id' => $item['id']]);
417 switch ($mailconf['action']) {
419 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
422 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
423 imap_delete($mbox, $msg_uid, FT_UID);
426 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
427 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
430 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
431 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
432 if ($mailconf['movetofolder'] != "") {
433 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
441 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
442 $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
443 if (!trim($raw_refs)) {
444 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
446 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
449 $refs_arr = explode(' ', $raw_refs);
450 if (count($refs_arr)) {
451 for ($x = 0; $x < count($refs_arr); $x ++) {
452 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
455 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
456 $parent = Item::selectFirst(['parent-uri'], $condition);
457 if (DBA::isResult($parent)) {
458 $datarray['parent-uri'] = $parent['parent-uri']; // Set the parent as the top-level item
462 // Decoding the header
463 $subject = imap_mime_header_decode($meta->subject);
464 $datarray['title'] = "";
465 foreach ($subject as $subpart) {
466 if ($subpart->charset != "default") {
467 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
469 $datarray['title'] .= $subpart->text;
472 $datarray['title'] = notags(trim($datarray['title']));
474 //$datarray['title'] = notags(trim($meta->subject));
475 $datarray['created'] = DateTimeFormat::utc($meta->date);
478 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
479 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
482 // Remove Reply-signs in the subject
483 $datarray['title'] = self::RemoveReply($datarray['title']);
485 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
486 if (empty($datarray['parent-uri']) && $reply) {
487 $condition = ['title' => $datarray['title'], 'uid' => importer_uid, 'network' => Protocol::MAIL];
488 $params = ['order' => ['created' => true]];
489 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
490 if (DBA::isResult($parent)) {
491 $datarray['parent-uri'] = $parent['parent-uri'];
495 if (empty($datarray['parent-uri'])) {
496 $datarray['parent-uri'] = $datarray['uri'];
499 $r = Email::getMessage($mbox, $msg_uid, $reply);
501 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
504 $datarray['body'] = escape_tags($r['body']);
505 $datarray['body'] = BBCode::limitBodySize($datarray['body']);
507 logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
509 /// @TODO Adding a gravatar for the original author would be cool
511 $from = imap_mime_header_decode($meta->from);
513 foreach ($from as $frompart) {
514 if ($frompart->charset != "default") {
515 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
517 $fromdecoded .= $frompart->text;
521 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->getHostName());
523 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
525 if (isset($fromarr[0]->personal)) {
526 $fromname = $fromarr[0]->personal;
528 $fromname = $frommail;
531 $datarray['author-name'] = $fromname;
532 $datarray['author-link'] = "mailto:".$frommail;
533 $datarray['author-avatar'] = $contact['photo'];
535 $datarray['owner-name'] = $contact['name'];
536 $datarray['owner-link'] = "mailto:".$contact['addr'];
537 $datarray['owner-avatar'] = $contact['photo'];
539 $datarray['uid'] = $importer_uid;
540 $datarray['contact-id'] = $contact['id'];
541 if ($datarray['parent-uri'] === $datarray['uri']) {
542 $datarray['private'] = 1;
544 if (($contact['network'] === Protocol::MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
545 $datarray['private'] = 1;
546 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
549 $stored_item = Item::insert($datarray);
551 switch ($mailconf['action']) {
553 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
556 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
557 imap_delete($mbox, $msg_uid, FT_UID);
560 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
561 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
564 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
565 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
566 if ($mailconf['movetofolder'] != "") {
567 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
574 logger("Mail: no mails for ".$mailconf['user']);
577 logger("Mail: closing connection for ".$mailconf['user']);
583 logger('received xml : ' . $xml, LOGGER_DATA);
584 if (!strstr($xml, '<')) {
585 logger('post_handshake: response from ' . $url . ' did not contain XML.');
587 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
588 self::updateContact($contact, $fields);
589 Contact::markForArchival($contact);
594 logger("Consume feed of contact ".$contact['id']);
596 consume_feed($xml, $importer, $contact, $hub);
598 // do it a second time for DFRN so that any children find their parents.
599 if ($contact['network'] === Protocol::DFRN) {
600 consume_feed($xml, $importer, $contact, $hub);
603 $hubmode = 'subscribe';
604 if ($contact['network'] === Protocol::DFRN || $contact['blocked']) {
605 $hubmode = 'unsubscribe';
608 if (($contact['network'] === Protocol::OSTATUS || $contact['network'] == Protocol::FEED) && (! $contact['hub-verify'])) {
616 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
618 if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $contact['network'] == Protocol::FEED)) {
619 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
620 $hubs = explode(',', $hub);
623 foreach ($hubs as $h) {
630 subscribe_to_hub($h, $importer, $contact, $hubmode);
635 $updated = DateTimeFormat::utcNow();
637 self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
638 DBA::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
639 Contact::unmarkForArchival($contact);
640 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
641 $updated = DateTimeFormat::utcNow();
643 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
644 DBA::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
645 Contact::markForArchival($contact);
647 $updated = DateTimeFormat::utcNow();
648 DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
654 private static function RemoveReply($subject)
656 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
657 $subject = trim(substr($subject, 4));
664 * @brief Updates a personal contact entry and the public contact entry
666 * @param array $contact The personal contact entry
667 * @param array $fields The fields that are updated
669 private static function updateContact(array $contact, array $fields)
671 DBA::update('contact', $fields, ['id' => $contact['id']]);
672 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);